Skip to main content

Usage Examples

note

Important: The Live Feed WebSocket endpoint is designed for backend-to-backend communication only. Frontend clients should not connect directly to this endpoint. Instead, implement a backend service that consumes the WebSocket feed and exposes data to frontend clients through appropriate REST endpoints or other secure mechanisms.

tip

The examples below connect to the L2 endpoint. To consume L1+ instead, set WEBSOCKET_URL to wss://csapis.com/2.0/market/feed/full/plus. L1+ only sends tick and tob messages, so the tor and tex handlers will not be called.

Backend Server Implementation (Node.js)​

import WebSocket from 'ws';
import express from 'express';

const app = express();
const BEARER_TOKEN = 'YOUR_BEARER_TOKEN';
const WEBSOCKET_URL = 'wss://csapis.com/2.0/market/feed/l2';

// Store for active WebSocket connection
let liveWebSocket = null;

// Function to establish WebSocket connection
function connectToLiveFeed() {
const headers = {
Authorization: `Bearer ${BEARER_TOKEN}`
};

liveWebSocket = new WebSocket(WEBSOCKET_URL, { headers });

liveWebSocket.on('open', () => {
console.log('Connected to Capital Stake Live Feed');
});

liveWebSocket.on('message', (data) => {
try {
const message = JSON.parse(data);

switch(message.type) {
case 'tick':
handleSnapshotTick(message.data);
break;
case 'tob':
handleOrderBookTick(message.data);
break;
case 'tor':
handleOrderTick(message.data);
break;
case 'tex':
handleExecutionTick(message.data);
break;
}
} catch (error) {
console.error('Error parsing message:', error);
}
});

liveWebSocket.on('error', (error) => {
console.error('WebSocket error:', error);
});

liveWebSocket.on('close', () => {
console.log('Connection closed, attempting reconnect...');
setTimeout(connectToLiveFeed, 5000); // Reconnect after 5 seconds
});
}

// Message handlers
function handleSnapshotTick(data) {
console.log(`[TICK] ${data.s}: Close=${data.c}, Volume=${data.v}`);
// Process and distribute to clients
}

function handleOrderBookTick(data) {
console.log(`[TOB] ${data.s}: Buy=${data.bs?.x}, Sell=${data.ss?.x}`);
// Process and distribute to clients
}

function handleOrderTick(data) {
console.log(`[ORDER] ${data.s}: Price=${data.x}, Qty=${data.v}, Side=${data.sd}`);
// Process and distribute to clients
}

function handleExecutionTick(data) {
console.log(`[EXECUTION] ${data.s}: Price=${data.x}, Qty=${data.v}`);
// Process and distribute to clients
}

// REST endpoint for frontend clients to consume market data
app.get('/api/market/data/:symbol', (req, res) => {
const { symbol } = req.params;
// Return cached/processed data from WebSocket feed
res.json({ symbol, data: 'market data from live feed' });
});

// Initialize connection on server start
connectToLiveFeed();

app.listen(3000, () => {
console.log('Backend server running on port 3000');
});

Backend Server Implementation (Python)​

import asyncio
import json
import websockets
from flask import Flask, jsonify

app = Flask(__name__)
BEARER_TOKEN = 'YOUR_BEARER_TOKEN'
WEBSOCKET_URL = 'wss://csapis.com/2.0/market/feed/l2'

# Store for market data cache
market_data_cache = {}

async def connect_to_live_feed():
"""Connect to Capital Stake Live Feed WebSocket"""
headers = {
'Authorization': f'Bearer {BEARER_TOKEN}'
}

while True:
try:
async with websockets.connect(WEBSOCKET_URL, extra_headers=headers) as websocket:
print('Connected to Capital Stake Live Feed')

async for message in websocket:
try:
data = json.loads(message)
await handle_message(data)
except json.JSONDecodeError:
print('Error parsing message')

except Exception as error:
print(f'WebSocket error: {error}')
print('Attempting reconnect in 5 seconds...')
await asyncio.sleep(5)

async def handle_message(message):
"""Process incoming WebSocket messages"""
msg_type = message.get('type')
data = message.get('data', {})

if msg_type == 'tick':
symbol = data.get('s')
market_data_cache[symbol] = data
print(f"[TICK] {symbol}: Close={data.get('c')}, Volume={data.get('v')}")

elif msg_type == 'tob':
symbol = data.get('s')
market_data_cache[f'{symbol}_tob'] = data
print(f"[TOB] {symbol}: Buy={data.get('bs', {}).get('x')}, Sell={data.get('ss', {}).get('x')}")

elif msg_type == 'tor':
print(f"[ORDER] {data.get('s')}: Price={data.get('x')}, Qty={data.get('v')}")

elif msg_type == 'tex':
print(f"[EXECUTION] {data.get('s')}: Price={data.get('x')}, Qty={data.get('v')}")

# REST endpoint for frontend clients
@app.route('/api/market/data/<symbol>', methods=['GET'])
def get_market_data(symbol):
"""Return cached market data from live feed"""
if symbol in market_data_cache:
return jsonify(market_data_cache[symbol])
return jsonify({'error': 'Symbol not found'}), 404

# Start WebSocket connection in background
@app.before_first_request
def startup():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.create_task(connect_to_live_feed())

if __name__ == '__main__':
app.run(port=3000, debug=False)

Error Responses​

Authentication Failed (4001)​

{
"type": "error",
"code": 4001,
"message": "Authentication failed"
}

Invalid Token (4002)​

{
"type": "error",
"code": 4002,
"message": "Invalid authentication token"
}

Connection Limit Exceeded (4003)​

{
"type": "error",
"code": 4003,
"message": "Connection limit exceeded"
}

Server Error (5000)​

{
"type": "error",
"code": 5000,
"message": "Internal server error"
}