Kana Perps Python Websocket API

Supported Markets

Asset

Market ID

Description

APT/USDC

396

Aptos-based trading market.

BTC/USDC

397

Bitcoin-based trading market.

ETH/USDC

398

Ethereum-based trading market.

WebSocket Client Documentation

Installation:

  1. Install Dependencies: You will need the websocket-client library. Install it using pip:

pip install websocket-client

1. WebSocket Client for Subscribing to Position Updates

WebSocket URL:

wss://perpetuals-indexer-ws.kanalabs.io/ws

Example Request:

When you connect to the WebSocket server, the client will send a subscription message like this:

{
  "topic": "positions",
  "address": "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770"
}
  • topic: The topic to subscribe to, which is positions in this case.

  • address: The address to track for position updates.

Example Response:

After subscribing, you will receive position updates as a response from the server. The response might look like this:

[client] Connected to the server
[client] Sent subscription request: {"topic": "positions", "address": "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770"}
[client] Received message: {"data":[{"address":"0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770","entry_price":"6050","is_long":false,"last_updated":"1739788459","leverage":2,"liq_price":"8853.658536585366","margin":"3025000","market_id":"396","size":"1000","sl":null,"tp":null,"trade_id":"16509835945970048696716","value":"6050000"}],"message":"positions"}

Example Code to Connect to the WebSocket and Subscribe:

Here’s a Python script that demonstrates how to connect to the WebSocket server and subscribe to position updates for a specific address.

import websocket
import json
import time
import threading

# WebSocket server URL
WS_URL = 'wss://perpetuals-indexer-ws.kanalabs.io/ws'

# Address to subscribe to
address = 'your_address'

# Global WebSocket variable
ws = None

# WebSocket event handlers
def on_open(ws):
    print('[client] Connected to the server')
    
    # Send subscription message to the WebSocket server
    subscription_message = json.dumps({
        'topic': 'positions',
        'address': address,
    })
    ws.send(subscription_message)
    print(f'[client] Sent subscription request: {subscription_message}')

    # Start ping thread to keep the connection alive
    start_ping_thread(ws)

def ping(ws):
    while ws.sock and ws.sock.connected:
        time.sleep(20)  # Send ping every 20 seconds
        try:
            ws.sock.ping()
            print('[client] Sent ping to keep connection alive')
        except Exception as e:
            print(f'[client] Error sending ping: {e}')
            break

def start_ping_thread(ws):
    ping_thread = threading.Thread(target=ping, args=(ws,))
    ping_thread.daemon = True
    ping_thread.start()

def on_message(ws, message):
    print(f'[client] Received message: {message}')

def on_pong(ws, message):
    print('[client] Received pong response')

def on_close(ws, close_status_code, close_msg):
    print('[client] Disconnected from the server')
    reconnect_websocket()

def on_error(ws, error):
    print(f'[client] WebSocket error: {error}')
    ws.close()

# WebSocket connection setup
def connect_websocket():
    global ws
    ws = websocket.WebSocketApp(WS_URL,
                                on_open=on_open,
                                on_message=on_message,
                                on_pong=on_pong,
                                on_close=on_close,
                                on_error=on_error)

    # Run the WebSocket connection
    ws.run_forever()

# Reconnect logic
def reconnect_websocket():
    print('[client] Attempting to reconnect...')
    time.sleep(5)
    connect_websocket()

# Start WebSocket connection
if __name__ == "__main__":
    connect_websocket()

2. WebSocket Client for Subscribing to Order Fills Updates

WebSocket URL:

wss://perpetuals-indexer-ws.kanalabs.io/ws

Example Request:

When you connect to the WebSocket server, the client will send a subscription message like this:

{
  "topic": "trade_history",
  "address": "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770"
}
  • topic: The topic to subscribe to, which is trade_history in this case.

  • address: The address to track for order fills updates.

Example Response:

After subscribing, you will receive order fills updates as a response from the server. The response might look like this:

