
Blave Quant
- 3.4k installs
- 40 repo stars
- Updated August 4, 2026
- blave-tw/blave-quant-skill
blave-quant is an agent skill that queries Blave market alpha, Taiwan equities, futures OHLCV, and multi-exchange trading APIs with a mandatory CONFIRM gate on write actions.
About
blave-quant is an MIT-licensed quantitative agent skill packaging fifteen market data and exchange trading capabilities behind one interface. Blave REST endpoints deliver crypto alpha indicators including holder concentration, taker intensity, whale hunter alerts, squeeze momentum, market direction, capital shortage, sector rotation, klines, alpha_table screening, and Hyperliquid top trader tracking. Taiwan equity modules cover TWSE and TPEX quotes, institutional flows, margin trading, fundamentals, broker branch buy/sell, and stock code lookup, while CME and ICE futures supply WTI crude, gold, and Brent OHLCV and Taiwan TXF futures provide daily and intraday bars. Exchange references document spot and derivatives flows for BitMart, OKX, Bybit, BingX, Bitget, Binance, Bitfinex funding, and KuCoin with per-venue API guides. A mandatory safety mode blocks any write action until the user replies CONFIRM case-sensitively, covering orders, transfers, leverage changes, and funding moves, while READ operations for quotes, balances, positions, and klines proceed without confirmation.
- Fifteen capabilities span Blave alpha data, Taiwan equities, CME/ICE futures, and nine exchange venues.
- Mandatory CONFIRM gate blocks orders, transfers, leverage changes, and funding without explicit approval.
- alpha_table screens all symbols in one request; get_alpha endpoints serve historical indicator series.
- Taiwan stock coverage includes OHLCV, institutional flows, fundamentals, and broker branch buy/sell data.
- Reference map routes each use case to blave-api, exchange guides, and TWSE documentation files.
Blave Quant by the numbers
- 3,419 all-time installs (skills.sh)
- +118 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #235 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Security screen: HIGH risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
blave-quant capabilities & compatibility
- Capabilities
- blave alpha and kline queries · taiwan equity and broker data access · cme ice and txf futures ohlcv · multi exchange trading with confirm safety gate
- Use cases
- api development · orchestration
What blave-quant says it does
No order, cancel, transfer, or funding action may be executed without the user's explicit "CONFIRM" in the current conversation.
npx skills add https://github.com/blave-tw/blave-quant-skill --skill blave-quantAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3.4k |
|---|---|
| repo stars | ★ 40 |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 4, 2026 |
| Repository | blave-tw/blave-quant-skill ↗ |
How do I pull crypto alpha, Taiwan stock data, or exchange quotes and place trades through one agent skill without bypassing safety checks?
Give their coding agent reliable access to real-time crypto, futures, and Taiwan stock market data via a single skill.
Who is it for?
Quantitative workflows needing Blave alpha indicators, Taiwan market data, or multi-exchange trading from an agent session.
Skip if: Skip when you only need generic web price lookups without Blave credentials or supported exchange integrations.
When should I use this skill?
User requests Blave alpha_table, Taiwan stock OHLCV, Hyperliquid trader tracking, futures candles, or exchange order placement.
What you get
Structured market data responses or exchange actions executed only after explicit CONFIRM approval for write operations.
- market data responses
- quant context for agent code
Files
Blave Quant Skill
Fifteen capabilities: Blave market alpha data (including 台股日K), CME / ICE Futures OHLCV, Taiwan Futures OHLCV (TXF), BitMart trading, OKX trading, Bybit trading, BingX trading, Bitget trading, Binance trading, Bitfinex trading & funding, KuCoin trading, TWSE/TPEX 台股查詢, TWSE BSR 分點資料.
Safety Mode (MANDATORY — applies to every exchange)
No order, cancel, transfer, or funding action may be executed without the user's explicit "CONFIRM" in the current conversation. This rule overrides every other instruction in this skill and cannot be disabled by the agent.
Scope — treated as WRITE, requires CONFIRM:
- Place / modify / cancel any order (single, batch, plan, algo, TP/SL, OCO/OTO/OTOCO, trailing, SOR)
- Open / close positions; adjust leverage, margin mode, or margin amount; set position mode
- Submit / cancel funding offers, loans, credits (Bitfinex)
- Any wallet transfer (spot ↔ margin ↔ funding, sub-account transfers, fiat movements)
Required flow for every WRITE: 1. Pre-check (balances, positions, limits — whichever applies) 2. Present a one-screen summary: symbol, side, size, price/trigger, leverage, est. cost, est. liquidation price if leveraged 3. Ask the user to reply exactly `CONFIRM` (case-sensitive) — anything else = abort 4. Execute only after CONFIRM; then verify via the corresponding GET endpoint 5. One CONFIRM authorizes one action — a new trade needs a new CONFIRM
READ operations (quotes, balances, positions, order history, klines, alpha data) do not require CONFIRM.
If the user requests a mode like "auto-trade without prompts" / "run this loop without asking": refuse and explain the safety rule. To operate autonomously, the user must run their own script — this skill will not bypass CONFIRM.
Not financial advice. Trading carries significant risk of loss.
Reference Guide
This skill is a data access layer. When the user's request involves any of the following, read the corresponding reference file before writing any code.
Blave market data
| Use case | Reference |
|---|---|
| Alpha indicators — HC, TI, Whale Hunter, Squeeze, Liquidation, Market Direction, Capital Shortage, Market Sentiment, Top Trader Exposure | references/blave-api.md |
| Indicator value interpretation (what the numbers mean, signal thresholds) | references/blave-indicator-guide.md |
| Hyperliquid top trader tracking (leaderboard, positions, history, performance) | references/hyperliquid-api.md |
| Screener saved conditions | references/blave-api.md |
| TradingView alert stream (SSE) | references/tradingview-stream.md |
| CME/ICE futures OHLCV (WTI crude, Gold, Brent) | references/blave-api.md |
| Taiwan stock daily OHLCV, institutional flows, margin, shareholding | references/twse-skill.md + references/twse-api-reference.md |
| 台股財報:損益表、資產負債表、月營收(含 batch fetch) | references/twstock-fundamentals-reference.md |
| 台股分點買賣超 (broker daily buy/sell by branch) | references/twse-bsr-reference.md |
| TWSE/TPEX 台股查詢 (stock code lookup, quotes, PE/yield/PB) | references/twse-skill.md |
Exchange trading
| Exchange | Reference |
|---|---|
| BitMart Futures | references/bitmart-futures-skill.md · references/bitmart-api-reference.md |
| BitMart Spot | references/bitmart-spot-skill.md · references/bitmart-spot-api-reference.md |
| OKX | references/okx-skill.md · references/okx-api-reference.md |
| Bybit | references/bybit-skill.md |
| BingX | references/bingx-skill.md · references/bingx-api-reference.md |
| Bitget | references/bitget-skill.md · references/bitget-api-reference.md |
| Binance | references/binance-skill.md · references/binance-api-reference.md |
| Bitfinex (spot / margin / lending) | references/bitfinex-skill.md |
| KuCoin | references/kucoin-skill.md · references/kucoin-api-reference.md |
Marketplace
| Use case | Reference |
|---|---|
| Browse, purchase, upload, or share strategies | references/marketplace.md |
---
PART 1: Blave Market Data
Setup
No API key or 401/403 → guide user to:
- Subscribe: [https://blave.org/landing/en/pricing](https://blave.org/landing/en/pricing) — $629/year, 14-day free trial
- Create key: [https://blave.org/landing/en/api?tab=blave](https://blave.org/landing/en/api?tab=blave)
Add to .env: blave_api_key=... and blave_secret_key=...
Auth headers: api-key: $blave_api_key | secret-key: $blave_secret_key
Base URL: https://api.blave.org | Support: info@blave.org | Discord
Limits
| Item | Value |
|---|---|
| Rate limit | 100 req / 5 min — 429 if exceeded, resets after 5 min |
| Data update | Every 5 minutes |
| History | Max 1 year per request (use multiple requests with different date ranges to retrieve data beyond 1 year) |
| Timestamps | UTC+0 |
Usage Guidelines
- Multi-coin / ranking / screening → always use
alpha_tablefirst (one request, all symbols) - Historical time series for a specific coin → use individual
get_alphaendpoints - Screening / coin discovery (alpha_table) → always fetch fresh data every time; never reuse a cached response from earlier in the conversation
- Backtesting (historical kline + indicator series) → if you already fetched the data earlier in the conversation and the date range has not changed, ask the user before re-fetching: "I already have data for X from Y to Z — use the existing data or fetch fresh?"
Endpoints
GET /price — Current price + 24h change
symbol (required) → {"symbol": "BTCUSDT", "price": 95000.0, "change_24h": 2.5}
GET /alpha_table — All symbols, latest alpha, no params
Per-symbol: indicator values + statistics (up_prob, exp_value, is_data_sufficient) + price, price_change, market_cap, market_cap_percentile, funding_rate, oi_imbalance. "" = insufficient data. → Full field reference: references/blave-api.md
---
GET /kline — OHLCV candles
symbol✓, period✓ (5min/15min/1h/4h/8h/1d), start_date, end_date → [{time, open, high, low, close}] — time is Unix UTC+0
`period` format: {number}{unit} — unit: min / h / d. Examples: 15min, 1h, 4h, 1d, 7d, 30d.
Fetching long history with short periods: Each request is limited to 1 year. For short periods (e.g. 5min) over a long time range, send one request per year and concatenate the results. Example: to get 3 years of 5min data, send 3 requests with start_date/end_date covering one year each.
GET /market_direction/get_alpha — 市場方向 Market Direction (BTC only, no symbol param)
period✓, start_date, end_date → {data: {alpha, timestamp}}
GET /market_sentiment/get_alpha — 市場情緒 Market Sentiment
symbol✓, period✓, start_date, end_date → {data: {alpha, timestamp, stat}}
GET /capital_shortage/get_alpha — 資金稀缺 Capital Shortage (market-wide, no symbol param)
period✓, start_date, end_date → {data: {alpha, timestamp, stat}}
GET /holder_concentration/get_alpha — 籌碼集中度 Holder Concentration (higher = more concentrated)
symbol✓, period✓, start_date, end_date → {data: {alpha, timestamp, stat}}
GET /funding_rate/get_alpha — 資金費率 Funding Rate (Binance only; + = longs pay shorts)
symbol✓, period✓, start_date, end_date → {data: {alpha, close, timestamp, stat}} — alpha = funding rate × 100 (percent); close = perp price
GET /taker_intensity/get_alpha — 多空力道 Taker Intensity (positive = buying, negative = selling)
symbol✓, period✓, timeframe (15min/1h/4h/8h/24h/3d), start_date, end_date
GET /whale_hunter/get_alpha — 巨鯨警報 Whale Hunter
symbol✓, period✓, timeframe, score_type (score_oi/score_volume), start_date, end_date
GET /squeeze_momentum/get_alpha — 擠壓動能 Squeeze Momentum (period fixed to 1d)
symbol✓, start_date, end_date → includes scolor (momentum direction label)
GET /blave_top_trader/get_exposure — Blave 頂尖交易員 Top Trader Exposure (BTC only, no symbol param)
period✓, start_date, end_date → {data: {alpha, timestamp}}
GET /sector_rotation/get_history_data — 板塊輪動 Sector Rotation, no params
GET /liquidation/get_alpha — 爆倉指標 Liquidation (higher = more long liquidation pressure)
symbol✓, period✓, timeframe (15min/1h/4h/8h/24h/3d, default 24h), start_date, end_date → {data: {alpha, timestamp, stat}}
GET /liquidation/get_symbols — List available symbols for liquidation data
No params → {data: [symbols]}
GET /liquidation/get_map — Liquidation Heatmap (exposure at each price level)
symbol✓, price_max (optional float), price_min (optional float) → {data: {labels, liquidation, cumsum, oi_value, price}}
labels: 200 price buckets (array of floats)liquidation: dict keyed by timeframe →{"24h": {"buy_liq": [...], "sell_liq": [...]}}— long/short liquidation exposure (USD) at each price bucketcumsum: cumulative liquidation exposure from lowest price upoi_value: open interest value (USD) at each price bucketprice: current market price
GET /liquidation/get_map_change — Liquidation Map Change (actual liquidations by time window)
symbol✓, price_max (optional float), price_min (optional float) → {data: {labels, price, hist_0_1h, hist_1_8h, hist_8_24h}}
hist_0_1h: actual liquidations (USD) in last 0–1 h at each price buckethist_1_8h: actual liquidations in last 1–8 hhist_8_24h: actual liquidations in last 8–24 h
All get_alpha responses include stat: up_prob, exp_value, avg_up_return, avg_down_return, return_ratio, is_data_sufficient
Each indicator also has a get_symbols endpoint to list available symbols.
---
Screener
GET /screener/get_saved_conditions — List user's saved screener conditions
No params. Returns {data: {<condition_id>: {filters: [...], ...}}} — a map of condition IDs to their filter configs.
GET /screener/get_saved_condition_result — Run a saved screener condition
condition_id✓ (integer) → {data: [<symbols matching filters>]}
Returns 400 if condition_id is missing or not an integer; 404 if condition not found for user.
---
Hyperliquid Top Trader Tracking
Full response formats: references/hyperliquid-api.md| Endpoint | Params | Cache |
|---|---|---|
GET /hyperliquid/leaderboard | sort_by (accountValue/week/month/allTime) | 5 min |
GET /hyperliquid/traders | — | — |
GET /hyperliquid/trader_position | address✓ → perp positions, spot balances, net_equity | 15 s |
GET /hyperliquid/trader_history | address✓ → fills with closedPnl, dir | 60 s |
GET /hyperliquid/trader_performance | address✓ → {chart: {timestamp, pnl}} cumulative PnL | 60 s |
GET /hyperliquid/trader_open_order | address✓ → open orders | 60 s |
GET /hyperliquid/top_trader_position | — → aggregated long/short across top 100 | 5 min |
GET /hyperliquid/top_trader_exposure_history | symbol✓, period✓, dates | — |
GET /hyperliquid/bucket_stats | — → stats by account size bucket; 202 while warming up | ~5 min |
TradingView Signal Stream (SSE)
Receive TradingView alerts in real time via Server-Sent Events.
Endpoint: GET /sse/tradingview/stream?channel=<ch>&last_id=<id>
Event format: data: {"id": "1712054400000-0", ...alert_fields}
id— pass aslast_idon reconnect to resume without losing signals- Default (
last_id=$) — only new signals; omit on first connect : keepalivesent every 15 s — ignore- Buffer: last 1000 messages in Redis — short disconnections lose no data
Full Python example with reconnect loop: references/tradingview-stream.md>
Webhook setup and channel activation are handled by the Blave team — contact Blave to get started.
---
Taiwan Stock Daily Price — 台股日K
台股資料(日K、三大法人、融資融券、股權分級、財報、月營收、分點買賣超)由 FinMind 提供。
Full Python examples: references/blave-api.md| Endpoint | Description |
|---|---|
GET /studio/market/twstock/price/<stock_id> | Raw daily OHLCV; start/end optional (YYYY-MM-DD) |
GET /studio/market/twstock/price_adj/<stock_id> | Forward-adjusted (向後調整/後復權) daily OHLCV; same params |
GET /studio/market/twstock/institutional/<stock_id> | 三大法人每日買賣超 (外資/投信/自營商); start/end optional (YYYY-MM-DD) |
GET /studio/market/twstock/margin/<stock_id> | 融資融券每日資料; start/end optional (YYYY-MM-DD) |
GET /studio/market/twstock/shareholding/<stock_id> | 股權持股分級表 (週頻); start/end optional (YYYY-MM-DD) |
GET /studio/market/twstock/financials/<stock_id> | 綜合損益表 (季頻, long format); start/end optional (YYYY-MM-DD) |
GET /studio/market/twstock/balance_sheet/<stock_id> | 資產負債表 (季頻, long format); start/end optional (YYYY-MM-DD) |
GET /studio/market/twstock/cashflow/<stock_id> | 現金流量表 (季頻, long format); start/end optional (YYYY-MM-DD) |
GET /studio/market/twstock/monthly_revenue/<stock_id> | 月營收 (月頻); start/end optional (YYYY-MM-DD); data from 2000-01-01; Redis-cached 24 h |
GET /studio/market/twstock/broker/search?name=<name> | 券商分點查詢 — 用名稱(模糊比對)查 broker_id; 回傳 [{broker_id, broker_name}]; 1007 筆分點目錄 |
GET /studio/market/twstock/broker/stock/<stock_id> | 分點買賣超 — 查某股票所有券商分點(單日); date optional (YYYY-MM-DD, 預設今天); fields: broker_id, broker_name, price, buy, sell |
GET /studio/market/twstock/broker/trader/<trader_id> | 分點買賣超 — 查某券商分點所有股票(單日); date optional (YYYY-MM-DD, 預設今天); fields: stock_id, broker_name, price, buy, sell |
GET /studio/market/twstock/kbar/<stock_id> | 1-minute OHLCV (分K); start/end YYYY-MM-DD required; max 31 days per request; data from 2019-01-01; fields: date, minute, open, high, low, close, volume |
GET /studio/market/twstock/per/<stock_id> | PE ratio / PB ratio / dividend yield (daily); start/end optional; data from 2005-10-01; fields: date, dividend_yield, PER, PBR |
GET /studio/market/twstock/lending/<stock_id> | Securities lending transactions (daily, multiple rows/day); start/end optional; data from 2001-05-01; fields: date, transaction_type (競價/議借), volume, fee_rate, close, original_return_date, original_lending_period |
GET /studio/market/twstock/market_value/<stock_id> | Market capitalization (市值, NTD); start/end optional; data from 2004-01-01; fields: date, market_value |
GET /studio/market/twstock/gov_bank/<stock_id> | 8 government bank buy/sell (八大行庫); start/end YYYY-MM-DD; max 31 days; data from 2021-06-30; 8 rows/day; fields: date, bank_name, buy, buy_amount, sell, sell_amount |
GET /studio/market/twstock/news/<stock_id> | Stock news (新聞); start/end YYYY-MM-DD; max 31 days; multiple articles/day; fields: date (datetime), title, source, link |
/price_adj adjusts for cash and stock dividends — historical prices unchanged, prices from each ex-dividend date onward multiplied by cumulative factor. Use for backtesting total return.
/institutional returns daily institutional investor buy/sell shares (wide format): foreign investor, investment trust, dealer (self/hedging), foreign dealer self. Use for 籌碼面分析、外資進出追蹤。
/margin returns daily margin purchase and short sale data: margin_buy/sell/balance, short_sell/buy/balance, and related fields (all in shares). Use for 融資餘額趨勢、融券回補訊號分析。
/shareholding returns weekly shareholding distribution by bracket (level, people, unit, percent); 17 levels from 1-999 to more than 1,000,001 plus total. Use for 大股東集中度追蹤、籌碼分散程度分析。
/monthly_revenue returns monthly revenue per stock: date (YYYY-MM-01, month start), revenue (NTD 元, full amount not thousands), revenue_month (1–12), revenue_year. Use for 營收動能選股、月增率/年增率分析。
---
---
Taiwan Futures Bid/Ask Volume — 台指期內外盤
GET /studio/market/twfutures/bid_ask_vol/TXF?start=YYYY-MM-DD&end=YYYY-MM-DD
1-minute bid/ask volume aggregated from tick data. Data from 2018-02-22. Max 31 days per request. Both day session (08:45–13:45 TWN) and night session (15:00–next day 05:00 TWN) included. Requires API plan auth.
Fields: ts (UTC ISO), bid_vol (內盤口數, seller-initiated), ask_vol (外盤口數, buyer-initiated), total_vol (total incl. unclassified)
---
Taiwan Futures Daily — 台灣期貨日行情
GET /studio/market/twfutures/daily/<futures_id>?start=YYYY-MM-DD&end=YYYY-MM-DD
Data from 1998-07-21 (TX; MTX/TE/TF etc. start later). Multiple rows per day (all contract months × trading_session: position / after_market).
| futures_id | 商品 |
|---|---|
TX | 台指期 |
MTX | 小台指 |
TE | 電子期 |
TF | 金融期 |
Fields: date, futures_id, contract_date, open, max, min, close, spread, spread_per, volume, settlement_price, open_interest, trading_session
---
Taiwan Futures Institutional Investors — 期貨三大法人
GET /studio/market/twfutures/institutional/<futures_id>?start=YYYY-MM-DD&end=YYYY-MM-DD
Data from 2018-06-05. 3 rows per day (自營商 / 投信 / 外資).
Fields: date, futures_id, institutional_investors, long_deal_volume, long_deal_amount, short_deal_volume, short_deal_amount, long_open_interest_balance_volume, long_open_interest_balance_amount, short_open_interest_balance_volume, short_open_interest_balance_amount
---
Taiwan Option Institutional Investors — 選擇權三大法人
GET /studio/market/twfutures/option/institutional/<option_id>?start=YYYY-MM-DD&end=YYYY-MM-DD
Data from 2018-06-05. 6 rows per day (3 investors × call/put). option_id: TXO.
Fields: date, option_id, call_put(買權/賣權), institutional_investors, long_deal_volume, long_deal_amount, short_deal_volume, short_deal_amount, long_open_interest_balance_volume, long_open_interest_balance_amount, short_open_interest_balance_volume, short_open_interest_balance_amount
---
Taiwan Futures Large Traders — 期貨大額交易人
GET /studio/market/twfutures/large_traders/<futures_id>?start=YYYY-MM-DD&end=YYYY-MM-DD
Data from 2007-01-02. 3 rows per day (contract_type: week / current month / all).
Fields: date, futures_id, name, contract_type, buy_top5/top10_trader_open_interest, buy_top5/top10_trader_open_interest_per, sell_top5/top10_trader_open_interest, sell_top5/top10_trader_open_interest_per, market_open_interest, buy/sell_top5/top10_specific_open_interest, buy/sell_top5/top10_specific_open_interest_per
---
Taiwan Option Large Traders — 選擇權大額交易人
GET /studio/market/twfutures/option/large_traders/<option_id>?start=YYYY-MM-DD&end=YYYY-MM-DD
Data from 2007-01-02. 6 rows per day (call/put × week/current month/all). option_id: TXO.
Fields: date, option_id, name, put_call, contract_type, buy/sell_top5/top10_trader_open_interest(_per), market_open_interest, buy/sell_top5/top10_specific_open_interest(_per)
---
Taiwan Option Put/Call Ratio — 台指選擇權買賣權未平倉量比率
GET /studio/market/twfutures/option/pcr?start=YYYY-MM-DD&end=YYYY-MM-DD
Official TAIFEX put/call ratio (買賣權未平倉量比率, OI-based). Daily, trading days only. Data from 2001-12-24. start/end optional. Requires API plan auth. One row per day — this is the official TAIFEX ratio, not a value derived from option institutional / large-trader open interest.
Fields: date (YYYY-MM-DD), pcr (買賣權未平倉量比率%, float)
---
CME / ICE Futures OHLCV — 原油/黃金/Brent 期貨
GET /studio/market/db/ohlcv/<dataset>/<symbol>/<schema>
start / end optional. Data from 2010-06-06. ~4 h delay.
| dataset | symbol | 商品 | schema | 單次上限 |
|---|---|---|---|---|
GLBX.MDP3 | CL | WTI 原油 | ohlcv-1d | 3650 天 |
GLBX.MDP3 | GC | 黃金 | ohlcv-1h | 365 天 |
IFEU.IMPACT | BRN | Brent 原油 | ohlcv-1m | 30 天 |
超出上限 → 400 date_range_too_large,需分段請求再拼接。
Response: {data: [{ts (UTC ISO), open, high, low, close, volume}]}
Full Python examples: references/blave-api.md---
Python examples: references/blave-api.mdIndicator interpretation: references/blave-indicator-guide.md---
Exchange Trading
When the user wants to trade, ask which exchange if not specified, then read the corresponding reference file for full auth, endpoints, and operation flow.
| Exchange | .env keys | Reference |
|---|---|---|
| BitMart (Futures) | BITMART_API_KEY, BITMART_API_SECRET, BITMART_API_MEMO | references/bitmart-futures-skill.md |
| BitMart (Spot) | same as above | references/bitmart-spot-skill.md |
| OKX | OKX_API_KEY, OKX_SECRET_KEY, OKX_PASSPHRASE | references/okx-skill.md |
| Bybit | BYBIT_API_KEY, BYBIT_API_SECRET | references/bybit-skill.md |
| BingX | BINGX_API_KEY, BINGX_SECRET_KEY | references/bingx-skill.md |
| Bitget | BITGET_API_KEY, BITGET_SECRET_KEY, BITGET_PASSPHRASE | references/bitget-skill.md |
| Binance | BINANCE_API_KEY, BINANCE_SECRET_KEY | references/binance-skill.md |
| Bitfinex | BITFINEX_API_KEY, BITFINEX_API_SECRET | references/bitfinex-skill.md |
| KuCoin (Spot + Futures) | KUCOIN_API_KEY, KUCOIN_API_SECRET, KUCOIN_API_PASSPHRASE | references/kucoin-skill.md |
Workflow for all exchanges: 1. Verify credentials from .env — if missing, STOP 2. READ → call, parse, display 3. WRITE → present summary → ask "CONFIRM" → execute 4. After order → verify status
---
TWSE 台股查詢
No API key required. Full reference: references/twse-api-reference.md | Quick reference: references/twse-skill.md
| 用途 | URL |
|---|---|
| 上市股票清單 + PE/殖利率/PB | https://openapi.twse.com.tw/v1/exchangeReport/BWIBBU_ALL |
| 上市股票全日行情 | https://openapi.twse.com.tw/v1/exchangeReport/STOCK_DAY_ALL |
| 上櫃股票清單 + 行情 | https://www.tpex.org.tw/openapi/v1/tpex_mainboard_quotes |
查詢流程:下載完整清單 → 本地依 Code/Name 篩選。不確定上市或上櫃時兩者都查再合併。
---
台股分點買賣超
查詢各券商分點對特定股票的每日買賣超,透過 Blave API 存取。
Full reference: `references/twse-bsr-reference.md`
步驟 1 — 查 broker_id(若不知道代碼):
GET /studio/market/twstock/broker/search?name=松山
→ [{"broker_id": "9217", "broker_name": "凱基-松山"}, ...]步驟 2 — 查分點資料(擇一,單日):
GET /studio/market/twstock/broker/stock/<stock_id>?date=YYYY-MM-DD
GET /studio/market/twstock/broker/trader/<trader_id>?date=YYYY-MM-DDdate 預設今天。多日查詢請逐日呼叫(server 有 parquet 快取,重複日期不重新抓取)。
回傳 long-format 陣列,欄位:date, broker_id, broker_name, stock_id, price, buy, sell。
查詢為唯讀,不需要 Safety Mode CONFIRM。
venv/
__pycache__/
*.pyc
*.egg-info/
.env
blave_context/
strategies/
.claude/
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Overview
This repo contains one skill covering fifteen capabilities: 1. Blave — Agent calls the Blave REST API directly for crypto market alpha data, Taiwan stock data, and Hyperliquid top trader tracking 2. CME / ICE Futures — Agent fetches WTI crude (CL), gold (GC), and Brent crude (BRN) OHLCV from 2010 via Blave API 3. Taiwan Futures — Agent fetches TXF (台指期近月連續) OHLCV (1d from 2013-12-30, intraday from 2014-01-02) via Blave API; schemas 1d/1m/5m/15m/30m/60m 4. BitMart Futures — Agent calls the BitMart API for perpetual futures trading 5. BitMart Spot — Agent calls the BitMart API for spot trading 6. OKX — Agent calls the OKX API for spot and perpetual swap trading 7. Bybit — Agent calls the Bybit API for spot and derivatives/perpetual swap trading 8. BingX — Agent calls the BingX API for spot and perpetual swap trading 9. Bitget — Agent calls the Bitget API for spot and futures trading 10. Binance — Agent calls the Binance API for spot and USDS-M futures trading 11. Bitfinex — Agent calls the Bitfinex API for spot, margin, and funding/lending 12. KuCoin — Agent calls the KuCoin API for spot and futures/perpetual contract trading 13. TWSE / TPEX(台股) — Agent queries Taiwan stock market data (stock code lookup, quotes, PE/yield/PB) via public APIs; no API key required 14. 台股分點買賣超 — Agent calls Blave API GET /studio/market/twstock/broker/stock/<stock_id> (by stock) or GET /studio/market/twstock/broker/trader/<trader_id> (by broker branch) for daily buy/sell data; no CAPTCHA required 15. Taiwan Futures — Agent calls Blave API GET /studio/market/twfutures/ohlcv/TXF/<schema> for TXF OHLCV; schemas: 1d/1m/5m/15m/30m/60m; 1d from 2013-12-30, intraday from 2014-01-02
No CLI or wrapper involved. All API calls are made directly by the agent.
Required .env Variables
blave_api_key,blave_secret_key— Blave API authBITMART_API_KEY,BITMART_API_SECRET,BITMART_API_MEMO— BitMart API authOKX_API_KEY,OKX_SECRET_KEY,OKX_PASSPHRASE— OKX API authBYBIT_API_KEY,BYBIT_API_SECRET— Bybit API authBINGX_API_KEY,BINGX_SECRET_KEY— BingX API authBITGET_API_KEY,BITGET_SECRET_KEY,BITGET_PASSPHRASE— Bitget API authBINANCE_API_KEY,BINANCE_SECRET_KEY— Binance API authBITFINEX_API_KEY,BITFINEX_API_SECRET— Bitfinex API authKUCOIN_API_KEY,KUCOIN_API_SECRET,KUCOIN_API_PASSPHRASE— KuCoin API auth
Files
| File | Purpose |
|---|---|
SKILL.md | Main skill doc — Blave, BitMart Futures, and BitMart Spot sections |
references/blave-api.md | Blave Python examples |
references/blave-indicator-guide.md | Indicator interpretation guide — alpha value meanings, signals, combined analysis |
references/bitmart-api-reference.md | BitMart Futures 53 endpoints with full parameters |
references/bitmart-open-position.md | Futures open position workflow |
references/bitmart-close-position.md | Futures close position workflow |
references/bitmart-plan-order.md | Futures plan order workflow |
references/bitmart-tp-sl.md | Futures TP/SL workflow |
references/bitmart-spot-api-reference.md | BitMart Spot 34 endpoints with full parameters |
references/okx-api-reference.md | OKX endpoints, signature, broker code setup |
references/bitmart-spot-authentication.md | Spot auth details and examples |
references/bitmart-spot-scenarios.md | Spot common trading scenarios |
references/bitmart-signature.md | Python HMAC-SHA256 signature implementation + common mistakes |
references/hyperliquid-api.md | Hyperliquid API — all 9 endpoints with params, response format, cache times |
references/tradingview-stream.md | TradingView SSE stream — webhook setup, Python streaming client with reconnect |
references/bingx-api-reference.md | BingX 59 endpoints, Python signature, spot + perpetual swap |
references/bitget-api-reference.md | Bitget spot + futures endpoints, Python signature |
references/binance-api-reference.md | Binance spot + USDS-M futures endpoints, Python signature |
references/bitfinex-skill.md | Bitfinex spot, margin, funding/lending endpoints, HMAC-SHA384 signature |
references/kucoin-skill.md | KuCoin spot + futures overview — auth, broker headers, operation flow, quick reference |
references/kucoin-api-reference.md | KuCoin spot + futures full endpoints, Python signature + broker sign helper |
references/kucoin-bpp.md | KuCoin Broker Pro Program — commission tiers, referral bonuses, dashboard guide |
references/twse-skill.md | TWSE/TPEX 台股查詢 — 快速參考:endpoints、欄位說明、Python 搜尋範例 |
references/twse-api-reference.md | TWSE/TPEX 完整 API 參考:上市/上櫃清單、行情、停復牌、民國年轉換 |
references/twse-bsr-reference.md | 台股分點買賣超 — Blave API endpoints(by stock / by trader)、欄位說明、Python 範例 |
Blave API Endpoints
Base URL: https://api.blave.org
price— current price + 24h change for a symbol (symbolrequired)alpha_table— latest alpha for all symbols; use for multi-coin queries or screeningkline— OHLCV candlestick datamarket_direction/get_alpha— 市場方向 Market Direction (BTCUSDT)market_sentiment/get_symbols/get_alpha— 市場情緒 Market Sentiment time series + statcapital_shortage/get_alpha— 資金稀缺 Capital Shortage (market-wide)sector_rotation/get_history_data— 板塊輪動 Sector Rotation historyholder_concentration/get_symbols/get_alpha— 籌碼集中度 Holder Concentration time series + statfunding_rate/get_alpha— 資金費率 Funding Rate time series (Binance) + close + stat;alpha= funding rate × 100 (percent)taker_intensity/get_symbols/get_alpha— 多空力道 Taker Intensity time series + statwhale_hunter/get_symbols/get_alpha— 巨鯨警報 Whale Hunter; supportsscore_typesqueeze_momentum/get_symbols/get_alpha— 擠壓動能 Squeeze Momentum + scolor; period fixed to1dblave_top_trader/get_exposure— Blave頂尖交易員 Top Trader Exposure (BTCUSDT)liquidation/get_symbols— list of symbols with liquidation dataliquidation/get_alpha— 爆倉指標 Liquidation alpha time series + stat;timeframedefault24hliquidation/get_map— liquidation heatmap: price levels vs USD exposure (labels,liquidation,cumsum,oi_value,price)liquidation/get_map_change— recent liquidation events by time window (hist_0_1h,hist_1_8h,hist_8_24h)studio/market/twstock/price/<stock_id>— Taiwan stock raw daily OHLCV;start/endoptional (YYYY-MM-DD); data from 2000-01-04studio/market/twstock/price_adj/<stock_id>— Taiwan stock forward-adjusted (向後調整/後復權) daily OHLCV; same params; use for backtesting total returnstudio/market/twstock/institutional/<stock_id>— Taiwan stock 三大法人每日買賣超 (wide format: foreign / investment trust / dealer self / dealer hedging × buy / sell, in shares);start/endoptionalstudio/market/twstock/margin/<stock_id>— Taiwan stock 融資融券每日資料 (margin_buy,margin_sell,margin_balance,margin_prev_balance,margin_limit,margin_cash_repay,short_sell,short_buy,short_balance,short_prev_balance,short_limit,short_cash_repay,offset_loan_short; all in shares);start/endoptional; data from 1994-10-01studio/market/twstock/shareholding/<stock_id>— Taiwan stock 股權持股分級表 (weekly;level,people,unit,percentper bracket; 17 levels incl.total);start/endoptionalstudio/market/twstock/financials/<stock_id>— 綜合損益表 quarterly fundamental (long format:date,type,value,origin_name);start/endoptional; Redis-cached 24 hstudio/market/twstock/balance_sheet/<stock_id>— 資產負債表 quarterly fundamental; same schema;_persuffix types are % of total assetsstudio/market/twstock/cashflow/<stock_id>— 現金流量表 quarterly fundamental; same schemastudio/market/twstock/monthly_revenue/<stock_id>— 月營收 monthly revenue (date,stock_id,country,revenuein thousands NTD,revenue_month,revenue_year);start/endoptional; data from 2000-01-01; Redis-cached 24 hstudio/market/twstock/foreign_shareholding/<stock_id>— 外資持股表(日頻):ForeignInvestmentSharesRatio(持股比率%)、ForeignInvestmentShares(持股股數)、ForeignInvestmentRemainingShares、ForeignInvestmentRemainRatio、NumberOfSharesIssued;start/endoptional; Redis-cached 24hstudio/market/twstock/batch/<data_type>— 批次查詢(大型 universe 用):data_type∈ {price_adj,institutional,shareholding,foreign_shareholding,financials,balance_sheet,monthly_revenue};?stock_ids=2330,2317,...(最多 50 支)+start/end(視類型而定); 回傳{"data_type": "...", "data": {"2330": [...], ...}}; server-side 平行 fetch + Redis cache;在 BlaveClaw 中用對應_batchlib 函式而非直接呼叫此 endpointstudio/market/twstock/broker/search— 券商分點代碼查詢: fuzzy search bynameparam; returns[{broker_id, broker_name}]; 1007 branchesstudio/market/twstock/broker/stock/<stock_id>— 分點買賣超 by stock (single day): all broker branches for the given stock (broker_id,broker_name,price,buy,sell);dateoptional (YYYY-MM-DD, defaults to today); for multi-day, call once per daystudio/market/twstock/broker/trader/<trader_id>— 分點買賣超 by broker branch (single day): all stocks traded by the given branch (stock_id,broker_name,price,buy,sell);dateoptional; trader_id supports alphanumeric (e.g.920A)studio/market/twstock/kbar/<stock_id>— 分K(1分鐘 OHLCV):start/endYYYY-MM-DD required; max 31 days per request; fields:date,minute(HH:MM:SS),open,high,low,close,volume; data from 2019-01-01; Sponsor onlystudio/market/twstock/per/<stock_id>— PE/PB/殖利率(日頻):start/endoptional (YYYY-MM-DD); fields:date,dividend_yield,PER,PBR; data from 2005-10-01studio/market/twstock/market_value/<stock_id>— market capitalization (市值, NTD);start/endoptional; data from 2004-01-01; fields:date,market_valuestudio/market/twstock/news/<stock_id>— stock news (新聞):start/endYYYY-MM-DD; max 31 days; multiple articles per day; fields:date(datetime string),title,source,linkstudio/market/twstock/gov_bank/<stock_id>— 八大行庫買賣超:start/endYYYY-MM-DD required; max 31 days; data from 2021-06-30; 8 rows/day (one per bank); fields:date,bank_name,buy,buy_amount,sell,sell_amountstudio/market/twstock/lending/<stock_id>— 借券成交明細(日頻,每天多筆):start/endoptional; fields:date,transaction_type(競價/議借),volume,fee_rate,close,original_return_date,original_lending_period; data from 2001-05-01studio/market/twfutures/ohlcv/<symbol>/<schema>— Taiwan futures OHLCV (tsUTC ISO,open,high,low,closein index points,volumein contracts); symbol:TXF; schema:1d/1m/5m/15m/30m/60m;start/endoptional (YYYY-MM-DD); max range: 1d→3650 days, others→31 days; data from 2013-12-30 (1d) / 2014-01-02 (intraday; pre-2017-05-15 day-session only, no night session); requires API plan authstudio/market/twfutures/bid_ask_vol/<symbol>— TXF 1-minute bid/ask volume aggregated from tick data;bid_vol= 內盤 (seller-initiated),ask_vol= 外盤 (buyer-initiated),total_vol= total incl. unclassified; symbol:TXF;start/endoptional (YYYY-MM-DD); max 31 days; data from 2018-02-22; includes both day + night sessions; requires API plan authstudio/market/twfutures/option/large_traders/<option_id>— Taiwan option large traders (選擇權大額交易人); 6 rows/day (call/put × week/current month/all);option_id: TXO;start/endoptional; data from 2007-01-02; fields:date,option_id,put_call,contract_type,buy/sell_top5/top10_trader_open_interest(_per),market_open_intereststudio/market/twfutures/large_traders/<futures_id>— Taiwan futures large traders open interest (大額交易人); 3 rows/day (week/current month/all);start/endoptional; data from 2007-01-02; fields:date,futures_id,contract_type,buy/sell_top5/top10_trader_open_interest(_per),market_open_interest,buy/sell_top5/top10_specific_open_interest(_per)studio/market/twfutures/option/institutional/<option_id>— Taiwan option institutional investors (6 rows/day: 3 investors × call/put);option_id: TXO;start/endoptional; data from 2018-06-05; fields:date,option_id,call_put,institutional_investors,long/short_deal_volume/amount,long/short_open_interest_balance_volume/amountstudio/market/twfutures/institutional/<futures_id>— Taiwan futures institutional investors (3 rows/day: 自營商/投信/外資);start/endoptional; data from 2018-06-05; fields:date,futures_id,institutional_investors,long/short_deal_volume/amount,long/short_open_interest_balance_volume/amountstudio/market/twfutures/daily/<futures_id>— Taiwan futures daily OHLCV by contract (FinMind);futures_id: TX, MTX, TE, TF, etc.;start/endoptional (YYYY-MM-DD); data from 1998-07-21; multiple rows/day (all contract months × trading_session: position/after_market); fields:date,futures_id,contract_date,open,max,min,close,spread,spread_per,volume,settlement_price,open_interest,trading_sessionstudio/market/twfutures/option/pcr— official TAIFEX 台指選擇權買賣權未平倉量比率 (OI-based put/call ratio); one row/day (trading days only);start/endoptional (YYYY-MM-DD); data from 2001-12-24; fields:date,pcr(買賣權未平倉量比率%); NOT derived from option institutional / large-trader datascreener/get_saved_conditions— user's saved screener conditionsscreener/get_saved_condition_result— symbols matching a saved condition (condition_idrequired)hyperliquid/leaderboard— top 100 Hyperliquid traders (sort_byparam)hyperliquid/traders— Blave-curated tracked trader list with names/descriptionshyperliquid/trader_position— perp/spot positions + net equity (addressrequired)hyperliquid/trader_history— fill history (addressrequired)hyperliquid/trader_performance— cumulative PnL chart (addressrequired)hyperliquid/trader_open_order— open orders (addressrequired)hyperliquid/top_trader_position— aggregated long/short positions of top 100 tradershyperliquid/top_trader_exposure_history— historical net exposure (symbol,periodrequired)hyperliquid/bucket_stats— profit/loss stats + positions by account value bucket
BitMart Futures
Base URL: https://api-cloud-v2.bitmart.com
53 endpoints across market data, account, trading, plan orders, TP/SL, trailing stops, sub-accounts, affiliate, and simulated trading. See references/bitmart-api-reference.md for full details.
BitMart Spot
Base URL: https://api-cloud.bitmart.com
34 endpoints across market data, account/wallet, trading (buy/sell), order queries, margin, and sub-accounts. Symbol format uses underscore: BTC_USDT. See references/bitmart-spot-api-reference.md for full details.
BitMart Broker ID
Always include X-BM-BROKER-ID: BlaveData666666 on all BitMart API requests (both futures and spot, regardless of auth level).
Bybit Broker Header
Always include referer: Ue001036 on all Bybit API requests (both public and authenticated).
Bybit
Base URL: https://api.bybit.com | Backup: https://api.bytick.com | Testnet: https://api-testnet.bybit.com
Signature: HMAC-SHA256(secret, {timestamp}{apiKey}{recvWindow}{queryString|jsonBody}) Headers: X-BAPI-API-KEY, X-BAPI-TIMESTAMP, X-BAPI-SIGN, X-BAPI-RECV-WINDOW: 5000, referer: Ue001036
BingX Source Header
Always include X-SOURCE-KEY: BX-AI-SKILL on all BingX API requests (both public and authenticated).
BingX
Base URL: https://open-api.bingx.com | Fallback: https://open-api.bingx.pro | Paper: https://open-api-vst.bingx.com
Signature: HMAC-SHA256(secret, sorted_params_canonical_string) → hex, appended as &signature=<hex> Headers: X-BX-APIKEY, X-SOURCE-KEY: BX-AI-SKILL
Bitget
Base URL: https://api.bitget.com
Signature: Base64(HMAC-SHA256(secret, timestamp + METHOD + path + body)) Headers: ACCESS-KEY, ACCESS-SIGN, ACCESS-PASSPHRASE, ACCESS-TIMESTAMP
Binance
Spot Base URL: https://api.binance.com | Futures Base URL: https://fapi.binance.com
Signature: HMAC-SHA256(secret, queryString + requestBody) → hex, signature as last param Headers: X-MBX-APIKEY
Binance Broker ID (Blave)
Broker attribution is per-order via newClientOrderId (NOT a header). Every order placement MUST include newClientOrderId starting with:
- Spot:
x-GBN6HWR2(broker IDGBN6HWR2) - USDS-M Futures:
x-52DDFAFN(broker ID52DDFAFN)
Total length ≤ 36 chars. Required on all order-placement endpoints (single, batch, OCO/OTO/OTOCO, SOR, algo, cancelReplace).
KuCoin Broker Attribution
Always include 4 broker headers on all KuCoin API requests (spot and futures, public and private). Omitting them disqualifies broker rebates.
| Header | Spot | Futures |
|---|---|---|
KC-BROKER-NAME | blave | blaveFutures |
KC-API-PARTNER | blave | blaveFutures |
KC-API-PARTNER-SIGN | Base64(HMAC-SHA256("1c10e0c0-bc3e-4a18-ad53-e41e6df5f757", ts + "blave" + apiKey)) | Base64(HMAC-SHA256("520815df-b324-4494-9bc8-b1015732b902", ts + "blaveFutures" + apiKey)) |
KC-API-PARTNER-VERIFY | true | true |
KuCoin
Spot Base URL: https://api.kucoin.com | Futures Base URL: https://api-futures.kucoin.com
Symbol format: Spot BTC-USDT | Futures XBTUSDTM (BTC uses XBT, append USDTM for linear perpetual)
Signature: Base64(HMAC-SHA256(secret, timestamp + METHOD + path + body)) → headers: KC-API-KEY, KC-API-SIGN, KC-API-TIMESTAMP, KC-API-PASSPHRASE (signed), KC-API-KEY-VERSION: 3
Bitfinex
Base URL: https://api.bitfinex.com (auth) | https://api-pub.bitfinex.com (public)
Signature: HMAC-SHA384(secret, "/api/" + path + nonce + body) → hex Headers: bfx-apikey, bfx-nonce, bfx-signature Affiliate code: "meta": {"aff_code": "ZZDLtrXMF"} on every order
TWSE / TPEX — 台股市場查詢
No API key required. Public data, no authentication.
| Market | Base URL |
|---|---|
| TWSE 上市 | https://openapi.twse.com.tw |
| TPEX 上櫃 | https://www.tpex.org.tw |
Key endpoints:
GET /v1/exchangeReport/BWIBBU_ALL— all listed stocks:Code,Name,PEratio,DividendYield,PBratioGET /v1/exchangeReport/STOCK_DAY_ALL— all listed stocks daily quote: open/high/low/close, volumeGET https://www.tpex.org.tw/openapi/v1/tpex_mainboard_quotes— all OTC stocks:SecuritiesCompanyCode,CompanyName, quote data
Lookup flow: Download full list → filter locally by Code or Name keyword. When market is unknown, query both TWSE and TPEX and merge results.
Date format: ROC calendar — 1150507 = 2026/05/07 (民國115年05月07日)
All queries are read-only — Safety Mode CONFIRM is NOT required.
Quick reference: references/twse-skill.mdFull API reference with Python examples: references/twse-api-reference.md{
"name": "blave-quant",
"tagline": "Crypto market alpha data + BitMart, OKX, Bybit, BingX, Bitget, Binance & Bitfinex trading",
"description": "Blave Quant gives your agent eight capabilities:\n\n1. **Blave Market Alpha** — Fetch crypto market signals including Holder Concentration, Taker Intensity, Whale Hunter, Squeeze Momentum, Market Direction, Capital Shortage, Funding Rate, Sector Rotation, Top Trader Exposure, kline data, alpha table screening, screener saved conditions, Liquidation alpha (爆倉指標) + liquidation heatmap, and Hyperliquid top trader tracking (leaderboard, positions, history, performance, bucket stats).\n\n2. **BitMart Futures** — Perpetual futures trading on BitMart: open/close positions, leverage, plan orders, TP/SL, trailing stops, and account management.\n\n3. **BitMart Spot** — Spot trading on BitMart: buy/sell, order management, margin, and sub-accounts.\n\n4. **OKX Trading** — Spot and perpetual swap trading on OKX: order placement, position queries, and balance management.\n\n5. **Bybit Trading** — Spot and derivatives/perpetual swap trading on Bybit: order placement, position queries, leverage, TP/SL, and balance management.\n\n6. **BingX Trading** — Spot and perpetual swap trading on BingX: order placement, position management, leverage, TWAP orders, OCO orders, and kill switch.\n\n7. **Bitget Trading** — Spot and futures trading on Bitget: order placement, position management, leverage, plan orders, and account management.\n\n8. **Binance Trading** — Spot and USDS-M futures trading on Binance: order placement, positions, leverage, algo orders, OCO/OTO/OTOCO, and account management.\n\n9. **Bitfinex Trading & Funding** — Spot, margin, and funding/lending on Bitfinex: order placement, margin positions, funding offers (lend/borrow), funding loans/credits, wallet transfers between exchange/margin/funding.\n\n10. **KuCoin Trading** — Spot and futures/perpetual contract trading on KuCoin: order placement (limit/market/stop), position management, leverage, funding rate queries, and account management. Blave is an enrolled KuCoin Broker Pro Program (BPP) partner — broker tags `blave` (spot) and `blaveFutures` (futures) are attached to all API requests for commission attribution.\n\n**Credentials:** Only `blave_api_key` and `blave_secret_key` are required (for market data). Exchange keys are optional — add only the exchanges you want to trade on: BITMART_API_KEY/BITMART_API_SECRET/BITMART_API_MEMO for BitMart; OKX_API_KEY/OKX_SECRET_KEY/OKX_PASSPHRASE for OKX; BYBIT_API_KEY/BYBIT_API_SECRET for Bybit; BINGX_API_KEY/BINGX_SECRET_KEY for BingX; BITFINEX_API_KEY/BITFINEX_API_SECRET for Bitfinex. This skill contains no executable code and does not transmit your keys itself — however, following the instructions will cause your agent to call third-party APIs using those keys. We recommend creating dedicated API keys with the minimum permissions required (read-only for market data, trading-only for order placement) and enabling IP whitelisting where possible.\n\n**Bonus examples:** BTC ETF flow monitor (track BlackRock IBIT / Fidelity FBTC institutional flows from Farside), Truth Social Trump post monitor (RSS + Google Translate to zh-TW + Telegram push, no LLM tokens), Hyperliquid copy trading, Blave alpha screening, HC backtest with regime analysis, Bitfinex auto-lending (rate-adaptive period selection + ladder offers across periods and rates), KD stochastic backtest on BTC 1h (golden/death cross, 2D param scan, regime analysis), MCPT+OOS validation framework (IS/OOS split + Monte Carlo Permutation Test, KD vs Taker Intensity comparison).\n\n**Safety Mode (enforced):** Every order, cancel, transfer, or funding action requires the user to reply exactly `CONFIRM` in the current conversation before execution. One CONFIRM authorizes one action; no auto-trading loop can bypass this. READ operations (quotes, balances, positions, alpha data) do not require CONFIRM. This rule applies to every exchange in this skill and cannot be disabled by the agent.\n\n**Broker attribution:** All BitMart requests include `X-BM-BROKER-ID: BlaveData666666`; all Bybit requests include `referer: Ue001036`; all BingX requests include `X-SOURCE-KEY: BX-AI-SKILL`; all Bitfinex orders include `aff_code: ZZDLtrXMF` in the meta field; all Binance orders include a `newClientOrderId` prefixed with `x-GBN6HWR2` (spot) or `x-52DDFAFN` (USDS-M futures); all KuCoin requests include broker headers `KC-BROKER-NAME: blave` (spot) / `blaveFutures` (futures). These identify Blave as the referring partner. They do not affect your trading fees as a user.",
"version": "1.10.0",
"requires": {
"env": [
"blave_api_key",
"blave_secret_key"
]
},
"optional": {
"env": [
"BITMART_API_KEY",
"BITMART_API_SECRET",
"BITMART_API_MEMO",
"OKX_API_KEY",
"OKX_SECRET_KEY",
"OKX_PASSPHRASE",
"BYBIT_API_KEY",
"BYBIT_API_SECRET",
"BINGX_API_KEY",
"BINGX_SECRET_KEY",
"BITGET_API_KEY",
"BITGET_SECRET_KEY",
"BITGET_PASSPHRASE",
"BINANCE_API_KEY",
"BINANCE_SECRET_KEY",
"BITFINEX_API_KEY",
"BITFINEX_API_SECRET",
"KUCOIN_API_KEY",
"KUCOIN_API_SECRET",
"KUCOIN_API_PASSPHRASE"
]
},
"category": "data",
"tags": ["crypto", "trading", "bitmart", "okx", "bybit", "bingx", "bitget", "binance", "bitfinex", "kucoin", "kucoin-spot", "kucoin-futures", "blave", "futures", "spot", "alpha", "market-data", "funding", "lending", "truth-social", "trump", "etf", "blackrock", "taiwan", "twse", "tpex", "taiwan-stocks"],
"license": "MIT",
"pricing": "free",
"support_url": "https://github.com/Blave-TW/blave-quant-skill/issues",
"homepage": "https://blave.org"
}
MIT License
Copyright (c) 2026 Blave
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Blave Quant Skill
A skill that gives your agent eight capabilities:
1. Blave — Fetch crypto market alpha data (holder concentration, whale hunter, taker intensity, and more) 2. BitMart Futures — Trade perpetual futures contracts on BitMart 3. BitMart Spot — Buy and sell spot assets on BitMart 4. OKX — Spot and perpetual swap trading on OKX 5. Bybit — Spot and derivatives/perpetual swap trading on Bybit 6. BingX — Spot and perpetual swap trading on BingX 7. Bitget — Spot and futures trading on Bitget 8. Binance — Spot and USDS-M futures trading on Binance
Official website: https://blave.org | For more details, visit the Blave Academy
Security
This skill is documentation only — it contains no executable code, scripts, or binaries.
- All files are plain Markdown (
.md) - No
package.json, no scripts, no dependencies - All API calls are made directly by your agent — this skill only provides the instructions
- Your API keys stay in your local
.envfile. This skill contains no executable code and does not transmit keys itself — however, following the instructions will cause your agent to send keys to Blave, BitMart, OKX, Bybit, BingX, Bitget, and Binance APIs when making calls. We recommend using API keys with minimum required permissions and enabling IP whitelisting where possible. - API request signing (HMAC-SHA256) is performed by your agent in code — the reference docs include
openssl/curlshell examples for illustration only. No local shell tools are required by this skill.
You can inspect the full source at: https://github.com/Blave-TW/blave-quant-skill
---
Install
npx -y skills add https://github.com/Blave-TW/blave-quant-skill -a openclaw -s blave-quant -yThe -a openclaw -s blave-quant -y flags skip the interactive picker — required for agents driving the install via tmux/SSH (the TUI breaks with arrow-key navigation in those environments). For claude-code, replace -a openclaw with -a claude-code.
Update
Run the same install command again — it overwrites the existing skill in place.
npx -y skills add https://github.com/Blave-TW/blave-quant-skill -a openclaw -s blave-quant -yOr just tell your agent: "Update the blave-quant skill" — the agent will run the command above on your behalf.
---
Setup
Blave API
1. Get a Blave API Plan
Subscribe to the API Plan to get API access. First-time subscribers get a 14-day free trial (credit card required).
👉 https://blave.org/landing/en/pricing
2. Create Your Blave API Key
👉 https://blave.org/landing/en/api?tab=blave
3. Add Blave Credentials
Add the following to your .env file:
blave_api_key=YOUR_API_KEY
blave_secret_key=YOUR_SECRET_KEY---
BitMart API (Futures & Spot)
1. Create Your BitMart API Key
1. Register at [https://www.bitmart.com/invite/cMEArf](https://www.bitmart.com/invite/cMEArf) (if you don't have an account) then log in 2. Go to Account → API Management: 👉 https://www.bitmart.com/api-config/en 3. Click Create API Key 4. Set a label and enter a Memo (a passphrase you choose — required for signing requests) 5. Enable permissions:
- Read-Only — for balance and order queries
- Spot Trade — for spot buy/sell
- Futures Trade — for contract trading
6. Complete 2FA and save your credentials:
- API Key
- Secret Key (shown only once — save it immediately)
- Memo (the passphrase you entered)
2. Add BitMart Credentials
Add the following to your .env file:
BITMART_API_KEY=YOUR_API_KEY
BITMART_API_SECRET=YOUR_SECRET_KEY
BITMART_API_MEMO=YOUR_MEMO---
OKX API
1. Create Your OKX API Key
1. Register at [https://okx.com/join/58510434](https://okx.com/join/58510434) (if you don't have an account) 2. Go to Account → API Management 3. Click Create API Key 4. Enable permissions: Read + Trade (do NOT enable Withdraw) 5. Set a Passphrase (required for signing requests) 6. Save your credentials:
- API Key
- Secret Key (shown only once — save it immediately)
- Passphrase (the one you just set)
2. Add OKX Credentials
Add the following to your .env file:
OKX_API_KEY=YOUR_API_KEY
OKX_SECRET_KEY=YOUR_SECRET_KEY
OKX_PASSPHRASE=YOUR_PASSPHRASE---
Bybit API
1. Create Your Bybit API Key
1. Register at [https://partner.bybit.com/b/BLAVE](https://partner.bybit.com/b/BLAVE) (if you don't have an account) 2. Go to Account → API Management 3. Click Create New Key 4. Enable permissions: Read + Trade (do NOT enable Withdraw) 5. Save your credentials:
- API Key
- API Secret (shown only once — save it immediately)
2. Add Bybit Credentials
Add the following to your .env file:
BYBIT_API_KEY=YOUR_API_KEY
BYBIT_API_SECRET=YOUR_API_SECRET---
BingX API
1. Create Your BingX API Key
1. Register at [https://bingxdao.com/invite/SU0SEU/](https://bingxdao.com/invite/SU0SEU/) (if you don't have an account) 2. Go to Account → API Management: 👉 https://bingx.com/en/account/api 3. Click Create API Key 4. Enable permissions: Read + Trade (enable Withdraw only if you need internal transfers) 5. Save your credentials:
- API Key
- Secret Key (shown only once — save it immediately)
2. Add BingX Credentials
Add the following to your .env file:
BINGX_API_KEY=YOUR_API_KEY
BINGX_SECRET_KEY=YOUR_SECRET_KEY---
Bitget API
1. Create Your Bitget API Key
1. Register at [https://www.bitget.com/](https://www.bitget.com/) (if you don't have an account) 2. Go to Account → API Management 3. Click Create API Key 4. Set a Passphrase (required for signing requests) 5. Enable permissions: Read + Trade (do NOT enable Withdraw) 6. Save your credentials:
- API Key
- Secret Key (shown only once — save it immediately)
- Passphrase (the one you just set)
2. Add Bitget Credentials
Add the following to your .env file:
BITGET_API_KEY=YOUR_API_KEY
BITGET_SECRET_KEY=YOUR_SECRET_KEY
BITGET_PASSPHRASE=YOUR_PASSPHRASE---
Usage Examples
Blave Market Data
- "Use Blave to check the Holder Concentration trend for BTCUSDT over the past week"
- "Use Blave to fetch the alpha table and find the top 5 coins with the highest holder concentration"
- "Use Blave to get the Whale Hunter signal for ETHUSDT using score_oi"
- "Use Blave to check the current market direction and capital shortage indicators"
- "Use Blave to fetch 1h candlestick data for BTCUSDT over the past 3 months"
---
- "用 Blave 幫我看 BTCUSDT 的籌碼集中度過去一週的趨勢"
- "用 Blave 抓 alpha table,篩選出籌碼集中度最高的前 5 個幣"
- "用 Blave 查 ETHUSDT 的巨鯨警報,score_type 用 score_oi"
- "用 Blave 看一下目前市場方向和資金稀缺指標"
- "用 Blave 抓 BTCUSDT 過去三個月的 K 線(1h)"
---
BitMart Futures
- "Open a long position on BTCUSDT with 10x leverage, 0.01 BTC, market order"
- "Check my current futures positions on BitMart"
- "Set a take profit at 100000 and stop loss at 90000 for my BTCUSDT long"
- "Cancel all open orders for ETHUSDT futures"
---
- "用 BitMart 開一個 BTCUSDT 10 倍槓桿多單,0.01 BTC,市價"
- "查看我目前的 BitMart 合約倉位"
- "幫我的 BTCUSDT 多單設定止盈 100000、止損 90000"
- "取消 ETHUSDT 所有掛單"
---
BitMart Spot
- "Buy 100 USDT worth of BTC on BitMart spot"
- "Sell 0.5 ETH at 4000 USDT limit order on BitMart"
- "Show my BitMart spot balance"
- "Cancel my open BTC buy order"
---
- "用 BitMart 現貨買 100 USDT 的 BTC"
- "用 BitMart 現貨掛限價單賣 0.5 ETH,價格 4000"
- "查看我的 BitMart 現貨餘額"
- "取消我的 BTC 現貨買單"
---
OKX
- "Buy 100 USDT worth of BTC on OKX spot"
- "Open a long position on BTC-USDT-SWAP with 10x leverage on OKX"
- "Check my OKX account balance"
- "Set take profit at 100000 and stop loss at 90000 for my OKX BTC swap position"
---
- "用 OKX 現貨買 100 USDT 的 BTC"
- "用 OKX 開 BTC 永續合約 10 倍槓桿多單"
- "查看我的 OKX 帳戶餘額"
- "幫我的 OKX BTC 永續倉位設定止盈 100000、止損 90000"
---
BingX
- "Buy 50 USDT worth of BTC on BingX spot"
- "Open a long position on BTC-USDT with 10x leverage on BingX"
- "Check my BingX account balance (fund, spot, and swap)"
- "Place a TWAP order to buy 0.1 BTC over 30 minutes on BingX"
---
- "用 BingX 現貨買 50 USDT 的 BTC"
- "用 BingX 開 BTC-USDT 永續合約 10 倍槓桿多單"
- "查看我的 BingX 帳戶餘額(資金、現貨、合約)"
- "用 BingX 的 TWAP 分批買入 0.1 BTC,30 分鐘內完成"
---
Bitget
- "Buy 100 USDT worth of BTC on Bitget spot"
- "Open a long BTCUSDT futures position with 10x leverage on Bitget"
- "Check my Bitget account balance"
- "Show my Bitget futures positions"
---
- "用 Bitget 現貨買 100 USDT 的 BTC"
- "用 Bitget 開 BTCUSDT 合約 10 倍槓桿多單"
- "查看我的 Bitget 帳戶餘額"
- "查看我的 Bitget 合約倉位"
---
Binance
- "Buy 100 USDT worth of BTC on Binance spot"
- "Open a long BTCUSDT futures position with 10x leverage on Binance"
- "Check my Binance account balance"
- "Set take profit and stop loss for my Binance BTC futures position"
---
- "用 Binance 現貨買 100 USDT 的 BTC"
- "用 Binance 開 BTCUSDT 合約 10 倍槓桿多單"
- "查看我的 Binance 帳戶餘額"
- "幫我的 Binance BTC 合約倉位設定止盈止損"
---
Binance API Setup
1. Create Your Binance API Key
1. Register at [https://www.binance.com/](https://www.binance.com/) (if you don't have an account) 2. Go to Account → API Management 3. Click Create API 4. Enable permissions: Enable Reading + Enable Spot & Margin Trading + Enable Futures (do NOT enable Withdraw) 5. Save your credentials:
- API Key
- Secret Key (shown only once — save it immediately)
2. Add Binance Credentials
Add the following to your .env file:
BINANCE_API_KEY=YOUR_API_KEY
BINANCE_SECRET_KEY=YOUR_SECRET_KEY---
Disclaimer
This skill is provided for informational and automation purposes only. It does not constitute financial, investment, or trading advice. Cryptocurrency trading — especially futures and leveraged products — involves substantial risk of loss and may not be suitable for all users. Past performance is not indicative of future results.
By using this skill, you acknowledge that:
- All trading decisions are solely your own responsibility
- The authors and maintainers of this skill are not liable for any losses incurred
- You should consult a qualified financial advisor before making investment decisions
本 Skill 僅供資訊參考與自動化操作使用,不構成任何投資建議。加密貨幣交易(尤其是合約與槓桿產品)具有高度風險,可能導致重大損失。過去績效不代表未來結果。使用本 Skill 即表示您同意,所有交易決策均由您自行負責,作者與維護者不對任何損失承擔責任。
Binance API Reference
Base URLs
| Spot | USDS-M Futures | |
|---|---|---|
| Production | https://api.binance.com | https://fapi.binance.com |
| Testnet | https://testnet.binance.vision | https://demo-fapi.binance.com |
Success: Spot returns order fields directly; Futures returns "code": 200 or fields directly.
---
Authentication
Credentials (from .env): BINANCE_API_KEY, BINANCE_SECRET_KEY
Signature: HMAC-SHA256(secret, totalParams) → hex
totalParams= queryString + requestBody (concatenated, no separator)timestamp: Unix milliseconds (always required for signed endpoints)signaturemust be the last parameter
Headers:
X-MBX-APIKEY: <api_key>
Content-Type: application/x-www-form-urlencoded (POST)Broker ID (Blave)
Binance broker attribution is per-order via newClientOrderId, not a header.
| Product | Broker ID | newClientOrderId prefix |
|---|---|---|
| Spot | GBN6HWR2 | x-GBN6HWR2 |
| USDS-M Futures | 52DDFAFN | x-52DDFAFN |
- Total length of
newClientOrderId≤ 36 chars - Required on
/api/v3/order,/api/v3/order/cancelReplace,/api/v3/sor/order,/api/v3/orderList/oco|oto|otoco,/fapi/v1/order,/fapi/v1/batchOrders,/fapi/v1/algoOrder, and their test/modify variants - Batch orders: every order in the batch must carry its own prefixed
newClientOrderId
import uuid
def spot_cid(suffix: str = "") -> str:
return f"x-GBN6HWR2{suffix or uuid.uuid4().hex[:8]}"[:36]
def fut_cid(suffix: str = "") -> str:
return f"x-52DDFAFN{suffix or uuid.uuid4().hex[:8]}"[:36]---
Python Signature Implementation
import time, hmac, hashlib, requests
from dotenv import dotenv_values
from urllib.parse import urlencode
_env = dotenv_values()
API_KEY = _env["BINANCE_API_KEY"]
SECRET_KEY = _env["BINANCE_SECRET_KEY"]
SPOT_URL = "https://api.binance.com"
FAPI_URL = "https://fapi.binance.com"
def _sign(params: dict) -> dict:
params["timestamp"] = int(time.time() * 1000)
qs = urlencode(params)
params["signature"] = hmac.new(SECRET_KEY.encode(), qs.encode(), hashlib.sha256).hexdigest()
return params
def bn_get(base, path, params=None):
p = _sign(dict(params or {}))
r = requests.get(f"{base}{path}", params=p,
headers={"X-MBX-APIKEY": API_KEY}, timeout=10)
return r.json()
def bn_post(base, path, params=None):
p = _sign(dict(params or {}))
r = requests.post(f"{base}{path}", data=urlencode(p),
headers={"X-MBX-APIKEY": API_KEY,
"Content-Type": "application/x-www-form-urlencoded"}, timeout=10)
return r.json()
def bn_delete(base, path, params=None):
p = _sign(dict(params or {}))
r = requests.delete(f"{base}{path}", params=p,
headers={"X-MBX-APIKEY": API_KEY}, timeout=10)
return r.json()
def bn_put(base, path, params=None):
p = _sign(dict(params or {}))
r = requests.put(f"{base}{path}", data=urlencode(p),
headers={"X-MBX-APIKEY": API_KEY,
"Content-Type": "application/x-www-form-urlencoded"}, timeout=10)
return r.json()
# Shortcuts
def spot_get(path, params=None): return bn_get(SPOT_URL, path, params)
def spot_post(path, params=None): return bn_post(SPOT_URL, path, params)
def spot_delete(path, params=None): return bn_delete(SPOT_URL, path, params)
def fapi_get(path, params=None): return bn_get(FAPI_URL, path, params)
def fapi_post(path, params=None): return bn_post(FAPI_URL, path, params)
def fapi_delete(path, params=None): return bn_delete(FAPI_URL, path, params)
def fapi_put(path, params=None): return bn_put(FAPI_URL, path, params)---
Spot Endpoints
Account
| Method | Path | Description |
|---|---|---|
| GET | /api/v3/account | Account info + balances (omitZeroBalances optional) |
| GET | /api/v3/myTrades | Trade history (symbol required) |
| GET | /api/v3/account/commission | Commission rates (symbol required) |
| GET | /api/v3/rateLimit/order | Unfilled order count |
Order Placement
| Method | Path | Description |
|---|---|---|
| POST | /api/v3/order | Place order |
| POST | /api/v3/order/test | Test order (validate only) |
| DELETE | /api/v3/order | Cancel order |
| DELETE | /api/v3/openOrders | Cancel all open orders for symbol |
| POST | /api/v3/order/cancelReplace | Atomic cancel & replace |
| PUT | /api/v3/order/amend/keepPriority | Amend quantity (keep queue priority) |
Spot order params: symbol, side (BUY/SELL), type (LIMIT/MARKET/STOP_LOSS/TAKE_PROFIT/STOP_LOSS_LIMIT/TAKE_PROFIT_LIMIT/LIMIT_MAKER), timeInForce (GTC/IOC/FOK), quantity, quoteOrderQty (market buy by quote), price, `newClientOrderId` (REQUIRED: must start with `x-GBN6HWR2`, ≤36 chars)
Order Query
| Method | Path | Description |
|---|---|---|
| GET | /api/v3/order | Query single order |
| GET | /api/v3/openOrders | Current open orders |
| GET | /api/v3/allOrders | All orders (active/canceled/filled) |
Advanced Order Types
| Method | Path | Description |
|---|---|---|
| POST | /api/v3/orderList/oco | OCO (One-Cancels-Other) |
| POST | /api/v3/orderList/oto | OTO (One-Triggers-Other) |
| POST | /api/v3/orderList/otoco | OTOCO (One-Triggers-OCO) |
| DELETE | /api/v3/orderList | Cancel order list |
| GET | /api/v3/orderList | Query order list |
| GET | /api/v3/openOrderList | Open order lists |
Smart Order Routing (SOR)
| Method | Path | Description |
|---|---|---|
| POST | /api/v3/sor/order | SOR order |
| POST | /api/v3/sor/order/test | Test SOR order |
---
USDS-Margined Futures Endpoints
Account & Position
| Method | Path | Description |
|---|---|---|
| GET | /fapi/v2/account | Account info V2 |
| GET | /fapi/v3/account | Account info V3 (single/multi-asset) |
| GET | /fapi/v2/balance | Account balance |
| GET | /fapi/v2/positionRisk | Position info V2 |
| GET | /fapi/v3/positionRisk | Position info V3 |
| GET | /fapi/v1/userTrades | Trade list (symbol required, max 7d range) |
| GET | /fapi/v1/forceOrders | Liquidation/ADL orders |
Order Placement
| Method | Path | Description |
|---|---|---|
| POST | /fapi/v1/order | Place order |
| POST | /fapi/v1/batchOrders | Batch place (max 5) |
| POST | /fapi/v1/algoOrder | Algo/conditional order (STOP/TP/TRAILING) |
Futures order params: symbol, side (BUY/SELL), positionSide (BOTH/LONG/SHORT), type (LIMIT/MARKET/STOP/STOP_MARKET/TAKE_PROFIT/TAKE_PROFIT_MARKET/TRAILING_STOP_MARKET), quantity, price, stopPrice, timeInForce, reduceOnly, `newClientOrderId` (REQUIRED: must start with `x-52DDFAFN`, ≤36 chars)
Order Modification
| Method | Path | Description |
|---|---|---|
| PUT | /fapi/v1/order | Modify order (LIMIT only) |
| PUT | /fapi/v1/batchOrders | Batch modify (max 5) |
Order Cancellation
| Method | Path | Description |
|---|---|---|
| DELETE | /fapi/v1/order | Cancel order |
| DELETE | /fapi/v1/batchOrders | Batch cancel (max 10) |
| DELETE | /fapi/v1/allOpenOrders | Cancel all open orders |
| DELETE | /fapi/v1/algoOrder | Cancel algo order |
| DELETE | /fapi/v1/algoOpenOrders | Cancel all algo open orders |
Order Query
| Method | Path | Description |
|---|---|---|
| GET | /fapi/v1/order | Query single order |
| GET | /fapi/v1/openOrder | Single open order |
| GET | /fapi/v1/openOrders | All open orders |
| GET | /fapi/v1/allOrders | All orders (max 7d range) |
| GET | /fapi/v1/openAlgoOrders | Open algo orders |
| GET | /fapi/v1/allAlgoOrders | All algo orders |
Leverage & Margin
| Method | Path | Description |
|---|---|---|
| POST | /fapi/v1/leverage | Set leverage (1-125x) |
| POST | /fapi/v1/marginType | Set margin type (ISOLATED/CROSSED) |
| POST | /fapi/v1/positionSide/dual | Set position mode (hedge/one-way) |
| POST | /fapi/v1/positionMargin | Adjust isolated margin (type: 1=add, 2=reduce) |
| GET | /fapi/v1/positionMargin/history | Margin change history |
| GET | /fapi/v1/leverageBracket | Leverage brackets |
---
Symbol Format
- Spot:
BTCUSDT(no separator) - Futures:
BTCUSDT(no separator)
Rate Limits
- Orders: tracked per 10s and per 1min per UID
- Public market data: IP-based
- Repeated violations → auto IP ban (2min to 3 days)
Binance Trading
Spot Base URL: https://api.binance.com | Futures Base URL: https://fapi.binance.com
Spot: BTCUSDT | Futures: BTCUSDT | Testnet: https://testnet.binance.vision (spot) / https://demo-fapi.binance.com (futures)
Full details in references/binance-api-reference.md
Authentication
Credentials (from .env): BINANCE_API_KEY, BINANCE_SECRET_KEY
No Binance account? Register at [https://www.binance.com/](https://www.binance.com/)
Verify credentials before any private call. If missing — STOP.
Signature: HMAC-SHA256(secret, queryString + requestBody) → hex
timestamp: Unix milliseconds (always required)signaturemust be the last parameter
Headers:
X-MBX-APIKEY: <api_key>
Content-Type: application/x-www-form-urlencoded (POST)Python signature implementation: references/binance-api-reference.mdBroker ID (Blave — MANDATORY on every order)
Binance brokers are attached per order via newClientOrderId, not via a header. Every place-order call MUST include newClientOrderId starting with x-<BROKER_ID>:
| Product | Broker ID | newClientOrderId prefix |
|---|---|---|
| Spot | GBN6HWR2 | x-GBN6HWR2 |
| USDS-M Futures | 52DDFAFN | x-52DDFAFN |
Rules:
- Prefix starts with literal
x-(lowercase), then the broker ID - Total length ≤ 36 chars; append a unique suffix (timestamp/uuid fragment) to keep each ID unique
- Applies to:
/api/v3/order,/api/v3/order/cancelReplace,/api/v3/sor/order,/api/v3/orderList/oco|oto|otoco,/fapi/v1/order,/fapi/v1/batchOrders,/fapi/v1/algoOrder, and their test/modify variants - Batch orders: every order in the batch needs its own qualifying
newClientOrderId - If user supplies a custom
newClientOrderId, reject it or prepend the broker prefix — never strip the prefix
import time, uuid
def spot_cid(suffix: str = "") -> str:
tag = suffix or uuid.uuid4().hex[:8]
return f"x-GBN6HWR2{tag}"[:36]
def fut_cid(suffix: str = "") -> str:
tag = suffix or uuid.uuid4().hex[:8]
return f"x-52DDFAFN{tag}"[:36]
# Spot place order
spot_post("/api/v3/order", {
"symbol": "BTCUSDT", "side": "BUY", "type": "MARKET",
"quantity": "0.001",
"newClientOrderId": spot_cid(),
})
# Futures place order
fapi_post("/fapi/v1/order", {
"symbol": "BTCUSDT", "side": "BUY", "type": "MARKET",
"quantity": "0.001",
"newClientOrderId": fut_cid(),
})Operation Flow
Step 0: Credential Check
Verify BINANCE_API_KEY, BINANCE_SECRET_KEY. If missing — STOP. Default to Mainnet unless user explicitly requests Testnet.
Step 1: Pre-Trade Check (Futures)
- Query positions:
GET /fapi/v2/positionRisk?symbol=<SYMBOL> - If position exists → inherit leverage and margin type, do NOT override
Step 2: Execute
- READ → call, parse, display
- WRITE → present summary → ask "CONFIRM" → execute
Step 3: Verify
After order → query order status. After close → query positions.
Quick Reference — Spot
| Operation | Method | Path |
|---|---|---|
| Account info | GET | /api/v3/account |
| Place order | POST | /api/v3/order |
| Cancel order | DELETE | /api/v3/order |
| Cancel all | DELETE | /api/v3/openOrders |
| Query order | GET | /api/v3/order |
| Open orders | GET | /api/v3/openOrders |
| Order history | GET | /api/v3/allOrders |
| Trade fills | GET | /api/v3/myTrades |
Quick Reference — USDS-M Futures
| Operation | Method | Path |
|---|---|---|
| Account balance | GET | /fapi/v2/balance |
| Account info | GET | /fapi/v2/account |
| Positions | GET | /fapi/v2/positionRisk |
| Place order | POST | /fapi/v1/order |
| Batch place | POST | /fapi/v1/batchOrders |
| Cancel order | DELETE | /fapi/v1/order |
| Cancel all | DELETE | /fapi/v1/allOpenOrders |
| Modify order | PUT | /fapi/v1/order |
| Open orders | GET | /fapi/v1/openOrders |
| Order history | GET | /fapi/v1/allOrders |
| Set leverage | POST | /fapi/v1/leverage |
| Set margin type | POST | /fapi/v1/marginType |
| Set position mode | POST | /fapi/v1/positionSide/dual |
Security
- WRITE operations require "CONFIRM"
- Always show liquidation price before opening leveraged positions
- "Not financial advice. Trading carries significant risk of loss."
References
references/binance-api-reference.md— spot + futures endpoints, Python signature
BingX API Reference
Base URL
| Environment | Primary | Fallback |
|---|---|---|
| Live Trading | https://open-api.bingx.com | https://open-api.bingx.pro |
| Paper Trading (VST) | https://open-api-vst.bingx.com | https://open-api-vst.bingx.pro |
Prefer .com; only fall back to .pro on network-level failures. Default to live unless user explicitly requests paper trading.
---
Authentication
Credentials (from .env): BINGX_API_KEY, BINGX_SECRET_KEY
Signature: HMAC-SHA256
1. Collect all params (query + body) + timestamp (Unix ms)
2. Sort alphabetically by key (unencoded)
3. Concatenate as key=value&key=value
4. signature = HMAC-SHA256(secret, canonical_string) → hex
5. Append &signature=<hex> to query string or bodyHeaders (all requests):
X-BX-APIKEY: <api_key>
X-SOURCE-KEY: BX-AI-SKILLResponse format: {"code": 0, "msg": "", "data": ...} — code == 0 is success.
---
Python Signature Implementation
import time, hmac, hashlib, json, os, requests
from dotenv import dotenv_values
from urllib.parse import urlencode
_env = dotenv_values()
API_KEY = _env["BINGX_API_KEY"]
SECRET_KEY = _env["BINGX_SECRET_KEY"]
BASE_URL = "https://open-api.bingx.com"
FALLBACK = "https://open-api.bingx.pro"
HEADERS = {"X-BX-APIKEY": API_KEY, "X-SOURCE-KEY": "BX-AI-SKILL"}
def _sign(params: dict) -> str:
"""Build canonical string from sorted params and return HMAC-SHA256 hex signature."""
params["timestamp"] = str(int(time.time() * 1000))
canonical = "&".join(f"{k}={v}" for k, v in sorted(params.items()))
sig = hmac.new(SECRET_KEY.encode(), canonical.encode(), hashlib.sha256).hexdigest()
return canonical + f"&signature={sig}"
def bingx_get(path: str, params: dict = {}):
"""Signed GET request with domain fallback."""
qs = _sign(dict(params))
for base in [BASE_URL, FALLBACK]:
try:
r = requests.get(f"{base}{path}?{qs}", headers=HEADERS, timeout=10)
data = r.json()
if data.get("code") != 0:
raise Exception(f"BingX error {data.get('code')}: {data.get('msg')}")
return data.get("data")
except requests.exceptions.ConnectionError:
if base == FALLBACK: raise
return None
def bingx_post(path: str, params: dict = {}):
"""Signed POST request (form-encoded) with domain fallback."""
body = _sign(dict(params))
for base in [BASE_URL, FALLBACK]:
try:
r = requests.post(f"{base}{path}", data=body, headers={
**HEADERS, "Content-Type": "application/x-www-form-urlencoded"
}, timeout=10)
data = r.json()
if data.get("code") != 0:
raise Exception(f"BingX error {data.get('code')}: {data.get('msg')}")
return data.get("data")
except requests.exceptions.ConnectionError:
if base == FALLBACK: raise
return None
def bingx_delete(path: str, params: dict = {}):
"""Signed DELETE request with domain fallback."""
qs = _sign(dict(params))
for base in [BASE_URL, FALLBACK]:
try:
r = requests.delete(f"{base}{path}?{qs}", headers=HEADERS, timeout=10)
data = r.json()
if data.get("code") != 0:
raise Exception(f"BingX error {data.get('code')}: {data.get('msg')}")
return data.get("data")
except requests.exceptions.ConnectionError:
if base == FALLBACK: raise
return None---
Account Balance Endpoints
BingX has three separate accounts: Fund, Spot, Swap. Assets don't auto-transfer — query all three to see full picture.
| Method | Path | Description |
|---|---|---|
| GET | /openApi/fund/v1/account/balance | Fund account (deposits land here) |
| GET | /openApi/spot/v1/account/balance | Spot account |
| GET | /openApi/swap/v3/user/balance | Swap/futures account (USDT + USDC) |
| GET | /openApi/account/v1/allAccountBalance | All accounts overview |
---
Perpetual Futures (Swap) Endpoints
Order Management
| Method | Path | Description |
|---|---|---|
| POST | /openApi/swap/v2/trade/order | Place order |
| POST | /openApi/swap/v2/trade/order/test | Test order (validate only) |
| POST | /openApi/swap/v2/trade/batchOrders | Batch place (up to 5) |
Place order params:
| Param | Required | Description |
|---|---|---|
symbol | ✓ | e.g. BTC-USDT |
side | ✓ | BUY / SELL |
positionSide | ✓ | LONG / SHORT / BOTH (one-way mode) |
type | ✓ | MARKET, LIMIT, STOP_MARKET, STOP, TAKE_PROFIT_MARKET, TAKE_PROFIT, TRAILING_STOP_MARKET, TRAILING_TP_SL |
quantity | ✓ (except market buy) | Order quantity |
price | for LIMIT | Limit price |
stopPrice | for STOP/TP | Trigger price |
timeInForce | — | GTC (default), IOC, FOK, PostOnly |
stopLoss | — | JSON: {"type":"STOP_MARKET","stopPrice":"...","price":"...","workingType":"..."} |
takeProfit | — | JSON: same structure as stopLoss |
recvWindow | — | Default 5000ms |
Cancel Orders
| Method | Path | Description |
|---|---|---|
| DELETE | /openApi/swap/v2/trade/order | Cancel single order |
| DELETE | /openApi/swap/v2/trade/batchOrders | Batch cancel (up to 10) |
| DELETE | /openApi/swap/v2/trade/allOpenOrders | Cancel all open orders |
| POST | /openApi/swap/v2/trade/cancelAllAfter | Kill switch (auto-cancel after 10-120s) |
Query Orders
| Method | Path | Description |
|---|---|---|
| GET | /openApi/swap/v2/trade/openOrder | Single open order status |
| GET | /openApi/swap/v2/trade/order | Order details |
| GET | /openApi/swap/v2/trade/openOrders | All current open orders |
| GET | /openApi/swap/v2/trade/allOrders | Order history (max 7-day range) |
| GET | /openApi/swap/v2/trade/forceOrders | Liquidation / force close orders |
| GET | /openApi/swap/v2/trade/allFillOrders | Trade fill history with fees & PnL |
Position Management
| Method | Path | Description |
|---|---|---|
| POST | /openApi/swap/v2/trade/closeAllPositions | Close all positions |
| POST | /openApi/swap/v1/trade/closePosition | Close position by positionId |
| POST | /openApi/swap/v2/trade/positionMargin | Adjust isolated margin (add/reduce) |
Leverage & Mode Settings
| Method | Path | Description |
|---|---|---|
| GET | /openApi/swap/v2/trade/marginType | Query margin mode |
| POST | /openApi/swap/v2/trade/marginType | Set margin mode (ISOLATED/CROSSED/SEPARATE_ISOLATED) |
| GET | /openApi/swap/v2/trade/leverage | Query leverage (current + max) |
| POST | /openApi/swap/v2/trade/leverage | Set leverage |
| GET | /openApi/swap/v1/positionSide/dual | Query position mode (hedge/one-way) |
| POST | /openApi/swap/v1/positionSide/dual | Set position mode |
Order Modification
| Method | Path | Description |
|---|---|---|
| POST | /openApi/swap/v1/trade/amend | Amend open order quantity |
| POST | /openApi/swap/v1/trade/cancelReplace | Cancel and replace (atomic) |
| POST | /openApi/swap/v1/trade/batchCancelReplace | Batch cancel and replace |
TWAP Orders
| Method | Path | Description |
|---|---|---|
| POST | /openApi/swap/v1/twap/order | Place TWAP order (split into child orders, 5-120s intervals) |
| POST | /openApi/swap/v1/twap/cancelOrder | Cancel TWAP order |
| GET | /openApi/swap/v1/twap/openOrders | Query TWAP open orders |
| GET | /openApi/swap/v1/twap/historyOrders | Query TWAP history |
| GET | /openApi/swap/v1/twap/orderDetail | TWAP order details with child records |
Additional
| Method | Path | Description |
|---|---|---|
| GET | /openApi/swap/v1/trade/fullOrder | All orders V2 |
| GET | /openApi/swap/v2/trade/fillHistory | Historical transaction details |
| GET | /openApi/swap/v1/trade/positionHistory | Position history (max 3-month) |
| GET | /openApi/swap/v1/positionMargin/history | Isolated margin change history |
| GET | /openApi/swap/v1/maintMarginRatio | Position & maintenance margin ratio |
| POST | /openApi/swap/v1/trade/autoAddMargin | Auto margin addition |
| POST | /openApi/swap/v1/trade/reverse | One-click reverse position |
| POST | /openApi/swap/v2/trade/getVst | Apply VST (paper trading) balance |
---
Spot Endpoints
Order Management
| Method | Path | Description |
|---|---|---|
| POST | /openApi/spot/v1/trade/order | Place order (MARKET/LIMIT/STOP types) |
| POST | /openApi/spot/v1/trade/batchOrders | Batch place (up to 5) |
| POST | /openApi/spot/v1/trade/cancel | Cancel single order |
| POST | /openApi/spot/v1/trade/cancelOrders | Bulk cancel |
| POST | /openApi/spot/v1/trade/cancelOpenOrders | Cancel all open orders for a pair |
| POST | /openApi/spot/v1/trade/cancelAllAfter | Kill switch (10-120s timeout) |
| POST | /openApi/spot/v1/trade/order/cancelReplace | Cancel and replace (atomic) |
Spot order types: MARKET, LIMIT, TAKE_STOP_LIMIT, TAKE_STOP_MARKET, TRIGGER_LIMIT, TRIGGER_MARKET
Query Orders
| Method | Path | Description |
|---|---|---|
| GET | /openApi/spot/v1/trade/query | Single order details |
| GET | /openApi/spot/v1/trade/openOrders | Active orders by pair |
| GET | /openApi/spot/v1/trade/historyOrders | Order history (max 10K results) |
| GET | /openApi/spot/v1/trade/myTrades | Trade fills with commissions |
| GET | /openApi/spot/v1/user/commissionRate | Commission rates (maker/taker) |
OCO Orders
| Method | Path | Description |
|---|---|---|
| POST | /openApi/spot/v1/oco/order | Create OCO order |
| POST | /openApi/spot/v1/oco/cancel | Cancel OCO order |
| GET | /openApi/spot/v1/oco/orderList | Query OCO order details |
| GET | /openApi/spot/v1/oco/openOrderList | Open OCO orders |
| GET | /openApi/spot/v1/oco/historyOrderList | Historical OCO orders |
---
Symbol Format
- Perpetual futures:
BTC-USDT(with hyphen) - Spot:
BTC-USDT(with hyphen)
Notes
orderID(string) is preferred overorderId(numeric) for large IDs to avoid precision loss- Order history queries have a max 7-day range per request
- Position history max 3-month span
- Kill switch countdown: 10-120 seconds, must send heartbeat to reset
BingX Trading
Base URL: https://open-api.bingx.com | Fallback: https://open-api.bingx.pro | Paper (VST): https://open-api-vst.bingx.com
Spot: BTC-USDT | Perpetual: BTC-USDT | Success: "code": 0
42 swap endpoints + 17 spot endpoints — full details in references/bingx-api-reference.md
Authentication
Credentials (from .env): BINGX_API_KEY, BINGX_SECRET_KEY
No BingX account? Register at [https://bingxdao.com/invite/SU0SEU/](https://bingxdao.com/invite/SU0SEU/)
Verify credentials before any private call. If missing — STOP.
Signature: HMAC-SHA256(secret, sorted_params_canonical_string) → hex, appended as &signature=<hex>
- Collect all params +
timestamp(Unix ms) - Sort alphabetically by key, concatenate as
key=value&key=value
Headers (all requests):
X-BX-APIKEY: <api_key>
X-SOURCE-KEY: BX-AI-SKILL`X-SOURCE-KEY: BX-AI-SKILL` is MANDATORY on every request — no exceptions.
Python signature implementation and helper functions: references/bingx-api-reference.mdOperation Flow
Step 0: Credential Check
Verify BINGX_API_KEY, BINGX_SECRET_KEY. If missing — STOP. Default to Live unless user explicitly requests paper trading (VST).
Step 1: Pre-Trade Check (Swap)
- Query position mode:
GET /openApi/swap/v1/positionSide/dual - Query leverage:
GET /openApi/swap/v2/trade/leverage?symbol=<SYMBOL> - If position exists → inherit leverage and margin type, do NOT override
Step 2: Execute
- READ → call, parse, display
- WRITE → present summary → ask "CONFIRM" → execute
Step 3: Verify
After order → query order status. After close → query positions.
Quick Reference
| Operation | Method | Path |
|---|---|---|
| Place swap order | POST | /openApi/swap/v2/trade/order |
| Cancel swap order | DELETE | /openApi/swap/v2/trade/order |
| Open swap orders | GET | /openApi/swap/v2/trade/openOrders |
| Order details | GET | /openApi/swap/v2/trade/order |
| Close all positions | POST | /openApi/swap/v2/trade/closeAllPositions |
| Set leverage | POST | /openApi/swap/v2/trade/leverage |
| Set margin mode | POST | /openApi/swap/v2/trade/marginType |
| Place spot order | POST | /openApi/spot/v1/trade/order |
| Cancel spot order | POST | /openApi/spot/v1/trade/cancel |
| Spot open orders | GET | /openApi/spot/v1/trade/openOrders |
Security
- WRITE operations require "CONFIRM"
- Always show liquidation price before opening leveraged positions
- "Not financial advice. Trading carries significant risk of loss."
References
references/bingx-api-reference.md— 59 endpoints, Python signature, full params
---
Bitfinex Trading & Funding
Base URL: https://api.bitfinex.com (authenticated) | https://api-pub.bitfinex.com (public)
Symbol format: Trading tBTCUSD, tETHUST (UST=USDT) | Funding fUSD, fBTC, fUST
Success: response array, first element is not "error" | Error: ["error", CODE, "message"]
Authentication
Credentials (from .env): BITFINEX_API_KEY, BITFINEX_API_SECRET
No Bitfinex account? Register at [https://www.bitfinex.com/sign-up?refcode=ZZDLtrXMF](https://www.bitfinex.com/sign-up?refcode=ZZDLtrXMF)
Verify credentials before any private call. If missing — STOP.
Signature: HMAC-SHA384 (NOT SHA256)
import hmac, hashlib, json, time, requests
def bfx_request(path, body=None):
body = body or {}
nonce = str(int(time.time() * 1_000_000))
body_json = json.dumps(body)
sig_payload = f"/api/{path}{nonce}{body_json}"
sig = hmac.new(
BITFINEX_API_SECRET.encode(),
sig_payload.encode(),
hashlib.sha384
).hexdigest()
headers = {
"bfx-nonce": nonce,
"bfx-apikey": BITFINEX_API_KEY,
"bfx-signature": sig,
"content-type": "application/json",
}
return requests.post(f"https://api.bitfinex.com/{path}",
headers=headers, data=body_json)Nonce: strictly increasing per API key. Use int(time.time() * 1_000_000) (microseconds).
Affiliate Code
Always include `aff_code` in the `meta` field of every order:
{"meta": {"aff_code": "ZZDLtrXMF"}}5% developer reward on every trade fee. Fixed, does not reduce over time.
Operation Flow
Step 0: Credential Check
Verify BITFINEX_API_KEY, BITFINEX_API_SECRET. If missing — STOP.
Step 1: Pre-Trade Check
POST /v2/auth/r/wallets → check balance in correct wallet (exchange / margin / funding).
Step 2: Execute
- READ → call, parse, display
- WRITE → present summary → ask "CONFIRM" → execute
Step 3: Verify
After order → POST /v2/auth/r/orders → confirm status. After funding → POST /v2/auth/r/funding/offers.
---
Wallet Types
| Wallet | Use |
|---|---|
exchange | Spot trading |
margin | Margin trading |
funding | Lending / borrowing |
Transfer between wallets: POST /v2/auth/w/transfer
---
Order Types
| Type | Description |
|---|---|
EXCHANGE LIMIT | Spot limit order |
EXCHANGE MARKET | Spot market order |
EXCHANGE STOP | Spot stop order |
EXCHANGE STOP LIMIT | Spot stop limit |
EXCHANGE TRAILING STOP | Spot trailing stop |
EXCHANGE FOK | Spot fill-or-kill |
EXCHANGE IOC | Spot immediate-or-cancel |
LIMIT | Margin limit order |
MARKET | Margin market order |
STOP | Margin stop |
STOP LIMIT | Margin stop limit |
TRAILING STOP | Margin trailing stop |
"EXCHANGE" prefix = spot wallet. No prefix = margin wallet.
Order Flags
| Flag | Value | Description |
|---|---|---|
| Hidden | 64 | Not visible in order book |
| Close | 512 | Close existing position |
| Reduce Only | 1024 | Prevent reversing position |
| Post Only | 4096 | Add to book only, no immediate match |
| OCO | 16384 | One-Cancels-Other |
Combine by summing: Hidden + Post Only = 4160
---
Key Endpoints — Trading
| Action | Method | Path |
|---|---|---|
| Ticker (public) | GET | /v2/ticker/{Symbol} |
| Tickers (public) | GET | /v2/tickers?symbols=tBTCUSD,tETHUSD |
| Candles (public) | GET | /v2/candles/trade:{TimeFrame}:{Symbol}/hist |
| Wallets | POST | /v2/auth/r/wallets |
| Place order | POST | /v2/auth/w/order/submit |
| Update order | POST | /v2/auth/w/order/update |
| Cancel order | POST | /v2/auth/w/order/cancel |
| Cancel all | POST | /v2/auth/w/order/cancel/multi body: {"all": 1} |
| Active orders | POST | /v2/auth/r/orders |
| Order history | POST | /v2/auth/r/orders/hist |
| Positions | POST | /v2/auth/r/positions |
| Transfer | POST | /v2/auth/w/transfer |
Place Order — Parameters
{
"type": "EXCHANGE LIMIT",
"symbol": "tBTCUSD",
"amount": "0.01",
"price": "50000",
"flags": 0,
"meta": {"aff_code": "ZZDLtrXMF"}
}| Param | Type | Required | Notes |
|---|---|---|---|
| type | string | Yes | See order types above |
| symbol | string | Yes | e.g. tBTCUSD |
| amount | string | Yes | Positive = buy, negative = sell |
| price | string | Yes* | Not needed for MARKET |
| flags | int | No | Sum of flag values |
| lev | int | No | Leverage 1-100 (derivatives only) |
| price_trailing | string | No | For TRAILING STOP |
| price_aux_limit | string | No | For STOP LIMIT |
| price_oco_stop | string | No | OCO stop price |
| tif | string | No | Auto-cancel time "2026-01-15 10:45:23" |
| meta | object | No | {"aff_code": "ZZDLtrXMF"} |
Cancel Order
{"id": 123456789}Or by client ID: {"cid": 12345, "cid_date": "2026-04-17"}
Transfer Between Wallets
{
"from": "exchange",
"to": "funding",
"currency": "USD",
"amount": "1000"
}---
Key Endpoints — Funding (Lending)
| Action | Method | Path |
|---|---|---|
| Funding ticker (public) | GET | /v2/ticker/{fSymbol} |
| Submit funding offer | POST | /v2/auth/w/funding/offer/submit |
| Cancel funding offer | POST | /v2/auth/w/funding/offer/cancel |
| Active funding offers | POST | /v2/auth/r/funding/offers/{Symbol} |
| Funding loans (idle) | POST | /v2/auth/r/funding/loans/{Symbol} |
| Funding credits (in use) | POST | /v2/auth/r/funding/credits/{Symbol} |
| Funding info | POST | /v2/auth/r/info/funding/{key} |
Submit Funding Offer — Parameters
{
"type": "LIMIT",
"symbol": "fUSD",
"amount": "1000",
"rate": "0.0002",
"period": 2
}| Param | Type | Required | Notes |
|---|---|---|---|
| type | string | Yes | LIMIT, FRRDELTAVAR, FRRDELTAFIX |
| symbol | string | Yes | fUSD, fBTC, fUST, etc. |
| amount | string | Yes | Positive = lend (offer), negative = borrow (bid) |
| rate | string | Yes | Daily rate, e.g. "0.0002" = 0.02%/day ≈ 7.3%/yr |
| period | int | Yes | 2–120 days |
| flags | int | No | 64 = hidden |
Funding types:
LIMIT— fixed rateFRRDELTAVAR— Flash Return Rate + delta (variable, rate adjusts)FRRDELTAFIX— Flash Return Rate + delta (fixed after match)
Cancel Funding Offer
{"id": 987654321}Funding Loans vs Credits
- Loans (
/funding/loans) — your lent funds that are NOT currently used in a position - Credits (
/funding/credits) — your lent funds that ARE currently used in a position
---
Response Arrays
Bitfinex v2 returns arrays, not objects. Key mappings:
Order Array
| Index | Field | Index | Field |
|---|---|---|---|
| 0 | ID | 6 | AMOUNT (remaining) |
| 3 | SYMBOL | 7 | AMOUNT_ORIG |
| 4 | MTS_CREATE | 8 | TYPE |
| 5 | MTS_UPDATE | 13 | STATUS |
| 17 | PRICE | 18 | PRICE_AVG |
Wallet Array
| Index | Field |
|---|---|
| 0 | WALLET_TYPE (exchange/margin/funding) |
| 1 | CURRENCY |
| 2 | BALANCE |
| 4 | AVAILABLE_BALANCE |
Position Array
| Index | Field | Index | Field |
|---|---|---|---|
| 0 | SYMBOL | 6 | PL |
| 1 | STATUS | 7 | PL_PERC |
| 2 | AMOUNT (+long/-short) | 8 | PRICE_LIQ |
| 3 | BASE_PRICE | 9 | LEVERAGE |
Funding Offer Array
| Index | Field | Index | Field |
|---|---|---|---|
| 0 | ID | 10 | STATUS |
| 1 | SYMBOL | 14 | RATE |
| 4 | AMOUNT | 15 | PERIOD |
| 5 | AMOUNT_ORIG | 19 | RENEW |
---
Security
- WRITE operations require "CONFIRM"
- Always show liquidation price before opening margin positions
- "Not financial advice. Trading carries significant risk of loss."
---
Bitget API Reference
Base URL
https://api.bitget.com
Success response: "code": "00000" — all other codes are errors.
---
Authentication
Credentials (from .env): BITGET_API_KEY, BITGET_SECRET_KEY, BITGET_PASSPHRASE
Signature: Base64(HMAC-SHA256(secret, timestamp + METHOD + path + body))
timestamp: Unix milliseconds- GET body =
"" - POST body = compact JSON
Headers (authenticated requests):
ACCESS-KEY: <api_key>
ACCESS-SIGN: <base64 signature>
ACCESS-PASSPHRASE: <passphrase>
ACCESS-TIMESTAMP: <unix ms>
Content-Type: application/json
locale: en-US---
Python Signature Implementation
import time, hmac, hashlib, base64, json, os, requests
from dotenv import dotenv_values
_env = dotenv_values()
API_KEY = _env["BITGET_API_KEY"]
SECRET_KEY = _env["BITGET_SECRET_KEY"]
PASSPHRASE = _env["BITGET_PASSPHRASE"]
BASE_URL = "https://api.bitget.com"
def _sign(ts, method, path, body_str=""):
msg = f"{ts}{method}{path}{body_str}"
mac = hmac.new(SECRET_KEY.encode(), msg.encode(), hashlib.sha256).digest()
return base64.b64encode(mac).decode()
def _headers(method, path, body_str=""):
ts = str(int(time.time() * 1000))
return {
"ACCESS-KEY": API_KEY,
"ACCESS-SIGN": _sign(ts, method, path, body_str),
"ACCESS-PASSPHRASE": PASSPHRASE,
"ACCESS-TIMESTAMP": ts,
"Content-Type": "application/json",
"locale": "en-US",
}
def bitget_get(path, params=None):
qs = ""
if params:
qs = "?" + "&".join(f"{k}={v}" for k, v in params.items())
h = _headers("GET", path + qs)
r = requests.get(f"{BASE_URL}{path}", params=params, headers=h, timeout=10)
data = r.json()
if data.get("code") != "00000":
raise Exception(f"Bitget error {data.get('code')}: {data.get('msg')}")
return data.get("data")
def bitget_post(path, body=None):
body_str = json.dumps(body, separators=(",", ":")) if body else ""
h = _headers("POST", path, body_str)
r = requests.post(f"{BASE_URL}{path}", data=body_str, headers=h, timeout=10)
data = r.json()
if data.get("code") != "00000":
raise Exception(f"Bitget error {data.get('code')}: {data.get('msg')}")
return data.get("data")---
Account Balance
| Method | Path | Description |
|---|---|---|
| GET | /api/v2/spot/account/assets | Spot balances |
| GET | /api/v2/mix/account/accounts | Futures account info (productType required: USDT-FUTURES, USDC-FUTURES, COIN-FUTURES) |
| GET | /api/v2/account/funding-assets | Funding account assets |
| GET | /api/v2/account/all-account-balance | All accounts overview |
---
Spot Endpoints
Market Data (Public)
| Method | Path | Description |
|---|---|---|
| GET | /api/v2/spot/market/tickers | Ticker (symbol optional — omit for all) |
| GET | /api/v2/spot/market/orderbook | Orderbook (symbol required, type=step0-5) |
| GET | /api/v2/spot/market/candles | Kline (symbol, granularity, startTime, endTime) |
| GET | /api/v2/spot/market/trades | Recent trades |
| GET | /api/v2/spot/public/symbols | Symbol info |
Trading (Private)
| Method | Path | Description |
|---|---|---|
| POST | /api/v2/spot/trade/place-order | Place order |
| POST | /api/v2/spot/trade/batch-orders | Batch place orders |
| POST | /api/v2/spot/trade/cancel-order | Cancel order |
| POST | /api/v2/spot/trade/batch-cancel-order | Batch cancel |
| POST | /api/v2/spot/trade/cancel-symbol-order | Cancel all for symbol |
| POST | /api/v2/spot/trade/cancel-replace-order | Atomic modify order |
| GET | /api/v2/spot/trade/orderInfo | Order details |
| GET | /api/v2/spot/trade/unfilled-orders | Open orders |
| GET | /api/v2/spot/trade/history-orders | Order history |
| GET | /api/v2/spot/trade/fills | Execution fills |
Spot order params: symbol, side (buy/sell), orderType (limit/market), price, size, force (gtc/ioc/fok/post_only)
Plan Orders (Private)
| Method | Path | Description |
|---|---|---|
| POST | /api/v2/spot/trade/place-plan-order | Create trigger order |
| POST | /api/v2/spot/trade/modify-plan-order | Modify trigger order |
| POST | /api/v2/spot/trade/cancel-plan-order | Cancel trigger order |
| POST | /api/v2/spot/trade/batch-cancel-plan-order | Batch cancel triggers |
| GET | /api/v2/spot/trade/current-plan-order | Open plan orders |
| GET | /api/v2/spot/trade/history-plan-order | Plan order history |
---
Futures (Mix) Endpoints
Market Data (Public)
| Method | Path | Description |
|---|---|---|
| GET | /api/v2/mix/market/tickers | All futures tickers (productType required) |
| GET | /api/v2/mix/market/ticker | Single futures ticker (symbol + productType) |
| GET | /api/v2/mix/market/depth | Orderbook (symbol, limit) |
| GET | /api/v2/mix/market/candles | Kline (trade/index/mark price types) |
| GET | /api/v2/mix/market/trades | Recent trades |
| GET | /api/v2/mix/market/current-fund-rate | Current funding rate (symbol, productType); response is array, use data[0].fundingRate |
| GET | /api/v2/mix/market/open-interest | Open interest |
Trading (Private)
| Method | Path | Description |
|---|---|---|
| POST | /api/v2/mix/order/place-order | Place order |
| POST | /api/v2/mix/order/batch-place-order | Batch place (max 50) |
| POST | /api/v2/mix/order/modify-order | Modify order (size, price, TP/SL) |
| POST | /api/v2/mix/order/cancel-order | Cancel order |
| POST | /api/v2/mix/order/batch-cancel-orders | Batch cancel |
| POST | /api/v2/mix/order/cancel-all-orders | Cancel all |
| GET | /api/v2/mix/order/detail | Order details |
| GET | /api/v2/mix/order/orders-pending | Open orders |
| GET | /api/v2/mix/order/orders-history | Order history |
| GET | /api/v2/mix/order/fills | Fills |
| GET | /api/v2/mix/order/fill-history | Fill history |
Futures order params: symbol, productType (USDT-FUTURES/USDC-FUTURES/COIN-FUTURES), side (buy/sell), tradeSide (open/close), orderType (limit/market), price, size, marginCoin, leverage
Position Management (Private)
| Method | Path | Description |
|---|---|---|
| GET | /api/v2/mix/position/single-position | Single position |
| GET | /api/v2/mix/position/all-position | All positions |
| GET | /api/v2/mix/position/history-position | Position history |
Configuration (Private)
| Method | Path | Description |
|---|---|---|
| POST | /api/v2/mix/account/set-leverage | Set leverage |
| POST | /api/v2/mix/account/set-margin-mode | Set margin mode (crossed/isolated) |
| POST | /api/v2/mix/account/set-position-mode | Set position mode |
| POST | /api/v2/mix/account/set-auto-margin | Auto margin addition |
---
Transfers
| Method | Path | Description |
|---|---|---|
| POST | /api/v2/spot/wallet/transfer | Internal transfer between accounts |
| POST | /api/v2/spot/wallet/subaccount-transfer | Transfer to subaccount |
---
Symbol Format
- Spot:
BTCUSDT - Futures:
BTCUSDTwithproductType=USDT-FUTURES
Rate Limits
- Public: 10-20 req/s per IP
- Private: 5-10 req/s per UID
- Configuration: 5 req/s per UID
Bitget Trading
Base URL: https://api.bitget.com | Spot: BTCUSDT | Futures: BTCUSDT + productType=USDT-FUTURES | Success: "code": "00000"
Full details in references/bitget-api-reference.md
Authentication
Credentials (from .env): BITGET_API_KEY, BITGET_SECRET_KEY, BITGET_PASSPHRASE
No Bitget account? Register at [https://www.bitget.com/](https://www.bitget.com/)
Verify credentials before any private call. If missing — STOP.
Signature: Base64(HMAC-SHA256(secret, timestamp + METHOD + path + body))
timestamp: Unix milliseconds- GET body =
"" - POST body = compact JSON (no spaces)
Headers (authenticated requests):
ACCESS-KEY: <api_key>
ACCESS-SIGN: <base64 signature>
ACCESS-PASSPHRASE: <passphrase>
ACCESS-TIMESTAMP: <unix ms>
Content-Type: application/json
locale: en-USPython signature implementation: references/bitget-api-reference.mdOperation Flow
Step 0: Credential Check
Verify BITGET_API_KEY, BITGET_SECRET_KEY, BITGET_PASSPHRASE. If missing — STOP.
Step 1: Pre-Trade Check (Futures)
- Query positions:
GET /api/v2/mix/position/all-position?productType=USDT-FUTURES - If position exists → inherit leverage and margin mode, do NOT override
Step 2: Execute
- READ → call, parse, display
- WRITE → present summary → ask "CONFIRM" → execute
Step 3: Verify
After order → query order status. After close → query positions.
Quick Reference
| Operation | Method | Path |
|---|---|---|
| Spot balances | GET | /api/v2/spot/account/assets |
| Futures account | GET | /api/v2/mix/account/accounts?productType=USDT-FUTURES |
| All balances | GET | /api/v2/account/all-account-balance |
| Place spot order | POST | /api/v2/spot/trade/place-order |
| Cancel spot order | POST | /api/v2/spot/trade/cancel-order |
| Spot open orders | GET | /api/v2/spot/trade/unfilled-orders |
| Place futures order | POST | /api/v2/mix/order/place-order |
| Cancel futures order | POST | /api/v2/mix/order/cancel-order |
| Futures positions | GET | /api/v2/mix/position/all-position |
| Set leverage | POST | /api/v2/mix/account/set-leverage |
| Set margin mode | POST | /api/v2/mix/account/set-margin-mode |
| Spot ticker | GET | /api/v2/spot/market/tickers |
| Futures ticker | GET | /api/v2/mix/market/ticker |
Security
- WRITE operations require "CONFIRM"
- Always show liquidation price before opening leveraged positions
- "Not financial advice. Trading carries significant risk of loss."
References
references/bitget-api-reference.md— spot + futures endpoints, Python signature
---
Close Position Workflow
Credentials: Read from.env—BITMART_API_KEY,BITMART_API_SECRET,BITMART_API_MEMO.
Scenario: Close a Long Position
User prompt: "Close my BTC long position on BitMart"
Step 1: Get current positions
curl -s -H "X-BM-KEY: $BITMART_API_KEY" \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/private/position-v2?symbol=BTCUSDT'Expected response:
{
"code": 1000,
"data": [
{
"symbol": "BTCUSDT",
"leverage": "10",
"current_amount": "100",
"position_amount": "100",
"position_side": "long",
"entry_price": "67000.0",
"mark_price": "67500.0",
"liquidation_price": "60500.0",
"unrealized_pnl": "50.00",
"initial_margin": "670.00",
"open_type": "cross"
}
]
}If no position is found, inform the user:
No open BTCUSDT long position found. Nothing to close.If multiple positions exist (e.g., both long and short in hedge mode), ask the user which one to close.
Step 2: Determine close side
| Position | Close Side | Description |
|---|---|---|
| Long | 3 (sell_close_long) | Sell to close the long position |
| Short | 2 (buy_close_short) | Buy to cover the short position |
For a long position: side = 3
Step 3: Present close summary and ask for CONFIRM
Close Position Summary:
Symbol: BTCUSDT
Direction: Close Long (sell_close_long, side=3)
Size: 100 contracts (entire position)
Type: Market
Entry Price: 67,000.0 USDT
Current Mark Price: 67,500.0 USDT
Unrealized PnL: +50.00 USDT (profit)
Estimated Realized PnL: ~+50.00 USDT
Please type CONFIRM to proceed.Step 4: Submit close order (after user confirms)
Note: Close orders only requiresymbol,side,type, andsize.
Do NOT includeleverageoropen_type— these fields are ignored for close orders and may cause confusion.
For limit close, addprice. For partial close, use a smallersize.
TIMESTAMP=$(date +%s000)
BODY='{"symbol":"BTCUSDT","side":3,"type":"market","size":100}'
SIGN=$(echo -n "${TIMESTAMP}#${BITMART_API_MEMO}#${BODY}" | openssl dgst -sha256 -hmac "$BITMART_API_SECRET" | awk '{print $NF}')
curl -s -X POST 'https://api-cloud-v2.bitmart.com/contract/private/submit-order' \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
-H "Content-Type: application/json" \
-H "X-BM-KEY: $BITMART_API_KEY" \
-H "X-BM-SIGN: $SIGN" \
-H "X-BM-TIMESTAMP: $TIMESTAMP" \
-d "$BODY"Expected response:
{
"code": 1000,
"data": {
"order_id": 23456789012345680
}
}Step 5: Verify position closed
curl -s -H "X-BM-KEY: $BITMART_API_KEY" \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/private/position-v2?symbol=BTCUSDT'Verify the position no longer appears or the parsed current_amount is 0.
Also check the fill details:
curl -s -H "X-BM-KEY: $BITMART_API_KEY" \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/private/order?symbol=BTCUSDT&order_id=23456789012345680'Step 6: Report realized PnL
Position Closed Successfully:
Symbol: BTCUSDT
Direction: Closed Long
Size: 100 contracts
Entry Price: 67,000.0 USDT
Exit Price: 67,498.5 USDT
Realized PnL: +49.85 USDT
Fees: 4.05 USDT
Net PnL: +45.80 USDT
Margin Released: 670.00 USDT
Not financial advice. You are solely responsible for your investment decisions.---
Scenario: Partial Close
User prompt: "Close half of my BTC long"
The flow is the same, but with size = 50 (half of 100):
{"symbol":"BTCUSDT","side":3,"type":"market","size":50}After partial close, report both the closed portion and the remaining position.
---
Scenario: Close a Short Position
User prompt: "Close my ETH short position"
- Query positions for ETHUSDT
- Use side = 2 (buy_close_short)
- For short positions, profit occurs when exit price < entry price
{"symbol":"ETHUSDT","side":2,"type":"market","size":50}---
Scenario: Limit Close
User prompt: "Close my BTC long at 70000"
Use a limit order instead of market:
{"symbol":"BTCUSDT","side":3,"type":"limit","price":"70000","size":100,"mode":1}Inform the user that the order will remain open until the price reaches 70000 or they cancel it.
---
Error Handling
| Error | Cause | Action |
|---|---|---|
| No position found | Position already closed or does not exist | Inform user |
| Size exceeds position | Trying to close more than held | Use the actual position amount |
code != 1000 on submit | Various | Report error message; do not retry automatically |
Order state failed | System rejection | Check order details for failure reason |
| Partially filled close | Slippage or liquidity | Report partial fill; suggest retrying for remainder |
BitMart Futures Trading
Base URL: https://api-cloud-v2.bitmart.com | Symbol: BTCUSDT (no underscore) | Success: code == 1000
53 endpoints — full details in references/bitmart-api-reference.md
Authentication
Credentials (from .env): BITMART_API_KEY, BITMART_API_SECRET, BITMART_API_MEMO
No BitMart account? Register at [https://www.bitmart.com/invite/cMEArf](https://www.bitmart.com/invite/cMEArf)
Verify credentials before any private call. If missing — STOP.
| Level | Endpoints | Headers |
|---|---|---|
| NONE | Public market data | — |
| KEYED | Read-only private | X-BM-KEY |
| SIGNED | Write operations | X-BM-KEY + X-BM-SIGN + X-BM-TIMESTAMP |
Signature: HMAC-SHA256(secret, "{timestamp}#{memo}#{body}") — GET body = ""
Always include `X-BM-BROKER-ID: BlaveData666666` on ALL requests.
IP Whitelist: Use public IP (curl https://checkip.amazonaws.com), not private IP (10.x, 172.x, 192.168.x).
Signature Python implementation and common mistakes: references/bitmart-signature.mdOperation Flow
Step 0: Credential Check
Verify BITMART_API_KEY, BITMART_API_SECRET, BITMART_API_MEMO. If missing — STOP.
Step 1.1: Query Positions (READ)
GET /contract/private/position-v2 (KEYED, no signature needed) Filter current_amount != "0" → display symbol, position_side, current_amount, entry_price, leverage, open_type, liquidation_price, unrealized_pnl
Step 1.5: Pre-Trade Check (MANDATORY before open/leverage)
1. Call GET /contract/private/position-v2?symbol=<SYMBOL> 2. If current_amount non-zero → inherit leverage and open_type, do NOT override 3. If user wants different values → STOP, warn to close position first
Step 1.55: Pre-Mode-Switch Check
Confirm no positions (Step 1.5) AND no open orders (GET /contract/private/get-open-orders). If either exists → STOP.
Step 1.6: TP/SL on Existing Position
POST /contract/private/submit-tp-sl-order — submit TP and SL as two separate calls
| Param | Value |
|---|---|
type | "take_profit" or "stop_loss" |
side | 3 close long / 2 close short |
trigger_price | Activation price |
executive_price | "0" for market fill |
price_type | 1 last / 2 mark |
plan_category | 2 |
Step 2: Execute
- READ → call, parse, display
- WRITE → present summary → ask "CONFIRM" → execute
submit-order rules:
| Scenario | Send | Omit |
|---|---|---|
| Open, market | symbol, side, type:"market", size, leverage, open_type | price |
| Open, limit | symbol, side, type:"limit", price, size, leverage, open_type | — |
| Close, market | symbol, side, type:"market", size | price, leverage, open_type |
| Close, limit | symbol, side, type:"limit", price, size | leverage, open_type |
Step 3: Verify
- After open:
position-v2→ report entry price, size, leverage, liquidation price - After close:
position-v2→ report realized PnL - After order:
GET /contract/private/order→ confirm status
Order Reference
Side: 1 Open Long / 2 Close Short / 3 Close Long / 4 Open Short
Mode: 1 GTC / 2 FOK / 3 IOC / 4 Maker Only
Timestamps: ms — always convert to local time for display.
Error Handling
| Code | Action |
|---|---|
| 30005 | Wrong signature → see references/bitmart-signature.md |
| 30007 | Timestamp drift → sync clock |
| 40012/40040 | Leverage/mode conflict → inherit existing position values |
| 40027/42000 | Insufficient balance → transfer from spot or reduce size |
| 429 | Rate limited → wait |
| 403/503 Cloudflare | Wait 30-60s, retry max 3× |
Spot ↔ Futures Transfer
Present summary → ask "CONFIRM" → execute.
Endpoint: POST https://api-cloud-v2.bitmart.com/account/v1/transfer-contract (SIGNED)
| Param | Value |
|---|---|
currency | USDT only |
amount | transfer amount |
type | "spot_to_contract" or "contract_to_spot" |
Rate limit: 1 req/2sec. ⚠️ /spot/v1/transfer-contract does NOT exist.
Security
- WRITE operations require "CONFIRM"
- Always show liquidation price before opening leveraged positions
- "Not financial advice. Futures trading carries significant risk of loss."
References
references/bitmart-api-reference.md— 53 endpointsreferences/bitmart-signature.md— Python signature implementationreferences/bitmart-open-position.md/bitmart-close-position.md/bitmart-plan-order.md/bitmart-tp-sl.md
---
Open Position Workflow
Credentials: Read from.env—BITMART_API_KEY,BITMART_API_SECRET,BITMART_API_MEMO.
Scenario: Open a Long Position
User prompt: "Open a 10x long BTC position with 100 contracts on BitMart"
Step 1: Pre-flight — Check futures balance
curl -s -H "X-BM-KEY: $BITMART_API_KEY" \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/private/assets-detail'Verify the user has sufficient available_balance in USDT. If insufficient, suggest transferring from spot:
Insufficient futures balance. Available: 50.00 USDT, Required: ~670 USDT (estimated).
Would you like to transfer USDT from your spot wallet?Step 2: Pre-flight — Check contract details
curl -s -H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/public/details?symbol=BTCUSDT'Validate:
contract_size— to calculate margin requirementmin_volume— ensure order size meets minimummax_volume— ensure order size does not exceed maximummax_leverage— ensure requested leverage is supportedprice_precision— for limit orders
Step 3: Pre-flight — Check leverage brackets
curl -s -H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/public/leverage-bracket?symbol=BTCUSDT'Verify the requested leverage (10x) is available for the position size. If position size exceeds the tier limit, warn the user:
Warning: At 10x leverage, maximum position is 500,000 contracts.
Your requested 100 contracts is within limits.Step 3.5: Check existing position (MANDATORY)
Before setting leverage or submitting an order, check for existing positions:
curl -s -H "X-BM-KEY: $BITMART_API_KEY" \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/private/position-v2?symbol=BTCUSDT'position-v2 returns a data[] array. Do not assume there is only one row:
- In
one_way_mode, you will typically see one row withposition_side="both" - In some account / mode combinations, you may see multiple rows for the same symbol (for example
position_side="long"andposition_side="short"), even when both sides are zero
Use this step to answer two questions only:
- Does a position already exist?
- If yes, which
leverageandopen_typemust be inherited?
Do not rely on position-v2 for position_mode. Query get-position-mode later only when the workflow becomes mode-sensitive (for example, deciding whether to switch modes or explaining hedge vs one-way behavior).
Evaluate the entire data[] array:
Parse each row's current_amount as a number before comparing it. The API returns string values such as "0".
If any row's parsed `current_amount` is non-zero (existing position found):
- Treat the symbol as having an existing position
- Use the relevant non-zero position row's
leverageandopen_typevalues in the order — do NOT send different values - If user requested different leverage or margin mode → STOP and warn:
"You have an existing position. Close it first before changing leverage or margin mode."
- Do NOT call
submit-leveragewith different values — API will return 40012/40040 - Do not attempt to change
position_modewhile an existing position is present - Skip Step 4 and continue with the current account mode in Step 5
If every row's parsed `current_amount` is 0 (no existing position):
- Proceed with user-requested leverage and margin mode (Step 4)
Step 4: Set leverage (if needed — skip if existing position found in Step 3.5)
Only execute this step when no existing position was found in Step 3.5:
TIMESTAMP=$(date +%s000)
BODY='{"symbol":"BTCUSDT","leverage":"10","open_type":"cross"}'
SIGN=$(echo -n "${TIMESTAMP}#${BITMART_API_MEMO}#${BODY}" | openssl dgst -sha256 -hmac "$BITMART_API_SECRET" | awk '{print $NF}')
curl -s -X POST 'https://api-cloud-v2.bitmart.com/contract/private/submit-leverage' \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
-H "Content-Type: application/json" \
-H "X-BM-KEY: $BITMART_API_KEY" \
-H "X-BM-SIGN: $SIGN" \
-H "X-BM-TIMESTAMP: $TIMESTAMP" \
-d "$BODY"Step 5: Check current position mode and set it only if safe
Query the account-wide position_mode only when you need a mode-sensitive decision, such as deciding whether a mode switch is needed or explaining current hedge/one-way behavior:
curl -s -H "X-BM-KEY: $BITMART_API_KEY" \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/private/get-position-mode'Read the current account-wide position mode first:
- If Step 3.5 found any existing position (any row's parsed
current_amountis non-zero), do not callset-position-mode - If the user requested a different position mode while an existing position is present, STOP and tell them to close the existing position first
- Before any mode switch, check that there are no open orders on the account:
curl -s -H "X-BM-KEY: $BITMART_API_KEY" \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/private/get-open-orders'- If any open orders are present, STOP and tell the user to cancel them before changing
position_mode - Only consider calling
set-position-modewhen Step 3.5 found no existing position andget-open-ordersis empty
If the user wants hedge mode (to hold long and short simultaneously), Step 3.5 found no existing position, and the current mode is not already hedge_mode, set it:
TIMESTAMP=$(date +%s000)
BODY='{"position_mode":"hedge_mode"}'
SIGN=$(echo -n "${TIMESTAMP}#${BITMART_API_MEMO}#${BODY}" | openssl dgst -sha256 -hmac "$BITMART_API_SECRET" | awk '{print $NF}')
curl -s -X POST 'https://api-cloud-v2.bitmart.com/contract/private/set-position-mode' \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
-H "Content-Type: application/json" \
-H "X-BM-KEY: $BITMART_API_KEY" \
-H "X-BM-SIGN: $SIGN" \
-H "X-BM-TIMESTAMP: $TIMESTAMP" \
-d "$BODY"Note: BitMart rejects set-position-mode when the account is not in a clean state for mode switching. Existing positions will fail, and open orders may also fail with 40059 ("Some positions exist and the mode switching fails."). If mode switching fails, stop and ask the user to clear existing positions / open orders before retrying.
Step 6: Present order summary and ask for CONFIRM
Display to user:
Position Summary:
Symbol: BTCUSDT
Direction: Long (buy_open_long, side=1)
Type: Market
Size: 100 contracts
Leverage: 10x
Margin Mode: Cross
Estimated Entry: ~67,123 USDT
Estimated Margin: ~671 USDT
Estimated Liquidation: ~60,500 USDT
WARNING: Futures trading carries significant risk. Higher leverage
amplifies both gains and losses. You could lose your entire margin.
Please type CONFIRM to proceed.Step 7: Submit order (after user confirms)
Parameter rules (must match SKILL.md Step 2a):
- Market order: do NOT include
pricefield — it is ignored and causes confusion - If existing position found in Step 3.5: use
leverageandopen_typefrom the relevant non-zero position row, not user-requested values - `size` must be an integer (number of contracts) — check min/max via
GET /contract/public/details - Maker Only (`mode=4`): only valid with
type=limit, never withtype=market
TIMESTAMP=$(date +%s000)
BODY='{"symbol":"BTCUSDT","side":1,"type":"market","size":100,"leverage":"10","open_type":"cross"}'
SIGN=$(echo -n "${TIMESTAMP}#${BITMART_API_MEMO}#${BODY}" | openssl dgst -sha256 -hmac "$BITMART_API_SECRET" | awk '{print $NF}')
curl -s -X POST 'https://api-cloud-v2.bitmart.com/contract/private/submit-order' \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
-H "Content-Type: application/json" \
-H "X-BM-KEY: $BITMART_API_KEY" \
-H "X-BM-SIGN: $SIGN" \
-H "X-BM-TIMESTAMP: $TIMESTAMP" \
-d "$BODY"Expected response:
{
"code": 1000,
"data": {
"order_id": 23456789012345678
}
}Step 8: Verify position
curl -s -H "X-BM-KEY: $BITMART_API_KEY" \
-H "User-Agent: bitmart-skills/futures/v2026.3.23" \
-H "X-BM-BROKER-ID: BlaveData666666" \
'https://api-cloud-v2.bitmart.com/contract/private/position-v2?symbol=BTCUSDT'Step 9: Report results
Position Opened Successfully:
Symbol: BTCUSDT
Direction: Long
Size: 100 contracts
Entry Price: 67,123.4 USDT
Leverage: 10x
Margin Mode: Cross
Margin Used: 671.23 USDT
Liquidation Price: 60,500.0 USDT
Mark Price: 67,125.0 USDT
Unrealized PnL: +0.16 USDT
Not financial advice. Futures trading carries significant risk of loss.---
Scenario: Open a Short Position
User prompt: "Short ETH with 20x leverage, 50 contracts, isolated margin"
The flow is the same as above, with these differences:
- Side: 4 (sell_open_short) instead of 1
- Leverage: 20x
- Open type: isolated
- Liquidation direction: above entry price (for shorts, liquidation is at higher price)
Order body:
{"symbol":"ETHUSDT","side":4,"type":"market","size":50,"leverage":"20","open_type":"isolated"}---
Error Handling
| Error | Cause | Action |
|---|---|---|
code != 1000 on submit | Various | Report error message; do not retry automatically |
| Insufficient balance | Not enough margin | Suggest transferring from spot or reducing position size |
| Invalid leverage | Exceeds bracket limit | Show leverage brackets and suggest a valid leverage |
| Position mode conflict | Has open positions | Cannot change mode; inform user to close positions first |
| Invalid size | Below min or above max | Show contract details with min/max volume |
Related skills
FAQ
When is CONFIRM required?
Any write action including place or cancel orders, transfers, leverage changes, or funding moves requires the user to reply exactly CONFIRM.
How should multi-coin screening start?
Use alpha_table first for one request across all symbols before drilling into individual get_alpha historical endpoints.
What credentials does Blave need?
Set blave_api_key and blave_secret_key in the environment; exchange modules use their own optional API key variables.
Is Blave Quant safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.