Skip to content
cloudQuantPublic

About

A Python SDK for Multi-Exchange Integration with Standardized API

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

1 watching

Forks

Latest commit

 

History

2,014 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

bt_api_py

The current checkout has SDK-family submodules under bt_api/, including Base, CTP, OKX, Binance, Risk, Gateway, Execution and Monitor. A checkout or installed package does not establish that a provider route, service, account or release has been accepted. Historical descriptions below are dated source snapshots.

The CTP operator calendar configuration can explicitly select native session day changes instead of a fixed simulation bootstrap. Keep mode: SIMULATION_ONLY, set simulation_bootstrap to null, and add:

day_switch:
  source: CTP_AUTHENTICATED_SESSION
  poll_interval_seconds: 1
  owner_wait_seconds: 1
  close_timeout_seconds: 3

The existing explicit calendar root, grants and range policies remain required. The original Gateway owner captures and rechecks its authenticated read session; a separate worker loads receipt-checked calendar files. A strictly later native trading day can activate a new version. Same-day publication or reconnect keeps the bound version; a new process can load the latest valid publication. A stale session, regressing day or failed load retains the old fixed view and reports a finite degraded status through binding.calendar_day_switch_status(). Unconfirmed worker cleanup retains the original resources. This observation does not establish settlement, R-3 recovery, account readiness or permission to trade. Calendar data keeps its existing simulation provenance and coverage limits.

GatewayRecoveryClockQualifier can qualify a past interval against the original owner's explicitly enabled clock publication history. It returns conservative UTC endpoint bounds and local sample references, or UNKNOWN for unavailable history, expired coverage or inconsistent overlapping calibrations. Truncated history is usable only after omitted calibrations are provably expired or a recorded reset starts a new segment. The result is local to the process; SNTP remains unauthenticated. The trusted Python factory can persist these results through the explicit local_clock_v1 recorder option described below. The trading operator loader supports explicit recorder settings; Monitor duration evaluation is not yet connected. Qualification does not prove that a recovery condition held.

Iteration 64 is in progress and not accepted. The SDK assembles an independent Risk service and authenticated Gateway clients; Risk owns pre-trade policy and its ledger, while providers supply source facts. Default self-trade protection currently refuses OPEN/CLOSE because complete source-bound active-order coverage is unavailable. Account and intraday coverage, financial facts, Execution parent/child write authority and cross-generation not-sent proof remain gaps. R-11 v2 parses scoped rule metadata but does not by itself prove venue facts or enable trading. Selected Risk never falls back to direct. Consult the Backtrader iteration-64 review for scoped source, simulation and wheel evidence.

Risk operator cancellation requires an explicit scope grant in the Risk service principal configuration. The following is an illustrative principal entry:

- principal_ref: operations-example
  role: operator
  actor_ref: operations-actor
  strategy_refs: []
  operations: [risk.cancel.request, risk.cancel.status]
  public_key_file: keys/operations-example.public
  cancel_scope_grants:
    account: false
    strategies: [strategy-a]
    instruments: ["SHFE:rb"]

account, strategies and instruments are independent grants: account-wide permission does not imply permission for a strategy or instrument. Instrument entries use <venue>:<native_symbol>. Omitting cancel_scope_grants denies all operator cancel scopes; configurations that previously relied only on risk.cancel.request or risk.cancel.status must add explicit grants. A malformed grant is rejected before key files are read. A caller also needs the corresponding operation and Gateway authorization. Strategy-scope Gateway dispatch and source-bound status remain under development; an authorized strategy request does not establish that any cancellation was sent or completed.

The Risk service setting service.strict_admin_cancel is optional and defaults to false. Set it to true to require Registry admission around the local operator-cancel claim and its commit-time grant recheck. This mode records a local UNKNOWN intent only and does not send a cancellation to Gateway; a repeat or uncertain commit does not authorize a retry. With false, the existing operator-cancel path remains in use: it can call the Gateway control adapter for supported scopes, but strategy scope is currently refused locally and remote status remains UNKNOWN without original journal/generation binding. Neither mode proves that a venue cancellation occurred.

Risk clients require a runtime that proves strict unregister acknowledgement. The SDK compose() path constructs its own lazy runtime and is the only path that installs an automatic reconnect factory. A publicly injected runtime_factory is accepted for compatibility but is not invoked; an injected initial runtime is a trusted in-process extension, not a sandbox against arbitrary Python side effects. Unconfirmed registrations or cleanup retain the original resources and block replacement; this can make automatic recovery unavailable. Explicit ACK does not by itself prove an earlier handler has drained or resolve an UNKNOWN command.

The Risk host now binds account-observer RPC responses to the configured Gateway SERVICE identity and CURVE key through the runtime owner's call_bound path, including after reconnect. An acknowledgement requires the original read's client-held token, epoch, registration and contiguous returned prefix; the Risk cursor is committed before acknowledgement. This authenticates the particular response, not account completeness or continuing authorization across a later database transaction. The v1 order quarantine remains enabled. Other callers of GatewayAccountObserverClient retain the compatibility mode unless both peer and fingerprint are explicitly supplied.

CTP front selection uses bt_api_ctp.ctp_env_selector; the old SDK facade and its YAML configuration are removed. The provider selects its own defaults, which differ from the old facade, and automatic set1 selection requires verified trading-day evidence. This source change has not been behavior- or account-accepted.

Position-mode acknowledgement codes are provider declarations: the Base default is unspecified. Binance, CTP and non-swap OKX preserve the previous 200; OKX swap preserves 0, and ten historical policies retain 200. These inherited values do not prove venue capability. Third-party Base subclasses no longer receive a default; dynamic policies, packaging and behavior remain unvalidated.

Binance/OKX bound read-only runtime registration and exact owner/config checks live in their providers; Base carries the SDK-injected API type, and SDK owns composition and finite error mapping. The two SDK-specific registration modules and compose_binance_read_only_runtime / compose_okx_read_only_runtime are removed. compose_read_only_runtime creates a new owner and differs from reusing an existing one. Entry points, thread/cleanup and behavior remain unaccepted. CTP managed-runtime route, environment and instrument-field checks live in bt_api_ctp.managed_runtime_route_validation; SDK retains grant expiry, session and lifecycle. Importing the CTP-specific SDK module requires that provider. CTP preflight settlement settings are provider-owned; the SDK selects the route and retains the call timing and error type. The CTP provider is loaded on demand and this path is unaccepted.

Execution-ledger identity format is declared per provider via bt_api_base.execution_ledger_identity_policy, not hard-coded venue names. The 13 built-in providers retain their prior format choices; this does not prove identity. Missing or undiscoverable declarations fail, including historical/custom providers, and successful selections are process-cached. Migration, packaging and behavior remain unaccepted. A separate provider account_risk_source_policy declares whether native account binding is still required for neutral risk reads. CTP remains unavailable; the other 12 retain the old branch, not proof of source. Undeclared providers fail and discovery/behavior are unaccepted.

Gateway SDK composition now accepts the neutral GatewayMarketBinding and a trusted provider factory; GatewayOkxMarketBinding and the okx_market parameter are removed. An OKX caller supplies bt_api_okx.market_provider.OkxTickerQueueMarketProvider as its factory. The generic binding permits nonempty per-principal subsets; OKX key validation occurs at subscription and provider settings at construction. This breaking source change and lifecycle behavior are unaccepted.

CTP managed Risk order payload construction and cancel-target matching live in bt_api_ctp.risk_dispatch_binding; Base declares the optional provider contract, while SDK retains evidence selection; Risk retains claims and journal fencing. Target orders with a schema now require a matching provider declaration: undeclared schemas fail, a breaking change. Journal compatibility and behavior remain unvalidated. The CTP provider also owns native request field comparison, dispatch/zero-fill projections and zero-fill evidence field matching; SDK retains session, exact type/source checks and journal lifecycle. The provider is trusted for field matching. Risk-order position-dimension source projection is selected by the provider policy, without an SDK venue-name branch. CTP declares the projection at bt_api_ctp.risk_source_position_projection; the other 12 built-ins retain the previous generic path. Missing declarations or required projectors fail closed, so third-party policies need updates. SDK retains source/session checks and error mapping; provider discovery and behavior are unvalidated.

CTP recovery row instrument/side/offset fields, active-order classification, order/intent matching and trade-key projection live in bt_api_ctp.recovery_row_projection; the SDK supplies its original value selector, quantity checks and instrument resolver, retaining proof, journal, session and authorization. The provider participates in field decisions; import timing and behavior remain unvalidated.

SDK account_risk_projection.position_audit_close_error classifies a blocked order using caller-supplied local position facts; the Broker retains its audit state and framework objects. This decision does not establish account provenance or grant write authority, and behavior is unvalidated. Neutral top-of-book checks and midpoint projection live in SDK market_stream_contracts.orderbook_midpoint; Feed retains event dispatch and bar-line updates. Tick trading-day and action-day fields are explicitly selected by each provider: CTP includes TradingDay and ActionDay alongside neutral names; the other 12 select neutral names only. Base defaults are None, and the former uppercase candidates for the other ten have been removed. Dynamic input coverage remains unvalidated. Base order-book sequence/audit defaults omit Binance-native fields; legacy providers keep their old values. Base balance, position, order, trade, status and position-mode defaults no longer include selected Binance/OKX/CTP native aliases; the explicit historical policy and its four direct consumers retain the prior mappings. Base permission, position-mode, event-identity and instrument-symbol defaults also contain neutral fields only; the three explicit provider policies retain their declarations and ten legacy providers retain historical fields. Third-party Base subclasses change behavior; coverage and behavior remain unaccepted.

All 13 providers explicitly declare trade_id_fields using neutral names and native fields confirmed in their container source; Base defaults to None and the SDK reads the selected fields. Bybit, dYdX and Kraken declare no additional native trade-ID fields. Unconfirmed generic id/tradeId aliases are no longer assumed across venues; narrowing and additions are breaking changes. The group_fill provenance alias contract is separate: IDs including Gateio, HTX and MEXC still require verification and normalization does not prove them. Dynamic inputs and behavior remain unvalidated.

Order-status and trade-fee field candidates are selected by provider policy. All 13 providers explicitly declare order-status candidates: Binance, OKX and CTP retain their existing declarations, while the other ten each declare status, order_status and state; the Base legacy policy no longer declares these candidates. Trade-fee candidates remain policy-selected. A policy without declarations fails explicitly. This field ownership move does not establish native status coverage; third-party policies and behavior remain unvalidated. Placement position-mode fencing is also provider-declared: OKX/Binance retain the existing guard, other built-in routes retain the previous unguarded behavior, and undeclared routes reject placement. This breaking change does not prove venue capability.

Neutral position-row matching against configured route and instrument identities lives in bt_api_py.broker_event_envelope; Backtrader retains feed/order binding collection and local positions. This source change is unaccepted.

The neutral unverified execution-event identifier projection lives in bt_api_py.execution_event_projection; Backtrader retains local order binding, UNKNOWN updates and drop recording. The Store completed-bar delivery queue remains framework-owned. Cross-package behavior is unaccepted.

CTP managed order and cancel identity value types live in bt_api_ctp.managed_request_identity. SDK request models resolve them lazily when those fields are used, with lazy legacy SDK exports. Module identity, serialization, annotation resolution, source binding, optional packaging and behavior remain unaccepted; these values grant no execution authority.

Binance, OKX and CTP declare their own explicit order-identity aliases and side projections; the remaining providers explicitly retain the historical set. Known identity aliases outside the selected policy raise an execution-unknown error. Dynamic payload coverage, packaging and behavior remain unvalidated.

Order provenance selects neutral fields and native aliases declared by each of the 13 providers, using scoped v5/v6. Risk and group proofs use only v6, bind route-specific alias digests, and group source events persist and recheck that digest. The v1–v4 contracts have been removed. Bybit, dYdX and Kraken currently declare no native fill aliases; their field coverage requires review. This is uncommitted source work; dynamic providers, old-record handling, packaging and behavior remain unvalidated.

SimNow native order, cancel and query projections, and the native query collection workflow, now reside in the CTP provider; the SDK retains the before/after session-source fence. The SDK retains session composition and injects its unified cancel request type; class origins, dependencies and behavior remain unvalidated.

