Skip to content

Binance SDK

Complete reference for ctx.binance — programmatic trading on Binance from worker code.

Binance APIs

This SDK wraps the Binance Spot v3 and USDⓈ-M Futures v1 REST APIs through one unified ctx.binance adapter. Live, demo, and testnet environments all supported.

Setup

  1. Add a Binance trading block to your workspace canvas.
  2. Open the inspector → API Keys → pick a key (Settings → API Keys → Binance to add new).
  3. Choose Market Type: spot or futures (USDⓈ-M).
  4. Connect the block to your Worker block via an edge.
  5. ctx.binance is now available in the worker.
python
def tick(ctx):
    px = float(ctx.binance.get_ticker("BTCUSDT")["lastPrice"])
    ctx.log.info(f"BTC: {px}")

If no Binance block is connected:

RuntimeError: No trading block connected. Connect a Binance block to this worker.

Markets & Modes

The market_type is configured on the block (and stored on the API key); methods that don't take an explicit override use it. Override per call where indicated.

market_typeEndpoint hostDescription
spotapi.binance.comSpot trading
futuresfapi.binance.comUSDⓈ-M perpetuals & futures

Account modes (api_mode on key):

ModeEndpointNotes
liveproductionReal funds
demodemo-api.binance.com / demo-fapi.binance.comPaper-trading, real prices
testnettestnet.binance.vision / testnet.binancefuture.comSandbox, synthetic data

Market Data

get_ticker

24-hour ticker (last price, bid, ask, change, volume).

python
ctx.binance.get_ticker(symbol: str = "BTCUSDT") -> dict

Returns: {"symbol", "lastPrice", "bidPrice", "askPrice", "priceChange", "priceChangePercent", "volume", "quoteVolume", ...}

python
t = ctx.binance.get_ticker("BTCUSDT")
last = float(t["lastPrice"])
change_pct = float(t["priceChangePercent"])

WebSocket cache

PRO/MAX plans return cached ticker data at 0ms latency from the live WS stream — no REST call.

get_klines

OHLCV candlestick data.

python
ctx.binance.get_klines(
    symbol: str = "BTCUSDT",
    interval: str = "1h",
    limit: int = 500,
    start_time: int = None,
    end_time: int = None,
    market_type: str = None,
) -> list
intervalValues
Minutes"1m", "3m", "5m", "15m", "30m"
Hours"1h", "2h", "4h", "6h", "8h", "12h"
Larger"1d", "3d", "1w", "1M"

Returns: [[open_time, open, high, low, close, volume, close_time, quote_volume, trades, ...]] — 12 fields per candle.

python
candles = ctx.binance.get_klines("BTCUSDT", interval="1h", limit=24)
closes = [float(c[4]) for c in candles]
sma_24h = sum(closes) / len(closes)

get_orderbook

Order book depth.

python
ctx.binance.get_orderbook(
    symbol: str = "BTCUSDT",
    limit: int = 20,    # 5 / 10 / 20 / 50 / 100 / 500 / 1000
    market_type: str = None,
) -> dict

Returns: {"lastUpdateId", "bids": [[price, size]], "asks": [[price, size]]}

python
ob = ctx.binance.get_orderbook("BTCUSDT", limit=20)
best_bid = float(ob["bids"][0][0])
best_ask = float(ob["asks"][0][0])
spread_bps = (best_ask - best_bid) / best_bid * 10000

get_recent_trades

Last public trades.

python
ctx.binance.get_recent_trades(symbol: str = "BTCUSDT", limit: int = 100, market_type: str = None) -> list

get_book_ticker

Best bid + ask (single symbol or all).

python
ctx.binance.get_book_ticker(symbol: str = None, market_type: str = None) -> dict

get_avg_price

5-minute volume-weighted average price (spot only). Useful for slippage calculations.

python
ctx.binance.get_avg_price(symbol: str = "BTCUSDT") -> dict

Returns: {"mins": 5, "price": "67234.12"}

get_mark_price

Mark price + funding (futures).

python
ctx.binance.get_mark_price(symbol: str = None) -> dict | list

Returns (single symbol): {"symbol", "markPrice", "indexPrice", "estimatedSettlePrice", "lastFundingRate", "interestRate", "nextFundingTime", "time"}

get_funding_rate

Historical funding rate for perpetuals.

python
ctx.binance.get_funding_rate(
    symbol: str = "BTCUSDT",
    limit: int = 100,
    start_time: int = None,
    end_time: int = None,
    market_type: str = None,
) -> list

get_funding_info

Current funding rate info for all symbols.

python
ctx.binance.get_funding_info() -> list

get_open_interest

Current open interest for a symbol.

