Skip to main content
curl -X GET "https://api.strike.markets/api-key/status" \
  -H "X-API-Key: stk_your_api_key_here"
{
  "success": true,
  "status": "active",
  "wallet_address": "0x742d35cc6c6c7532b1140da4c8a2f6c8ecfc9b46",
  "created_at": "2024-01-15T14:30:00Z",
  "last_used_at": "2024-01-15T16:45:00Z",
  "request_count": 142,
  "rate_limit": {
    "limit": 10,
    "remaining": 8,
    "reset_at": "2024-01-15T16:46:00Z"
  }
}
curl -X GET "https://api.strike.markets/api-key/status" \
  -H "X-API-Key: stk_your_api_key_here"
{
  "success": true,
  "status": "active",
  "wallet_address": "0x742d35cc6c6c7532b1140da4c8a2f6c8ecfc9b46",
  "created_at": "2024-01-15T14:30:00Z",
  "last_used_at": "2024-01-15T16:45:00Z",
  "request_count": 142,
  "rate_limit": {
    "limit": 10,
    "remaining": 8,
    "reset_at": "2024-01-15T16:46:00Z"
  }
}

Description

Check the status and metadata of an API key. This endpoint is useful for verifying that your API key is valid and active, monitoring usage, and checking rate limits.

Authentication

This endpoint requires:
  • The API key you want to check status for

Request Headers

HeaderTypeRequiredDescription
X-API-KeystringYesThe API key to check

Response Fields

FieldTypeDescription
successbooleanWhether the operation was successful
statusstringStatus of the key: active or inactive
wallet_addressstringThe wallet address associated with this key
created_atstringISO 8601 timestamp of when the key was created
last_used_atstringISO 8601 timestamp of last API call (null if never used)
request_countnumberTotal number of requests made with this key
rate_limitobjectCurrent rate limit status

Rate Limit Object

FieldTypeDescription
limitnumberMaximum requests allowed in the window
remainingnumberRequests remaining in current window
reset_atstringISO 8601 timestamp when the rate limit resets

Error Codes

CodeDescription
INVALID_API_KEYThe provided key is invalid or has been revoked
API_KEY_NOT_FOUNDNo API key was provided
UNAUTHORIZEDAuthentication failed

Use Cases

1. Health Check / Monitoring

import requests
import time

def monitor_api_key_health(api_key: str):
    """Monitor API key health and rate limits"""
    
    while True:
        response = requests.get(
            'https://api.strike.markets/api-key/status',
            headers={'X-API-Key': api_key}
        )
        
        if response.status_code == 200:
            data = response.json()
            
            # Check if key is active
            if data['status'] != 'active':
                print("WARNING: API key is not active!")
                break
            
            # Check rate limits
            rate_limit = data['rate_limit']
            if rate_limit['remaining'] < 2:
                print(f"Rate limit warning: Only {rate_limit['remaining']} requests remaining")
                print(f"Resets at: {rate_limit['reset_at']}")
                # Wait until reset
                time.sleep(60)
            
            print(f"API Key healthy - Requests made: {data['request_count']}")
        else:
            print(f"API Key check failed: {response.json()}")
            break
        
        time.sleep(300)  # Check every 5 minutes

2. Validate Key Before Trading

async function validateKeyBeforeTrading(apiKey: string): Promise<boolean> {
  try {
    const response = await fetch('https://api.strike.markets/api-key/status', {
      headers: { 'X-API-Key': apiKey }
    });
    
    if (!response.ok) {
      console.error('API key validation failed');
      return false;
    }
    
    const data = await response.json();
    
    // Check key is active
    if (data.status !== 'active') {
      console.error('API key is not active');
      return false;
    }
    
    // Check rate limits
    if (data.rate_limit.remaining < 5) {
      console.warn(`Low rate limit: ${data.rate_limit.remaining} requests remaining`);
    }
    
    return true;
  } catch (error) {
    console.error('Failed to validate API key:', error);
    return false;
  }
}

// Use before trading
if (await validateKeyBeforeTrading(process.env.STRIKE_API_KEY)) {
  // Proceed with trading
  console.log('API key validated, proceeding with trades...');
} else {
  console.error('Cannot trade - API key validation failed');
}

3. Rate Limit Management

class RateLimitManager:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.strike.markets"
    
    def check_rate_limit(self):
        """Check current rate limit status"""
        response = requests.get(
            f"{self.base_url}/api-key/status",
            headers={'X-API-Key': self.api_key}
        )
        
        if response.status_code == 200:
            data = response.json()
            return data['rate_limit']
        return None
    
    def wait_if_needed(self):
        """Wait if rate limit is exhausted"""
        rate_limit = self.check_rate_limit()
        
        if rate_limit and rate_limit['remaining'] == 0:
            reset_time = datetime.fromisoformat(rate_limit['reset_at'].replace('Z', '+00:00'))
            wait_seconds = (reset_time - datetime.now(timezone.utc)).total_seconds()
            
            if wait_seconds > 0:
                print(f"Rate limit reached. Waiting {wait_seconds:.1f} seconds...")
                time.sleep(wait_seconds + 1)  # Add 1 second buffer
                return True
        return False
    
    def safe_request(self, method, endpoint, **kwargs):
        """Make a request with rate limit checking"""
        self.wait_if_needed()
        
        response = requests.request(
            method,
            f"{self.base_url}{endpoint}",
            headers={'X-API-Key': self.api_key, **kwargs.get('headers', {})},
            **{k: v for k, v in kwargs.items() if k != 'headers'}
        )
        
        return response

# Usage
manager = RateLimitManager(os.environ['STRIKE_API_KEY'])

# Safe request that respects rate limits
response = manager.safe_request(
    'POST',
    '/long',
    json={'margin': '100', 'leverage': 10, 'symbol': 'BTC-USD'}
)

4. Key Rotation Reminder

async function checkKeyAge(apiKey) {
  const response = await fetch('https://api.strike.markets/api-key/status', {
    headers: { 'X-API-Key': apiKey }
  });
  
  if (response.ok) {
    const data = await response.json();
    const createdAt = new Date(data.created_at);
    const ageInDays = (Date.now() - createdAt) / (1000 * 60 * 60 * 24);
    
    if (ageInDays > 90) {
      console.warn(`API key is ${ageInDays.toFixed(0)} days old. Consider rotating for security.`);
      return true;
    }
    
    console.log(`API key age: ${ageInDays.toFixed(0)} days`);
    return false;
  }
}

// Check key age periodically
setInterval(async () => {
  if (await checkKeyAge(process.env.STRIKE_API_KEY)) {
    // Send notification to rotate key
  }
}, 24 * 60 * 60 * 1000); // Check daily

Rate Limiting

This endpoint itself has minimal rate limiting:
  • 60 requests per minute per API key
  • Does not count against your trading rate limits

Notes

  • This endpoint is useful for debugging authentication issues
  • The request_count is a lifetime counter for the key
  • The last_used_at field helps identify inactive keys
  • Rate limit information is real-time and updates with each request
  • Use this endpoint to implement smart rate limit management in your applications

Best Practices

  1. Check key validity before starting trading sessions
  2. Monitor rate limits to avoid hitting limits during critical trades
  3. Use the request count to track API usage
  4. Check key age and rotate periodically for security
  5. Validate keys after configuration changes