The working-tree CTP gate approval, credential binding comparison, selected-front scope and entry/recovery scope checks are SDK-owned; the provider invokes them under its native lock. Retired runtime provenance and remaining reverse dependencies are unresolved; no behavior or trust acceptance is claimed.

The working-tree managed_execution_mailbox supplies the bounded synchronous owner-thread handoff using runtime-owned state; it neither creates a thread nor grants execution authority. Concurrency and behavior remain unvalidated.

Python 3.11-3.13 Tests

bt_api_py is a Python façade for exchange plugins and direct Feed calls. Managed live execution uses Backtrader's explicit ServiceExecutionSession and the service-v2 ServiceHost; this SDK does not provide a separate forwarding runtime. The package is an integration framework—not a declaration that every registered plugin or venue is ready for live trading.

Risk analytics, limits, policy and ML live in the optional bt_api_risk package. The historical SDK top-level risk entry lazily exposes that package; its former risk submodule paths are removed. The SDK risk extra selects risk analytics and ML extras. The working-tree merge uses the SDK split implementation in place of the Risk package analytical copies; behavioral and distribution acceptance remain outstanding.

The former bt_api_py.backtrader.BtApiBroker mock-only placeholder and the unrelated legacy bt_api.adapters mock broker registry have been removed. The framework integration belongs to Backtrader and venue discovery uses the SDK provider/plugin contracts; external users of the retired adapter API must migrate. This is an unaccepted breaking source change.

The working-tree risk-only direct journal, SQLite/OS-lock storage, record types, event chain and writer fencing reside in bt_api_risk. bt_api_py.service_risk_order_journal composes provider evidence selection and Gateway receipt verification for the SDK journal subclass; its existing entry and record names remain. Optional Execution cancellation-source binding, verification and projections are composed by service_execution_risk_journal_bridge with lazy Execution imports; the Risk journal itself no longer imports Execution. A standalone Risk journal rejects those paths without the bridge. Cross-package types, source binding, installation, concurrency and behavior remain unvalidated. CTP native order/action field construction and prepared-request, target and receipt binding belong to the CTP provider; owner thread, session and authorization remain in the SDK. The provider participates in field-consistency checks; MRO, source binding and behavior remain unvalidated. These source changes are not behavior- or distribution-accepted.

The working-tree neutral normalized order observation and source projection types reside in bt_api_base.order_observation_contracts; the former SDK normalization import remains an alias to those same types. This is not source attestation, behavior acceptance or distribution compatibility evidence.

CTP native order, cancel, insert-error and trade callback parsing/mapping resides in bt_api_ctp.execution_callback_mapping; Execution retains its event/correlation types and lazy mapping compatibility entrypoints. Managed integration requires both packages and remains source-only, without behavior or installation acceptance.

The working-tree SDK computes target coverage against neutral account-execution instrument snapshots. Backtrader retains strategy, broker and feed ownership; coverage does not establish source authenticity. This source move is unaccepted.

The CTP callback session, native-source bridge and callback-ledger adapter are provider-owned; Execution retains its store, leases and event types and exposes lazy compatibility imports. Their cross-package source, import and behavior remain unaccepted.

CTP managed request/binding and native sender/result contracts reside in the CTP provider; the durable single-worker claim, UNKNOWN and completion workflow remains in Execution. Source and distribution are not behavior-accepted.

CTP trade-stream selection and native Trader/feed state comparison are provider-owned; SDK subscription state and approval authority stay in the SDK. The source split is not runtime or account acceptance.

The working-tree CTP path-budget policy, limits, journal value/row projections and budget transition rules reside in optional Risk; SDK session reservation seals, source bindings, writer fences and durable state stay in the SDK. The budget path loads Risk lazily and fails when unavailable. This source split and its exception/import compatibility are unvalidated.

Risk dispatch evidence uses a Base declaration selected by the exact Risk account provider; CTP declares its existing field and schema names. The Risk journal retains the claim, event chain and writer fence; SDK composition selects the provider profile. Other providers are not established by this source refactor, and entry-point installation and behavior remain unvalidated.

SDK family and responsibility boundaries

The package names describe separate boundaries, not a promise that every route has been composed or deployed. The detailed Chinese system architecture is in TRADING_SYSTEM_ARCHITECTURE.md.

The shared trading-mode standard defines replay, read-only shadow, paper using an external simulated account, and live using a production account. Iteration 53 first restores and refactors the direct-trading boundary without requiring optional components; the remaining Iteration 52 paper and live work follows. replay, shadow, and old local matching remain deferred. A mode name does not authorize account writes, and provider capabilities and environment-specific differences still require validation.

The long-term integration goal is to reuse the same compatible Backtrader strategy source for backtesting and these four modes, selecting the appropriate Feed, Broker, Store and configuration instead of rewriting strategy code. Adapter capabilities and differences must be explicit; this goal does not claim all combinations are implemented or accepted today.

Area Responsibility Boundary
Backtrader Backtesting and strategy engine. Its ServiceExecutionSession is the Backtrader-side entry for managed execution through the service-v2 ServiceHost. Owns strategy and framework lifecycle; it is not an exchange plugin package.
bt_api_py Public BtApi façade, direct Feed access, and assembly/discovery of exchange plugins. Direct calls use the configured local provider path. The SDK has no separate forwarding runtime.
bt_api_base Shared plugin contracts, data containers, feed protocols, and common integration utilities. Shared primitives do not certify an exchange implementation or account.
bt_api_runtime Optional run configuration and runtime assembly. Its contract parses configuration and matches symbolic references. A source/fake candidate assembles read-only paper/live bar observation with existing Backtrader components; it does not verify actual provider/account identity, authorize orders, or establish complete runtime or account acceptance. Iteration 53 plans to migrate responsibilities, switch active callers, and remove the old backtrader_runtime after verification; the optional runtime remains unnecessary for the direct route.
bt_api_gateway Provider-neutral account-scoped command and read-side routing, with durable local journal contracts. Requires server-composed authentication, account-owner execution, and write admission. It has no provider client, credential loader, or socket server.
bt_api_risk Reusable risk, policy/admission, and portfolio analytics components. A package being installed does not mean a particular order route invokes or is authorized by a risk gate.
bt_api_execution Optional execution management: durable dispatch and reconciliation; target scope also includes aggregation of registered strategy signals/intents, order slicing, algorithmic execution, and fill/fee allocation. Multi-strategy aggregation, slicing, and algorithm scheduling are target responsibilities, not fully implemented or accepted capabilities. Strategies generate signals; Risk owns admission; provider ports supply venue facts. The target direct route does not require this package.
bt_api_monitor Metrics, health observations, telemetry, and optional event intake components. Monitoring roles must be explicitly composed and enabled; observations alone do not establish account readiness.
bt_api_transport_zmq Optional versioned wire protocol and authenticated ZeroMQ transport. Transports commands and events; it does not own provider execution, order state, or risk policy.
Venue provider packages (bt_api_binance, bt_api_okx, bt_api_ctp, and others) Exchange-specific REST, WebSocket, native API, and Feed integrations. Registration or source presence is not evidence that the package is installed, configured, or accepted for live use.

Direct account-configuration method aliases are declared per provider route; the SDK discovers them and uses the standard method when none is declared. OKX/Binance source declarations and distribution compatibility remain unvalidated.

Neutral event-time field selection, UTC conversion and connection/subscription scope classification now reside in bt_api_py.market_tick_contracts; Feed retains its own scope and bar state, and the classification does not attest provenance; these conversions do not attest source clocks. This source migration has not been behavior-validated.

Order-side projector entry points receive the full row; provider-specific nested-field extraction is owned by each provider. Binance's nested o selection is no longer in the unified SDK. This is an uncommitted breaking entry-point signature change and has not been behavior- or installation-validated.

The working-tree service_recovery facade checks neutral paper-fill field sets, source-event identities, bindings and economics, and encodes recovery context scalars and exact decimals for the host recovery attestor; the host still owns feed/bar and commission-context bindings. This source migration is not recovery or account acceptance.

The working-tree service_execution_assembly owns shared runtime-state, nonnegative-counter and bounded error-code projections, plus aggregation of owned runtime facts; the framework session retains its own engine lifecycle, cleanup error classification and report. This cross-package source change has not been behavior-validated.

The working-tree monitor_threshold_composition wraps Monitor threshold workers as SDK Host resources. Monitor owns the worker and rules, while SDK owns the exact Host-resource composition. The former Monitor package-level composition exports moved to the SDK; lifecycle and installation remain unvalidated.

SDK and Monitor ELK formatters refer to the same working-tree bt_api_base.logging_context identifiers; their configuration paths share bt_api_base.logging_setup. Aligned distributions and runtime behavior remain unvalidated.

The working-tree monitoring extra selects bt_api_monitor; metrics, the default registry, collector, system metrics, exchange health, Grafana, decorators, Prometheus and ELK are Monitor-owned. The corresponding former bt_api_py.monitoring submodules are removed, while the old package entry uses these Monitor objects. The unified versions retain the former SDK async-duration, Prometheus and ELK behavior; direct exporter calls default to loopback, while monitoring configuration may explicitly select another host. Monitoring configuration now lives in bt_api_monitor.config, using the former SDK configuration validation and cleanup implementation; the former SDK configuration submodule was removed. This is a breaking source change without installation or behavior acceptance.

CTP native query-method selection and public session-field projection are provider-owned; the SDK retains route and transport guards. This source migration has not been behavior-validated.

CTP recovery-row account/day field selection and the existing active-order status projection are provider-owned; the SDK retains query and session coordination. Status semantics and distribution compatibility have not been validated.

CTP query terminal-packet and native account-row validation are provider-owned in the working tree; the SDK retains its pre/post session guards. The cross-package source is not runtime acceptance.

SDK-internal CTP ingress queue views, sealing and private-event fences live in bt_api_py._ctp_ingress; BtApi retains per-instance binding and authorization timing. This source refactor has not been behavior-validated.

CTP native active-front and authenticated market-identity checks are being moved to bt_api_ctp.credential_binding_fronts; BtApi retains its feed, stream, ingress and authorization state. This source migration has not been validated.

The isolated SimNow probe is provider-owned in bt_api_ctp.simnow_probe; bt_api_py.ctp_probe delegates lazily. This uncommitted migration has not been validated for installation or runtime.

The working-tree SDK projects fields from already verified neutral submit acknowledgements; the marker in a mapping does not establish provenance. This source migration is not behavior acceptance.

Correlated-command contract types are loaded through the SDK command module; framework order bindings and dispatch lifecycle remain with the consuming adapter. The source migration has not been behavior-validated.

The working-tree market_stream_contracts also validates neutral tick/order-book channel selections and configured depth; callers retain subscription timing and lifecycle. This source migration has not been behavior-validated.

The working-tree route_identity_projection checks supplied route sets and selects exact live route names; the host retains instance and lifecycle checks. Route names do not grant account authority. This source migration has not been behavior-validated.

The working-tree execution_identity_fence retains host-generation identity-vector fence history while the host supplies its current API and generation. It does not create provider identity evidence; this source migration has not been behavior-validated.

The working-tree order_preflight owns rule/economics decision coordination and identity bindings; hosts supply their order projection and lifecycle context. This source migration has not been behavior-validated.

Direct execution-option extraction, command-queue sizing and funding refresh-option normalization are owned by the SDK assembly, queue and funding modules; callers retain their own session lifecycle. These source changes are not behavior or installation acceptance.

The working-tree market_delivery_projection projects neutral event fields and continuity for consumers; the host retains delivery state, and this projection does not attest the source clock. This source migration has not been behavior-validated.

The working-tree service_recovery_quote owns neutral quote-revision validation, quote-to-fill field comparison and per-consumer cursor state; the host binds observations to its own bars and retains source-trust responsibility. This source migration has not been behavior-validated.

The working-tree service_market_bindings owns neutral service bar and order-book binding types, consumed by Backtrader and optional bt_api_runtime; cross-package imports and distribution remain unvalidated.

The working-tree SDK account-balance reader also checks configured/live route alignment and batch shape before a framework projects balances. Route names do not establish account identity; the migration is not behavior or installation acceptance.

The same SDK module checks service binding collections, account coverage, and distinct client instances. The consuming framework retains its feed/position mapping; these checks do not establish account authority. The migration is source-only and unvalidated.

