For DevelopersAPISDKs (TypeScript, Python, Rust)

SDKs

GX Exchange provides official SDK libraries for TypeScript, Python, and Rust. These SDKs handle EIP-712 signing, connection management, and type-safe request/response handling.

TypeScript SDK

Installation

npm install @gx-exchange/sdk

Quick Start

import { GxClient } from "@gx-exchange/sdk";
 
async function main() {
  const client = new GxClient();
  await client.connect("https://api.gx.exchange");
 
  // --- Public Data ---
  const markets = await client.getMarkets();
  console.log(`${markets.length} markets available`);
 
  const mids = await client.getAllMids();
  console.log("BTC mid:", mids["BTC"]);
 
  const book = await client.getL2Book("BTC");
  console.log("Best bid:", book.levels[0][0].px);
 
  const account = await client.getAccount("0xYourAddress...");
  console.log("Account value:", account.marginSummary.accountValue);
 
  // --- Authenticated Trading ---
  client.setWallet("0xYourPrivateKey...");
 
  const result = await client.placeOrder([{
    coin: "BTC",
    isBuy: true,
    sz: 0.001,
    limitPx: 60000,
    tif: "Gtc",
    reduceOnly: false,
  }]);
  console.log("Order result:", result);
 
  // Cancel
  const oid = result.response.data.statuses[0].resting.oid;
  await client.cancel([{ coin: "BTC", oid }]);
 
  // --- WebSocket ---
  const unsub = client.subscribe(
    { type: "trades", coin: "BTC" },
    (msg) => console.log("Trade:", msg.data)
  );
 
  // Cleanup
  // unsub();
}
 
main().catch(console.error);

Key Classes

ClassDescription
GxClientMain client for REST and WebSocket operations
InfoClientRead-only info queries
ExchangeClientAuthenticated exchange actions
WebSocketManagerLow-level WebSocket connection management

Configuration

const client = new GxClient({
  baseUrl: "https://api.gx.exchange",      // REST base URL
  wsUrl: "wss://api.gx.exchange/ws",       // WebSocket URL
  timeout: 10000,                           // Request timeout (ms)
  maxRetries: 3,                            // Auto-retry on 5xx
});

Python SDK

Installation

pip install gx-exchange-python-sdk

Quick Start

from gx_exchange.info import Info
from gx_exchange.exchange import Exchange
from gx_exchange.utils.constants import MAINNET_API_URL
import eth_account
 
# --- Public Data ---
info = Info(MAINNET_API_URL, skip_ws=True)
 
mids = info.all_mids()
print(f"BTC mid: {mids.get('BTC')}")
 
book = info.l2_snapshot("BTC")
print(f"Best bid: {book['levels'][0][0]['px']}")
 
state = info.user_state("0xYourAddress...")
print(f"Account value: {state['marginSummary']['accountValue']}")
 
# --- Authenticated Trading ---
account = eth_account.Account.from_key("0xYourPrivateKey...")
exchange = Exchange(account, MAINNET_API_URL)
 
# Place a limit buy
result = exchange.order("BTC", is_buy=True, sz=0.001, limit_px=60000,
                        order_type={"limit": {"tif": "Gtc"}})
print(f"Order status: {result['status']}")
 
# Cancel
oid = result["response"]["data"]["statuses"][0]["resting"]["oid"]
cancel_result = exchange.cancel("BTC", oid=oid)
print(f"Cancel: {cancel_result['status']}")
 
# --- WebSocket ---
info_ws = Info(MAINNET_API_URL)
info_ws.subscribe(
    {"type": "trades", "coin": "BTC"},
    lambda msg: print(f"Trade: {msg}")
)

Key Classes

ClassDescription
InfoPublic data queries and WebSocket subscriptions
ExchangeAuthenticated trading operations

Agent Wallet Usage

# Authorize an agent (one-time setup with main wallet)
main_account = eth_account.Account.from_key("0xMainPrivateKey...")
main_exchange = Exchange(main_account, MAINNET_API_URL)
main_exchange.approve_agent(agent_address="0xAgentAddress...",
                             agent_name="Bot")
 
# Trade using the agent
agent_account = eth_account.Account.from_key("0xAgentPrivateKey...")
agent_exchange = Exchange(agent_account, MAINNET_API_URL,
                          vault_address="0xMainAddress...")
agent_exchange.order("BTC", is_buy=True, sz=0.001, limit_px=60000,
                     order_type={"limit": {"tif": "Gtc"}})

Rust SDK

Installation

# Cargo.toml
[dependencies]
gx_rust_sdk = "0.1"
tokio = { version = "1", features = ["full"] }

Or via the command line:

cargo add gx_rust_sdk

Quick Start

use gx_rust_sdk::{BaseUrl, ExchangeClient, InfoClient};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // --- Public Data ---
    let info = InfoClient::new(None, Some(BaseUrl::Mainnet)).await?;
 
    let meta = info.meta().await?;
    println!("{} perpetual markets", meta.universe.len());
 
    let mids = info.all_mids().await?;
    println!("BTC mid: {:?}", mids.get("BTC"));
 
    let book = info.l2_snapshot("BTC").await?;
    println!("Book levels: {:?}", book.levels.len());
 
    // --- Authenticated Trading ---
    let wallet = "0xYourPrivateKey...".parse()?;
    let exchange = ExchangeClient::new(
        None, wallet, Some(BaseUrl::Mainnet)
    ).await?;
 
    let result = exchange.order(
        "BTC",    // coin
        true,     // is_buy
        0.001,    // size
        60000.0,  // limit_px
        None,     // client_oid
        None,     // vault_address
    ).await?;
    println!("Order: {:?}", result);
 
    let cancel = exchange.cancel("BTC", 12345).await?;
    println!("Cancel: {:?}", cancel);
 
    Ok(())
}

Key Types

TypeDescription
InfoClientPublic data queries
ExchangeClientAuthenticated exchange operations with built-in signing
BaseUrlEnum for mainnet/testnet URL selection

SDK Feature Comparison

FeatureTypeScriptPythonRust
Info queriesYesYesYes
Exchange actionsYesYesYes
EIP-712 signingYesYesYes
WebSocket subscriptionsYesYesPlanned
Agent wallet supportYesYesYes
Auto-reconnectYesNoPlanned
Rate limit handlingYesNoNo
Batch ordersYesYesYes

Source Code

All SDKs are open source:

Community SDKs

Community-maintained SDKs for additional languages may be available. Check the GX-EXCHANGE GitHub organization for the latest listings. Community SDKs are not officially supported.