Skip to content

Bitget SDK

Complete reference for ctx.bitget — programmatic spot and USDT-perpetual trading on Bitget from worker code.

Bitget v2 API

This SDK wraps the Bitget v2 unified API for spot and futures (USDT-FUTURES, USDC-FUTURES, COIN-FUTURES). Live and demo (paper-trading) modes supported.

New in this release

ctx.bitget is a new worker adapter introduced in this PR. If your worker was deployed before, redeploy it to pick up the new methods.

Setup

  1. Add a Bitget trading block to your workspace canvas.
  2. Open the inspector → API Keys → pick a key (Settings → API Keys → Bitget to add new). Bitget requires api_key + api_secret + passphrase.
  3. Connect the block to your Worker block via an edge.
  4. ctx.bitget is now available.
python
def tick(ctx):
    t = ctx.bitget.futures_tickers(symbol="BTCUSDT")
    last = t["data"][0]["last"]
    ctx.log.info(f"BTC: {last}")

If no Bitget block is connected:

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

Markets & Modes

Bitget uses product_type to disambiguate derivatives, and a separate spot endpoint family:

MarketIdentifierDescription
Spot(no product_type)BTCUSDT, ETHUSDT, …
USDT-margined FuturesUSDT-FUTURESLinear perpetuals, USDT settled
USDC-margined FuturesUSDC-FUTURESLinear perpetuals, USDC settled
Coin-margined FuturesCOIN-FUTURESInverse perpetuals (BTCUSD, ETHUSD …)

The block's Product Type dropdown sets the default for every call. Override per-call with product_type=... where applicable.

Account modes (api_mode on key):

ModeDescription
liveReal funds. Default.
demoPaper-trading via the paptrading: 1 header. Real prices, fake execution.

Demo mode

Bitget uses the same hostname for live + demo — only an HTTP header switches modes. The SDK adds paptrading: 1 automatically when your key is in demo mode.

Public Market Data

These methods do not require a key and skip auth.

futures_tickers

All futures tickers, or one symbol.

python
ctx.bitget.futures_tickers(
    product_type: str = "USDT-FUTURES",
    symbol: str = None,
) -> dict

Returns: {"code": "00000", "data": [{"symbol", "lastPr", "askPr", "bidPr", "high24h", "low24h", "openUtc", "fundingRate", "indexPrice", "markPrice", "openInterest", "ts", ...}]}

python
t = ctx.bitget.futures_tickers(symbol="BTCUSDT")
last = float(t["data"][0]["lastPr"])

spot_tickers

All spot tickers, or one symbol.

python
ctx.bitget.spot_tickers(symbol: str = None) -> dict

futures_candles

Futures OHLCV candles.

python
ctx.bitget.futures_candles(
    symbol: str = "BTCUSDT",
    granularity: str = "1H",
    product_type: str = "USDT-FUTURES",
    limit: int = 200,
    start_time: int = None,
    end_time: int = None,
) -> dict
granularityValues
Sub-hour"1m", "3m", "5m", "15m", "30m"
Hours"1H", "4H", "6H", "12H"
Days+"1D", "3D", "1W", "1M"
python
candles = ctx.bitget.futures_candles("BTCUSDT", granularity="1H", limit=24)
closes = [float(c[4]) for c in candles["data"]]   # [ts, o, h, l, c, vol, …]
sma_24h = sum(closes) / len(closes)

spot_candles

Spot OHLCV (lower-case granularity codes — Bitget quirk).

python
ctx.bitget.spot_candles(symbol: str = "BTCUSDT", granularity: str = "1h", limit: int = 200) -> dict

futures_orderbook

Futures order book depth.

python
ctx.bitget.futures_orderbook(
    symbol: str = "BTCUSDT",
    product_type: str = "USDT-FUTURES",
    limit: int = 20,
) -> dict

Returns: {"data": {"asks": [[price, size], ...], "bids": [[price, size], ...], "ts"}}

Account & Wallet

futures_accounts

Futures account balance, equity, available margin, locked margin per margin_coin.

python
ctx.bitget.futures_accounts(
    product_type: str = None,        # defaults to block's product_type
    margin_coin: str = "USDT",
) -> dict
python
acc = ctx.bitget.futures_accounts()
free = float(acc["data"][0]["available"])
ctx.log.info(f"Free margin: {free} USDT")

spot_assets

Spot wallet balances per coin.

python
ctx.bitget.spot_assets(coin: str = None) -> dict

Positions

futures_positions

Open futures positions.

python
ctx.bitget.futures_positions(
    product_type: str = None,
    margin_coin: str = "USDT",
) -> dict

Returns position fields: symbol, holdSide (long / short), total, available, averageOpenPrice, unrealizedPL, liquidationPrice, markPrice, leverage, marginMode, ...

Orders

futures_pending_orders

Active (open) futures orders.

python
ctx.bitget.futures_pending_orders(
    product_type: str = None,
    symbol: str = None,
) -> dict

futures_orders_history

Filled, cancelled, or rejected futures orders (recent history).

python
ctx.bitget.futures_orders_history(
    product_type: str = None,
    symbol: str = None,
    limit: int = 50,
) -> dict

futures_place_order

Place a futures order.

python
ctx.bitget.futures_place_order(
    symbol: str,
    side: str,                      # "buy" | "sell"
    size,                           # contracts
    order_type: str = "market",     # "market" | "limit"
    price: str = None,              # required for limit
    trade_side: str = None,         # "open" | "close" (one-way mode is automatic)
    margin_coin: str = "USDT",
    margin_mode: str = "isolated",  # "isolated" | "crossed"
    product_type: str = None,
    reduce_only: str = None,        # "YES" | "NO"
    force: str = "gtc",             # "gtc" | "ioc" | "fok" | "post_only"
) -> dict
python
# Open a 0.01 BTC long perp at market with 5x leverage (set separately)
ctx.bitget.futures_set_leverage("BTCUSDT", 5)
r = ctx.bitget.futures_place_order(
    symbol="BTCUSDT", side="buy", size="0.01", order_type="market",
)