The working-tree ServiceBarHistoryHandoff owns per-consumer history/live bootstrap, ordering and deduplication state; callers supply their bar projection and identity. This source migration has not been behavior-validated.

The working-tree ServiceBarStreamSession retains the epoch and sequence of one service bar stream; its caller projects validated bars and owns client closure. This change is not behavior or installation acceptance.

The working-tree bt_api_py.factor_order_correlation matches neutral local and provider order observations by client ID while the caller constructs its own result; it does not establish provider authority and has not been validated.

Result collection fields are selected by provider policy in the working tree; Binance and MEXC declare the native symbols container, while nine other providers retain the legacy candidate pending review. CTP/OKX field narrowing and distribution compatibility have not been validated.

Neutral reconciliation projection checks include caller-bounded position flatness, and neutral risk projections can be marked incomplete without changing their facts. These working-tree changes are unvalidated.

Exact reconciliation-route selection and caller-bounded timeout validation are SDK source work in progress; the caller remains responsible for active API lifecycle binding.

The working-tree bt_api_py.command_coordinator coordinates a command lane and its UNKNOWN safety state while callers supply receipt projections and lifecycle callbacks. Its behavior remains unvalidated.

The working-tree bt_api_py.market_stream_session retains exact subscription handles per consumer and delegates provider operations while callers supply route/lifecycle callbacks; it has not been validated for runtime or installation.

The working-tree bt_api_py.account_risk_state owns a per-instance neutral risk snapshot cache and refresh reservation; callers retain lifecycle and identity callbacks. This does not enable optional business risk policy or establish account facts, and remains unvalidated.

The working-tree execution configuration policy is selected by exact provider route; its declarations describe fields and do not attest account or credential identity. These changes require aligned base and provider distributions and are not runtime acceptance.

Direct calls and managed service calls

  • Direct SDK path: application code calls BtApi or a Feed in its process; the configured provider plugin performs the exchange interaction. The optional execution_config wraps this direct API with the SDK's own local execution journal. It is separate from Backtrader's managed execution path.
  • Managed service path: a Backtrader strategy uses its explicit ServiceExecutionSession and service-v2 interfaces. A server-side ServiceHost composes authenticated scopes and the configured service handlers; transport, gateway, risk, execution, and provider adapters remain separate boundaries. Installing this SDK or configuring a direct BtApi object does not enable that service route.

Repository or submodule presence, source tests, examples, and successful package installation are not live-account acceptance. They do not by themselves prove authentication, current and complete account state, authorized order dispatch, cancellation and recovery, or operational monitoring for a specific venue and account. Use the support-status evidence and deployment-specific acceptance records for those claims.

Release-blocking CI targets Python 3.11–3.13. Python 3.14 is canary-only.

Release 0.15.4

This quality-focused patch makes the lint-debt gate compare checkout paths consistently on Windows and POSIX, retains the iteration-07 execution-session typing and rollback coverage, and pins the bundled adapter source revisions to commits derived from their current master branches. It does not expand the set of venues represented as ready for live trading; use doctor and the support-status policy to inspect the evidence available in your environment.

Install and diagnose

python -m pip install bt_api_py
python -m bt_api_py.doctor --bundle core-reference --format json

The doctor command verifies installed package metadata and reports plugins as installed, disabled, or unavailable. It does not authenticate to an exchange or place orders.

Direct typed order example

from decimal import Decimal

from bt_api_py import BtApi, OrderRequest, OrderType, Side

api = BtApi(exchange_kwargs={"BINANCE___SPOT": {"testnet": True}})
ack_or_venue_result = api.make_order(
    "BINANCE___SPOT",
    OrderRequest(
        symbol="BTCUSDT",
        side=Side.BUY,
        order_type=OrderType.LIMIT,
        quantity=Decimal("0.001"),
        price=Decimal("50000"),
        account_id="paper",
        client_order_id="example-order-1",
    ),
)

account_id="paper" above is an illustrative account identifier, not a trading-mode selector or write authorization. The selected provider, endpoint, credentials, and account determine the actual environment.

OrderRequest is the cross-transport contract. The historical positional form remains only as a compatibility layer and must include a side-qualified type such as "buy-limit"; a bare "limit" or "market" cannot safely infer side.

Normalized results and durable execution

The existing BtApi methods accept normalized=True for standard account, instrument, position and order results. poll_event(exchange_name) returns standard market, order and trade dictionaries; quantities retain the venue's native units. Position intent uses position_side, offset, position_mode and quantity_unit on OrderRequest, including CTP dated closes and native order references. Unsupported venue capabilities fail explicitly.

Enable a durable execution session with the optional constructor argument:

api = BtApi(
    exchange_kwargs=exchange_config,  # Supply your configured accounts.
    debug=False,
    execution_config={
        "order_journal": "local-orders.jsonl",
        "account_currency": "USDT",
        "order_poll_interval": 0.2,
    },
)

BtApi remains the direct SDK facade. Its optional execution session owns the exclusive journal lock, intent persistence, client ID uniqueness, uncertain execution reconciliation and cumulative fill/fee state. Call new_client_order_id(exchange_name) before binding a local order reference, submit a typed request with normalized=True, then keep polling poll_event even when no market bar arrives. A timeout never triggers a replacement order. An unresolved historical intent blocks new placements until the original order is reconciled. Reuse the same journal across restarts and call close() when done.

With a session enabled, legacy/raw writes, asynchronous writes and bulk cancellation are explicitly rejected where they cannot honor its journal contract. Omitting execution_config preserves the historical API behavior. get_execution_summary() reports the session's unresolved orders and fees; get_all_balances(normalized=True) preserves individual account currencies, and get_portfolio_balance() rejects mixed or nonzero unknown currencies. This is direct provider execution support; it does not contain Backtrader orders, feeds or strategy accounting. Managed live execution that requires Host-owned admission and dispatch uses Backtrader's explicit ServiceExecutionSession and service-v2 ServiceHost path.

Direct provider reads

The direct backend preserves each provider Feed's native result shape. Forwarding reads through BtApi have been retired. For managed service market or account reads, use the configured service-v2 read services; this package's direct Feed API does not silently route to a remote service.

To configure the direct provider path, pass its registered exchange settings when constructing BtApi. The service transport and its read scopes are configured separately at the Host boundary.

Historical tick collection (CTP)

The bt_api_ctp plugin ships a whole-market tick collector that persists every depth snapshot to Parquet for backtesting: one file per instrument under <data_root>/<trading_day>/<exchange>/<instrument_id>.parquet, plus a per-day report.json with row counts and in-session gaps. It is driven by an external scheduler (cron/systemd/launchd units included) and exits by itself at the close:

# 推荐:启动脚本(自动加载 .env、定位解释器、前台跑到收盘)
sh ctp_data/start_collector.sh

# 等价的手工方式(必须在仓库根目录执行:data_root 是相对仓库根的相对路径)
python -m bt_api_ctp.collector --config ctp_data/collector.yaml --until-close --wait-open

ctp_data/ is the collection runtime directory; see ctp_data/README.md for setup, scheduling and stopping. Reading the data and the deployment checklist: bt_api/bt_api_ctp/README.md and bt_api/bt_api_ctp/deploy/collector/README.md.

Support status

Support status

The entries below are evidence tiers, not a count of production-ready exchanges.

Scope Tier Evidence boundary Current limitation
core-reference bundle experimental Bundle metadata for BINANCE___SPOT, OKX___SPOT and CTP___FUTURE; not a live-trading or installed-plugin certification. Current isolated submodule diagnostic has no initialized plugin worktrees, so package install/import/test certification is pending.
other registered plugins unverified Registry or submodule presence only. Do not infer REST, WebSocket, paper-trading, or production readiness from registration alone.

Blocking CI supports Python 3.11, 3.12, 3.13; Python 3.14 is canary-only.

See docs/operations/support-status-policy.md for the evidence and expiry rules.

免责声明与使用风险(审阅草案)

免责声明与使用风险草案说明软件、数据、回测和实盘交易的主要风险;该文件尚未批准生效,其中拟议的责任限制不是现行条款。 现行软件许可及第三方许可保持;许可调整状态和待审事项见许可审阅说明。

Contributing and verification

Use a clean checkout and retain JSON/JUnit/log artifacts when validating exchange plugins. A registry entry, source directory, or historical test number is not release evidence.

Iteration 63 development contracts

The 0.16.0.dev63 SDK/Base development versions introduce a required provider direct_write_error_policy: DirectWriteErrorPolicy for PLACE and CANCEL. It contains separate immutable sets of error codes that mean the native outcome is unknown. A missing or invalid declaration refuses writes before preparation; read-only provider access is unchanged. CTP, OKX and Binance in the matching development version matrix declare their policies. Old provider names and contracts are not silently adapted. This is a partial iteration 63 delivery, not acceptance of a shared Gateway or any account capability.

bt_api_py.service_runtime_thread.ThreadedServiceClientRuntime owns the actual ServiceClientRuntime and its registrations on one dedicated thread. Its trusted factory constructs that runtime there; queued calls and lease maintenance use the same registration. Before-start timeouts cancel the queued call, while after-start timeouts remain unknown and must not be retried blindly. Startup and close report unresolved cleanup; inherited instances reject use after fork. An injected monotonic clock must share the runtime's clock domain. A transport that blocks despite its timeout can still stop renewal; the wrapper does not make such a call cancellable or automatically reconnect/replay it.

Local source tests and a synthetic ServiceHost/CURVE loopback have been checked. The new Gateway trading client has not yet been connected. No SimNow/production write acceptance or cross-platform certification is implied.

Standalone services and Runtime composition (2026-11-16)

The SDK provides an explicit Monitor process with separate authenticated event ingress and Gateway heartbeat listeners. Provision private CURVE files and the scope/principal grants described in examples/services/monitor-service.example.yaml, then validate and run it:

python -m bt_api_py.monitor_service_host validate --config /path/to/monitor-service.yaml
python -m bt_api_py.monitor_service_host run --config /path/to/monitor-service.yaml

Validation reads configuration only. storage.event_types requires 1–16 unique event names, matching the actual Monitor ingress target; an oversized allowlist is rejected before keys or service resources are opened. Running opens the protected local outbox and two registries; MONITOR_LISTENERS_READY does not mean producers, alert rules, or trading are ready. Protected file handling currently requires POSIX. Local acceptance covers authenticated loopback processes and persistence, not an actual CTP account or the complete five-component deployment.

For a separate observation-only query listener, use examples/services/monitor-query-service.example.json. The listener reads one configured Monitor outbox in read-only mode and exposes only the authenticated observation.query operation. validate and run --dry-run inspect the configuration without opening key, SQLite, or registry files; a normal run reads the protected Curve/HMAC keys and starts the listener:

bt-monitor-query-service validate --config /path/to/monitor-query-service.json
bt-monitor-query-service run --config /path/to/monitor-query-service.json --dry-run
bt-monitor-query-service run --config /path/to/monitor-query-service.json

The module form is also available with python -m bt_api_py.monitor_query_service_host. Readiness confirms the local query listener started; it does not establish producer health, account readiness, or trading authorization.

For per-producer event authorization, explicitly select schema: bt_api_monitor.service.v2 and add 1–1024 producer_bindings. Each entry has exactly binding_ref, source_ref, identity, scope, outbox_scope and event_types. Identity contains an existing ingress principal's principal_ref and actor_ref; the Host uses SERVICE without delegation. Scope must spell out all nine WireScope fields: this Host currently requires its exact domain and account, account_refs: [], and null strategy/run/manual-book/portfolio/group/leg fields. Each binding selects 1–16 event types already granted to the same outbox; overlapping producer/scope/type bindings are rejected. This adds no principal, target or strategy scope grant. Version 1 configuration keeps its original shape, without producer_bindings.

V2 producers send schema_version: 2 with explicit binding_ref and source_ref. The receiver retains full scope and producer metadata with a separate ID namespace. Ordinary v1 IDs remain unchanged, but the reserved gateway.recovery.journal.v1 type and any type selected by a v2 binding require v2 requests. Intake ACKs do not prove payload semantics or completed alert evaluation; a source relay and duration evaluator require separate composition.