[client] Connected to the server
[client] Sent subscription request: {"topic": "trade_history", "address": "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770"}
[client] Received message: {"data":[{"address":"0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770","fee":"3025","last_updated":"1739788459","market_id":"396","order_type":2,"pnl":"0","price":"6050","size":"1000","timestamp":"1739788459","trade_id":"16509835945970048696716"},"message":"trade_history"}

Example Code to Connect to the WebSocket and Subscribe:

Here’s a Python script that demonstrates how to connect to the WebSocket server and subscribe to order fills updates for a specific address.

import websocket
import json
import time
import threading

# WebSocket server URL
WS_URL = 'wss://perpetuals-indexer-ws.kanalabs.io/ws'

# Address to subscribe to
address = 'your_address'

# Global WebSocket variable
ws = None

# WebSocket event handlers
def on_open(ws):
    print('[client] Connected to the server')
    
    # Send subscription message to the WebSocket server
    subscription_message = json.dumps({
        'topic': 'trade_history',
        'address': address,
    })
    ws.send(subscription_message)
    print(f'[client] Sent subscription request: {subscription_message}')

    # Start ping thread to keep the connection alive
    start_ping_thread(ws)

def ping(ws):
    while ws.sock and ws.sock.connected:
        time.sleep(20)  # Send ping every 20 seconds
        try:
            ws.sock.ping()
            print('[client] Sent ping to keep connection alive')
        except Exception as e:
            print(f'[client] Error sending ping: {e}')
            break

def start_ping_thread(ws):
    ping_thread = threading.Thread(target=ping, args=(ws,))
    ping_thread.daemon = True
    ping_thread.start()

def on_message(ws, message):
    print(f'[client] Received message: {message}')

def on_pong(ws, message):
    print('[client] Received pong response')

def on_close(ws, close_status_code, close_msg):
    print('[client] Disconnected from the server')
    reconnect_websocket()

def on_error(ws, error):
    print(f'[client] WebSocket error: {error}')
    ws.close()

# WebSocket connection setup
def connect_websocket():
    global ws
    ws = websocket.WebSocketApp(WS_URL,
                                on_open=on_open,
                                on_message=on_message,
                                on_pong=on_pong,
                                on_close=on_close,
                                on_error=on_error)

    # Run the WebSocket connection
    ws.run_forever()

# Reconnect logic
def reconnect_websocket():
    print('[client] Attempting to reconnect...')
    time.sleep(5)
    connect_websocket()

# Start WebSocket connection
if __name__ == "__main__":
    connect_websocket()

3. WebSocket Client for Subscribing to Open Orders Updates

WebSocket URL:

wss://perpetuals-indexer-ws.kanalabs.io/ws

Example Request:

When you connect to the WebSocket server, the client will send a subscription message like this:

{
  "topic": "open_orders",
  "address": "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770"
}
  • topic: The topic to subscribe to, which is open_orders in this case.

  • address: The address to track for open orders updates.

Example Response:

After subscribing, you will receive open orders updates as a response from the server. The response might look like this:

[client] Connected to the server
[client] Sent subscription request: {"topic": "open_orders", "address": "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770"}
[client] Received message: {"data":[],"message":"open_orders"}
[client] Received message: {"data":[{"address":"0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770","last_updated":"1739790733","leverage":2,"market_id":"396","order_id":"12907057702855018828273522","order_type":1,"order_value":"6002000","price":"6002","remaining_size":"1000","timestamp":"1739790733","total_size":"1000","trade_id":"16528282690043758248332"}],"message":"open_orders"}

Example Code to Connect to the WebSocket and Subscribe:

Here’s a Python script that demonstrates how to connect to the WebSocket server and subscribe to open orders updates for a specific address.

import websocket
import json
import time
import threading

# WebSocket server URL
WS_URL = 'wss://perpetuals-indexer-ws.kanalabs.io/ws'

# Address to subscribe to
address = 'your_address'

# Global WebSocket variable
ws = None

# WebSocket event handlers
def on_open(ws):
    print('[client] Connected to the server')
    
    # Send subscription message to the WebSocket server
    subscription_message = json.dumps({
        'topic': 'open_orders',
        'address': address,
    })
    ws.send(subscription_message)
    print(f'[client] Sent subscription request: {subscription_message}')

    # Start ping thread to keep the connection alive
    start_ping_thread(ws)

def ping(ws):
    while ws.sock and ws.sock.connected:
        time.sleep(20)  # Send ping every 20 seconds
        try:
            ws.sock.ping()
            print('[client] Sent ping to keep connection alive')
        except Exception as e:
            print(f'[client] Error sending ping: {e}')
            break

def start_ping_thread(ws):
    ping_thread = threading.Thread(target=ping, args=(ws,))
    ping_thread.daemon = True
    ping_thread.start()

def on_message(ws, message):
    print(f'[client] Received message: {message}')

def on_pong(ws, message):
    print('[client] Received pong response')

def on_close(ws, close_status_code, close_msg):
    print('[client] Disconnected from the server')
    reconnect_websocket()

def on_error(ws, error):
    print(f'[client] WebSocket error: {error}')
    ws.close()

# WebSocket connection setup
def connect_websocket():
    global ws
    ws = websocket.WebSocketApp(WS_URL,
                                on_open=on_open,
                                on_message=on_message,
                                on_pong=on_pong,
                                on_close=on_close,
                                on_error=on_error)

    # Run the WebSocket connection
    ws.run_forever()

# Reconnect logic
def reconnect_websocket():
    print('[client] Attempting to reconnect...')
    time.sleep(5)
    connect_websocket()

# Start WebSocket connection
if __name__ == "__main__":
    connect_websocket()

4. WebSocket Client for Subscribing to Order history Updates

WebSocket URL:

wss://perpetuals-indexer-ws.kanalabs.io/ws

Example Request:

When you connect to the WebSocket server, the client will send a subscription message like this:

{
  "topic": "order_history",
  "address": "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770"
}
  • topic: The topic to subscribe to, which is order_history in this case.

  • address: The address to track for order history updates.

Example Response:

After subscribing, you will receive order history updates as a response from the server. The response might look like this:

[client] Connected to the server
[client] Sent subscription request: {"topic": "order_history", "address": "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770"}
[client] Received message: {"data":[{"address":"0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770","is_market_order":false,"last_updated":"1739790733","leverage":2,"market_id":"396","order_id":"12907057702855018828273522","order_type":1,"order_value":"6002000","price":"6002","size":"1000","status":"Open","timestamp":"1739790733","trade_id":"16528282690043758248332"},{"address":"0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770","is_market_order":false,"last_updated":"1739790700","leverage":2,"market_id":"396","order_id":"12906965467445688751095808","order_type":4,"order_value":"6002000","price":"6002","size":"1000","status":"Filled","timestamp":"1739790700","trade_id":"16509835945970048696716"}],"message":"order_history"}

Example Code to Connect to the WebSocket and Subscribe:

Here’s a Python script that demonstrates how to connect to the WebSocket server and subscribe to order history updates for a specific address.

import websocket
import json
import time
import threading

# WebSocket server URL
WS_URL = 'wss://perpetuals-indexer-ws.kanalabs.io/ws'

# Address to subscribe to
address = 'your_address'

# Global WebSocket variable
ws = None

# WebSocket event handlers
def on_open(ws):
    print('[client] Connected to the server')
    
    # Send subscription message to the WebSocket server
    subscription_message = json.dumps({
        'topic': 'order_history',
        'address': address,
    })
    ws.send(subscription_message)
    print(f'[client] Sent subscription request: {subscription_message}')

    # Start ping thread to keep the connection alive
    start_ping_thread(ws)

def ping(ws):
    while ws.sock and ws.sock.connected:
        time.sleep(20)  # Send ping every 20 seconds
        try:
            ws.sock.ping()
            print('[client] Sent ping to keep connection alive')
        except Exception as e:
            print(f'[client] Error sending ping: {e}')
            break

def start_ping_thread(ws):
    ping_thread = threading.Thread(target=ping, args=(ws,))
    ping_thread.daemon = True
    ping_thread.start()

def on_message(ws, message):
    print(f'[client] Received message: {message}')

def on_pong(ws, message):
    print('[client] Received pong response')

def on_close(ws, close_status_code, close_msg):
    print('[client] Disconnected from the server')
    reconnect_websocket()

def on_error(ws, error):
    print(f'[client] WebSocket error: {error}')
    ws.close()

# WebSocket connection setup
def connect_websocket():
    global ws
    ws = websocket.WebSocketApp(WS_URL,
                                on_open=on_open,
                                on_message=on_message,
                                on_pong=on_pong,
                                on_close=on_close,
                                on_error=on_error)

    # Run the WebSocket connection
    ws.run_forever()

# Reconnect logic
def reconnect_websocket():
    print('[client] Attempting to reconnect...')
    time.sleep(5)
    connect_websocket()

# Start WebSocket connection
if __name__ == "__main__":
    connect_websocket()

5. WebSocket Client for Subscribing to Order Book Updates

WebSocket URL:

wss://perpetuals-indexer-ws.kanalabs.io/ws

Example Request:

When you connect to the WebSocket server, the client will send a subscription message like this:

{
  "topic": "orderbook",
  "address": "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770"
}
  • topic: The topic to subscribe to, which is orderbook in this case.

  • address: The address to track for order book updates.

Example Response:

After subscribing, you will receive order book updates as a response from the server. The response might look like this:

[client] Connected to the server
[client] Sent subscription request: {"topic": "orderbook", "market_id": "396"}
[client] Received message: {"data":[{"is_ask":true,"last_updated":"1739790988","market_id":"396","price":"6036","size":"169320"},{"is_ask":true,"last_updated":"1739790988","market_id":"396","price":"6037","size":"253735"},{"is_ask":true,"last_updated":"1739790988","market_id":"396","price":"6040","size":"230485"},{"is_ask":true,"last_updated":"1739790996","market_id":"396","price":"6044","size":"255685"},{"is_ask":true,"last_updated":"1739790996","market_id":"396","price":"6051","size":"264082"},{"is_ask":true,"last_updated":"1739790990","market_id":"396","price":"6053","size":"235088"},{"is_ask":true,"last_updated":"1739790996","market_id":"396","price":"6057","size":"230868"},{"is_ask":true,"last_updated":"1739790990","market_id":"396","price":"6059","size":"487477"},{"is_ask":true,"last_updated":"1739758360","market_id":"396","price":"8000","size":"500"},{"is_ask":false,"last_updated":"1739790988","market_id":"396","price":"6031","size":"174998"},{"is_ask":false,"last_updated":"1739790988","market_id":"396","price":"6027","size":"225183"},{"is_ask":false,"last_updated":"1739790988","market_id":"396","price":"6024","size":"244770"},{"is_ask":false,"last_updated":"1739790996","market_id":"396","price":"6019","size":"238312"},{"is_ask":false,"last_updated":"1739790987","market_id":"396","price":"6018","size":"260393"},{"is_ask":false,"last_updated":"1739790996","market_id":"396","price":"6014","size":"267821"},{"is_ask":false,"last_updated":"1739790996","market_id":"396","price":"6011","size":"234869"},{"is_ask":false,"last_updated":"1739790990","market_id":"396","price":"6006","size":"447877"},{"is_ask":false,"last_updated":"1739790990","market_id":"396","price":"6002","size":"1000"},{"is_ask":false,"last_updated":"1739779575","market_id":"396","price":"5800","size":"103303"}],"message":"orderbook"}

Example Code to Connect to the WebSocket and Subscribe:

Here’s a Python script that demonstrates how to connect to the WebSocket server and subscribe to order book updates for a specific address.

import websocket
import json
import time
import threading

# WebSocket server URL
WS_URL = 'wss://perpetuals-indexer-ws.kanalabs.io/ws'

# Address to subscribe to
market_id= 'your_market_id'

# Global WebSocket variable
ws = None

# WebSocket event handlers
def on_open(ws):
    print('[client] Connected to the server')
    
    # Send subscription message to the WebSocket server
    subscription_message = json.dumps({
        'topic': 'orderbook',
        'market_id': market_id,
    })
    ws.send(subscription_message)
    print(f'[client] Sent subscription request: {subscription_message}')

    # Start ping thread to keep the connection alive
    start_ping_thread(ws)

def ping(ws):
    while ws.sock and ws.sock.connected:
        time.sleep(20)  # Send ping every 20 seconds
        try:
            ws.sock.ping()
            print('[client] Sent ping to keep connection alive')
        except Exception as e:
            print(f'[client] Error sending ping: {e}')
            break

def start_ping_thread(ws):
    ping_thread = threading.Thread(target=ping, args=(ws,))
    ping_thread.daemon = True
    ping_thread.start()

def on_message(ws, message):
    print(f'[client] Received message: {message}')

def on_pong(ws, message):
    print('[client] Received pong response')

def on_close(ws, close_status_code, close_msg):
    print('[client] Disconnected from the server')
    reconnect_websocket()

def on_error(ws, error):
    print(f'[client] WebSocket error: {error}')
    ws.close()

# WebSocket connection setup
def connect_websocket():
    global ws
    ws = websocket.WebSocketApp(WS_URL,
                                on_open=on_open,
                                on_message=on_message,
                                on_pong=on_pong,
                                on_close=on_close,
                                on_error=on_error)

    # Run the WebSocket connection
    ws.run_forever()

# Reconnect logic
def reconnect_websocket():
    print('[client] Attempting to reconnect...')
    time.sleep(5)
    connect_websocket()    

# Start WebSocket connection
if __name__ == "__main__":
    connect_websocket()

Last updated