> ## Documentation Index
> Fetch the complete documentation index at: https://docs.strike.markets/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> How to authenticate with Strike Protocol API using API keys

## Overview

Strike Protocol uses **API key authentication** for accessing protected endpoints. This system supports two authentication methods to accommodate different use cases:

1. **Personal API Keys** - For individual traders and bot developers
2. **Service API Keys** - For frontend applications (with wallet address)

## Authentication Methods

### Method 1: Personal API Keys

Personal API keys are the recommended method for individual traders and automated trading systems. Each wallet can have one active API key at a time.

**Format**: `stk_` followed by a secure random string

**Headers Required**:

```bash theme={null}
X-API-Key: stk_your_personal_api_key_here
```

### Method 2: Service API Keys

Service keys are used by the Strike Protocol frontend and other authorized applications. They require an additional wallet address header.

**Headers Required**:

```bash theme={null}
X-API-Key: your_service_key_here
X-Wallet-Address: 0x742d35cc6c6c7532b1140da4c8a2f6c8ecfc9b46
```

## Getting Your API Key

### Step 1: Access the Strike Protocol Interface

1. Visit [strike.markets](https://strike.markets)
2. Connect your Ethereum wallet (MetaMask, WalletConnect, etc.)
3. Navigate to your account settings

### Step 2: Generate Your API Key

1. Click on your wallet address in the top navigation
2. Select the "API Keys" tab
3. Click "Generate API Key"
4. **Save the key immediately** - it will only be shown once

### Step 3: Secure Storage

<Warning>
  **Critical**: API keys are shown only once during generation. Store them securely:

  * Use environment variables in production
  * Never commit keys to version control
  * Consider using key management services for enterprise applications
</Warning>

## Authentication Examples

### Personal API Key Authentication

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.strike.markets/long" \
    -H "X-API-Key: stk_abc123def456ghi789jkl012mno345pqr678stu901vwx234yz" \
    -H "Content-Type: application/json" \
    -d '{
      "margin": "100.0",
      "leverage": 10,
      "symbol": "BTC-USD"
    }'
  ```

  ```python Python theme={null}
  import requests
  import os

  API_KEY = os.getenv('STRIKE_API_KEY')
  BASE_URL = 'https://api.strike.markets'

  headers = {
      'X-API-Key': API_KEY,
      'Content-Type': 'application/json'
  }

  def create_long_position(margin: str, leverage: int, symbol: str):
      response = requests.post(
          f"{BASE_URL}/long",
          headers=headers,
          json={
              "margin": margin,
              "leverage": leverage,
              "symbol": symbol
          }
      )
      
      if response.status_code == 401:
          raise Exception("Authentication failed - check your API key")
      
      response.raise_for_status()
      return response.json()

  # Create a long position
  position = create_long_position("100.0", 10, "BTC-USD")
  print(f"Position created: {position['positionId']}")
  ```

  ```javascript JavaScript/Node.js theme={null}
  const API_KEY = process.env.STRIKE_API_KEY;
  const BASE_URL = 'https://api.strike.markets';

  async function createLongPosition(margin, leverage, symbol) {
    const response = await fetch(`${BASE_URL}/long`, {
      method: 'POST',
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        margin: margin.toString(),
        leverage: leverage,
        symbol: symbol
      })
    });
    
    if (!response.ok) {
      if (response.status === 401) {
        throw new Error('Authentication failed - check your API key');
      }
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }
    
    return response.json();
  }

  // Usage
  try {
    const position = await createLongPosition(100, 10, 'BTC-USD');
    console.log('Position created:', position.positionId);
  } catch (error) {
    console.error('Error:', error.message);
  }
  ```
</CodeGroup>

### Service Key Authentication (Frontend Applications)

```bash theme={null}
curl -X POST "https://api.strike.markets/long" \
  -H "X-API-Key: your_service_key_here" \
  -H "X-Wallet-Address: 0x742d35cc6c6c7532b1140da4c8a2f6c8ecfc9b46" \
  -H "Content-Type: application/json" \
  -d '{
    "margin": "100.0",
    "leverage": 10,
    "symbol": "BTC-USD"
  }'