A shutdown or startup rollback that cannot confirm cleanup reports MONITOR_CLEANUP_PENDING and retains the original host and resources. The CLI keeps its signal handlers installed; a later SIGINT or SIGTERM retries cleanup on the same owners. It exits only after their close result and state are confirmed. An unavailable diagnostic output stream does not end this wait. The original storage and keys must remain available; starting a replacement process does not resolve uncertain cleanup. Each close attempt still depends on the underlying ServiceHost close operation's completion time.

bt_api_py.runtime_gateway_control.RuntimeGatewayControlBridge connects Runtime's existing strategy-scoped control port to Gateway using explicit SDK client configurations, identities, keys and externally supplied delegation proofs. It owns client threads and preserves ambiguous calls without retrying. The SDK's explicit runtime_operator_cli composes this bridge with RuntimeServiceHost and RuntimeMonitorBridge; it does not change the optional Runtime package's default CLI. See the Runtime deployment templates for the separate subject-token file, exact route bindings and protected CURVE keys. The deployment must bind its client proof to Gateway's independently installed proof; the existing wire does not exchange delegation IDs. Starting the control listener does not start strategies or prove trading readiness.

The combined Execution CLI accepts run --enable-owner-stop-file for cooperative shutdown without a console. Create an empty owner-protected regular file beside the deployment config, with the basename announced by EXECUTION_COMBINED_STOP_FILE. EXECUTION_COMBINED_STOPPED and exit code 0 confirm that the listener and journal owner closed. A cleanup failure retains the original owner and announces a fresh marker for an explicit retry.

For standalone parent listeners, use python -m bt_api_py.execution_parent_service_host --config <parent-config> --enable-owner-stop-file. Use the basename announced by EXECUTION_PARENT_STOP_FILE beside the parent config, and verify EXECUTION_PARENT_STOPPED and exit code 0.

bt_api_py.execution_read_service_host provides an independent authenticated management listener for three local parent-journal reads. See execution-read-service.example.json. It does not provide parent submission, intake leases, scheduling or dispatch; an empty journal is not evidence of an empty trading account. The SDK order router currently keeps unverified port replies UNKNOWN, including plain ACCEPTED or NOT_SENT, and does not retry or fall back to a native route.

Iteration 63 Gateway dispatch and storage RPC slice

The optional gateway extra installs bt_api_gateway>=0.2.0.dev63 and bt_api_transport_zmq>=0.1.0: ZeroMQ is the default Gateway transport. The independent transport-zmq extra remains available. Future middleware implementations belong in separate transport packages behind the same neutral service contracts; no additional backend is introduced by this iteration. compose_gateway_direct_dispatcher binds the trusted local provider instance to the Gateway guard and durable DISPATCHING commit port. Only complete scalar OrderRequest.to_dict() payloads are accepted; account and all order fields are checked again before commit.

The explicit trading_owner service role defaults to direct.reserve, direct.release, and direct.command_status. dispatch_enabled: true additionally requires a trusted binding to a started GatewayDirectOwner using the exact same journal, and publishes direct.dispatch. The handler hands off to a bounded owner-thread queue without waiting for native I/O. QUEUED and ALREADY_QUEUED are volatile observations, not durable dispatch or provider acknowledgement; query the original command key for durable state. This is a partial service composition, not a complete trading owner. Strategy identity comes from the authenticated registry context; service proxies are not yet accepted. After STOP_NEW, pass gateway_direct_service.recovery_requested_operations() to ServiceClientRuntime(requested_operations=...) for the same run's limited status/release registration. Release keeps its write claim; reserve remains blocked, as does dispatch. The future remote client must use this recovery path explicitly.

The first reservation's TTL is not extended by a duplicate request, even if a different TTL is supplied. Replies expose the original generation, relative remaining TTL and expiry_pending; expiry observation is not durable EXPIRED or evidence of NOT_SENT. Durable native identity is returned separately from hashed strong-key projections; those hashes are not venue lookup keys. Registry-issued admission is rechecked before native preparation and again inside the journal write transaction. Ownership, native readiness and business admission remain trusted server responsibilities. A blocked native call is not cancelled by timeout: the owner retains its guard until cleanup succeeds. SQLite waits can still block the service thread, and FIFO does not provide per-strategy fairness. Actual native/GIL behavior, complete account lifecycle, settlement, strategy ledgers, remote-client/BT wiring and independent-process acceptance remain unverified. The intended deployment is an independent Gateway process reached through strategy configuration, with no embedded owner or local fallback.

Iteration 63 bound settlement and owner maintenance

The matching development packages require an explicit boolean settlement_required declaration. CTP requires a provider-issued SettlementObservation; OKX and Binance explicitly require no settlement step. Missing or invalid declarations stay UNKNOWN. The SDK binds the durable marker and one-use write grant to the same observation and rechecks it before and after commit. A failure after commit, including grant cleanup, stays UNKNOWN.

GatewaySettlementController uses the existing guard-bound dispatcher and journal. On the owner thread it reads fresh provider state, commits at most one attempt for an account/route/trading day, and reconciles existing attempts by readback without resending. Its ready property is an owner-thread live ticket check; status.observed_ready is only a cached diagnostic. The optional owner maintenance callback runs on that same thread, between commands and while idle, with a paired interval of 0.001 to 3600 seconds. Neither queue work nor due maintenance can indefinitely starve the other. Blocking native calls still retain cleanup custody and can delay both.

The provider verifier and durable commit port are trusted composition inputs; a DTO or marker string does not prove physical durability or defeat arbitrary in-process code. The complete TD/MD factory, dispatch readiness wiring and Backtrader integration remain unfinished. Local synthetic checks do not certify CTP calendar semantics, an account, or a complete Gateway deployment.

Iteration 63 CTP trading-owner composition

build_ctp_gateway_trading_profile registers a trusted trading_owner profile. Building the profile opens no native session. When the independent Gateway service starts, its account-owner thread acquires a local account guard, opens an existing schema-v3 journal with its required identity/revision anchor, and creates one CtpGatewaySession. The account scope must equal the canonical AccountKey.account_key_id; display names and front addresses are not lock keys. The current factory explicitly supports SimNow and defaults to writes disabled. Journal initialization and upgrade are separate operations, never startup repair.

The trusted Python factory optionally accepts recovery_observation_settings (GatewayRecoveryObservationSettings). Its source/account binding and separate isolated journal path must match the selected market profile; all queue, page, storage and timing budgets are explicit. The original CTP owner captures local recovery pages, while a separate recorder thread writes the Gateway source log. Timeouts keep the original owner-call handle, and failed writes keep the same page until its commit is confirmed. Close first fences dispatch, then retains an unconfirmed call, page or worker for retry on the original resources. A durable capture-stop marker identifies the last committed sequence and leaves later coverage unknown; it does not claim the provider's remaining buffer was drained or that the source recovered. binding.recovery_observation_status() exposes finite local worker status; ready is not proof of network health. The default remains disabled. An explicit Monitor relay can forward v2 records as described below; calendar accumulation and the duration evaluator remain unconnected. Local monotonic timestamps must not be treated as a cross-process clock.

An explicitly enabled recorder may select qualification_mode="local_clock_v1" and an explicit positive clock_max_interval_ns. The default disabled mode requires that interval setting to remain None. On the original account owner, a capture helper pairs every raw observation with its first local clock result; missing, expired or inconsistent clock history produces UNKNOWN with no UTC bounds. Unknown source observations remain SOURCE_UNKNOWN. Qualification checks publication history, valid intervals, overlapping calibration constraints and feasible UTC endpoint ordering; it neither authenticates SNTP nor proves recovery.

The paired page is written by the recorder thread to an explicit schema-v2 Gateway source log, atomically with raw records and checkpoint. Qualification rows count toward storage limits. Exact raw replays retain the first persisted qualification even when later clock calculations differ. The default v1 log and the opt-in v2 log reject each other's format; there is no automatic migration or repair of an existing log. Queued/running owner calls, pending pairs and the capture-stop marker retain their existing close/retry semantics. A clock that cannot be bound at initial helper construction stays unavailable for that helper; a later replacement is not silently adopted.

The trusted factory's GatewayServerClockRefreshSettings can separately select history_capacity (2–4096, default 0). The original background clock records actual SAMPLE, UNAVAILABLE and STOPPED publications in bounded memory; read_history() runs on its original owner and reports sequence gaps. Each restart has a new history epoch. An observed configuration change or recorder failure leaves history unavailable for that epoch, without changing the existing clock/dispatch behavior. Availability does not mean a sample is valid, and SNTP remains unauthenticated. This history has no disk or wire interface. The local qualifier can derive UTC endpoint bounds for eligible past intervals, and the explicit recorder option above persists those results. This is not cross-process monotonic comparison, a continuous market-health assertion, or a Monitor duration-rule implementation.

The protected JSON bundle for ctp-simnow-trading can explicitly add a recovery_observation object. All fields shown below are required when the section exists; null, unknown fields and invalid numeric types are rejected. The loader derives scope_ref and source_ref from the existing trading settings, so they must not be repeated in this section. The path must be absolute and isolated from the other service databases. These values are an illustrative configuration, not deployment sizing advice:

{
  "recovery_observation": {
    "journal_path": "/operator-owned/recovery-observations.sqlite",
    "source_capacity": 64,
    "page_limit": 32,
    "max_events": 100000,
    "max_bytes": 67108864,
    "sqlite_timeout_seconds": 1,
    "poll_interval_seconds": 1,
    "owner_wait_seconds": 1,
    "close_timeout_seconds": 3,
    "qualification_mode": "local_clock_v1",
    "clock_max_interval_ns": 60000000000
  }
}

For local clock qualification, the existing clock object can also explicitly set history_capacity to 2–4096; omission or 0 disables history. With unavailable history, v2 records remain UNKNOWN rather than obtaining invented UTC values. To record only v1 observations, use qualification_mode: "disabled" and clock_max_interval_ns: null. Omitting the entire recovery section creates no recorder. The ctp-local-readonly profile rejects this section. Existing market, clock, storage-isolation and journal compatibility requirements still apply; selecting the trading profile does not itself enable native trading writes.

To forward this same v2 source, explicitly add recovery_monitor_relay to the protected trading bundle. All fields below are required. The source path, source reference and source scope are derived from recovery_observation; the destination scope_ref below belongs to Monitor. Provision the exact Gateway SERVICE principal and matching source/binding/type in Monitor's v2 configuration separately. No principal or event permission is added to Monitor automatically. Replace the key placeholders with provisioned CURVE keys in the protected bundle, never in a public manifest:

{
  "recovery_monitor_relay": {
    "monitor_identity": {
      "role": "service",
      "principal_ref": "synthetic-monitor-events-principal",
      "actor_ref": "synthetic-monitor-events",
      "delegate_ref": null
    },
    "instance_id": "synthetic-monitor-events-instance",
    "scope_ref": "synthetic-events-scope",
    "rpc_connect": "tcp://127.0.0.1:7603",
    "server_curve_public_key": "<provisioned server public key>",
    "client_curve_public_key": "<provisioned Gateway public key>",
    "client_curve_secret_key": "<provisioned Gateway secret key>",
    "outbox_scope": "synthetic-outbox",
    "binding_ref": "synthetic-gateway-recovery",
    "checkpoint_path": "/operator-owned/recovery-monitor-checkpoint.sqlite",
    "poll_interval_seconds": 1,
    "start_timeout_seconds": 5,
    "close_timeout_seconds": 5,
    "request_timeout_seconds": 2,
    "max_records": 16,
    "max_bytes": 65536
  }
}

These budgets are illustrative. RPC timeout is separate from poll/start/close timeouts; the runtime heartbeat interval is rounded up from poll seconds with a minimum of one second. The current Host destination is account-scoped, and the dedicated client requests only events.append. Its worker owns the client, sink and checkpoint on a separate thread; required-Monitor heartbeat and its trading gate use their existing independent runtime. Omission enables nothing; the read-only profile, a v1 source, invalid configuration or aliased storage are rejected. An enabled relay that cannot start does not silently disappear.

The relay borrows the recorder's original v2 journal and only reads it; the journal's underlying SQLite connections still use mode=rw. It persists one pending envelope before sending, and advances its checkpoint only after a matching authenticated intake receipt. Unknown outcomes replay the same envelope and ID. The envelope timestamp is first enqueue time, not a source clock claim. Original-file checks and source row anchors detect observed replacement or history changes; the POSIX lock coordinates local cooperating writers only. Cross-process checkpoint rollback, simultaneous rollback of both databases, hostile filesystem ABA and power-loss persistence remain unproven.

