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/sdkQuick 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
| Class | Description |
|---|---|
GxClient | Main client for REST and WebSocket operations |
InfoClient | Read-only info queries |
ExchangeClient | Authenticated exchange actions |
WebSocketManager | Low-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-sdkQuick 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
| Class | Description |
|---|---|
Info | Public data queries and WebSocket subscriptions |
Exchange | Authenticated 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_sdkQuick 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
| Type | Description |
|---|---|
InfoClient | Public data queries |
ExchangeClient | Authenticated exchange operations with built-in signing |
BaseUrl | Enum for mainnet/testnet URL selection |
SDK Feature Comparison
| Feature | TypeScript | Python | Rust |
|---|---|---|---|
| Info queries | Yes | Yes | Yes |
| Exchange actions | Yes | Yes | Yes |
| EIP-712 signing | Yes | Yes | Yes |
| WebSocket subscriptions | Yes | Yes | Planned |
| Agent wallet support | Yes | Yes | Yes |
| Auto-reconnect | Yes | No | Planned |
| Rate limit handling | Yes | No | No |
| Batch orders | Yes | Yes | Yes |
Source Code
All SDKs are open source:
- TypeScript: github.com/GX-EXCHANGE/sdk-typescript
- Python: github.com/GX-EXCHANGE/sdk-python
- Rust: github.com/GX-EXCHANGE/sdk-rust
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.