事件驱动Event-driven
tick / K 线 / 报单 / 成交 / 持仓 / 账户 / 合约回调,按需重写。Override only the callbacks you care about: tick / bar / order / trade / position / account / contract.
面向中国期货市场的交易与行情引擎 —— CTP 回调之上的一层干净抽象:事件驱动的策略开发、本地持仓管理、Redis 订单中继、内置回测、独立工具注册原语。 A trading & market-data engine for the Chinese futures markets — a clean abstraction over CTP callbacks: event-driven strategies, local position management, a Redis order relay, built-in backtesting, and a standalone tool-register primitive.
pip 安装后写一个最小策略:在合约回报时订阅目标合约,逐笔接收行情。 After installing, write a minimal strategy: subscribe to the target contract on the contract callback and receive every tick.
from ctpbee import CtpBee, CtpbeeApi from ctpbee.constant import TickData, ContractData class Main(CtpbeeApi): def on_tick(self, tick: TickData): # 每笔行情 / every tick print(tick.local_symbol, tick.last_price) def on_contract(self, contract: ContractData): # 登录后合约信息全量推送, 适合在此订阅 # contracts are pushed after login: subscribe here if contract.symbol == "ag2612": self.action.subscribe(contract.local_symbol) app = CtpBee("market", __name__, refresh=True) app.config.from_json("config.json") app.add_extension(Main("hello")) app.start(log_output=True)
tick / K 线 / 报单 / 成交 / 持仓 / 账户 / 合约回调,按需重写。Override only the callbacks you care about: tick / bar / order / trade / position / account / contract.
今昨仓拆分、冻结计算、逐 tick 盯市盈亏,平今平昨自动拆单。Today/yesterday split, frozen calculation, per-tick mark-to-market, automatic close-today/yesterday splitting.
API 直连模式与 DISPATCHER Redis 中继模式,进程间解耦。Direct API mode and DISPATCHER Redis relay mode for process decoupling.
looper 模式灌入历史 K 线,同一套策略代码跑实盘与回测。Feed historical bars in looper mode — the same strategy code runs live and backtested.
JSON 文件 + CTPBEE_ 前缀环境变量覆盖,凭据不进代码库。JSON file plus CTPBEE_-prefixed env overrides — credentials stay out of the repo.
tool_register 仅依赖标准库,其他项目可单独引入。tool_register is stdlib-only and can be imported by any project.
JSON 文件为基础,环境变量可覆盖——部署时凭据与参数不必进代码库。 A JSON file as the base with environment-variable overrides — credentials and parameters stay out of the codebase at deploy time.
{
"CONNECT_INFO": {
"userid": "your_userid",
"password": "your_password",
"brokerid": "9999",
"md_address": "tcp://127.0.0.1:30013",
"td_address": "tcp://127.0.0.1:30003",
"appid": "simnow_client_test",
"auth_code": "0000000000000000"
},
"INTERFACE": "ctp",
"MD_FUNC": true,
"TD_FUNC": true,
"SUBSCRIBE_CONTRACT": ["ag2612.SHFE"],
"SLIPPAGE_BUY": 0, "SLIPPAGE_SELL": 0,
"SLIPPAGE_SHORT": 0, "SLIPPAGE_COVER": 0
}
| 键Key | 说明Description |
|---|---|
| CONNECT_INFO | 柜台连接(userid / password / brokerid / md_address / td_address / appid / auth_code)Broker connection (userid / password / brokerid / md_address / td_address / appid / auth_code) |
| INTERFACE | 接口:ctp / local 等,默认 ctpInterface: ctp / local etc., defaults to ctp |
| MD_FUNC / TD_FUNC | 是否启用行情 / 交易功能Enable market data / trading functions |
| SUBSCRIBE_CONTRACT | 合约列表,初始订阅Contract list for the initial subscription |
| INSTRUMENT_INDEPEND | 按策略 instrument_set 过滤行情(集合需含 local_symbol 形式)Filter ticks per-strategy via instrument_set (use local_symbol form) |
| SLIPPAGE_* | BUY / SELL / SHORT / COVER 四向滑点,默认 0Four-way slippage: BUY / SELL / SHORT / COVER, default 0 |
| PATTERN | real(实盘) / looper(回测)real (live) / looper (backtest) |
| RD_CLIENT_* | DISPATCHER 模式 Redis 地址/端口/库Redis host/port/db for DISPATCHER mode |
from_envvars 读取 CTPBEE_ 前缀的环境变量,值按 JSON 解析(布尔/数字/列表/字典均可,CONNECT_INFO 可整体传 JSON 字符串),解析失败保留原始字符串:
from_envvars reads CTPBEE_-prefixed variables; values are JSON-parsed (bool/number/list/dict — CONNECT_INFO may be passed as one JSON string), falling back to the raw string when unparseable:
export CTPBEE_TD_FUNC=false export CTPBEE_RD_CLIENT_PORT=6379 export CTPBEE_CONNECT_INFO='{"userid": "001", "password": "***", ...}' # 推荐优先级: 文件值 < 环境变量 / precedence: file < env app.config.from_json("config.json") app.config.from_envvars() # prefix="CTPBEE_", silent=True
其他导入方式:from_mapping(dict)、from_object(obj)(取全大写属性)、from_pyfile(file);统一过滤非大写键。
Other loaders: from_mapping(dict), from_object(obj) (uppercase attributes), from_pyfile(file) — non-uppercase keys are always filtered out.
仓库 examples/ 内全部可运行——合约代码与账号配置请按自己的环境更新。
Everything under examples/ is runnable — update contract codes and account config to your own environment.
ATR + SMA 趋势过滤开仓,按 ATR 倍数动态止损止盈;DISPATCHER 模式经 Redis 中继下单,合约回报时批量订阅。 ATR + SMA trend-filtered entries with dynamic ATR-multiple stops; runs in DISPATCHER mode and subscribes on contract callbacks.
双腿价差 5/20 均线 + 阈值偏离入场,主子合约成对开平;价差按分钟时间戳对齐,同分钟去重。 5/20 MA on the two-leg spread with deviation-threshold entries; spreads are minute-aligned and deduped.
注入 ctpbee_kline 的 K 线工具后,策略的 on_bar 逐根收到合成 K 线。
With the ctpbee_kline tool injected, strategies receive synthesized bars in on_bar.
灌入 kline.csv 历史数据,逐项配置保证金/手续费/乘数,跑双均线策略并输出报告。
Feeds kline.csv, configures margin/commission/size per contract, runs a double-MA strategy and reports.
local 接口客户端 + 服务端:客户端限频发单并跟踪本地净持仓,经 Redis 通道与 openctp 服务端交互。 local-interface client and server: the client rate-limits its orders and tracks a local net position over Redis channels.
ATR、布林、双均线、MACD、RSI、跨期套利六个策略实现,全部基于 CtpbeeApi,可直接继承改造。
Six strategies — ATR, Bollinger, double MA, MACD, RSI, spread arbitrage — all CtpbeeApi subclasses ready to extend.
CTP 的 C++ 回调在最底层,向上只经一次信号分发——每个环节都可替换、可模拟、可测试。 C++ CTP callbacks sit at the bottom with a single signal fan-out above — every stage is replaceable, mockable and testable.
TICK_KERNEL / ORDER_UP_KERNEL / ORDER_DOWN_KERNEL 通道与外部进程交互(键名可配);断线自动重连、行情异步入队、发布失败不阻断回调链Redis relay mode: ticks/orders flow through configurable TICK_KERNEL / ORDER_UP_KERNEL / ORDER_DOWN_KERNEL channels; auto-reconnect, async tick queue, publish failures never break the callback chain策略内经 self.recorder 取最新状态:get_tick / get_last_price / get_order / get_trade / get_contract 等;账户初始化完成后 on_init 触发一次。
Inside a strategy, query latest state via self.recorder: get_tick / get_last_price / get_order / get_trade / get_contract etc.; on_init fires once after the account initializes.
继承 CtpbeeApi,重写你关心的回调。
Subclass CtpbeeApi and override the callbacks you care about.
| 回调Callback | 触发Fires when |
|---|---|
| on_tick(tick) | 每笔行情(须重写,基类为 NotImplemented)every tick (must override; base raises NotImplemented) |
| on_bar(bar) | K 线(需注入 K 线 Tool,如 ctpbee_kline)a bar is formed (requires a kline tool such as ctpbee_kline) |
| on_order(order) / on_trade(trade) | 报单状态 / 成交回报order status updates / fills |
| on_position / on_account | 持仓与账户回报position / account updates |
| on_contract(contract) | 合约信息(登录后全量推送,适合在此订阅)contract info (full push after login — a good place to subscribe) |
| on_init(init) | 账户初始化完成(仅一次)account initialization completes (once) |
| on_realtime() | 定时器触发the timer fires |
不想写完整类骨架时可用路由装饰器:Prefer not to write a full class skeleton? Use the route decorator:
strategy = Main("hello") @strategy.route(handler="tick") # "tick" / "order" / "trade" / ... def handle_tick(self, tick): print(tick.last_price)
instrument_set 配合 INSTRUMENT_INDEPEND 按合约过滤行情,集合内请放 local_symbol 形式(如 "ag2612.SHFE")。
instrument_set plus INSTRUMENT_INDEPEND filters ticks per strategy; keep local_symbol forms (e.g. "ag2612.SHFE") in the set.
所有行情/交易对象都继承 Entity:构造后受 frozen 保护(仅下划线调用方可写),并自动派生 local_symbol(如 ag2612.SHFE)。_to_dict() 可导出枚举已转换的字典。
Every market/trade object derives from Entity: frozen after construction (only underscore callers may write) and auto-derives local_symbol (e.g. ag2612.SHFE). _to_dict() exports a dict with enums converted.
| 字段Field | 含义Meaning |
|---|---|
| symbol / exchange | 合约与交易所(派生 local_symbol)contract and exchange (local_symbol derived) |
| datetime | 交易所本地时间(100ms 量化)exchange-local time (100 ms quantized) |
| last_price / volume | 最新价与当日累计成交量——增量需自行差分last price and the cumulative day volume — diff it yourself for increments |
| turnover / open_interest | 累计成交额 / 持仓量cumulative turnover / open interest |
| bid/ask_price_1..5 + volume | 五档买卖价量5-level order book |
| upper_limit / lower_limit | 涨跌停价(limit_up/limit_down)price limits (limit_up/limit_down) |
| pre_settlement_price | 昨结算价(盯市基准)previous settlement (mark basis) |
| 字段Field | 含义Meaning |
|---|---|
| direction | LONG=买 / SHORT=卖;无论开平,Δ持仓 = 方向 × 手数LONG=buy / SHORT=sell; Δpos = direction × volume regardless of offset |
| offset | OPEN 开 / CLOSETODAY 平今 / CLOSEYESTERDAY 平昨 / CLOSE 平(自动)OPEN / CLOSETODAY / CLOSEYESTERDAY / CLOSE (auto) |
| status | SUBMITTING→NOTTRADED→PARTTRADED→ALLTRADED / CANCELLED / REJECTED;活动态 = NOTTRADED|PARTTRADEDSUBMITTING→NOTTRADED→PARTTRADED→ALLTRADED / CANCELLED / REJECTED; active = NOTTRADED|PARTTRADED |
| price / volume / traded | 报单价、委托量、已成交量(多笔成交=多个 TradeData)order price, requested volume, filled volume (multiple fills = multiple TradeData) |
| order_id / tradeid | 柜台号;派生 local_order_id / local_trade_id(带网关前缀)exchange ids; local_order_id / local_trade_id derived with gateway prefix |
| 字段Field | 含义Meaning |
|---|---|
| direction / volume | 多空方向与总手数direction and total volume |
| yd_volume | 昨仓手数(今仓 = volume − yd_volume)yesterday volume (today = volume − yd_volume) |
| price / open_price | 持仓均价 / 开仓均价position average / opening average price |
| frozen | 冻结手数(挂平仓单占用)frozen volume (locked by pending close orders) |
| pnl / float_pnl | 浮动盈亏(对均价) / 盯市盈亏(对开仓价)floating pnl (vs avg price) / mark pnl (vs open price) |
| 结构Struct | 关键字段Key fields |
|---|---|
| BarData | open/high/low/close_price、volume、datetime——K 线 Tool 合成open/high/low/close_price, volume, datetime — synthesized by a kline tool |
| ContractData | size(合约乘数)、pricetick(最小变动)、net_position(是否净持仓模式)size (multiplier), pricetick, net_position (net-position mode) |
| AccountData | balance、available、frozenbalance, available, frozen |
| OrderRequest / CancelRequest | 下单/撤单请求,exchange 枚举或字符串均可order/cancel requests; exchange accepts enum or string |
注意:direction/offset/status 枚举值为中文(如 "多"/"开"),比较请用枚举成员而非字符串。
Note: direction/offset/status enum values are Chinese (e.g. "多"/"开") — compare with enum members, not strings.
四个语义化入口,平仓自动按今昨持仓拆分——命名按「方向_开平」理解,别被 buy_close 字面意思带偏。 Four semantic entry points with automatic close-today/yesterday splitting — read the names as direction_offset; don't be misled by the literal "buy_close".
| 接口Call | 语义Meaning | 底层Alias |
|---|---|---|
| action.buy_open(price, volume, origin) | 多头开仓open long | buy |
| action.buy_close(...) | 平多头(卖出平仓,自动拆平今/平昨)close a long (sell to close, auto split today/yesterday) | cover |
| action.sell_open(...) | 空头开仓open short | short |
| action.sell_close(...) | 平空头(买入平仓)close a short (buy to close) | sell |
| action.cancel(order_id, origin) | 撤单cancel an order | — |
origin 传触发行的行情/K 线对象,用于提取合约与交易所;可加 price_type=OrderType.FOK 等参数;价格会叠加对应方向的 SLIPPAGE_* 配置。上期所平仓会按持仓自动拆分平今/平昨报单。
origin is the triggering tick/bar used to extract symbol and exchange; pass price_type=OrderType.FOK etc. as needed; prices include the configured SLIPPAGE_*. SHFE closes are auto-split into close-today / close-yesterday orders.
Tool 是挂在 Recorder 分发链上的旁路处理器:策略收到行情之前/之外,按数据流做聚合、推送等加工。K 线就是这样实现的。 A Tool is a side-processor on the Recorder fan-out: it aggregates or relays the data stream alongside strategies. Kline synthesis is implemented exactly this way.
from ctpbee import CtpBee from ctpbee.level import Tool from ctpbee.constant import TickData class MyTool(Tool): # 基类五个回调(on_tick/on_order/on_trade/on_position/on_account) # 已默认挂接 tool_register —— 重写即可被订阅 def on_tick(self, tick: TickData): return tick.last_price # 返回值会喂给订阅者 app = CtpBee("market", __name__) app.with_tools(MyTool("my_tool")) # 或 app.add_tool(tool) app.get_tool("my_tool") # 按名取回; delete_tool 移除
from ctpbee.constant import ToolRegisterType # 策略侧: 订阅名为 my_tool 的工具在 TICK 通道的输出 strategy.subscribe("my_tool", lambda price: print(price), ToolRegisterType.TICK) # 也可直接在工具对象上增删 (按注册序执行 + 去重) tool.add_func(my_func, ToolRegisterType.TICK) tool.remove_func(my_func, ToolRegisterType.TICK) # 注册类型: TICK / ORDER / TRADE / POSITION / ACCOUNT / BAR / WHATEVER
from ctpbee_kline import Kline # pip install ctpbee_kline app = CtpBee("market", __name__, refresh=True).with_tools(Kline()) # 策略重写 on_bar 即可逐根收到合成 K 线
要点:回调返回值即订阅者收到的载荷;单个订阅者异常被隔离(不影响其余订阅者与行情链);订阅按注册顺序执行、同一函数去重。 Notes: a callback's return value is the payload subscribers receive; a failing subscriber is isolated (other subscribers and the tick chain are unaffected); subscriptions run in registration order and dedupe by function identity.
from ctpbee.tool_register import tool_register, register_tool_hook class Calc: # 任意类, 无需继承任何基类 @tool_register("tick") # 键任意可哈希: 字符串/枚举/None def on_tick(self, tick): return tick.last_price # 返回值喂给订阅者 c = Calc() register_tool_hook(c, "tick", print) # 订阅 # unregister_tool_hook(c, "tick", print) 退订
PATTERN="looper" 模式下,同一套策略代码可以直接灌历史数据回测。
With PATTERN="looper", the same strategy code runs directly over historical data.
app = CtpBee("looper", __name__) info = { "PATTERN": "looper", "LOOPER": { "initial_capital": 100000, "margin_ratio": {code: 0.00003}, "commission_ratio": {code: {"close": 0.00001, "close_today": 0.00001}}, "size_map": {code: 10}, }, } app.config.from_mapping(info) app.add_local_contract(ContractData(local_symbol=code, ...)) app.add_extension(DoubleMa("ma", code)) app.add_data(*data) # 历史 K 线序列 app.start() result = app.get_result(report=True, auto_open=True)
保证金、手续费率、合约乘数按合约逐项配置;完整示例见 examples/backtest/looper_example.py(配套 kline.csv)。策略开发建议:因子研究在 notebook 完成,ctpbee 负责交易执行。
Margin, commission and contract size are configured per contract; see examples/backtest/looper_example.py (with kline.csv). Suggested workflow: do factor research in notebooks, let ctpbee handle execution.
为全市场订阅设计——数千合约并发时,Python 侧每 tick 的固定开销在微秒级。 Built for full-market subscription — with thousands of contracts flowing, the per-tick Python overhead stays in the microsecond range.
参考量级 · Windows / Python 3.11-3.13Indicative figures · Windows / Python 3.11-3.13
data_api 只探测一次(失败的 import 不进 sys.modules,否则每根 bar 都要重扫 sys.path);交易日解析走 O(1) 日历索引并按(自然日, 夜盘)记忆化No per-bar overhead in backtests: the optional data_api dependency is probed once (a failed import is not cached in sys.modules, so every bar would otherwise re-walk sys.path); trade-day resolution uses an O(1) calendar index memoized per (calendar day, night session)ctpbee/date.py,否则时段判断与交易日推导将失效Calendar horizon: the built-in calendar currently covers up to 2026-12-31 — update ctpbee/date.py around year-end or session gating and trade-day derivation silently stop workingdate.today() 拼接——请在北京时区主机上运行DCE uses the local date: DCE's ActionDay is the trading day, so the engine stitches date.today() — run on a Beijing-time hostExchange 枚举Exchange types: data objects accept both strings and enums; prefer the Exchange enum in your own codelocal_symbol(如 ag2612.SHFE),策略的 instrument_set 需放同形式(或在 on_contract 中补全)INSTRUMENT_INDEPEND: filtering compares local_symbol (e.g. ag2612.SHFE) — keep the same form in instrument_set (or enrich it in on_contract)仓库自带独立脚本套件,共 161 项断言——不依赖 pytest、不连柜台、不需要真实 Redis。 The repo ships standalone script suites totalling 161 assertions — no pytest, no broker, no real Redis.
for t in tests/test_*.py; do python "$t" || exit 1; done # test_hotpath_optimization 10 · timestamp build / frozen / bulk init # test_position_hotpath 4 · pnl randomized-sequence oracle # test_dispatcher 11 · Redis relay (FakeRedis injection) # test_tool_register 15 · register primitive matrix # test_config_env 8 · env-var config # test_upper_layers 66 · FakeApp full event-flow simulation # test_examples_strategies 15 · example strategies regression # test_backtest_hotpath 32 · looper hot path vs pre-optimization oracles == 161 checks ==
每个脚本独立可运行(python tests/<name>.py),失败时以非零码退出,可直接接入 CI。贡献代码请随改动附带测试。
Each script runs standalone (python tests/<name>.py) and exits non-zero on failure — CI-ready. Please land changes together with tests.