# Limit short 0.5 ETH at $3500
r = ctx.bitget.futures_place_order(
    symbol="ETHUSDT", side="sell", size="0.5",
    order_type="limit", price="3500",
)

Trade logging

Every successful futures or spot order is recorded in your TradeLog table — visible in the Journal block.

futures_cancel_order

Cancel a single futures order.

python
ctx.bitget.futures_cancel_order(
    symbol: str,
    order_id: str = None,
    client_oid: str = None,
    product_type: str = None,
) -> dict

futures_close_position

Close a position immediately at market price.

python
ctx.bitget.futures_close_position(
    symbol: str,
    hold_side: str = None,         # "long" | "short" (hedge mode); omit in one-way
    product_type: str = None,
) -> dict

futures_set_leverage

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

python
ctx.bitget.futures_set_leverage(
    symbol: str,
    leverage: int,
    hold_side: str = None,         # for hedge mode (long / short legs)
    product_type: str = None,
    margin_coin: str = "USDT",
) -> dict

spot_place_order

Place a spot order.

python
ctx.bitget.spot_place_order(
    symbol: str,
    side: str,                     # "buy" | "sell"
    size,
    order_type: str = "market",    # "market" | "limit"
    price: str = None,
    force: str = "gtc",
) -> dict

Common Patterns

Demo mode during development

Set the API-key mode to demo in Settings → API Keys → Bitget. All worker calls automatically route via the paptrading: 1 header. Switch back to live when ready.

Error handling

python
def tick(ctx):
    try:
        positions = ctx.bitget.futures_positions()
    except Exception as e:
        ctx.log.error(f"Bitget unreachable: {e}")
        return

BitgetAPIError is raised for API errors with code, detail, and context attributes. Network failures raise httpx.HTTPStatusError.

Cloud-Run proxy

Bitget calls go directly through httpx (not the Cloud-Run proxy) in this release. Future versions may switch this to match other exchanges.

Server-only

Bitget signing requires a passphrase — not safe to expose to a browser. Workers must run in Server mode.

Recipes

DCA into a USDT perp

python
def setup(ctx):
    ctx.state.set("last_buy_ts", 0)
    # Set a sensible leverage once
    ctx.bitget.futures_set_leverage("BTCUSDT", 3)

def tick(ctx):
    import time
    now = int(time.time())
    if now - ctx.state.get("last_buy_ts", 0) < 3600:
        return  # once an hour

    px = float(ctx.bitget.futures_tickers(symbol="BTCUSDT")["data"][0]["lastPr"])
    qty = round(50 / px, 4)   # $50 worth (3x lev)

    r = ctx.bitget.futures_place_order(
        symbol="BTCUSDT", side="buy", size=str(qty), order_type="market",
    )
    ctx.state.set("last_buy_ts", now)
    ctx.log.info(f"DCA long {qty} BTC @ ~{px}{r.get('data')}")

Auto-flat at end of day

python
import time
from datetime import datetime, timezone

def tick(ctx):
    now = datetime.now(timezone.utc)
    # 23:55 UTC — close everything
    if now.hour == 23 and now.minute >= 55:
        positions = ctx.bitget.futures_positions()["data"]
        for p in positions:
            if float(p.get("total", 0)) > 0:
                ctx.bitget.futures_close_position(
                    symbol=p["symbol"],
                    hold_side=p.get("holdSide"),
                )
                ctx.log.info(f"Closed {p['symbol']} {p['holdSide']}")

Spot-vs-perp basis arb scanner

python
def tick(ctx):
    # Get top USDT perps
    fut = ctx.bitget.futures_tickers(product_type="USDT-FUTURES")["data"][:30]
    spot_map = {t["symbol"]: float(t["lastPr"])
                for t in ctx.bitget.spot_tickers()["data"]}

    rich = []
    for f in fut:
        sym = f["symbol"]
        if sym not in spot_map:
            continue
        spot = spot_map[sym]
        perp = float(f["lastPr"])
        basis_bps = (perp - spot) / spot * 10000
        rich.append((sym, basis_bps, perp, spot))

    rich.sort(key=lambda x: abs(x[1]), reverse=True)
    for sym, bps, perp, spot in rich[:5]:
        ctx.log.info(f"{sym:12} basis={bps:+.1f} bps  perp={perp}  spot={spot}")

Reference

Bitget v2 endpointSDK methodAuth
GET /api/v2/mix/market/tickersfutures_tickerspublic
GET /api/v2/spot/market/tickersspot_tickerspublic
GET /api/v2/mix/market/candlesfutures_candlespublic
GET /api/v2/spot/market/candlesspot_candlespublic
GET /api/v2/mix/market/merge-depthfutures_orderbookpublic
GET /api/v2/mix/account/accountsfutures_accountsprivate
GET /api/v2/spot/account/assetsspot_assetsprivate
GET /api/v2/mix/position/all-positionfutures_positionsprivate
GET /api/v2/mix/order/orders-pendingfutures_pending_ordersprivate
GET /api/v2/mix/order/orders-historyfutures_orders_historyprivate
POST /api/v2/mix/order/place-orderfutures_place_orderprivate
POST /api/v2/mix/order/cancel-orderfutures_cancel_orderprivate
POST /api/v2/mix/order/close-positionsfutures_close_positionprivate
POST /api/v2/mix/account/set-leveragefutures_set_leverageprivate
POST /api/v2/spot/trade/place-orderspot_place_orderprivate

AiSpinner Documentation