Shutdown closes the recorder before the relay. A pending event may remain for the next explicit start; local resource cleanup does not mean all source events were delivered. binding.recovery_monitor_relay_status() reports finite resource and delivery observations. Unconfirmed shutdown retains the original worker, runtime and checkpoint for explicit retry. No automatic replacement runtime or source database is created. Source qualification, receipt and cursor do not prove recovery, calendar coverage, completed alert evaluation or trading rights; the ordinary positive for_seconds guard remains in place.

The same protected trading bundle can explicitly enable instrument-status diagnostics with instrument_status_read. This section has exactly two fields: principal_instruments, a mapping from existing principal references to lists of complete six-field MarketInstrumentKey objects, and owner_wait_seconds (greater than 0 and at most 5). The allowlist is copied and bounded to 256 principals and 4096 keys in total; duplicates, empty lists and null are rejected. Each key must match the configured provider/environment, futures product type, account venue coverage and that principal's existing native-symbol grant. The Registry resource grant must separately include direct.instrument_status on service.direct_write. Omitting the section leaves this capability disabled; the read-only profile does not accept it. This creates no new native session or database and does not enable trading writes.

Clients must explicitly request direct.instrument_status; default operation selection does not include it. GatewayBtApi.query_instrument_status(exchange_name, instrument, timeout_seconds=5) uses the existing authenticated runtime and returns a detached GatewayInstrumentStatusQueryResult: either OBSERVED with a scoped projection or UNAVAILABLE with a finite reason. The server reads on the original CTP owner and rechecks the captured session/status revision; the Registry rechecks registration, epoch, lease, authority and global readiness before returning. The first read that initializes a source scope may return unavailable; a later explicit read can observe that scope. A timed-out client keeps its original pending handle rather than implicitly issuing another query.

CURRENT means the provider ledger was current at the captured local view. The client token rechecks only its original runtime, registration and peer; it does not query the server again or prove the status is still current at delivery. The result always has decision_eligible=False, continuity_proven=False, authorizes_trading=False and product_mapping="NOT_PROVEN". Do not adapt an unavailable response to a missing provider observation or use it to authorize orders, compose a trading calendar, or release waiting orders. Source continuity, freshness, actual account acceptance and that decision path remain separate work.

The session's account reader owns the sole TD client. Direct orders and daily settlement borrow that client; the MD provider is lazy and shared across symbols. The network Host and native account owner use separate threads. A fresh settlement ticket and the caller's explicit assert_admitted(record) is True are both required to dispatch. That callback must enforce the applicable durable ledger, UNKNOWN and recovery gates; a constant-True production substitute is not an implementation of those gates. RPC readiness alone does not mean trading readiness. Default transport remains bt_api_transport_zmq.

Cleanup runs on the account owner. Unconfirmed session stop retains custody and the account guard for retry; a False owner close result becomes an exception to the original ComponentResources callback. Temporary TD unavailability that causes maintenance to fail currently closes the owner; automatic service recovery and post-reconnect reconciliation remain unfinished. This profile exposes command RPCs and optional explicitly authorized account-read and market ports. R21 adds the same-session market composition described below; complete trading account projection and recovery remain unfinished. The explicit-front config_front_pair label selects addresses, not execution authority. Direct admission and the legacy managed approval path retain separate contracts; the native identity/session gate remains mandatory in either case. Fake-provider dispatch success is not evidence of native order submission or of the legacy managed path's additional per-field business approval. Factories are trusted installed code, not manifest-selected imports. Local thread, fake-native and CURVE tests do not establish account or deployment acceptance, cross-host fencing, or Backtrader integration.

Iteration 63 durable client-host contracts

bt_api_py.gateway_direct_client exposes validated intent construction, schema-v1 intent/release mapping codecs, and validate_gateway_record_progress for local host implementations. Intent payloads are bounded before parsing; fixed identity fields and their scalar types cannot change across durable observations. A host must atomically retain the first intent and release plan, validate record progress under its own lock, and commit a marker before dispatch. These codecs do not provide storage, authorization, or venue truth.

A restarted client may query or release an old intent through the exact registered scope of that persisted intent when the Registry has adopted the released durable run. The current runtime identity/run and all other route fields remain checked; this recovery path cannot reserve or dispatch. A release is cancellation of a logical reservation, not cancellation of an order already sent to a venue.

project_direct_strong_identity_keys(identity, day_scoped_ids=...) exposes the coordinator's pure identity-key projection without creating a provider. The caller must choose the scope explicitly; projection does not attest it. Malformed partial key fields now raise direct_identity_strong_key_invalid, while missing strong keys remain unavailable and unrelated provider metadata remains permitted.

Backtrader's explicit Gateway pending host uses these contracts in its existing local journal. Broker/Store integration, complete read/event/cancel ports, account acceptance, and whole-iteration acceptance remain incomplete.

Iteration 63 shared account read model

CtpGatewayAccountReadSettings and account_read_principals explicitly enable the trading profile's account-read port. The existing native owner publishes through GatewayAccountReadModel; no additional account session or worker is created. Validated same-native login changes invalidate and refresh the read model; unproven source changes stop the owner pending recovery. Ordinary query failures invalidate account freshness while command status remains available. RPC readiness, account freshness and write admission are distinct.

The read port exposes only account.snapshot, account.snapshot.typed, account.head, account.read_after, account.ack, and account.progress. It retains Registry and Gateway ACL checks and rejects execution-stream reads. Dual-port composition requires the public account reference and both journal scopes to match. Explicit read permission grants no direct-write permission. Read, command and observation-identity journals must be distinct files, including symlink/hardlink aliases; their writes are not one cross-database transaction.

Account reads require an existing observation_identity_path, its saved expected_observation_issuer_id, and an explicit future-instrument catalog in observation_instruments. Initialize the identity store explicitly with DurableOrderCorrelationIssuer and retain its non-secret issuer_id. open_existing(..., expected_issuer_id=...) refuses missing, empty, damaged or mismatched stores instead of creating a replacement identity. The owner opens this store before native resources, lends it to the CTP session, and closes it after confirmed session shutdown and before releasing the account guard. A failed close preserves the exact connection for retry and disables business operations. If initialization cleanup also fails, callers must retain OrderCorrelationIssuerCleanupError and retry its close() before releasing resource ownership.

CTP account reads verify the complete native request-filter intent and readback contract supplied by the provider and project supported active orders with opaque observation IDs. Equal canonical native identities under the same issuer retain their IDs across reopening; an identity changing from front/local fields to a system identity is a different input, with no alias-merge guarantee. These IDs are not strategy ownership, native cancellation keys or UNKNOWN resolution. Unsupported conditional orders, missing catalog entries and inconsistent rows invalidate the snapshot. Account position cost basis remains unspecified, so no average price or currency is guessed. Strategy positions and recovery must come from their own attributed ledger. Synthetic and local CURVE checks do not establish real-account or whole-iteration acceptance.

Iteration 63 sealed CTP query ingestion

CtpGatewayReturnIngestor composes the provider's source-sealed query reader and precise native projector with the existing same-database execution ledger. It validates the bound account and trusted catalog, projects every row before writing, and uses the shared SDK strong-key encoder only for the provider's explicit binding/venue identities. Unknown instruments fail the batch instead of silently disappearing. Each fact commits independently; failure can leave a committed prefix, and an explicit fresh query replays those facts idempotently. A successful local summary does not establish account readiness, complete attribution, complete venue history or permission to clear UNKNOWN. The service owner composes this ingestion with bounded callback processing as described below; complete recovery and account acceptance remain outstanding.

GatewayDirectServiceBinding can inject a trusted reservation admission fence using the authenticated context and canonical OrderRequest. Only an exact GatewayReservationAdmissionDenied from factory/entry is translated to a finite rejection. Commit and context-exit errors remain uncertain. Storage-only composition retains its explicit behavior; this optional hook is not a production startup/recovery policy.

Iteration 63 trading-owner return maintenance

CtpGatewayReturnSettings supplies an explicit CTP futures catalog, bounded query timeout/interval and callback batch limit. Write-enabled CTP profiles require this configuration. The original owner, guard, Trader and command database perform return ingestion; no second TD or execution database is created. Orders/trades are projected before any batch write. ACK occurs only after every fact in an offered prefix has committed, so a partial failure replays the whole prefix through durable deduplication. Unsupported error returns remain retained and block new dispatch until their handling/recovery contract is implemented.

Maintenance alternates account reads and return queries when both are due, with at most one of those read phases per tick; settlement may perform its own reads. Queries and native callbacks never run inside ledger write transactions. A new source needs a new reader and a complete same-generation orders/trades pair. The callback path can retain a current source's historical native trading date without relabeling it as the receiving date; future dates remain unavailable. Old-source unacknowledged records still require recovery.

Reservation admission uses a cached local fence, initially closed and closed before maintenance failure/cleanup. Dispatch rechecks the live source and buffer as well as settlement and the caller's existing admission policy. Query completion does not establish an external baseline, account readiness, funds/closeable capacity or UNKNOWN resolution. Buffer gaps cannot be cleared by an empty query or ACK. No automatic order resend or real-account acceptance is implied.

Iteration 63 authenticated strategy execution stream

The trading-owner service exposes direct.events.read_after, direct.events.progress and direct.events.ack on its existing direct-write port only when the original return ledger is composed. Clients must request these operations explicitly; existing default registrations do not expand. Registry authorization and static strategy grants select the data scope. Read and ACK cross the migration cursor-write fence but confer no trading rights. execution_events_requested_operations() selects event-only recovery without claiming reservation-release rights.

GatewayExecutionStreamClient reuses an existing threaded SDK runtime. It validates the response binding, stable consumer, epoch and sparse sequence, without creating provider resources or acknowledging automatically. The caller must persist its projection and cursor before explicit ACK. Lost responses remain uncertain and can be resolved by progress queries or replay. Reply budgets include the full transport envelope and are checked before offered/ACK progress commits.

The SDK composes the same owner ledger with bounded close/drain handling. Shutdown rejects new stream requests and closes reservation admission; failure to drain retains the original resources for retry. This implementation does not complete Backtrader projection/cursor atomicity, native cancellation, error attempt correlation, full recovery, external balances or real-account acceptance.

Iteration 63: explicit prepared cancellation composition (R15)

DirectWriteCoordinator.cancel_prepared requires the provider's preparation, submission and release methods. It persists the exact PreparedCancelRequest through the existing host commit port before issuing the grant and invoking native. It never falls back to legacy cancel; uncertain or malformed post-submit outcomes remain UNKNOWN. compose_gateway_direct_cancel_dispatcher binds this path to the exact existing local provider, owner dispatcher, account guard and v6 command journal.

GatewayDirectOwnerResources.cancel_dispatcher explicitly adds cancellation to the same owner thread. GatewayCancelCommand and enqueue_cancel use a separate bounded queue (default capacity 16), operation-specific deduplication and cancellation priority while preserving periodic maintenance. The status accepting field still describes place capacity; cancel callers must inspect the enqueue result. Closing or failed maintenance disposes both pending queues without pretending to interrupt an active native call or release its guard.

This local composition does not yet enable a cancel operation in service capabilities, add a network client, process cancellation callbacks, or connect Backtrader's Broker/Store. Request submission is not order cancellation. The complete Gateway, recovery, delegated permissions and real-account acceptance remain incomplete.

Iteration 63 R16: explicit remote cancellation

The existing trading_owner service can explicitly enable cancel_enabled: true alongside dispatch_enabled: true. direct.cancel and direct.cancel_status use the same account owner and durable cancellation journal; they are not added to legacy clients' default registrations. The write operation has its own Registry-issued authorization and remains available under STOP_NEW when its current identity, lease, run and resource grants allow it. It cannot borrow PLACE permission or bypass the migration write barrier. The trading profile still requires its return infrastructure.

GatewayDirectClient accepts an optional cancel_host, persists a stable operation plan before RPC, and supports cancellation status recovery. The host must atomically retain the first plan and merge observations monotonically across all clients/processes, return the durable winner, and permit readback. The SDK cannot provide those guarantees for an incorrectly implemented host. New cancellation requires the original current run; an explicitly authorized later run may read an old attempt without automatically resubmitting it.