python
ctx.binance.get_open_interest(symbol: str = "BTCUSDT") -> dict

get_long_short_ratio

Long/short ratio across all accounts.

python
ctx.binance.get_long_short_ratio(
    symbol: str = "BTCUSDT",
    period: str = "5m",   # "5m" | "15m" | "30m" | "1h" | "2h" | "4h" | "6h" | "12h" | "1d"
    limit: int = 30,
) -> list

get_top_trader_ratio

Long/short ratio specifically for top traders (more predictive).

python
ctx.binance.get_top_trader_ratio(symbol, period, limit) -> list

get_taker_volume

Buy vs sell taker volume — short-term flow direction.

python
ctx.binance.get_taker_volume(symbol, period, limit) -> list

get_basis

Futures basis (premium / discount vs spot).

python
ctx.binance.get_basis(
    pair: str = "BTCUSDT",
    contract_type: str = "PERPETUAL",  # "PERPETUAL" | "CURRENT_QUARTER" | "NEXT_QUARTER"
    period: str = "5m",
    limit: int = 30,
) -> list

get_liquidation_orders

Recent forced liquidations on the futures market.

python
ctx.binance.get_liquidation_orders(symbol: str = None, limit: int = 50) -> list

Account & Wallet

get_account

Account info (balances + permissions for spot, balances + positions for futures).

python
ctx.binance.get_account() -> dict

TIP

Auto-routes to /api/v3/account (spot) or /fapi/v2/account (futures) based on the block's market type.

get_futures_balance

Balances on the USDⓈ-M Futures wallet (always futures, even if block is spot).

python
ctx.binance.get_futures_balance() -> list

get_account_snapshot

Daily account snapshots — last 30 days. Useful for plotting equity curves.

python
ctx.binance.get_account_snapshot(
    account_type: str = "SPOT",   # "SPOT" | "MARGIN" | "FUTURES"
    limit: int = 7,
    start_time: int = None,
    end_time: int = None,
) -> dict

get_commission_rate

Maker/taker commission for your tier on a symbol.

python
ctx.binance.get_commission_rate(symbol: str = "BTCUSDT") -> dict

get_income_history

Realized PnL, funding, fees, transfers (futures account ledger).

python
ctx.binance.get_income_history(
    symbol: str = None,
    income_type: str = None,   # TRANSFER | WELCOME_BONUS | REALIZED_PNL | FUNDING_FEE | COMMISSION | …
    start_time: int = None,
    end_time: int = None,
    limit: int = 100,
) -> list

Positions & Risk

get_positions

Open futures positions (auto-filtered to non-zero size).

python
ctx.binance.get_positions(symbol: str = None) -> dict

WebSocket cache

PRO/MAX: cached from private WS stream at 0ms.

get_position_mode

Returns whether the account is in one-way or hedge (dual-side) mode.

python
ctx.binance.get_position_mode() -> dict

set_position_mode

Switch between one-way and hedge mode (requires no open positions).

python
ctx.binance.set_position_mode(dual_side: bool = False) -> dict

set_leverage

Set leverage (1-125x depending on symbol).

python
ctx.binance.set_leverage(symbol: str, leverage: int) -> dict

set_margin_type

Switch isolated ↔ cross margin.

python
ctx.binance.set_margin_type(symbol: str, margin_type: str = "CROSSED") -> dict
# margin_type: "CROSSED" | "ISOLATED"

get_leverage_brackets

Notional-tier brackets that determine max leverage at each position size.

python
ctx.binance.get_leverage_brackets(symbol: str = None) -> list

adjust_isolated_margin

Add or remove margin from an isolated position.

python
ctx.binance.adjust_isolated_margin(
    symbol: str,
    amount: str,
    type: int,           # 1 = ADD, 2 = REDUCE
    position_side: str = "BOTH",  # "BOTH" | "LONG" | "SHORT"
) -> dict

Orders

place_order

