Liquidity.io

SDK

Trading SDKs for Liquidity.io — TypeScript, Python, Go, Rust, C++

Liquidity.io provides SDKs for programmatic access to the exchange. Built on the @luxfi/trading library, the SDKs offer unified liquidity aggregation, smart order routing, execution algorithms, and risk management.

TypeScript SDK

Installation

npm install @luxfi/trading
# or
pnpm add @luxfi/trading

Quick Start

import { Client, Config, NativeVenueConfig } from '@luxfi/trading';

// Configure connection to Liquidity.io ATS
const config = new Config()
  .withNative('liquidity', NativeVenueConfig.lxDex('https://api.satschel.com/v1'))
  .withVenuePriority(['liquidity'])
  .withSmartRouting(false);

const client = new Client(config);
await client.connect();

// Get orderbook
const book = await client.orderbook('AAPL');
console.log(`Best bid: ${book.bestBid}, Best ask: ${book.bestAsk}`);
console.log(`Spread: ${book.spread}, Mid: ${book.midPrice}`);

// Place a market buy
const order = await client.buy('AAPL', 10);
console.log(`Order ${order.order_id} filled at ${order.average_price}`);

// Place a limit buy
const limitOrder = await client.limitBuy('BTC-USD', '0.1', '80000');
console.log(`Limit order ${limitOrder.order_id} status: ${limitOrder.status}`);

// Get balances
const balances = await client.balances();
for (const b of balances) {
  console.log(`${b.asset}: ${b.totalFree} free, ${b.totalLocked} locked`);
}

await client.disconnect();

Convenience Functions

For single-venue usage, use the DEX or AMM shorthand:

import { DEX, AMM } from '@luxfi/trading';

// CLOB orderbook exchange
const dex = await DEX({
  rpcUrl: 'https://api.satschel.com/v1',
  apiKey: 'your-api-key',
});

const order = await dex.limitBuy('BTC-USD', '0.1', '80000');

// AMM for swaps and liquidity
const amm = await AMM({
  rpcUrl: 'https://api.satschel.com/v1',
  apiKey: 'your-api-key',
});

const quote = await amm.quote('BTC', 'USDC', '0.1', true, 'lx-amm');

Multi-Venue Aggregation

Connect to multiple venues simultaneously and route orders to the best price:

import { Client, Config, NativeVenueConfig, CcxtConfig } from '@luxfi/trading';

const config = new Config()
  .withNative('liquidity', NativeVenueConfig.lxDex('https://api.satschel.com/v1'))
  .withCcxt('binance', CcxtConfig.new('binance').withCredentials('key', 'secret'))
  .withVenuePriority(['liquidity', 'binance'])
  .withSmartRouting(true);

const client = new Client(config);
await client.connect();

// Aggregated orderbook across all venues
const aggBook = await client.aggregatedOrderbook('BTC-USDC');
const bestBid = aggBook.bestBid();
const bestAsk = aggBook.bestAsk();
console.log(`Best bid: ${bestBid?.price} on ${bestBid?.venue}`);
console.log(`Best ask: ${bestAsk?.price} on ${bestAsk?.venue}`);

// Smart routing automatically picks the best venue
const order = await client.buy('BTC-USDC', '0.1');
console.log(`Routed to ${order.venue}`);

// Or target a specific venue
const binanceOrder = await client.buy('BTC-USDC', '0.1', 'binance');

Execution Algorithms

Built-in execution algorithms for large orders:

import { TwapExecutor, VwapExecutor, IcebergExecutor, SniperExecutor } from '@luxfi/trading';

// TWAP — spread order over time
const twap = new TwapExecutor(client, {
  symbol: 'BTC-USDC',
  side: 'buy',
  totalQuantity: 10,
  durationSeconds: 3600,
  numSlices: 12,
});
const twapOrders = await twap.execute();

// Iceberg — hide large order behind small visible slices
const iceberg = new IcebergExecutor(client, {
  symbol: 'BTC-USDC',
  side: 'buy',
  totalQuantity: 100,
  visibleQuantity: 5,
  price: 80000,
});
const icebergOrders = await iceberg.execute();

// Sniper — wait for target price then execute immediately
const sniper = new SniperExecutor(client, {
  symbol: 'BTC-USDC',
  side: 'buy',
  quantity: 1,
  targetPrice: 78000,
});
const sniperOrder = await sniper.execute();