Queue receipts and SENT are cancellation-request observations, not venue cancellation. Real CURVE loopback with a separate Gateway process and synthetic providers covers this connection; asynchronous CTP cancel-error attribution, complete BT integration, recovery and account acceptance remain separate unfinished work. Default Gateway transport remains bt_api_transport_zmq.

Iteration 63 R17: source-bound cancellation error delivery

CTP callback ingestion now resolves positive action errors through the same journal's cancellation-key namespace, validates the exact prepared source/target, projects original-order strong keys, and rechecks the offered source before the atomic fact/event commit. Failed projection or source checks leave the callback unacknowledged. Existing authenticated execution streams expose bounded operation/attempt attribution in explicit v2 pages; account/strategy authorization, reply budgets and cursor transactions remain in force. No private native source labels are exposed.

The Backtrader pending host supplies the four cancellation persistence methods after explicit pending v2-to-v3 upgrade, using its existing local file lock and atomic replacement. This is not complete Broker/Store Gateway wiring. Concurrent state-directory rebind versus independent writers is a separately tracked open lifecycle issue; a local CAS test does not close it. Successful action responses, insert errors and full recovery/account acceptance are not established by this slice.

Iteration 63 R18: explicit strategy client session

bt_api_py.gateway_strategy_client.GatewayStrategyClientSession assembles one owner-thread runtime with the existing command and execution-stream clients. Load public YAML with service_config_io.load_client_config; separately supply the trusted journal/account/strategy route, peer identity, resolved CURVE keys, durable host and explicit operation set. Construction validates and freezes configuration without starting threads or network I/O. The required direct-write binding uses bt_api_transport_zmq; provider credentials and unselected client bindings are rejected. Raw runtime and transport construction occur on the independent lease owner thread. R20 adds the explicit optional read bindings described below.

start, status and bounded close retain the same runtime handle, including incomplete cleanup. A stopped instance is not restarted, calls are not automatically replayed, and failure never falls back to direct. Runtime health describes registration/transport only. The exposed runtime remains a trusted low-level API, not a security boundary against a caller deliberately changing private or frozen Python objects. The session does not own a provider or BT Broker and never acknowledges an execution event automatically.

The BT pending host can enumerate its validated durable cancellation plans in stable operation order, including after reopening. This does not dispatch or resolve them, and does not fix the separately tracked state-directory rebind race. The integration uses public synthetic YAML, a separate Gateway process and real BT pending storage; its small in-memory event projection is not production BT projection/cursor persistence. Complete account/market composition, Broker/Store integration, recovery and account acceptance remain unfinished.

Iteration 63 R19: prepared CTP placement and insert-error association

The explicit DirectWriteCoordinator.place_prepared path commits the provider's complete preparation before native submission. compose_gateway_direct_dispatcher(..., prepared_place=True) selects it; the CTP Gateway trading profile requires this path. Missing preparation support fails without falling back to ordinary place. The ordinary direct path keeps its prior selection semantics.

CTP preparation requires an explicit exchange and quantity units contracts, lots, or native (positive whole native lots). The default base unit is rejected. Only speculative hedge settings are currently represented; unsupported hedge flags/classes fail before native IDs are allocated. The strategy integration must supply these explicit fields from its configured contract.

Positive insert errors are checked against the same persisted request, source, and login before the existing callback ticket can be acknowledged. Public event pages use v3 and expose only a preparation digest for this association; v1/v2 decoding remains available. These are request-error observations, with no terminal order status, automatic balance release, or implicit UNKNOWN resolution. Older markers without preparation are not backfilled. Local synthetic validation does not establish live-account operation or complete Broker/Store integration.

Iteration 63 R20: account and market clients on the same owner

The session accepts optional GatewayAccountClientSettings and GatewayMarketClientSettings, each with its own explicit requested operations and required store.account or store.market binding. They use the same service, instance, scope and ZMQ profile as the direct binding. A market binding omits account_ref in public YAML; the trusted common scope resolver supplies its account registration. Its event stream scope remains public. Market selection requires market_connect alongside rpc_connect. The server must grant each port separately; selecting a client never grants access.

account_client.refresh() and snapshot() run the original typed account client on the owner. Returned observations keep their original monotonic freshness deadline, do not represent strategy allocations, and cannot be persisted as readiness tokens. Retained results need current-owner validation before delivery after a timeout. The old account.instrument_metadata operation is not exposed by this composition; R26 adds a separate explicit instrument-spec client described below.

market_client.subscription(name) provides explicit start, poll, history and recovery methods. Subscription names and complete keys must be unique. A subscription has one locally bound consumer, with at most one unresolved call; retrying the same operation after a wait timeout retrieves its original result. No automatic resync or acknowledgement of data loss occurs. poll() uses zero SUB wait but may still perform bounded maintenance/replay RPC. An unrecoverable result conversion failure latches a subscription gap and permits only diagnosis and shutdown. Local subscriber close failures retain the original resource for retry; owner_cleanup_uncertainties preserves remote unsubscribe uncertainty after local close.

The public ServiceHost trading-owner component can explicitly combine service.direct_write, service.account_read and service.market_source. The trusted resource provider supplies the existing direct binding, account read service and market hub; original Registry authorization, publisher audience checks and registration cleanup remain in force. This generic composition does not complete the CTP operator's joint TD/MD factory, Backtrader integration, full recovery or account acceptance. R20 final source and installed validation are recorded separately in the Backtrader iteration archive.

Iteration 63 R21: CTP joint trading, account and market profile

CtpGatewayMarketSettings explicitly adds the market port to the existing CTP trading profile. Configure supported tick keys and a per-principal key ACL; matching Registry grants must independently authorize the exact account and domain. Account reads remain optional and separately authorized. No historical market capability is advertised. The operator accepts this composition through its trusted resource provider, without a second independent market binding.

GatewayOwnerMarketProvider lends the original session's lazy shared MD provider to the Host's market hub. Its logical handles and detached results cross a bounded service queue on the original TD owner; native handles remain on that owner. Cancellations retain their independent queue capacity and priority. Completed results survive local wait timeouts. Per-key materialization gaps remain latched across unsubscribe, and the same owner cannot acquire a second market bridge to bypass retained state.

Maintenance advances reset, epoch acknowledgement and unsubscribe calls without waiting for the native owner. A pending result is not replayed; an old epoch ACK must finish before another reset is considered. Cached delivery also requires the provider's retained_events_ready observation, using the same source and recovery checks as native polling. A false reset flag alone is insufficient. The observation expires and is consumed once; it does not promise that a source cannot disconnect after the owner check and before network delivery. Events keep their original source, epoch and observation time.

R21 subscription and source-description requests used bounded waits that could accumulate on the Host. R23 introduces the asynchronous service path described below; a running native call still cannot be preempted. Legacy low-level Python synchronous methods are not the asynchronous Host entry point. Full-profile shutdown first stops new market calls, then closes the original owner within its existing budget. Only confirmed session cleanup permits the Hub and proxy to discard uncertain acquisitions. Failed cleanup retains the same resources and account guard for retry.

This is source work undergoing R21 validation. The independent-process tests use the real Python CTP session/provider and synthetic native TD/MD implementations. They do not establish SimNow operation, complete BT wiring, recovery, strategy economic ledgers, cross-platform behavior or whole-iteration acceptance.

Iteration 63 R23: asynchronous market bootstrap

The CTP market bridge provides begin_subscribe, subscription_ready and probe_source without waiting for the native owner. The original handle and pending result survive caller timeouts; acquisition and descriptor queries are not submitted again just because they are still pending. A bounded descriptor slot retains the original epoch and completion time when another maintenance operation consumes its future. Reset and ACK observations retain their own consumer; stale descriptors are not relabelled or given new validity.

The server advertises market.bootstrap_begin, market.bootstrap_status and market.bootstrap_cancel only for a provider supporting all three asynchronous methods. GatewayMarketClientSettings explicitly requests these operations by default; the server must grant them. Generic raw-runtime registration without an explicit operation selection does not add them to older requests. An async Hub rejects the old synchronous subscribe/bootstrap RPCs before provider I/O.

ServiceMarketClient.begin_start_many returns a local operation whose step() performs at most one control RPC and returns None while pending. It keeps one operation ID, original registration and complete payload, including after a lost reply. Synchronous convenience methods use this state machine and maintain the runtime between steps. Gateway strategy owners instead return a trusted OwnerOperationContinuation, allowing the same owner thread to renew leases and serve other requests between steps. No extra native owner or strategy scheduler is introduced. A pending handle cannot be cancelled as if it had never started.

Recovery may request refresh_existing=True to refresh a same-registration active subscription while borrowing its existing reference. It does not cancel other members of the original batch or acquire a second upstream. Requested source descriptors, current authorization floors and original-registration uncertainties remain mandatory. Closing one active client unsubscribes its own key; cancelling an unresolved batch retains the batch operation ID until cleanup is confirmed. Explicit authorization interruptions require the regrant path.

The server bounds outstanding and terminal bootstrap records and retained result bytes; reaching capacity is an explicit error. These records are scoped to a registration in one service lifetime, not a durable transaction journal or proof that an account is ready. The default transport remains bt_api_transport_zmq. Validation results and exact source/install scope are recorded in the Backtrader Iteration 63 round reports. Complete Backtrader wiring, economic ledgers, whole-iteration and account acceptance remain separate.

Iteration 63 shared-session instrument rules (R26 candidate)

GatewayStrategyClientSession accepts explicit GatewayInstrumentClientSettings and exposes session.instruments plus session.get_instrument_spec(exchange_name, symbol). The existing account binding must explicitly request and receive all three account.instrument_spec.begin/status/cancel operations. Selecting them neither adds a provider to the strategy process nor expands old default grants. The client uses the existing ZMQ runtime owner and continuation mechanism.

The CTP trading profile mounts the query source when account reads are configured. It borrows the existing TD session and restricts queries to configured observation instruments. Results use the existing InstrumentSpec, with native limit-order minimum/maximum quantities and exact Decimal wire values. max_quantity remains optional in the general SDK DTO; this CTP source requires both native limit bounds. The new path supplies static futures rules, not market-order support, actual trade fees, market-price freshness, or an execution authorization receipt.

session.instruments.lookup(...) returns a view with the original observed time and a conservative local expiry. validate(view) checks its retained runtime binding and expiry. A timed-out caller retrieves the same pending operation; cleanup_pending() retries an original unresolved job, reporting uncertainty instead of inventing cancellation. Ready results are source-checked on the owner within that asynchronous delivery cycle; this is not atomic proof of the native session at a later socket-send instant.

Pending jobs are bounded at 64 globally and 8 per registration. Total retained jobs are bounded at 256/64 respectively, with terminal retention starting at first completion. Close retains cleanup responsibility on the original owner. Callback, rate and query-slot waits yield; existing source-lock critical sections and entered vendor calls can still block. Account refresh also retains its separately tracked synchronous path. Source, isolated-install, complete recovery and real-account acceptance must be reported separately; consult the R26 round report for status.

The profile also distinguishes a verified reconnect of the original CTP native source from source replacement. During a verified transient disconnect it invalidates account observations and pauses return admission while retaining the same owner, session and account guard. Resuming still requires the existing login-generation, settlement and reconciliation checks. This does not clear UNKNOWN or other control reasons. Unexpected failures and changed identities remain fatal; consult the R26 round report for validation status and limits.

Iteration 63 explicit Gateway API entry (R29)

BtApi.from_gateway(session, exchange_name="CTP___FUTURE", owns_session=False) returns a bt_api_py.gateway_api.GatewayBtApi over an explicitly constructed GatewayStrategyClientSession. It does not construct a local provider or another runtime, transport, thread or durable host. The session continues to use bt_api_transport_zmq by default. Configuration parsing, trusted identity, keys, permissions and the durable host are still supplied through the session contract.

The selected route is exact and is checked before business operations. It is a route label, not the native venue in OrderRequest.exchange_id. reserve_order preserves the request's idempotency_key; dispatch_order, command_status, release_order and cancel_order use that original durable key. Release and cancellation additionally require their explicit stable operation_id. Results retain the existing typed Gateway outcomes: a queued request or SENT observation is not venue acceptance, a fill or a completed cancellation. There is no implicit reserve-and-dispatch operation, retry or fallback to direct trading.