Place a spot or futures order (auto-routes by block's market type).

python
ctx.binance.place_order(
    symbol: str,
    side: str,                    # "BUY" | "SELL"
    qty: str,                     # quantity as string
    order_type: str = "MARKET",   # "MARKET" | "LIMIT" | "STOP" | "TAKE_PROFIT" | "STOP_MARKET" | "TAKE_PROFIT_MARKET"
    price: str = None,            # required for LIMIT
) -> dict
python
# Spot market buy
r = ctx.binance.place_order("BTCUSDT", "BUY", "0.001", "MARKET")

# Futures limit short with TP/SL via subsequent calls
ctx.binance.set_leverage("BTCUSDT", 5)
r = ctx.binance.place_order("BTCUSDT", "SELL", "0.01", "LIMIT", "70000")

spot_oco_order

Spot OCO (One-Cancels-Other): atomically place a take-profit limit + stop-loss stop-limit. When one fills, the other is auto-cancelled.

python
ctx.binance.spot_oco_order(
    symbol: str,
    side: str,                              # "BUY" | "SELL"
    quantity,
    price,                                  # take-profit limit price
    stop_price,                             # stop trigger price
    stop_limit_price,                       # limit price after stop trigger
    stop_limit_time_in_force: str = "GTC",
    list_client_order_id: str = None,
    limit_client_order_id: str = None,
    stop_client_order_id: str = None,
) -> dict
python
# After buying 0.01 BTC at 65000, set OCO: TP at 70000, SL at 63000 (limit 62800)
ctx.binance.spot_oco_order(
    symbol="BTCUSDT", side="SELL", quantity="0.01",
    price="70000",
    stop_price="63000", stop_limit_price="62800",
)

cancel_order

Cancel a single order by ID.

python
ctx.binance.cancel_order(symbol: str, order_id: int) -> dict

futures_modify_order

Modify an unfilled futures order (qty + price).

python
ctx.binance.futures_modify_order(
    symbol: str,
    order_id: int,
    quantity: str = None,
    price: str = None,
) -> dict

futures_batch_orders

Place up to 5 futures orders atomically.

python
ctx.binance.futures_batch_orders(orders: list) -> list

futures_cancel_all

Cancel ALL open futures orders for a symbol.

python
ctx.binance.futures_cancel_all(symbol: str) -> dict

spot_cancel_all

Cancel ALL open spot orders for a symbol.

python
ctx.binance.spot_cancel_all(symbol: str) -> list

countdown_cancel_all

Dead-man's switch — auto-cancel all orders for a symbol if not refreshed within countdown_time ms. Set to 0 to disable.

python
ctx.binance.countdown_cancel_all(symbol: str, countdown_time: int = 10000) -> dict
python
# Refresh every tick — if worker stops, orders auto-cancel after 30 seconds
def tick(ctx):
    ctx.binance.countdown_cancel_all("BTCUSDT", countdown_time=30000)
    # … rest of strategy

get_orders

Active (unfilled) orders.

python
ctx.binance.get_orders(symbol: str = None) -> dict

WebSocket cache

PRO/MAX: cached from private WS stream at 0ms.

get_query_order

Status of a single order.

python
ctx.binance.get_query_order(symbol: str, order_id: int, market_type: str = None) -> dict

get_all_orders

Full order history (active + filled + cancelled + rejected).

python
ctx.binance.get_all_orders(symbol: str = "BTCUSDT", limit: int = 100, market_type: str = None) -> list

get_trade_history

Filled trades with fees (the actual transactions).

python
ctx.binance.get_trade_history(symbol: str = "BTCUSDT", limit: int = 100, market_type: str = None) -> list

Common Patterns

Demo / testnet

Set the API-key mode in Settings → API Keys → Binance to demo or testnet. All calls auto-route to the right environment. Note: Binance demo (paper-trading) has more realistic data than testnet.

Error handling

python
def tick(ctx):
    try:
        positions = ctx.binance.get_positions()
    except Exception as e:
        ctx.log.error(f"Binance unreachable: {e}")
        return

BinanceAPIError (extends ExchangeAPIError) is raised for API errors with code and msg attributes. Network failures raise httpx.HTTPStatusError.

Cloud-Run proxy

PRO+ workers route Binance traffic through a Cloud Run proxy with rotating exit IPs to dodge rate-limit concentration. Transparent — no code changes.

WebSocket caching

PRO+ subscribes to public + private streams in the background. Methods get_ticker, get_account, get_positions, get_orders auto-prefer the cache when fresh.

Recipes

DCA on hourly close

python
def setup(ctx):
    ctx.state.set("last_buy_hour", -1)

def tick(ctx):
    import time
    hour = int(time.time() // 3600)
    if hour == ctx.state.get("last_buy_hour", -1):
        return

    # Use 5-min VWAP for slippage-aware sizing
    avg = float(ctx.binance.get_avg_price("BTCUSDT")["price"])
    qty = round(50 / avg, 5)  # $50 worth

    r = ctx.binance.place_order("BTCUSDT", "BUY", str(qty), "MARKET")
    ctx.state.set("last_buy_hour", hour)
    ctx.log.info(f"DCA: {qty} BTC at ~{avg}{r}")

Spot entry with auto OCO exit

python
def tick(ctx):
    # Only enter when not already holding
    acct = ctx.binance.get_account()
    btc = next((b for b in acct.get("balances", []) if b["asset"] == "BTC"), None)
    if btc and float(btc["free"]) >= 0.001:
        return

    px = float(ctx.binance.get_ticker("BTCUSDT")["lastPrice"])

    # Buy 0.001 BTC at market
    ctx.binance.place_order("BTCUSDT", "BUY", "0.001", "MARKET")

    # Set OCO: +5% take-profit, -2% stop-loss (limit 0.5% beyond)
    ctx.binance.spot_oco_order(
        symbol="BTCUSDT", side="SELL", quantity="0.001",
        price=str(round(px * 1.05, 2)),
        stop_price=str(round(px * 0.98, 2)),
        stop_limit_price=str(round(px * 0.975, 2)),
    )
    ctx.log.info(f"Entered at {px} with OCO exit")

Futures momentum with countdown safety

python
def setup(ctx):
    ctx.binance.set_leverage("BTCUSDT", 5)

def tick(ctx):
    # Activate dead-man switch — orders cancel if worker dies for 30s
    ctx.binance.countdown_cancel_all("BTCUSDT", countdown_time=30000)

    # Check 1h trend via SMA
    candles = ctx.binance.get_klines("BTCUSDT", interval="1h", limit=24)
    closes = [float(c[4]) for c in candles]
    sma = sum(closes) / len(closes)
    last = closes[-1]

    pos = ctx.binance.get_positions("BTCUSDT")
    has_long = any(float(p.get("positionAmt", 0)) > 0 for p in pos)

    if last > sma * 1.005 and not has_long:
        ctx.binance.place_order("BTCUSDT", "BUY", "0.01", "MARKET")
        ctx.log.info(f"Long entry: {last} > SMA {sma:.2f}")
    elif last < sma * 0.995 and has_long:
        ctx.binance.place_order("BTCUSDT", "SELL", "0.01", "MARKET")
        ctx.log.info(f"Exit: {last} < SMA {sma:.2f}")

Reference

Binance endpointSDK methodMarket
GET /api/v3/ticker/24hr
/fapi/v1/ticker/24hr
get_tickerboth
GET /api/v3/avgPriceget_avg_pricespot
GET /api/v3/depth
/fapi/v1/depth
get_orderbookboth
GET /api/v3/klines
/fapi/v1/klines
get_klinesboth
GET /api/v3/trades
/fapi/v1/trades
get_recent_tradesboth
GET /api/v3/ticker/bookTicker
/fapi/v1/ticker/bookTicker
get_book_tickerboth
GET /fapi/v1/premiumIndexget_mark_pricefutures
GET /fapi/v1/fundingRateget_funding_ratefutures
GET /fapi/v1/fundingInfoget_funding_infofutures
GET /fapi/v1/openInterestget_open_interestfutures
GET /futures/data/globalLongShortAccountRatioget_long_short_ratiofutures
GET /futures/data/topLongShortPositionRatioget_top_trader_ratiofutures
GET /futures/data/takerlongshortRatioget_taker_volumefutures
GET /futures/data/basisget_basisfutures
GET /fapi/v1/forceOrdersget_liquidation_ordersfutures
GET /api/v3/account
/fapi/v2/account
get_accountboth
GET /fapi/v2/balanceget_futures_balancefutures
GET /sapi/v1/accountSnapshotget_account_snapshotspot/margin/futures
GET /fapi/v1/commissionRateget_commission_ratefutures
GET /fapi/v1/incomeget_income_historyfutures
GET /fapi/v2/positionRiskget_positionsfutures
GET /fapi/v1/positionSide/dualget_position_modefutures
POST /fapi/v1/positionSide/dualset_position_modefutures
POST /fapi/v1/leverageset_leveragefutures
POST /fapi/v1/marginTypeset_margin_typefutures
GET /fapi/v1/leverageBracketget_leverage_bracketsfutures
POST /fapi/v1/positionMarginadjust_isolated_marginfutures
POST /api/v3/order
/fapi/v1/order
place_orderboth
POST /api/v3/order/ocospot_oco_orderspot
DELETE /api/v3/order
/fapi/v1/order
cancel_orderboth
PUT /fapi/v1/orderfutures_modify_orderfutures
POST /fapi/v1/batchOrdersfutures_batch_ordersfutures
DELETE /fapi/v1/allOpenOrdersfutures_cancel_allfutures
DELETE /api/v3/openOrdersspot_cancel_allspot
POST /fapi/v1/countdownCancelAllcountdown_cancel_allfutures
GET /api/v3/openOrders
/fapi/v1/openOrders
get_ordersboth
GET /api/v3/order
/fapi/v1/order
get_query_orderboth
GET /api/v3/allOrders
/fapi/v1/allOrders
get_all_ordersboth
GET /api/v3/myTrades
/fapi/v1/userTrades
get_trade_historyboth

AiSpinner Documentation