Liquid

SDK

Python SDK

The official Python client for the Liquid Trading API — automatic signing, typed models, and structured error handling.

Installation

Link
pip
bash
pip install liquidtrading-python
uv
bash
uv add liquidtrading-python

Requires Python 3.9+.

Quick Start

Link
main.py
python
from liquidtrading import LiquidClient

client = LiquidClient(
    api_key="lq_...",
    api_secret="sk_...",
)

ticker = client.get_ticker("BTC-PERP")
print(ticker.mark_price)

Client Configuration

Link
config.py
python
from liquidtrading import LiquidClient

client = LiquidClient(
    api_key="lq_...",
    api_secret="sk_...",
    base_url="https://api.liquid.trade",  # default
    timeout=30.0,                          # seconds
    max_retries=0,                         # retries for GET on 429/5xx
)
ParameterTypeDefaultDescription
api_keystrYour Liquid API key
api_secretstrYour Liquid API secret
base_urlstrhttps://api.liquid.tradeREST API base URL
timeoutfloat30.0Request timeout in seconds
max_retriesint0Retry count for GET requests on 429 and 5xx

Retries use exponential backoff with jitter and respect Retry-After headers. Only GET requests are retried — mutations are never automatically retried.

Market Data

Link
MethodReturnsDescription
get_markets()list[dict]All tradeable markets with symbol, ticker, exchange, max_leverage
get_ticker(symbol)TickerMark price, 24h volume, 24h change, funding rate
get_orderbook(symbol, depth=20)OrderbookL2 snapshot with bids and asks (price, size, count per level)
get_candles(symbol, interval, limit, start, end)list[Candle]OHLCV candles (intervals: 1m, 5m, 15m, 30m, 1h, 4h, 1d)
market_data.py
python
# Get all markets
markets = client.get_markets()

# Get ticker
ticker = client.get_ticker("ETH-PERP")
print(f"ETH: {ticker.mark_price} | Funding: {ticker.funding_rate}")

# Get order book
book = client.get_orderbook("BTC-PERP", depth=10)
print(f"Spread: {book.asks[0].price - book.bids[0].price}")

# Get 1h candles
candles = client.get_candles("BTC-PERP", interval="1h", limit=24)

Account

Link
MethodReturnsDescription
get_account()AccountEquity, margin_used, available_balance, account_value
get_balances()BalanceDetailed balance breakdown with optional cross_margin
get_positions()list[Position]Open positions with full detail
account.py
python
account = client.get_account()
print(f"Equity: {account.equity}")
print(f"Available: {account.available_balance}")

for pos in client.get_positions():
    print(f"{pos.symbol} {pos.side} | PnL: {pos.unrealized_pnl}")

Orders

Link
MethodReturnsDescription
place_order(...)OrderPlace market or limit order
get_open_orders()list[OpenOrder]All currently open orders
get_order(order_id)OrderFetch specific order by ID
cancel_order(order_id)boolCancel single order
cancel_all_orders()intCancel all open orders, returns count
orders.py
python
# Market buy with TP/SL
order = client.place_order(
    symbol="BTC-PERP",
    side="buy",
    type="market",
    size=100.0,       # USD notional
    leverage=2,
    tp=72000.0,
    sl=68000.0,
)
print(f"Filled: {order.order_id}")

# Limit sell
limit = client.place_order(
    symbol="ETH-PERP",
    side="sell",
    type="limit",
    size=50.0,
    price=4200.0,
    leverage=3,
)

# Cancel
client.cancel_order(limit.order_id)
ParameterTypeRequiredDescription
symbolstrYesMarket symbol
sidestrYesbuy or sell
typestrNomarket (default) or limit
sizefloatYesUSD notional (must be > 0)
pricefloatLimit onlyRequired for limit orders
leverageintNo1-200 (default 1)
time_in_forcestrNogtc (default) or ioc
tpfloatNoTake-profit trigger
slfloatNoStop-loss trigger
reduce_onlyboolNoOnly reduce existing position

Positions

Link
MethodReturnsDescription
close_position(symbol, size=None)CloseResultFull close if size omitted, partial close in coin units
set_tp_sl(symbol, tp=None, sl=None)TpSlResultSet or update take-profit and/or stop-loss
update_leverage(symbol, leverage, is_cross=False)LeverageResultUpdate leverage (1-200) and margin mode
update_margin(symbol, amount)MarginResultAdjust isolated margin (positive adds, negative removes)
positions.py
python
# Close entire position
client.close_position("BTC-PERP")

# Partial close (0.025 BTC, not USD)
client.close_position("BTC-PERP", size=0.025)

# Update TP/SL
client.set_tp_sl("BTC-PERP", tp=75000.0, sl=65000.0)

# Change leverage
client.update_leverage("ETH-PERP", leverage=10, is_cross=False)
Size units differ between orders and position closes

place_order uses USD notional for size. close_position uses coin units for partial closes (e.g. 0.025 BTC). Omit size to close the entire position.

Error Handling

Link

All API exceptions inherit from LiquidError. The SDK also raises ValueError for client-side validation failures before the request is sent.

errors.py
python
from liquidtrading import LiquidClient
from liquidtrading.errors import (
    InvalidApiKeyError,
    InvalidSignatureError,
    InsufficientScopeError,
    InsufficientBalanceError,
    OrderRejectedError,
    SymbolNotFoundError,
    RateLimitError,
    ValidationError,
)

client = LiquidClient(api_key="lq_...", api_secret="sk_...")

try:
    client.place_order("BTC-PERP", "buy", size=100, leverage=2)
except InvalidApiKeyError:
    print("Check your API key")
except InvalidSignatureError:
    print("Check your API secret")
except InsufficientScopeError:
    print("Key needs TRADE scope")
except InsufficientBalanceError:
    print("Not enough balance")
except OrderRejectedError as exc:
    print(f"Exchange rejected: {exc.message}")
except SymbolNotFoundError:
    print("Invalid symbol — call get_markets() to list valid symbols")
except RateLimitError as exc:
    print(f"Retry after {exc.retry_after}s")
except ValidationError as exc:
    print(f"Bad request: {exc.message}")
ExceptionWhen
AuthenticationErrorBase class for all auth failures (401)
InvalidApiKeyErrorAPI key does not exist or is disabled
InvalidSignatureErrorHMAC signature mismatch
ExpiredTimestampErrorTimestamp outside 5s skew window
ReplayedNonceErrorNonce already used
ForbiddenErrorBase class for permission errors (403)
InsufficientScopeErrorKey lacks required scope
IpForbiddenErrorRequest from non-whitelisted IP
NotFoundErrorResource not found (e.g. bad order ID)
SymbolNotFoundErrorTrading symbol does not exist
ValidationErrorInvalid request parameters (422)
InsufficientBalanceErrorNot enough balance for order
OrderRejectedErrorExchange rejected the order
RateLimitErrorRate limit exceeded (has retry_after attribute)
ServerErrorInternal server error (500)
ExchangeErrorUpstream exchange error (502)
ServiceUnavailableErrorService temporarily unavailable (503)
GatewayTimeoutErrorUpstream timeout (504)
TimeoutErrorRequest timed out (client-side)
ConnectionErrorNetwork unreachable (client-side)

Client-side validation catches: invalid side, invalid type, invalid time_in_force, leverage out of range, non-positive size, and missing limit price — before sending the request.

Models

Link

The SDK exports typed dataclass models. Numeric values from the API (serialized as strings) are automatically converted to Python floats.