BtApi¶
BtApi is the single public façade. It builds a DirectBackend by default; passing transport_mode=TransportMode.ZMQ and a ForwardingConfig activates the forwarding backend.
from bt_api_py import BtApi, ForwardingConfig, TransportMode
api = BtApi(
debug=False,
transport_mode=TransportMode.ZMQ,
forwarding_config=ForwardingConfig(
command_endpoint="tcp://gateway.example:5555",
market_endpoint="tcp://gateway.example:5556",
private_endpoint="tcp://gateway.example:5557",
account_id="paper",
strategy_id="strategy-a",
),
)
The endpoints above are illustrative; configuring a client does not establish a production authorization boundary. Inspect api.get_capabilities(exchange_name) before relying on an operation.
bt_api_py.bt_api.BtApi ¶
Bases: DataDownloaderMixin, BalanceManagerMixin
统一多交易所 API 入口,通过 ExchangeRegistry 实现交易所即插即用。
configure_execution(execution_config, *, _exchange_names=()) ¶
Enable an optional execution session; the same configuration is idempotent.
Configure before subscribing or submitting orders. Replacing a live session's journal is forbidden. The journal lock is held until close().
new_client_order_id(exchange_name, account_id=None, strategy_id=None) ¶
Allocate a numeric client reference before the caller binds its order.
Allocation reserves the value locally; only a persisted order intent consumes it. Decimal references also fit CTP's native OrderRef contract.
get_execution_identity(exchange_name) ¶
Return the SDK-owned ledger identity used for typed order requests.
get_execution_summary() ¶
Read session execution evidence without touching a transport adapter.
recover_reservation_only_cancel_unknowns() ¶
Resolve locally proven reservation-only cancel unknowns before Store startup.
The SDK execution session checks the durable journal sequence and writes only a local terminal journal event. No venue adapter is consulted.
recover_historical_documented_definite_rejections() ¶
Resolve only historical unknowns proven rejected by a documented venue code.
evaluate_ctp_execution_budget(evidence, *, mode='ordinary', now=None) staticmethod ¶
Evaluate provider-neutral CTP path evidence without reserving funds.
reserve_ctp_execution_budget(evidence, *, mode='ordinary', now=None, reservation_id=None) ¶
Durably reserve one CTP path budget in the existing execution journal.
get_account_risk_snapshot(*, initialize_baseline=False) ¶
Return SDK-owned, durable account-equity evidence for execution.
The method performs authenticated normalized account and position reads for every configured crypto venue. Before the first baseline it also queries each venue's remote open orders through this public normalized API. It never accepts runner-supplied equity, flatness, or empty-order claims. A first baseline is persisted only when both the initial and commit-time remote open-order sweeps are known empty, all positions are authoritatively known flat, and the execution journal has no active or unknown order.
reset_account_maximum_loss_latch() ¶
Explicitly reset a breached loss latch after authoritative flat proof.
The reset re-baselines equity only after two normalized open-order sweeps, normalized flat positions on every configured venue, and a clean durable execution ledger. Any missing or conflicting evidence leaves the persisted latch unchanged.
async_get_account_risk_snapshot(*, initialize_baseline=False) async ¶
Run the authenticated risk snapshot without blocking an event loop.
async_reset_account_maximum_loss_latch() async ¶
Run the explicit loss-latch reset without blocking an event loop.
get_event_metrics() ¶
Return process-local ingress/coalescing counters without resetting them.
reconcile_private_state(exchange_name, *, connection_generation=None) ¶
Backfill private state after reconnect and publish one audit status.
async_reconcile_private_state(exchange_name, *, connection_generation=None) async ¶
Run private reconnect backfill without blocking the caller's loop.
get_environment_info(exchange_name) ¶
Return the selected transport environment without configuration secrets.
Direct feeds expose their resolved environment through the venue's exchange-data object. A ZMQ client cannot prove the gateway's server-side environment, so it deliberately reports an unverified unknown value.
poll_event(exchange_name) ¶
Poll normalized events and advance configured pending-order reconciliation.
Reconciliation is time based and runs even while market events keep arriving. No placement is retried. Call this without requiring a bar.
poll_events(exchange_name, *, max_raw_items=100, coalesce_market_snapshots=()) ¶
Poll a finite batch of normalized events from one exchange.
poll_event(exchange_name) keeps its historical one-event FIFO contract. This batch API is an opt-in path for latency-sensitive consumers which may explicitly coalesce complete market snapshots.
max_raw_items counts items removed from the exchange transport, not normalized events produced by a container. None means the finite Queue.qsize() snapshot observed at the start of a direct-transport call; items appended by producers during the call remain for the next poll. Transports without an inspectable queue use the conservative default batch bound of 100 when None is requested.
Only explicitly named complete snapshot kinds are coalesced. Currently orderbook and tick are supported. Coalescing is per kind and symbol, and only within a contiguous market-data segment. Every other event is a barrier, so order, trade, account and position events are neither discarded nor reordered. Callers must not opt incremental order-book deltas into snapshot coalescing.
init_exchange(exchange_kwargs) ¶
根据 exchange_kwargs 初始化并添加交易所。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
exchange_kwargs | dict[str, Any] | {exchange_name: params} 格式的配置。 | 必需 |
init_logger() ¶
Initialize and return the API logger instance.
add_exchange(exchange_name, exchange_params) ¶
Add a new exchange to the API instance.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
exchange_name | str | Exchange identifier (e.g., "BINANCESPOT", "OKXSWAP") | 必需 |
exchange_params | dict[str, Any] | Exchange-specific parameters (api_key, secret, etc.) | 必需 |
Example
api = BtApi() api.add_exchange("BINANCE___SPOT", { ... "api_key": "your_key", ... "secret": "your_secret", ... "testnet": True ... })
get_request_api(exchange_name) ¶
Get the REST Feed instance for the specified exchange (synchronous API).
ZMQ transport has no direct feed escape hatch and raises CapabilityNotSupportedError instead of returning None.
get_async_request_api(exchange_name) ¶
Deprecated alias for get_request_api.
build_ctp_execution_approval_context(context, *, exchange_name='CTP___FUTURE', configuration=None, strategy_source=None, preflight=None, evidence=None, source='sdk_runtime', deployment_manifest=None) ¶
Collect a sealed approval context from this running deployment.
Runtime package/native hashes, the CTP account/day/generation and the resolved environment are read here; callers cannot establish those identities by copying strings into a mapping. Application material is supplied as raw bytes, paths, or JSON values and hashed by the SDK. deployment_manifest can pin the locally observed runtime hashes, but it cannot replace them.
verify_ctp_execution_approval(artifact, *, trust_root, context) ¶
Verify an independent CTP approval without arming a native gate.
trust_root is deployment-owned key and revocation configuration; context must be the sealed SDK-collected runtime/deployment-manifest identity for non-synthetic sources, including the exact instrument scope and all artifact hashes. A plain mapping is reserved for explicit synthetic_test offline evidence. The method performs no network I/O and never invokes the controlled test issuer or a native CTP write path.
verify_ctp_execution_recovery_approval(artifact, *, trust_root, context) ¶
Verify only the versioned recovery-purpose approval contract.
redeem_ctp_execution_approval(approval, *, trust_root, context) ¶
Durably consume a verified approval and return process-local opaque evidence.
Revalidation immediately before consumption observes expiry, current deployment context, and the current trusted revocation snapshot. The existing execution journal must fsync the nonce before this method returns. An ordinary-purpose capability remains ineligible for native arming; a recovery-purpose capability is accepted only by the separate bounded recovery entry point.
preauthorize_ctp_execution_approval(approval, *, trust_root, context) ¶
Persist approval evidence while retaining a read-only session.
record_ctp_execution_approval_revocation_snapshot(*, trust_root) ¶
Durably record a newer deployment revocation snapshot.
The SDK does not fetch or infer revocations. A deployment supplies its independently managed trust-root snapshot; this method records it in the same fenced execution journal so a restart cannot roll back to an older version.
arm_execution_from_preflight(authorization) ¶
Atomically arm CTP only from a core-issued opaque authorization.
prepare_execution_authorization(reason='execution_authorization_prepared') ¶
Reset managed CTP to reusable read-only state before Stage A.
prepare_execution_recovery(*, proof) ¶
Issue an SDK-owned recovery plan from two fenced query rounds.
arm_execution_recovery(*, authorization=None, recovery_token_sha256, proof=None, budget_capability=None) ¶
Arm bounded recovery from a redeemed opaque recovery approval.
proof is retained as an audit-only compatibility keyword. It is never interpreted as authority and cannot reach the native bridge.
arm_execution_from_approval(approval_capability) ¶
Arm normal CTP execution from one redeemed entry approval.
The capability must come from redeem_ctp_execution_approval with a signed ctp-execution-entry-approval-v1 artifact whose scope, run material, and strategy identity match this running deployment. The approval is one-shot: every later failure stays conservative and the nonce cannot arm twice in-process.
confirm_ctp_settlement_from_approval(approval_capability, *, exchange_name='CTP___FUTURE', timeout=5.0) ¶
Confirm settlement once from a separately redeemed entry approval.
The settlement confirmation is the one terminal write a still market-data-only session may perform: without it the account can never reach the confirmed state ordinary arming requires. The caller must redeem an independently signed ctp-execution-entry-approval-v1 artifact bound to this session's account/day/generation; the capability is one-shot for settlement and independent of its entry arming use.
complete_execution_recovery(*, recovery_token_sha256) ¶
Prove flatness with a fresh query barrier and revoke recovery writes.
disarm_execution(reason='execution_arm_revoked') ¶
Idempotently revoke execution while retaining read-only CTP access.
get_ctp_session_state(exchange_name='CTP___FUTURE') ¶
Return CTP auth/login/settlement evidence without exposing the native client.
query_ctp_result(exchange_name, query_type, **kwargs) ¶
Run one typed, completion-aware CTP read query.
verify_ctp_settlement(exchange_name='CTP___FUTURE', *, timeout=5.0) ¶
Verify an account/day server record and promote only that live session.
confirm_ctp_settlement(exchange_name='CTP___FUTURE', *, timeout=5.0) ¶
Fail closed: public callers cannot authorize a terminal CTP write.
A settlement confirmation is not a read preflight action. This iteration has no production core signer, so state hashes, a managed capability, and this public method itself are deliberately insufficient to issue the independent one-shot native settlement authorization.
get_data_queue(exchange_name) ¶
Get the data queue for the specified exchange.
The data queue receives market data and order updates from WebSocket streams.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
exchange_name | str | Exchange identifier (e.g., "BINANCE___SPOT") | 必需 |
返回:
| 类型 | 描述 |
|---|---|
Any | None | Queue instance if exchange exists, None otherwise |
Example
api = BtApi({"BINANCESPOT": {...}}) queue = api.getdata_queue("BINANCE_SPOT") data = queue.get() # Blocks until data arrives
subscribe(dataname, topics) ¶
通过 ExchangeRegistry 查找订阅处理函数,无需硬编码交易所类型
get_event_bus() ¶
获取事件总线实例
put_ticker(ticker_data, exchange_name=None) ¶
Push a simulated ticker update into the event bus and optional exchange queue.
list_exchanges() ¶
列出所有已添加的交易所
close() ¶
Release transports and the execution lock, including on close failure.
async_close() async ¶
Close all exchange feeds (WebSocket streams + HTTP clients).
list_available_exchanges() staticmethod ¶
列出所有已注册可用的交易所
get_tick(exchange_name, symbol, extra_data=None, **kwargs) ¶
获取最新行情 :param exchange_name: 交易所标识, 如 "BINANCE___SWAP" :param symbol: 交易对, 如 "BTC-USDT"
get_depth(exchange_name, symbol, count=20, extra_data=None, **kwargs) ¶
获取深度数据 :param exchange_name: 交易所标识 :param symbol: 交易对 :param count: 深度档数
get_kline(exchange_name, symbol, period, count=20, extra_data=None, **kwargs) ¶
获取K线数据 :param exchange_name: 交易所标识 :param symbol: 交易对 :param period: K线周期, 如 "1m", "5m", "1H", "1D" :param count: K线数量
get_exchange_info(exchange_name, symbol=None, extra_data=None, **kwargs) ¶
Read native instrument metadata through the direct transport.
Returns the feed's native response unchanged. Binance exchange info includes symbols[].filters; OKX instruments include ctVal, ctValCcy, lotSz, minSz and tickSz. Callers must use these fields to distinguish base-asset quantities from contract quantities. The forwarding protocol does not currently support this operation.
get_funding_rate(exchange_name, symbol, extra_data=None, **kwargs) ¶
Read perpetual funding data, preserving the feed-native response and units.
get_instrument_spec(exchange_name, symbol, extra_data=None, *, refresh=False, **kwargs) ¶
Return strict Decimal quantity/price rules while preserving legacy reads.
get_fee_schedule(exchange_name, symbol, account_id, extra_data=None, **kwargs) ¶
Read account fee rates as an explicit available/unavailable snapshot.
get_funding_snapshot(exchange_name, symbol, extra_data=None, **kwargs) ¶
Read the next funding settlement as a Decimal typed snapshot.
get_trading_readiness(exchange_name, symbol, account_id, quantity_native=None, *, margin_mode='cross', position_mode=None, extra_data=None) ¶
Return a conservative typed preflight for OKX or Binance perpetuals.
async_get_trading_readiness(exchange_name, symbol, account_id, quantity_native=None, *, margin_mode='cross', position_mode=None, extra_data=None) async ¶
Run the same typed readiness contract without blocking the event loop.
get_account_config(exchange_name, extra_data=None, *, normalized=False) ¶
Read account mode and explicit trading permission without changing either.
OKX exposes this operation as get_config; its native data entries include posMode and API-key permissions. Binance USD-M futures exposes dualSidePosition and canTrade together through its read-only account-configuration endpoint.
get_position_mode(exchange_name, extra_data=None, *, normalized=False) ¶
Read the native position mode without modifying it.
Binance returns dualSidePosition. OKX reports posMode inside its account configuration response. Neither format is normalized to a boolean, and unsupported feeds fail explicitly.
set_position_mode(exchange_name, position_mode, extra_data=None, *, normalized=True, **kwargs) ¶
Set and read back an account-wide perpetual position mode.
The public contract accepts only net and dual_side. A provider acknowledgement is insufficient: the method reads the position mode back from the account and returns only after the requested value is observed. An uncertain outcome invalidates the local mode cache and blocks normalized placements until a fresh normalized read verifies it.
get_order_readiness(exchange_name, symbol, quantity_native, *, margin_mode='cross', position_mode=None, normalized=True, extra_data=None) ¶
Inspect perpetual order prerequisites without submitting an order.
quantity_native is an OKX contract count or Binance base-asset quantity. A result with ready=True still carries execution_unproven=True because only an exchange order response can prove execution access.
make_order(exchange_name, symbol, volume=None, price=None, order_type=None, offset='open', post_only=False, client_order_id=None, extra_data=None, **kwargs) ¶
下单。
标准形式(v1):make_order(exchange_name, OrderRequest(...))。 兼容形式:make_order(exchange_name, symbol, volume, price, "buy-limit"); 仅当 order_type 能推导 side(side-type)时兼容,裸 limit/market 无法推导 side 时抛 LegacyOrderApiError。
cancel_order(exchange_name, symbol, order_id=None, extra_data=None, **kwargs) ¶
撤单 :param exchange_name: 交易所标识 :param symbol: 交易对 :param order_id: 订单ID
cancel_all(exchange_name, symbol=None, extra_data=None, **kwargs) ¶
撤销所有订单 :param exchange_name: 交易所标识 :param symbol: 交易对 (None 表示所有品种)
query_order(exchange_name, symbol, order_id=None, extra_data=None, **kwargs) ¶
查询订单 :param exchange_name: 交易所标识 :param symbol: 交易对 :param order_id: 订单ID
get_open_orders(exchange_name, symbol=None, extra_data=None, **kwargs) ¶
查询挂单 :param exchange_name: 交易所标识 :param symbol: 交易对 (None 表示所有品种)
get_deals(exchange_name, symbol=None, extra_data=None, **kwargs) ¶
查询账户成交/成交明细,用于获取真实手续费。
Different exchange feeds expose private fills as get_deals. Keep the unified facade thin so callers can pass through exchange-specific arguments such as limit, count, start_time or end_time.
get_trades(exchange_name, symbol=None, extra_data=None, **kwargs) ¶
查询成交记录。
Some venues use this for public recent trades, while gateway adapters may map it to account fills. Callers that require real account fees should prefer :meth:get_deals when the feed supports it.
get_balance(exchange_name, symbol=None, extra_data=None, **kwargs) ¶
查询余额 :param exchange_name: 交易所标识 :param symbol: 币种 (None 表示全部)
get_account(exchange_name, symbol='ALL', extra_data=None, **kwargs) ¶
查询账户信息 :param exchange_name: 交易所标识 :param symbol: 币种
get_position(exchange_name, symbol=None, extra_data=None, **kwargs) ¶
查询持仓 :param exchange_name: 交易所标识 :param symbol: 交易对 (None 表示所有品种)
get_capabilities(exchange_name) ¶
Return a read-only capability report for the given exchange.
get_command_status(exchange_name, command_id) ¶
Reconcile a ZMQ command after :class:CommandResultUnknownError.
Direct feeds have no shared forwarding receipt store, so callers must use their native venue query semantics in that transport mode.
get_all_ticks(symbol, extra_data=None, **kwargs) ¶
从所有已连接的交易所获取行情 :param symbol: 交易对 :return: dict {exchange_name: ticker_data 或 Exception}
get_all_balances(symbol=None, extra_data=None, **kwargs) ¶
从所有已连接的交易所查询余额 :return: dict {exchange_name: balance_data 或 Exception}
get_portfolio_balance(*, venue_balances=None) ¶
Aggregate normalized accounts only when all values share a currency.
A supplied snapshot avoids issuing the same account requests twice. No currency conversion or partial-success aggregation is implied.
get_all_positions(symbol=None, extra_data=None, **kwargs) ¶
从所有已连接的交易所查询持仓 :return: dict {exchange_name: position_data 或 Exception}
cancel_all_orders(symbol=None, extra_data=None, **kwargs) ¶
撤销所有已连接交易所的所有订单 :return: dict {exchange_name: result 或 Exception}