API Key Guide

Premia V4 API Key Guide

Overview

To interact with the Premia V4 exchange programmatically, you need an API key for authentication. This guide explains how to obtain, configure, and use API keys with the Premia V4 API.

Getting an API Key

Contact Support

Since API key creation is managed externally through Unkey (an enterprise key management service), you'll need to contact the Premia team to obtain your API key:

  1. Email Support: Contact the Premia team through their official channels
  2. Discord: Join the Premia Discord server and reach out to administrators
  3. Website: Visit premia.io for contact information

Information Required

When requesting an API key, provide:

  • Purpose: Describe how you plan to use the API (trading, market making, data analysis, etc.)
  • Expected Volume: Estimated trading volume or request frequency
  • Organization: Company or project name (if applicable)
  • Technical Contact: Email address for technical communications

Using Your API Key

Authentication Method

All API requests require authentication using the x-apikey header:

// TypeScript
const API_KEY = 'your-api-key-here';
const BASE_URL = 'https://staging.kyan.sh';

const response = await fetch(`${BASE_URL}/instruments?market=ETH`, {
  headers: {
    'x-apikey': API_KEY,
    'Content-Type': 'application/json',
  },
});
# Python
import requests

API_KEY = 'your-api-key-here'
BASE_URL = 'https://staging.kyan.sh'

headers = {
    'x-apikey': API_KEY,
    'Content-Type': 'application/json'
}

response = requests.get(f'{BASE_URL}/instruments',
                       params={'market': 'ETH'},
                       headers=headers)

Basic Usage Example

// TypeScript
const API_KEY = 'your-api-key-here';
const BASE_URL = 'https://staging.kyan.sh';

// Fetch instruments
const response = await fetch(`${BASE_URL}/instruments?market=ETH`, {
  headers: {
    'x-apikey': API_KEY,
    'Content-Type': 'application/json',
  },
});

const instruments = await response.json();
console.log(instruments);
# Python
import requests

API_KEY = 'your-api-key-here'
BASE_URL = 'https://staging.kyan.sh'

headers = {
    'x-apikey': API_KEY,
    'Content-Type': 'application/json'
}

# Fetch instruments
response = requests.get(f'{BASE_URL}/instruments',
                       params={'market': 'ETH'},
                       headers=headers)

instruments = response.json()
print(instruments)

API Key Security Best Practices

Environment Variables

Never hardcode API keys in your source code. Use environment variables instead:

const API_KEY = process.env.PREMIA_API_KEY;

if (!API_KEY) {
  throw new Error('PREMIA_API_KEY environment variable is required');
}
# Python
import os

API_KEY = os.environ.get('PREMIA_API_KEY')

if not API_KEY:
    raise ValueError('PREMIA_API_KEY environment variable is required')

Key Rotation

  • Monitor your API key usage through logs
  • Contact support if you suspect your key has been compromised
  • Request new keys periodically for enhanced security

Network Security

  • Always use HTTPS endpoints
  • Implement proper error handling for authentication failures
  • Consider using IP whitelisting if available

WebSocket Authentication

For real-time data via WebSocket connections:

Important: WebSocket client sessions have a maximum duration of 1 hour. For long-running applications, you must implement reconnection logic to maintain persistent data streams.

const ws = new WebSocket('wss://staging.kyan.sh/ws');

ws.onopen = () => {
  // Authenticate with API key using correct message format
  ws.send(
    JSON.stringify({
      type: 'auth',
      api_key: process.env.PREMIA_API_KEY,
    }),
  );
};

ws.onmessage = (event: MessageEvent) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);

  // Handle authentication response
  if (data.type === 'auth' && data.success) {
    console.log('WebSocket authenticated successfully');
    // Proceed with subscriptions
  } else if (data.type === 'auth' && !data.success) {
    console.error('WebSocket authentication failed:', data.error);
  }
};

ws.onclose = (event) => {
  console.log(`WebSocket closed: ${event.code} - ${event.reason}`);
  // Implement reconnection logic here
};
import websocket
import json
import os

def on_open(ws):
    # Authenticate with API key using correct message format
    auth_message = {
        'type': 'auth',
        'api_key': os.environ.get('PREMIA_API_KEY')
    }
    ws.send(json.dumps(auth_message))

def on_message(ws, message):
    data = json.loads(message)
    print('Received:', data)

    # Handle authentication response
    if data.get('type') == 'auth' and data.get('success'):
        print('WebSocket authenticated successfully')
        # Proceed with subscriptions
    elif data.get('type') == 'auth' and not data.get('success'):
        print(f'WebSocket authentication failed: {data.get("error")}')