gateway_execution_stream, account_read, market_subscription and get_instrument_spec delegate to the configured session ports. Stream reads do not ACK automatically; missing optional ports fail explicitly. Returned clients keep their original runtime and permission checks. They are not revoked merely by closing a borrowed facade, and the market proxy is not a MarketStreamPort. Account observations do not establish a strategy's available balance.

start() explicitly starts the existing session. close() defaults to closing only the facade; owns_session=True also closes its originally captured runtime, without closing the durable host. status() returns that runtime's unchanged snapshot, while lifecycle_state reports the facade's state. An incomplete or failed owned close remains retryable. Detected binding changes reject business operations but retain the original process's status and cleanup path; they do not redirect cleanup to a replacement object or restore business eligibility.

This is a separate capability facade, not an implementation of UnifiedBtApiFacade or a drop-in replacement for its ordinary order/event mapping. Complete Backtrader Store/Broker/Feed wiring, production event projection and ACK recovery, config-only startup and real-account acceptance remain open.

Iteration 63 trade date enrichment stream (R30)

The execution-stream service preserves the journal's trade_metadata_only effect when projecting a v4 trade fact into a v2 public observation. A metadata-only event adds a known natural date to the original trade; consumers must not apply its quantity again. It retains the original request, reservation and trade identity, uses the ordinary bounded page/consumer cursor, and requires explicit ACK. Ordinary v1 observations keep their prior canonical bytes. The default transport continues to be bt_api_transport_zmq, and permission checks and reply budgets remain in force. The protocol supplies no inferred date, timezone or actual trade fees.

This propagation and the existing BT pending consistency checks do not install the complete Broker/Store event consumer or update Strategy Order/Trade objects by themselves. Source, installed-package, synthetic process and real-account evidence remain separate; see the Iteration 63 R30 review for the exact delivered scope.

CTP Gateway simulation calendar configuration

The protected CTP operator resource bundle may contain an optional calendars object. It is required exactly when the Gateway component binds service.calendar_read. The object is strict: supply all six fields shown below; each grant and range policy also requires exactly its shown fields. Values in this example are fictional, and matching strategy identities, account scopes, and read-only Registry resource grants must be configured separately.

{
  "root": "calendars",
  "mode": "SIMULATION_ONLY",
  "route": "CTP___FUTURE",
  "grants": [{
    "principal_ref": "example-principal", "execution_domain_ref": "example-domain",
    "account_ref": "example-account", "strategy_ref": "example-strategy",
    "run_id": "example-run", "route": "CTP___FUTURE", "venue": "SIM",
    "kind": "future", "product": "x", "contract": "x2601"
  }],
  "range_policies": [{
    "policy_id": "example-policy", "route": "CTP___FUTURE", "venue": "SIM",
    "kind": "future", "product": "x", "contract": "x2601",
    "max_advance_days": 0, "max_spill_days": 0
  }],
  "simulation_bootstrap": {"trading_day": "2026-01-01"}
}

The root is resolved relative to the protected resource file, not the launch file or working directory. A range policy's exact route and instrument scope must be covered by either a strategy grant with Registry calendar.windows.v1 permission or the separate Monitor grant and resource described below; strategy day queries require calendar.query.v1. The strategy grant identifies one run and does not grant any order or native trading capability. A matching Registry resource may name that exact run, or leave its run unset; it cannot authorize a calendar grant for a different fixed run. Product and contract are explicit calendar scopes, not inferred from CTP symbols.

For an explicit Monitor service reader, add both monitor_clients and monitor_grants to that same calendars object. The following fields are complete; replace the key placeholder with that Monitor's separate 40-character CURVE public key and match the configured service instance, scope and policy:

"monitor_clients": [{
  "identity": {"role": "service", "principal_ref": "example-monitor-principal",
               "actor_ref": "example-monitor", "delegate_ref": null},
  "curve_public_key": "<monitor CURVE public key>",
  "resources": [{"instance_id": "example-gateway", "port": "service.calendar_read",
    "scope_ref": "example-scope", "scope": {
      "execution_domain_ref": "example-domain", "account_ref": "example-account",
      "account_refs": [], "strategy_ref": null, "run_id": null,
      "manual_book_ref": null, "portfolio_ref": null, "group_id": null, "leg_id": null
    }, "operations": ["calendar.monitor.windows.v1"]}]
}],
"monitor_grants": [{"principal_ref": "example-monitor-principal", "actor_ref": "example-monitor",
  "execution_domain_ref": "example-domain", "account_ref": "example-account",
  "route": "CTP___FUTURE", "venue": "SIM", "kind": "future",
  "product": "x", "contract": "x2601"}]

The reader must explicitly configure the upstream.calendar mount and request only calendar.monitor.windows.v1. Both the account-scoped Registry resource and the exact Monitor grant are required; neither grants direct or trading operations. A calendar component advertises the new handler even in older configurations, but advertisement is not permission. Existing strategy clients still request their previous default day operation and cannot use the Monitor operation. Monitor results retain the bounded simulation contract, DEPLOYMENT_DECLARED_UNVERIFIED, NOT_PROVEN, the data origin, and no trade authorization; they do not prove exchange calendar completeness.

Bootstrap pins the current receipt-checked calendar version at startup to the explicit day. Its operator-simulation-... generation is created locally for that process and is not a CTP session generation. Changes to CURRENT do not update the running view; restart loads the then-current version using the configured day. With simulation_bootstrap: null, or an unavailable or invalid snapshot, reads remain UNKNOWN. The package_seed root may be declared only without bootstrap; this process never installs a seed. Responses describe simulation only, with source authentication not proven and no trade authorization.

The formal mock publisher binds SYNTHETIC_MOCK into the coverage manifest for its exact generated BASE and AFTERNOON_CHANGE schedules. The manifest and binding digests travel with the published snapshot, so direct and Gateway day and UTC-range reads retain the label. A matching source name or metadata field alone cannot add it. Mixed observations retain their own provenance, and old snapshots without a declaration remain UNSPECIFIED. This classification is still simulation, not exchange-source authentication. Range policies must cover the published owner-day mappings, including the mock weekend night sessions.

Atomic Execution parent listener (quarantined by default)

The SDK entry point python -m bt_api_py.execution_parent_service_host --config /absolute/path/parent.json starts the selected atomic_intake ServiceHost with its AccountJournalHost, atomic intake, explicit strategy grants and separate service action grant. The JSON file and CURVE key files must be private, owner-controlled regular files (mode 0600 on POSIX, no symlinks or hard links); the journal directory and the separate registry directory must already exist, be private, and not overlap. The listener accepts a loopback IPv4 TCP endpoint only. The stable storage UUID and exact account/strategy/run binding must be supplied by the operator; they do not authenticate an account or establish an old-writer fence. A local lease is not such a fence. The default quarantined Atomic service reports UNREADY and refuses registration. The explicit cooperative mode below supports local parent intake; neither mode establishes provider or trading capability.

The former capture_prepared_parent_source entry points are retired and reject calls. Trusted in-process integrations may explicitly compose GatewaySourcePreparation with the running parent, an authenticated Gateway runtime and its bound target, then call observe with the original parent reference, request ID and request digest. The recorded path binds the original service identity, instance and intake lease, persists an attempt before SOURCE, and reports OBSERVED, HISTORICAL, UNKNOWN or INVALID_REQUEST. Historical or unknown results are not a new successful SOURCE, and a local observation grants no dispatch authority. Older receipts without the original binding cannot use this path. Combined-service JSON may explicitly configure gateway_source with one loopback endpoint, Gateway service/instance/scope, expected peer, a configured strategy principal, three separate CURVE key files and timeout_ms (1–250). Its owned strict runtime requires SOURCE and register_v2 grants for the existing registration contract, but this adapter sends only SOURCE. With run --source-control-stdin, the POSIX process owner can submit bounded JSON lines containing parent_ref, request_id and request_sha256. The same parent owner processes each accepted command once; UNKNOWN is never automatically retried. Input and status output are bounded and nonblocking, output pressure pauses new input, and EOF closes only control input. A missing response, including buffered output at shutdown, means UNKNOWN. Network waiting is bounded by the configured deadline; filesystem, SQLite and scheduling latency are not bounded, so this is not a guarantee of concurrent heartbeat service. Without the optional configuration no upstream client is created. Unconfirmed closure retains the original client before parent journal release.

The JSON schema is exact: unknown fields and duplicate keys are rejected. The following is a structure example, not credentials or a ready-to-run deployment. Replace every illustrative reference and supply distinct key files. service is a normal parsed SDK ServiceConfig with exactly one Execution atomic_intake component and no outbound clients.

{
  "schema": "bt_api_execution.parent_service.v1",
  "service": {
    "service_config_schema_version": 1, "process_role": "service",
    "service_id": "execution-service", "scope_ref": "root-scope",
    "transport_ref": "listener", "registration_policy_ref": "registration-policy",
    "service_requirements_ref": "requirements",
    "components": {"execution": {"config_schema_version": 2, "settings": {
      "instance_id": "execution-a", "bind_ports": ["service.execution_parent"],
      "options": {"role": "atomic_intake"}}}},
    "communication": {"config_schema_version": 1, "profiles": {"listener": {
      "backend": "zmq", "config_schema_version": 1,
      "endpoints": {"rpc_bind": "tcp://127.0.0.1:18971"}, "security_profile_ref": "listener-key"}}}
  },
  "service_identity": {"role": "service", "principal_ref": "execution-principal", "actor_ref": "execution-service"},
  "authority_versions": {"scope": "v1", "security": "v1", "registration_policy": "v1", "requirements": "v1"},
  "execution_scope": {"provider": "ctp", "environment": "simnow", "account_ref": "account-a", "strategy_id": "strategy-a"},
  "wire_scope": {"execution_domain_ref": "paper", "account_ref": "account-a", "strategy_ref": "strategy-a", "run_id": "run-a"},
  "storage": {"journal_root": "/private/example/journal", "registry_path": "/private/example/registry/registry.sqlite", "storage_id": "00000000-0000-4000-8000-000000000001"},
  "server_keys": {"public_key_file": "/private/example/server.pub", "secret_key_file": "/private/example/server.key"},
  "strategy_grants": [{
    "identity": {"role": "strategy_client", "principal_ref": "strategy-principal", "actor_ref": "strategy-a"},
    "scope_ref": "strategy-scope", "revision": "v1",
    "instruments": [{"provider": "ctp", "venue": "SHFE", "environment": "simnow", "product_type": "future", "instrument_id": "rb", "native_symbol": "rb"}],
    "operations": ["execution.parent.submit", "execution.parent.query"], "public_key_file": "/private/example/client.pub"
  }],
  "action_grant": {"revision": "v1", "instruments": [{"provider": "ctp", "venue": "SHFE", "environment": "simnow", "product_type": "future", "instrument_id": "rb", "native_symbol": "rb"}], "plan_versions": ["v1"], "actions": ["accept", "query"]},
  "schedule_build_id": "build-a",
  "algorithm_policies": [{"plan_version": "v1", "schedules": [{"name": "PASS", "version": 1, "params": {}, "max_retry": 0}]}],
  "lease": {"owner": "local-owner", "ttl_ns": 300000000000}
}

The default quarantined mode permits this listener to start only with a fresh journal and keeps parent registration unavailable. Reopening an existing journal requires the explicit cooperative recovery contract below. Creating a new journal does not resolve writer continuity or authorize bypassing an existing account journal.

A first SIGINT or SIGTERM requests bounded close on the original owner thread. If cleanup is unknown, the process reports EXECUTION_PARENT_CLEANUP_PENDING, retains the original resources, and waits for another signal to retry. Status messages are finite labels and do not include configuration or key values.

Local Execution parent recovery

The parent-service configuration optionally accepts storage.writer_mode and storage.require_existing. Defaults remain quarantined and false. single_host_cooperative requires require_existing: true in this CLI and uses the Execution package's explicit local deployment contract. It preserves the original journal and advances an existing lease. The operator must establish that all writers cooperate with the same local Host lock, old and remote writers are excluded, and storage has not been rolled back. The option cannot establish these deployment facts or grant provider/account authority.

An original management-only journal with no intake lease has a separate, explicit first-claim configuration:

"lease": {
  "owner": "local-owner",
  "ttl_ns": 300000000000,
  "initial_claim": {
    "claim_id": "00000000-0000-4000-8000-000000000002",
    "expected_incarnation": "00000000000000000000000000000001",
    "history_assertion": "management_read_only_no_prior_intake"
  }
}

The values above are illustrative. Supply a new claim ID and the original journal incarnation. This setting is an operator declaration, not historical proof. Execution verifies the exact initial schema and metadata and empty business tables, then commits the marker and first lease together. Preserve the original journal throughout. After a confirmed successful claim, remove lease.initial_claim for subsequent recovery; reusing it fails closed. Even if startup later fails, the claim may already be committed. Confirm cleanup and inspect the original marker and lease before choosing ordinary recovery. Never delete a marker, lease, or journal to retry an uncertain result.

The SDK consumes Execution's local_intake_status() three-state contract so temporary Host/Store lock contention can recover without permanently revoking readiness. Missing contracts and invalid resources remain unavailable. A local parent receipt is not a Risk approval, Gateway acknowledgement or sent order. The independent management-read and parent CLIs each own an exclusive journal lock and cannot run against the same root at the same time. To expose both interfaces, use python -m bt_api_py.execution_combined_service_host validate --config /absolute/path/combined.json, followed by the run command. Its owner-only JSON configuration has exactly schema, parent, and management: schema is bt_api_execution.combined_service.v1; the other fields embed the existing parent and management configurations. They must name the same original root, storage UUID, local account/strategy and wire domain/account/strategy, distinct loopback endpoints, and separate audit and Registry storage.

The combined host opens one parent-owned journal and lets the management listener borrow it. Management closes before the parent; uncertain cleanup keeps the same owners available for retry. Each listener reports its own readiness, so management can remain available while parent intake is unready. Management reads do not observe uncommitted parent rows. A failure to start management can occur after first-claim commit and follows the same explicit recovery steps above. The tested local CURVE paths establish local receipt/read behavior only, not Risk approval, Gateway dispatch or provider execution.

Explicit service ProductID observations

The trading Gateway can explicitly mount upstream.instrument_products on service.instrument_product_read, with instrument.product.begin.v1, instrument.product.status.v1 and instrument.product.cancel.v1. The protected instrument_product_observers section supplies SERVICE identities, exact account-scoped resource grants and a per-principal instrument allowlist. A Monitor may share one exact identity and key with the explicit calendar observer section; both ports still require separate grants. Default profiles add neither this mount nor a query, and configuration parsing does not require CTP imports.

The service reuses the original trading owner, CTP session and bounded query lane. The returned product_id comes from the same immutable native instrument row as the validated rules. Current support remains futures-only and requires the full rule fields. It is a current session observation, not a historical as-of mapping, complete product membership, account-read grant or write permit.

GatewayInstrumentProductClient borrows an already started, thread-owned ServiceClientRuntime; it does not start or close that runtime. It pins the authenticated peer and registration lineage, starts its local expiry bound before sending, and retains pending or unknown operations. Explicit retire() releases only known terminal local entries. A call requires the same binding object before send, after the response and after result projection. Renewal between calls is allowed; renewal during a call refuses that result and keeps the operation for a later explicit status query. Synthetic owner/profile/CURVE tests cover these paths; native account and deployment acceptance remain separate.

Monitor member consumers and typed calendar reads

A v2 standalone Monitor configuration may explicitly add a nonempty recovery_duration list. Each item fixes consumer_id, binding_ref, source_ref, scope_ref, config_version and a complete member_key. The Host uses its original durable outbox and complete ingress binding list, with one independent consumer/checkpoint per configured member. An owned background thread performs bounded steps. Missing mapping/calendar facts remain durable pending and pause that consumer; this composition currently supplies no remote facts. An optional alert_rule declares rule_id, rule_version, threshold_ns, max_candidates, severity and notify: false. Its owned worker reconciles committed candidates into the original local alert outbox, including while that member is pending. No network notification is configured. Candidate capacity exhaustion fails the worker closed with a distinct finite status; existing candidates and resources remain available for inspection. Without a rule, this composition creates no alert tables. Cached snapshots are explicitly historical only, with current state UNKNOWN. Unconfirmed worker shutdown retains the original worker, listeners and resources for explicit retry.

When this processor is selected, the shared SQLite lock wait is 0.05 seconds (the unselected default remains unchanged). A busy ingress call may have an UNKNOWN outcome and is not an acknowledgement or safe-retry proof. SQL errors make the selected worker UNKNOWN and drive the Host's normal failure/cleanup path. The short lock wait is not a bound on all disk or operating-system I/O.

GatewayMonitorCalendarClient reads calendar.monitor.windows.v1 using a borrowed, thread-owned runtime and exact authenticated account/peer binding. It accepts legitimate renewal between calls, but requires the same binding object throughout each individual call. The immutable result retains the simulation and unproven-source labels. Domain/account come from the Registry binding; they are not echoed by the calendar wire payload. Window consistency relies on the Gateway's single-view fence, not a per-window cryptographic proof. This reader is not yet a historical ProductID/calendar fact adapter.

The conditional Monitor fact API binds each pending response to the original head, member generation and explicitly rechecked mapping/calendar versions. It performs no remote collection; a current ProductID read is not historical mapping evidence. The original account Execution journal can resume under a new strategy scope after confirmed owner closure without repeating its initial claim. Its account lease advances while old strategy history remains isolated and unresolved historical outcomes remain unresolved; the combined host serves only its configured strategy scope. Local synthetic scope-resume tests do not prove an actual owner has stopped or that an account is ready to trade.

Risk first-reservation receipt bridge

RiskGatewayFirstReserveBridge explicitly composes an existing Risk ledger, Registry admission and dedicated strict ServiceClientRuntime on the same owner thread. It commits one v4 attempt before sending, rechecks the original permit and registration after payload projection, and releases the Registry scope and SQLite transaction before network I/O. Receipt consumption checks the original authenticated socket and registration again; closing, renewing or replacing that binding invalidates the captured observation. Uncertain outcomes consume the local attempt and never trigger a resend.

The returned one-use result is a historical observation. It does not confirm the reservation, authorize dispatch or establish continuously valid authority throughout a network call. An explicit internal engine composition is available; the bridge is not yet installed in the service host. Production source verification and Gateway write gates remain closed; existing v3 ledgers have no automatic migration to the v4 attempt schema.

Optional CTP observed order tracking

CtpGatewayReturnMaintenance(..., observed_order_source=True) explicitly records validated native callback receipts in the original Gateway journal before acknowledgement. Duplicate records retain separate sequence receipts; failed projections persist a gap, retain the original ticket and close existing reservation admission. A source begin with an uncertain outcome retains its original binding and retries invalidation during cleanup. Only a conflict in the independently verified original record invalidates that source; conflicting fact arguments do not establish source drift.

This option remains absent from the production profile. Its local contiguous prefix is not account-wide coverage. The return buffer acknowledgement and concurrent callback arrival are separate operations; acknowledging a processed prefix does not prove the absence of a later source gap. Risk R05 and trading gates remain closed.

The Risk service may explicitly select pretrade.schema_version: 4. An existing v4 journal requires no upgrade setting. A one-time upgrade_from_v3 additionally requires the previously saved database and lock device/inode pairs and maintenance_window: true. The Host verifies existing files before entry, uses its original inner fence manager for migration, and opens v4 before any Gateway client or listener starts. Remove upgrade_from_v3 from the resume configuration after confirmed success; it is never an automatic startup retry. The status command refuses configurations that request an upgrade.

An uncertain migration retains the original acquiring stack, manager and fence through the existing cleanup wait path. These checks assume a trusted maintenance window; the underlying fence constructor can still create files if an external actor deletes them after the pre-entry check. This composition does not claim to prevent malicious replacement or create permission to release an uncertain owner. Default v3 configuration and all source/write gates remain unchanged.

CtpGatewayOrderCutCoordinator explicitly coordinates one original CTP query with that same maintenance owner, tracker and journal. It projects the original query rows and verifies at most one pinned callback receipt per advance before persisting a candidate. Query absence does not delete observed orders. Gaps, expired evidence and uncertain post-write validation retain the original pin and fail closed. Current candidate reads include subsequently observed account history gaps without rewriting the historical cut. Failure invalidation performs SQLite I/O only after releasing the native query lock.

Receipt immutability relies on the original guard and immutable-table triggers, whose DDL is checked by journal transactions; it does not protect against an external actor temporarily replacing and restoring database objects. Each step still validates the full native result and window, and the final step compares all pinned digests. In synthetic 64-record tests, splitting receipt checks reduced the maximum step from about 5.17s to 0.36s but increased their cumulative time to about 15.10s. Maximum-size workloads and slow storage are not accepted. Native submission and SQLite I/O can block. No production profile, remote cut manifest or Risk coverage consumer is wired by this local coordinator.

The Execution action vocabulary now includes a separately granted reserve_parent action for explicit local preparation against the original account journal. The formal parent service still accepts only its existing actions and does not enable this operation. Local preparation persists one UNKNOWN attempt before issuing a one-use capability and rechecks journal, Registry, lease and parent deadlines on consumption. It has no Risk RPC or dispatch path; canonical returned facts are a historical local observation, not continuous cross-service authorization.

Authenticated account fact pages

GatewayAccountFactsClient can explicitly require the expected peer and CURVE key fingerprint. Strict reads and ACKs retain the original registration socket; an ACK consumes the token from that authenticated nonempty page. An uncertain ACK is not automatically retried. An explicit authenticated reread can issue a new token for an idempotent ACK of the same page. This binds a local RPC observation, not a committed consumer transaction or remote account completeness. The optional unbound reader retains its previous behavior without this proof.

Gateway cut manifests provide bounded read-only pages and a stable local digest. They recheck the original cut, facts and prior callback evidence, and reject unprovable compacted history. Empty queries report only the current session day; this is not a native query-day proof or a replacement for pinned receipt checks. No R05 coverage gate or trading authority is enabled by these readers.

The first-attempt engine path rechecks built-in policy and the original permit and facts immediately before strict transport entry. Both Registry and ledger locks are released before network I/O. The earliest used fact/permit wall expiry and a conservative monotonic cap restrict the actual send; expiry or uncertainty after sending retains the original attempt and does not authorize a retry.

RiskAccountFactsCoordinator explicitly composes a strict authenticated Gateway facts client with the original v4 Risk ledger and an explicitly enabled R05 v2 extension. poll_once() commits the page and source binding before ACK; recover_pending_once() rereads exactly the original pending range. UNKNOWN does not trigger automatic retry. Reconstructing a coordinator checks the stored source before any RPC, including service instance and key fingerprint. Source changes need a future explicit transition. The calls are synchronous on the ledger owner thread. They do not establish account coverage or enable the R05 trading gate.

The Risk Host can explicitly select this consumer with a top-level setting:

account_facts_observation:
  poll_interval_seconds: 1
  timeout_seconds: 0.1
  page_size: 64

The original ledger must already be v4 with an R05 v2 extension. Startup only attaches the existing extension; it neither installs it nor combines observation startup with a schema upgrade. The consumer uses a separate strict connection on the existing upstream.account mount, requesting only account.facts.read_after.v2 and account.facts.ack. The original events observer keeps its own registration. At most one page is attempted per due Host tick. UNKNOWN or a pending ACK pauses this consumer until explicit recovery; Host maintenance does not retry it or replace its stored source binding.

Poll intervals are 1–3600 seconds, network timeouts 0.001–0.250 seconds and pages 1–256 items. These limits do not bound SQLite or operating-system I/O. Unconfirmed runtime or ledger cleanup retains the original Host and fence. The local account_facts_observation_status() reports a finite consumer state, not account readiness or authority. With no setting, this consumer remains disabled.

The explicit account.facts.read_after.v2 operation returns the original Gateway journal identity with the same authenticated fact page. The strict client can validate and detach only its exact issued response using one canonical snapshot. Mutated responses cannot be copied or acknowledged. A source change after the read transaction returns UNKNOWN because its offered cursor may already be committed. The detached page is a historical observation; a consumer must still bind its actual local commit to that page before ACK.

About

A Python SDK for Multi-Exchange Integration with Standardized API

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages