SDK Guide
Client libraries for integrating with LX - TypeScript, Python, Go, Rust, C, and C++ SDKs
LX SDK Documentation
Specification: LP-9002 DEX API & RPC | Discussions
Releases
Latest: v1.2.1 | All Releases
Overview
LX provides multiple SDKs and APIs for integration:
- TypeScript/JavaScript - Web and Node.js applications
- Python - Data analysis and algorithmic trading
- Go - High-performance server applications
- Rust - Systems programming with zero-cost abstractions
- C/C++ - High-frequency trading and native integration
Implementation Status
| SDK | Package | Install | Status |
|---|---|---|---|
| TypeScript (base) | @luxfi/dex | npm install @luxfi/dex | ✅ Published |
| TypeScript (trading) | @luxfi/trading | npm install @luxfi/trading | ✅ Published |
| Python | lux-dex | pip install lux-dex | ✅ Published |
| Go | github.com/luxfi/dex/sdk/go | go get github.com/luxfi/dex/sdk/go | ✅ Published |
| Rust | lux-dex | cargo add lux-dex | ✅ Published |
| C | lxdex | Build from source | ✅ Complete |
| C++ | lxdex | Build from source | ✅ Complete |
Quick Start
Start the DEX Node
# Build the node
make build
# Run the node
./bin/luxdThis starts:
- JSON-RPC API on port 8080
- gRPC server on port 50051
- WebSocket server on port 8081
- P2P networking on port 5000
TypeScript SDK
LX provides two TypeScript packages:
@luxfi/dex- Core SDK for building on the DEX (Client class, types, low-level API)@luxfi/trading- High-level trading SDK with convenience helpers (DEX(), AMM(), CCXT)
Installation
# Core SDK (for building applications)
npm install @luxfi/dex
# Trading SDK (for bots and trading strategies)
npm install @luxfi/trading
# Or install both
npm install @luxfi/dex @luxfi/tradingQuick Start with @luxfi/trading
import { DEX } from '@luxfi/trading'
// Simple initialization with factory function
const dex = await DEX({ rpcUrl: 'http://localhost:8080/rpc' })
// Place an order
const order = await dex.limitBuy('BTC-USD', '1.0', '50000')
console.log('Order placed:', order.orderId)Building with @luxfi/dex
import { Client, ClientConfig, OrderType, OrderSide } from '@luxfi/dex'
// Full control with the base Client
const config: ClientConfig = {
rpcUrl: 'http://localhost:8080/rpc',
wsUrl: 'ws://localhost:8081',
apiKey: 'your-api-key'
}
const client = new Client(config)
await client.connect()
// Place order with full type safety
const order = await client.placeOrder({
symbol: 'BTC-USD',
type: OrderType.LIMIT,
side: OrderSide.BUY,
price: 50000,
size: 1.0
})WebSocket Subscriptions
// Works with either package
dex.subscribeOrderBook('BTC-USD', (book) => {
console.log('Best bid:', book.bids[0])
console.log('Best ask:', book.asks[0])
})
// Subscribe to trades
dex.subscribeTrades('BTC-USD', (trade) => {
console.log('New trade:', trade)
})
// Subscribe to your orders
dex.subscribeUserOrders((order) => {
console.log('Order update:', order)
})Multi-Venue Trading with @luxfi/trading
import { Client, Config, NativeVenueConfig } from '@luxfi/trading'
// Aggregate liquidity across venues
const config = new Config()
.withNative('lx-dex', NativeVenueConfig.lxDex('https://api.lux.network/rpc'))
.withCCXT('binance', { apiKey: '...', secret: '...' })
.withApiKey('your-api-key')
.withTimeout(30000)
const client = new Client(config)
await client.connect()Python SDK
Installation
pip install lux-dexBasic Usage
from lux_dex import Client
client = Client(
json_rpc_url='http://localhost:8080/rpc',
ws_url='ws://localhost:8081'
)
# Place an order
order = client.place_order(
symbol='BTC-USD',
order_type='limit',
side='buy',
price=50000,
size=1.0
)
print(f'Order placed: {order.order_id}')Get Market Data
# Get order book
book = client.get_order_book('BTC-USD', depth=10)
print(f"Best bid: {book['bids'][0]}")
print(f"Best ask: {book['asks'][0]}")
# Get recent trades
trades = client.get_trades('BTC-USD', limit=100)
for trade in trades:
print(f"{trade['side']} {trade['size']} @ {trade['price']}")Async Support
import asyncio
from lux_dex import AsyncClient
async def main():
client = AsyncClient(
json_rpc_url='http://localhost:8080/rpc',
ws_url='ws://localhost:8081'
)
# Place order asynchronously
order = await client.place_order(
symbol='BTC-USD',
order_type='limit',
side='buy',
price=50000,
size=1.0
)
# Stream market data
async for book in client.stream_order_book('BTC-USD'):
print(f"Bid: {book.best_bid}, Ask: {book.best_ask}")
asyncio.run(main())Go SDK
Installation
go get github.com/luxfi/dex/sdk/goBasic Usage
package main
import (
"context"
"fmt"
"log"
"github.com/luxfi/dex/sdk/go/lxdex"
)
func main() {
client := lxdex.NewClient(
lxdex.WithJSONRPC("http://localhost:8080/rpc"),
lxdex.WithGRPC("localhost:50051"),
)
ctx := context.Background()
// Place an order
order, err := client.PlaceOrder(ctx, &lxdex.Order{
Symbol: "BTC-USD",
Type: lxdex.OrderTypeLimit,
Side: lxdex.Buy,
Price: 50000,
Size: 1.0,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Order placed: %s\n", order.OrderID)
}Streaming Data
// Stream order book
stream, err := client.StreamOrderBook(ctx, "BTC-USD")
if err != nil {
log.Fatal(err)
}
for {
update, err := stream.Recv()
if err != nil {
break
}
fmt.Printf("Order book update: %+v\n", update)
}gRPC Integration
import (
"context"
"google.golang.org/grpc"
pb "github.com/luxfi/dex/pkg/grpc/pb"
)
// Connect to gRPC server
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
defer conn.Close()
client := pb.NewLXDEXServiceClient(conn)
// Place an order via gRPC
resp, err := client.PlaceOrder(context.Background(), &pb.PlaceOrderRequest{
Symbol: "BTC-USD",
Type: pb.OrderType_LIMIT,
Side: pb.OrderSide_BUY,
Price: 50000,
Size: 1.0,
UserId: "trader1",
})Rust SDK
Installation
cargo add lux-dexOr add to Cargo.toml:
[dependencies]
lux-dex = "1.2"Basic Usage
use lux_dex::{Client, ClientConfig, Order, OrderType, OrderSide};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ClientConfig {
rpc_url: "http://localhost:8080/rpc".to_string(),
ws_url: Some("ws://localhost:8081".to_string()),
..Default::default()
};
let client = Client::new(config).await?;
// Place an order
let order = client.place_order(Order {
symbol: "BTC-USD".to_string(),
order_type: OrderType::Limit,
side: OrderSide::Buy,
price: Some(50000.0),
size: 1.0,
..Default::default()
}).await?;
println!("Order placed: {}", order.order_id);
Ok(())
}C++ SDK
Installation
git clone https://github.com/luxfi/dex
cd dex/sdk/cpp
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)
sudo make installBasic Usage
#include <lxdex/client.hpp>
#include <iostream>
int main() {
using namespace lxdex;
ClientConfig config;
config.ws_url = "ws://localhost:8081";
config.api_key = "your-api-key";
auto client = make_client(config);
if (auto err = client->connect()) {
std::cerr << "Failed to connect: " << err.message << std::endl;
return 1;
}
// Place an order
Order order;
order.symbol = "BTC-USD";
order.type = OrderType::Limit;
order.side = OrderSide::Buy;
order.price = 50000.0;
order.size = 1.0;
auto result = client->place_order(order);
if (result.ok()) {
std::cout << "Order placed: " << result.value.order_id << std::endl;
}
return 0;
}C SDK
Installation
git clone https://github.com/luxfi/dex
cd dex/sdk/c
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)
sudo make installBasic Usage
#include <lxdex.h>
#include <stdio.h>
int main() {
lxdex_config_t config = {
.ws_url = "ws://localhost:8081",
.api_key = "your-api-key"
};
lxdex_client_t* client = lxdex_client_new(&config);
if (lxdex_client_connect(client) != 0) {
fprintf(stderr, "Failed to connect\n");
return 1;
}
// Place an order
lxdex_order_t order = {
.symbol = "BTC-USD",
.type = LXDEX_ORDER_LIMIT,
.side = LXDEX_SIDE_BUY,
.price = 50000.0,
.size = 1.0
};
lxdex_order_response_t response;
if (lxdex_place_order(client, &order, &response) == 0) {
printf("Order placed: %s\n", response.order_id);
}
lxdex_client_free(client);
return 0;
}Linking
# CMakeLists.txt
find_package(lxdex REQUIRED)
target_link_libraries(your_app PRIVATE lxdex::lxdex)Or with pkg-config:
gcc -o myapp myapp.c $(pkg-config --cflags --libs lxdex)Order Types
| Type | Value | Description |
|---|---|---|
| LIMIT | 0 | Order at specific price |
| MARKET | 1 | Execute at best price |
| STOP | 2 | Trigger at stop price |
| STOP_LIMIT | 3 | Stop becomes limit |
| ICEBERG | 4 | Hidden quantity order |
| PEG | 5 | Pegged to best bid/ask |
Order Sides
| Side | Value | Description |
|---|---|---|
| BUY | 0 | Buy order |
| SELL | 1 | Sell order |
Time in Force
| TIF | Description |
|---|---|
| GTC | Good Till Cancelled |
| IOC | Immediate Or Cancel |
| FOK | Fill Or Kill |
| DAY | Day Order |
Error Handling
TypeScript
try {
const order = await dex.limitBuy('BTC-USD', '1.0', '50000')
} catch (error) {
if (error.code === 'INSUFFICIENT_BALANCE') {
console.error('Not enough funds')
} else if (error.code === 'RATE_LIMIT_EXCEEDED') {
console.error('Too many requests')
}
}Python
from lux_dex.exceptions import InsufficientBalanceError, RateLimitError
try:
order = client.place_order(...)
except InsufficientBalanceError:
print('Not enough funds')
except RateLimitError:
print('Too many requests')
except Exception as e:
print(f'Error: {e}')Go
order, err := client.PlaceOrder(ctx, &lxdex.Order{...})
if err != nil {
switch e := err.(type) {
case *lxdex.InsufficientBalanceError:
log.Printf("Not enough funds: need %f, have %f", e.Required, e.Available)
case *lxdex.RateLimitError:
log.Printf("Rate limited, retry after %v", e.RetryAfter)
default:
log.Printf("Error: %v", err)
}
}Rate Limits
| Endpoint | Limit |
|---|---|
| Orders | 100/sec per user |
| Cancellations | 100/sec per user |
| Market Data | 1000 req/min |
| WebSocket | 10 connections/IP |
Authentication
API Key Setup
const dex = await DEX({
rpcUrl: 'https://api.lux.network/rpc',
apiKey: 'your-api-key'
})JWT Authentication
client = Client(
jwt_token='eyJhbGciOiJIUzI1NiIs...'
)Testing
Test Network
# Start test node
./bin/luxd --testnet
# Use test endpoints
JSON-RPC: http://localhost:18080/rpc
gRPC: localhost:15051
WebSocket: ws://localhost:18081Example Test Script
# Run SDK tests
npm test # TypeScript
python -m pytest # Python
go test ./... # GoPerformance
- Order Matching: 597ns latency (C++ engine)
- Throughput: 100M+ orders/second (with MLX GPU)
- Block Time: 1ms finality
- Network: Quantum-secure with BLS signatures
Support
- GitHub: https://github.com/luxfi/dex
- Documentation: https://dex.lux.network
- Discord: https://discord.gg/luxfi