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
- Add a Bitget trading block to your workspace canvas.
- Open the inspector → API Keys → pick a key (Settings → API Keys → Bitget to add new). Bitget requires
api_key+api_secret+passphrase. - Connect the block to your Worker block via an edge.
ctx.bitgetis now available.
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:
| Market | Identifier | Description |
|---|---|---|
| Spot | (no product_type) | BTCUSDT, ETHUSDT, … |
| USDT-margined Futures | USDT-FUTURES | Linear perpetuals, USDT settled |
| USDC-margined Futures | USDC-FUTURES | Linear perpetuals, USDC settled |
| Coin-margined Futures | COIN-FUTURES | Inverse 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):
| Mode | Description |
|---|---|
live | Real funds. Default. |
demo | Paper-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.
ctx.bitget.futures_tickers(
product_type: str = "USDT-FUTURES",
symbol: str = None,
) -> dictReturns: {"code": "00000", "data": [{"symbol", "lastPr", "askPr", "bidPr", "high24h", "low24h", "openUtc", "fundingRate", "indexPrice", "markPrice", "openInterest", "ts", ...}]}
t = ctx.bitget.futures_tickers(symbol="BTCUSDT")
last = float(t["data"][0]["lastPr"])spot_tickers
All spot tickers, or one symbol.
ctx.bitget.spot_tickers(symbol: str = None) -> dictfutures_candles
Futures OHLCV candles.
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,
) -> dictgranularity | Values |
|---|---|
| Sub-hour | "1m", "3m", "5m", "15m", "30m" |
| Hours | "1H", "4H", "6H", "12H" |
| Days+ | "1D", "3D", "1W", "1M" |
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).
ctx.bitget.spot_candles(symbol: str = "BTCUSDT", granularity: str = "1h", limit: int = 200) -> dictfutures_orderbook
Futures order book depth.
ctx.bitget.futures_orderbook(
symbol: str = "BTCUSDT",
product_type: str = "USDT-FUTURES",
limit: int = 20,
) -> dictReturns: {"data": {"asks": [[price, size], ...], "bids": [[price, size], ...], "ts"}}
Account & Wallet
futures_accounts
Futures account balance, equity, available margin, locked margin per margin_coin.
ctx.bitget.futures_accounts(
product_type: str = None, # defaults to block's product_type
margin_coin: str = "USDT",
) -> dictacc = 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.
ctx.bitget.spot_assets(coin: str = None) -> dictPositions
futures_positions
Open futures positions.
ctx.bitget.futures_positions(
product_type: str = None,
margin_coin: str = "USDT",
) -> dictReturns position fields: symbol, holdSide (long / short), total, available, averageOpenPrice, unrealizedPL, liquidationPrice, markPrice, leverage, marginMode, ...
Orders
futures_pending_orders
Active (open) futures orders.
ctx.bitget.futures_pending_orders(
product_type: str = None,
symbol: str = None,
) -> dictfutures_orders_history
Filled, cancelled, or rejected futures orders (recent history).
ctx.bitget.futures_orders_history(
product_type: str = None,
symbol: str = None,
limit: int = 50,
) -> dictfutures_place_order
Place a futures order.
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# 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.
ctx.bitget.futures_cancel_order(
symbol: str,
order_id: str = None,
client_oid: str = None,
product_type: str = None,
) -> dictfutures_close_position
Close a position immediately at market price.
ctx.bitget.futures_close_position(
symbol: str,
hold_side: str = None, # "long" | "short" (hedge mode); omit in one-way
product_type: str = None,
) -> dictfutures_set_leverage
Set leverage on a futures pair (1-125x depending on symbol).
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",
) -> dictspot_place_order
Place a spot order.
ctx.bitget.spot_place_order(
symbol: str,
side: str, # "buy" | "sell"
size,
order_type: str = "market", # "market" | "limit"
price: str = None,
force: str = "gtc",
) -> dictCommon 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
def tick(ctx):
try:
positions = ctx.bitget.futures_positions()
except Exception as e:
ctx.log.error(f"Bitget unreachable: {e}")
returnBitgetAPIError 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
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
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
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 endpoint | SDK method | Auth |
|---|---|---|
GET /api/v2/mix/market/tickers | futures_tickers | public |
GET /api/v2/spot/market/tickers | spot_tickers | public |
GET /api/v2/mix/market/candles | futures_candles | public |
GET /api/v2/spot/market/candles | spot_candles | public |
GET /api/v2/mix/market/merge-depth | futures_orderbook | public |
GET /api/v2/mix/account/accounts | futures_accounts | private |
GET /api/v2/spot/account/assets | spot_assets | private |
GET /api/v2/mix/position/all-position | futures_positions | private |
GET /api/v2/mix/order/orders-pending | futures_pending_orders | private |
GET /api/v2/mix/order/orders-history | futures_orders_history | private |
POST /api/v2/mix/order/place-order | futures_place_order | private |
POST /api/v2/mix/order/cancel-order | futures_cancel_order | private |
POST /api/v2/mix/order/close-positions | futures_close_position | private |
POST /api/v2/mix/account/set-leverage | futures_set_leverage | private |
POST /api/v2/spot/trade/place-order | spot_place_order | private |