Risk Management

import { RiskManager } from '@luxfi/trading';

const risk = new RiskManager({
  enabled: true,
  maxPositionSize: 100,
  maxOrderSize: 10,
  maxDailyLoss: 1000,
  killSwitchEnabled: true,
});

// Validate before placing
try {
  risk.validateOrder(orderRequest);
} catch (e) {
  if (e instanceof RiskError) {
    console.error(`Order rejected: ${e.message}`);
  }
}

// Update after fills
risk.updatePosition('BTC', 1, 'buy');
risk.updatePnl(-50);

console.log(`BTC position: ${risk.position('BTC')}`);
console.log(`Daily PnL: ${risk.dailyPnl}`);

Financial Math

import {
  blackScholes,
  impliedVolatility,
  greeks,
  constantProductPrice,
  volatility,
  sharpeRatio,
  valueAtRisk,
  conditionalVaR,
} from '@luxfi/trading';

// Options pricing
const callPrice = blackScholes(100, 100, 1, 0.05, 0.2, 'call');
const iv = impliedVolatility(10.45, 100, 100, 1, 0.05, 'call');
const g = greeks(100, 100, 1, 0.05, 0.2);
console.log(`Delta: ${g.delta}, Gamma: ${g.gamma}, Theta: ${g.theta}`);

// AMM pricing
const result = constantProductPrice(1000000, 1000000, 1000, 0.003);
console.log(`Output: ${result.output}, Price: ${result.price}`);

// Risk metrics
const returns = [0.01, -0.02, 0.03, -0.01, 0.02];
console.log(`Volatility: ${volatility(returns)}`);
console.log(`Sharpe: ${sharpeRatio(returns)}`);
console.log(`VaR 95%: ${valueAtRisk(returns, 0.95)}`);

Type Reference

Key types exported by @luxfi/trading:

TypeDescription
ClientMain trading client, connects to multiple venues
ConfigConfiguration builder for venues and settings
OrderOrder with status, fills, fees
OrderRequestOrder creation request
TradeIndividual fill/trade
TickerQuote data (bid, ask, last, volume)
OrderbookSingle-venue orderbook with VWAP calculation
AggregatedOrderbookMulti-venue aggregated orderbook
BalanceAsset balance per venue
SideBUY or SELL
OrderTypeMARKET, LIMIT, LIMIT_MAKER, STOP_LOSS, etc.
OrderStatusPENDING, OPEN, PARTIALLY_FILLED, FILLED, CANCELLED, REJECTED, EXPIRED
TimeInForceGTC, IOC, FOK, GTD, POST_ONLY

Python SDK

Installation

pip install lx-trading

Quick Start

import asyncio
from decimal import Decimal
from lx_trading import Client, Config
from lx_trading.config import NativeVenueConfig

async def main():
    # Configure
    config = Config()
    config.with_native("liquidity", NativeVenueConfig.lx_dex("https://api.satschel.com/v1"))

    # Connect
    client = Client(config)
    await client.connect()

    # Orderbook
    book = await client.orderbook("BTC-USD")
    print(f"Best bid: {book.best_bid}, Best ask: {book.best_ask}")
    print(f"Spread: {book.spread}, Mid: {book.mid_price}")

    # Market buy with smart routing
    order = await client.buy("BTC-USD", Decimal("0.1"))
    print(f"Filled on {order.venue} at {order.average_price}")

    # Limit order on a specific venue
    order = await client.limit_buy("BTC-USD", Decimal("0.1"), Decimal("80000"))
    print(f"Order {order.order_id} status: {order.status}")

    # Balances
    balances = await client.balances()
    for b in balances:
        print(f"{b.asset}: {b.total_free} free, {b.total_locked} locked")

    await client.disconnect()

asyncio.run(main())

Configuration via TOML

[general]
log_level = "info"
smart_routing = true
venue_priority = ["liquidity"]

[risk]
enabled = true
max_position_size = 1000
max_daily_loss = 5000

[native.liquidity]
venue_type = "dex"
api_url = "https://api.satschel.com/v1"
api_key = "your-api-key"
api_secret = "your-api-secret"
config = Config.from_file("config.toml")
client = Client(config)
await client.connect()

Execution Algorithms