def on_close(ws, close_status_code, close_msg):
    print(f'WebSocket closed: {close_status_code} - {close_msg}')
    # Implement reconnection logic here

ws = websocket.WebSocketApp('wss://staging.kyan.sh/ws',
                           on_open=on_open,
                           on_message=on_message,
                           on_close=on_close)
ws.run_forever()

One-Click Trading Sessions

For high-frequency trading, you can establish one-click trading sessions to avoid signing each transaction:

Step 1: Create Session

interface SessionPayload {
  signature: string;
  signature_deadline: number;
}

const sessionPayload: SessionPayload = {
  signature: '0x...', // EIP-712 signature
  signature_deadline: Math.floor(Date.now() / 1000) + 300, // 5 minutes
};

const response = await fetch(`${BASE_URL}/session`, {
  method: 'POST',
  headers: {
    'x-apikey': API_KEY,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(sessionPayload),
});

const { sessionHash } = await response.json();
import time
import requests

session_payload = {
    'signature': '0x...',  # EIP-712 signature
    'signature_deadline': int(time.time()) + 300  # 5 minutes
}

response = requests.post(f'{BASE_URL}/session',
                        headers=headers,
                        json=session_payload)

session_data = response.json()
session_hash = session_data['sessionHash']

Step 2: Use Session for Trading

// Place orders without individual signatures
const orderResponse = await fetch(`${BASE_URL}/limit`, {
  method: 'POST',
  headers: {
    'x-apikey': API_KEY,
    'x-one-click': sessionHash,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(orders), // No signature required
});
# Place orders without individual signatures
order_headers = {
    **headers,
    'x-one-click': session_hash
}

order_response = requests.post(f'{BASE_URL}/limit',
                              headers=order_headers,
                              json=orders)  # No signature required

Rate Limiting

Be aware of rate limits:

  • General endpoints: Standard rate limiting applies
  • RFQ endpoints: 6 requests per minute
  • WebSocket connections: Connection limits may apply

Monitor response headers for rate limit information and implement appropriate backoff strategies.

Error Handling

Common Authentication Errors

// Handle authentication errors
const response = await fetch(url, { headers });

if (response.status === 401) {
  console.error('Invalid or expired API key');
  // Handle re-authentication or key refresh
} else if (response.status === 429) {
  console.error('Rate limit exceeded');
  // Implement backoff strategy
} else if (!response.ok) {
  console.error(`API error: ${response.status} ${response.statusText}`);
}
# Handle authentication errors
response = requests.get(url, headers=headers)

if response.status_code == 401:
    print('Invalid or expired API key')
    # Handle re-authentication or key refresh
elif response.status_code == 429:
    print('Rate limit exceeded')
    # Implement backoff strategy
elif not response.ok:
    print(f'API error: {response.status_code} {response.reason}')

Best Practices

  1. Implement retry logic with exponential backoff
  2. Log authentication failures for debugging
  3. Monitor API key usage patterns
  4. Cache valid responses when appropriate to reduce API calls

Testing Your Integration

Sandbox Environment

Use the staging environment for testing:

const BASE_URL = 'https://staging.kyan.sh';
BASE_URL = 'https://staging.kyan.sh'

Local Development

For local development against a development server:

const BASE_URL = 'http://localhost:8000';
# Python
BASE_URL = 'http://localhost:8000'

API Endpoints Summary

With your API key, you can access:

Market Data (GET endpoints)

  • /instruments - Available trading instruments
  • /order_book - Order book data
  • /options_chain - Options chain data
  • /last_trades - Recent trade history
  • /expirations - Available expiration dates

Trading (POST endpoints)

  • /limit - Place limit orders
  • /market - Place market orders
  • /combo - Place combo orders
  • /rfq/* - Request for Quote endpoints

Account Management

  • /orders - Manage your orders
  • /account_state/{account} - Account information
  • /deposit - Deposit funds
  • /withdraw - Withdraw funds

Risk Assessment

  • /calculate_user_risk - Portfolio risk metrics

Support

If you encounter issues with your API key:

  1. Check your key format - Ensure no extra spaces or characters
  2. Verify headers - Use x-apikey (case-sensitive)
  3. Test connectivity - Try a simple GET request first
  4. Contact support - Provide request examples and error messages

Next Steps

  1. Get your API key from the Premia team
  2. Test authentication with a simple market data request
  3. Implement error handling and rate limiting
  4. Set up monitoring for your API usage
  5. Review the full API documentation for available endpoints