```

## Authenticated Endpoints

### Trading Operations

All trading operations require authentication:

* `POST /long` - Create long position
* `POST /short` - Create short position
* `POST /close` - Close position
* `POST /emergency-exit` - Emergency exit position

### Account Management

* `POST /deposit` - Record deposit transaction
* `POST /withdraw` - Record withdrawal transaction

### API Key Management

* `POST /api-key/generate` - Generate new API key
* `GET /api-key/status` - Check API key status
* `DELETE /api-key/revoke` - Revoke API key

## Public Endpoints

These endpoints do **not** require authentication:

### Market Data

* `GET /markets` - Get available markets
* `GET /market/{symbol}` - Get market details

### Data and Analytics

* `GET /positions/{wallet}` - Get positions for wallet
* `GET /positions/{wallet}/queue-positions` - Get queue positions
* `GET /balances/{wallet}` - Get account balances
* `GET /analytics` - Get protocol analytics

## API Key Management

### Testing Your API Key

Before making trading requests, test your API key:

```bash theme={null}
curl -X GET "https://api.strike.markets/api-key/status" \
  -H "X-API-Key: stk_your_api_key_here"
```

**Expected Response:**

```json theme={null}
{
  "has_api_key": true,
  "last_updated": "2024-01-15T14:30:00Z"
}
```

### Key Rotation

For security, regularly rotate your API keys:

1. **Revoke** your current key: `DELETE /api-key/revoke`
2. **Generate** a new key: `POST /api-key/generate`
3. **Update** your applications with the new key

## Rate Limiting

API endpoints have different rate limits based on endpoint type:

### Trading Endpoints

* **Limit**: 10 requests per minute per wallet
* **Applies to**: `/long`, `/short`, `/close`, `/emergency-exit`

### General Endpoints

* **Limit**: 60 requests per minute per IP address
* **Applies to**: All other authenticated endpoints

### Rate Limit Headers

All responses include rate limit information:

```bash theme={null}
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 8
X-RateLimit-Reset: 1640995200
```

### Service Key Bypass

Service API keys bypass rate limiting for frontend applications.

## Error Handling

### Authentication Errors

#### Missing API Key

```json theme={null}
{
  "error": "AUTHENTICATION_REQUIRED",
  "message": "No API key provided"
}
```

#### Invalid API Key

```json theme={null}
{
  "error": "INVALID_API_KEY", 
  "message": "Invalid or revoked API key"
}
```

#### Service Key Missing Wallet

```json theme={null}
{
  "error": "WALLET_ADDRESS_REQUIRED",
  "message": "Service key requires wallet address"
}
```

### Rate Limit Errors

```json theme={null}
{
  "error": "RATE_LIMIT_EXCEEDED",
  "message": "Rate limit exceeded. Please wait 45 seconds.",
  "retry_after": 45
}
```

## Security Best Practices

### API Key Security

1. **Never expose keys in client-side code**
2. **Use environment variables** for key storage
3. **Rotate keys regularly** (every 90 days recommended)
4. **Revoke compromised keys immediately**
5. **Use HTTPS only** for all API requests

### Production Considerations

```python theme={null}
# Good: Use environment variables
import os
API_KEY = os.getenv('STRIKE_API_KEY')

# Bad: Hard-coded keys
API_KEY = "stk_abc123..."  # Never do this!
```

### Key Monitoring

Implement monitoring to detect:

* Unusual API usage patterns
* Failed authentication attempts
* Rate limit violations
* Key age and rotation needs

## Troubleshooting

### Common Issues

1. **"No API key provided"**
   * Ensure the `X-API-Key` header is included
   * Check header name spelling and casing

2. **"Invalid or revoked API key"**
   * Verify your key was copied correctly (no extra spaces)
   * Check if the key has been revoked
   * Generate a new key if needed

3. **"Service key requires wallet address"**
   * Add the `X-Wallet-Address` header when using service keys
   * Ensure the wallet address format is correct (0x prefix)

4. **Rate limit exceeded**
   * Wait for the rate limit window to reset
   * Implement proper request spacing in your application
   * Check the `X-RateLimit-Reset` header for reset time

## Migration from Legacy Systems

If you're migrating from an older authentication system:

1. **Generate a new API key** through the web interface
2. **Update your application code** to use `X-API-Key` header instead of `Authorization: Bearer`
3. **Test thoroughly** with the new authentication method
4. **Remove old authentication code** once migration is complete

For additional support, refer to the [API Key Management](/api-reference/api-keys/generate) documentation or contact the Strike Protocol team.