from lx_trading.execution import TwapExecutor, IcebergExecutor
from lx_trading.types import Side

# TWAP
twap = TwapExecutor(
    client=client,
    symbol="BTC-USDC",
    side=Side.BUY,
    total_quantity=Decimal("10"),
    duration_seconds=3600,
    num_slices=12,
)
orders = await twap.execute()

# Iceberg
iceberg = IcebergExecutor(
    client=client,
    symbol="BTC-USDC",
    side=Side.BUY,
    total_quantity=Decimal("100"),
    visible_quantity=Decimal("5"),
    price=Decimal("80000"),
)
orders = await iceberg.execute()

Risk Management

from lx_trading import RiskManager
from lx_trading.config import RiskConfig

risk = RiskManager(RiskConfig(
    enabled=True,
    max_position_size=Decimal("100"),
    max_order_size=Decimal("10"),
    max_daily_loss=Decimal("1000"),
    kill_switch_enabled=True,
))

try:
    risk.validate_order(order_request)
except RiskError as e:
    print(f"Order rejected: {e}")

Financial Math

from lx_trading.math import (
    black_scholes, implied_volatility, greeks,
    constant_product_price,
    volatility, sharpe_ratio, var, cvar,
)

# Options pricing
call = black_scholes(S=100, K=100, T=1, r=0.05, sigma=0.2, option_type="call")
iv = implied_volatility(price=10.45, S=100, K=100, T=1, r=0.05, option_type="call")
g = greeks(S=100, K=100, T=1, r=0.05, sigma=0.2)
print(f"Delta: {g['delta']:.4f}, Gamma: {g['gamma']:.6f}")

# AMM pricing
output, price = constant_product_price(1000000, 1000000, 1000, fee_rate=0.003)

# Risk metrics
returns = [0.01, -0.02, 0.03, -0.01, 0.02]
print(f"Volatility: {volatility(returns):.2%}")
print(f"VaR 95%: {var(returns, 0.95):.2%}")
print(f"CVaR 95%: {cvar(returns, 0.95):.2%}")

Go SDK

import "github.com/luxfi/dex/sdk/go"

client := lxdex.NewClient(lxdex.Config{
    APIURL:    "https://api.satschel.com/v1",
    APIKey:    "your-api-key",
    APISecret: "your-api-secret",
})

// Place order
order, err := client.PlaceOrder("BTC-USD", "buy", "limit", 80000, 0.1)
if err != nil {
    log.Fatal(err)
}

// Get orderbook
book, err := client.GetOrderbook("BTC-USD", 20)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Best bid: %v, Best ask: %v\n", book.BestBid(), book.BestAsk())

Rust SDK

use luxfi_trading::{Client, Config, NativeVenueConfig};

let config = Config::new()
    .with_native("liquidity", NativeVenueConfig::lx_dex("https://api.satschel.com/v1"))
    .with_api_key("your-api-key");

let client = Client::new(config);
client.connect().await?;

// Place order
let order = client.buy("BTC-USD", 0.1).await?;
println!("Order {} filled at {}", order.id, order.average_price);

// Orderbook
let book = client.orderbook("BTC-USD").await?;
println!("Spread: {}", book.spread());

C++ SDK

#include <luxfi/trading.h>

auto config = lx::Config()
    .withNative("liquidity", lx::NativeVenueConfig::lxDex("https://api.satschel.com/v1"))
    .withApiKey("your-api-key");

auto client = lx::Client(config);
client.connect();

// Place order
auto order = client.buy("BTC-USD", 0.1);
std::cout << "Order " << order.id << " at " << order.averagePrice << std::endl;

// Orderbook with VWAP
auto book = client.orderbook("BTC-USD");
auto vwap = book.vwapBuy(1.0);
std::cout << "VWAP for 1 BTC: " << vwap << std::endl;

Supported Venues

All SDKs support the same set of venues through the adapter pattern:

Venue TypeExamplesFeatures
Native (CLOB)Liquidity.io ATSFull orderbook, limit/market orders
Native (AMM)Liquidity.io AMMSwaps, liquidity provision, LP tracking
CCXTBinance, MEXC, OKX, Bybit, KuCoin, 100+Orderbook, orders, balances
Hummingbot GatewayAny Gateway-supported DEXSwaps, LP positions

On this page