ctpbee_

面向中国期货市场的交易与行情引擎 —— 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.

01 / QUICKSTART

01快速开始Quickstart

pip 安装后写一个最小策略:在合约回报时订阅目标合约,逐笔接收行情。 After installing, write a minimal strategy: subscribe to the target contract on the contract callback and receive every tick.

hello_ctpbee.py
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)
⇄

事件驱动Event-driven

tick / K 线 / 报单 / 成交 / 持仓 / 账户 / 合约回调,按需重写。Override only the callbacks you care about: tick / bar / order / trade / position / account / contract.

◎

本地持仓Local positions

今昨仓拆分、冻结计算、逐 tick 盯市盈亏,平今平昨自动拆单。Today/yesterday split, frozen calculation, per-tick mark-to-market, automatic close-today/yesterday splitting.

⇋

双模式Dual mode

API 直连模式与 DISPATCHER Redis 中继模式,进程间解耦。Direct API mode and DISPATCHER Redis relay mode for process decoupling.

⟲

内置回测Built-in backtest

looper 模式灌入历史 K 线,同一套策略代码跑实盘与回测。Feed historical bars in looper mode — the same strategy code runs live and backtested.

⊞

环境变量配置Env-var config

JSON 文件 + CTPBEE_ 前缀环境变量覆盖,凭据不进代码库。JSON file plus CTPBEE_-prefixed env overrides — credentials stay out of the repo.

⌘

可嵌入原语Embeddable primitive

tool_register 仅依赖标准库,其他项目可单独引入。tool_register is stdlib-only and can be imported by any project.

02 / CONFIG

02配置Configuration

JSON 文件为基础,环境变量可覆盖——部署时凭据与参数不必进代码库。 A JSON file as the base with environment-variable overrides — credentials and parameters stay out of the codebase at deploy time.

config.json 完整示例full example

config.json
{
  "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
PATTERNreal(实盘) / looper(回测)real (live) / looper (backtest)
RD_CLIENT_*DISPATCHER 模式 Redis 地址/端口/库Redis host/port/db for DISPATCHER mode

环境变量Environment variables

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:

env.sh
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.

03 / EXAMPLES

03示例集Examples

仓库 examples/ 内全部可运行——合约代码与账号配置请按自己的环境更新。 Everything under examples/ is runnable — update contract codes and account config to your own environment.

examples/login.py

ATR 策略实盘入口ATR strategy, live

ATR + SMA 趋势过滤开仓,按 ATR 倍数动态止损止盈;DISPATCHER 模式经 Redis 中继下单,合约回报时批量订阅。 ATR + SMA trend-filtered entries with dynamic ATR-multiple stops; runs in DISPATCHER mode and subscribes on contract callbacks.

Mode.DISPATCHERstrategy/atr_strategy
examples/run_arb.py

跨期套利Calendar-spread arbitrage

双腿价差 5/20 均线 + 阈值偏离入场,主子合约成对开平;价差按分钟时间戳对齐,同分钟去重。 5/20 MA on the two-leg spread with deviation-threshold entries; spreads are minute-aligned and deduped.

strategy/spread_arbitragepaired legs
examples/kline.py

K 线注入Kline injection

注入 ctpbee_kline 的 K 线工具后,策略的 on_bar 逐根收到合成 K 线。 With the ctpbee_kline tool injected, strategies receive synthesized bars in on_bar.

with_toolson_barctpbee_kline
examples/backtest/looper_example.py

looper 回测Looper backtest

灌入 kline.csv 历史数据,逐项配置保证金/手续费/乘数,跑双均线策略并输出报告。 Feeds kline.csv, configures margin/commission/size per contract, runs a double-MA strategy and reports.

PATTERN=looperget_resultdouble_ma
examples/openctp/

openctp 子账户分发openctp sub-account relay

local 接口客户端 + 服务端:客户端限频发单并跟踪本地净持仓,经 Redis 通道与 openctp 服务端交互。 local-interface client and server: the client rate-limits its orders and tracks a local net position over Redis channels.

INTERFACE=localFOK
examples/strategy/

策略库Strategy library

ATR、布林、双均线、MACD、RSI、跨期套利六个策略实现,全部基于 CtpbeeApi,可直接继承改造。 Six strategies — ATR, Bollinger, double MA, MACD, RSI, spread arbitrage — all CtpbeeApi subclasses ready to extend.

atrbollingerdouble_mamacdrsispread
04 / ARCHITECTURE

04架构Architecture

CTP 的 C++ 回调在最底层,向上只经一次信号分发——每个环节都可替换、可模拟、可测试。 C++ CTP callbacks sit at the bottom with a single signal fan-out above — every stage is replaceable, mockable and testable.

C++ CTP 回调callbacksmd_api / td_api · interface/{ctp, ctp_rohon, ctp_mini}
数据对象构造Data objectsTickData / OrderData / TradeData … · 时间戳快速构造fast timestamp build
blinker 信号signalscommon_signals(tick/bar/timer) + 每应用信号per-app signals(order/trade/…)
Recorder 数据中心data center@call 装饰分发 · 最新行情/报单/成交簿记 · 查询接口dispatch · latest tick/order/trade bookkeeping · queries
本地持仓Local positions盈亏纯函数 · 输入未变跳过重算pure-function pnl · skip when unchanged
Toolstool_register 钩子 · K 线聚合等hooks · kline aggregation …
你的策略Your strategyCtpbeeApi 子类subclass · on_tick / on_trade …

工作模式Working modes

  • Mode.API —— 常规模式,策略在本进程内直接收到行情与交易回报regular mode; the strategy receives market data and trade reports in-process
  • Mode.DISPATCHER —— Redis 中继模式:行情/订单经 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

数据查询Data queries

策略内经 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.

05 / STRATEGY API

05策略回调Strategy callbacks

继承 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:

route.py
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.

06 / DATA STRUCTURES

06数据结构Data structures

所有行情/交易对象都继承 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.

TickData · 行情· market data

字段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)

OrderData · 报单· order / TradeData · 成交· trade

字段Field含义Meaning
directionLONG=买 / SHORT=卖;无论开平,Δ持仓 = 方向 × 手数LONG=buy / SHORT=sell; Δpos = direction × volume regardless of offset
offsetOPEN 开 / CLOSETODAY 平今 / CLOSEYESTERDAY 平昨 / CLOSE 平(自动)OPEN / CLOSETODAY / CLOSEYESTERDAY / CLOSE (auto)
statusSUBMITTING→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

PositionData · 持仓· position

字段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)

其他常用结构Other common structures

结构Struct关键字段Key fields
BarDataopen/high/low/close_price、volume、datetime——K 线 Tool 合成open/high/low/close_price, volume, datetime — synthesized by a kline tool
ContractDatasize(合约乘数)、pricetick(最小变动)、net_position(是否净持仓模式)size (multiplier), pricetick, net_position (net-position mode)
AccountDatabalance、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.

06 / ACTION

07下单接口Order actions

四个语义化入口,平仓自动按今昨持仓拆分——命名按「方向_开平」理解,别被 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 longbuy
action.buy_close(...)平多头(卖出平仓,自动拆平今/平昨)close a long (sell to close, auto split today/yesterday)cover
action.sell_open(...)空头开仓open shortshort
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.

07 / TOOLS

08Tool 用法usage

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.

1. 写一个 Tool 并挂到应用Write a Tool and attach it

my_tool.py
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 移除

2. 订阅 / 退订工具的输出Subscribe to a tool's output

subscribe.py
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

3. 注入现成工具:K 线Inject a ready-made tool: kline

kline.py
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.

独立原语(其他项目可直接用)Standalone primitive (usable from any project)STDLIB-ONLY

standalone.py
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)  退订
08 / BACKTEST

09回测Backtesting

PATTERN="looper" 模式下,同一套策略代码可以直接灌历史数据回测。 With PATTERN="looper", the same strategy code runs directly over historical data.

backtest.py
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.

09 / PERFORMANCE

10性能与稳定性Performance & stability

为全市场订阅设计——数千合约并发时,Python 侧每 tick 的固定开销在微秒级。 Built for full-market subscription — with thousands of contracts flowing, the per-tick Python overhead stays in the microsecond range.

0.3 µs
行情时间戳构造(ActionDay 缓存)tick timestamp build (ActionDay cache)
3.1 µs
TickData 对象构造(批量初始化)TickData construction (bulk init)
0.1 µs
同价 tick 持仓盈亏(纯函数跳过)pnl on unchanged price (pure-function skip)
~3.4 µs
每 tick Python 固定成本合计total per-tick Python overhead
15 µs
回测每根 bar 框架成本(原 ~1.12 ms,72×)per-bar backtest framework cost (was ~1.12 ms, 72×)

参考量级 · Windows / Python 3.11-3.13Indicative figures · Windows / Python 3.11-3.13

稳定性设计Stability design

  • 回调隔离: tool_register 钩子、DISPATCHER 发布的单点异常被捕获并节流告警,不沿 CTP 回调链向上传播Callback isolation: exceptions in tool hooks or DISPATCHER publishes are caught and throttled — they never propagate up the CTP callback chain
  • 中继自愈: DISPATCHER 断线 5s 退避重连;行情异步入队(有界,满丢最旧)Self-healing relay: DISPATCHER reconnects on a 5 s backoff; ticks are queued asynchronously (bounded, drop-oldest)
  • 盈亏纯函数: 价格/持仓/均价/乘数输入未变即跳过重算;外部改动后同价 tick 也会重算,不留陈旧盈亏Pure-function pnl: recompute is skipped while price/position/avg-price/size inputs are unchanged; any external mutation re-triggers it, so pnl never goes stale
  • frozen 保护: 数据对象属性仅允许下划线调用方写入,防策略层误改行情数据frozen protection: data-object attributes only accept writes from underscore callers, preventing accidental mutation of market data
  • 序列化自洽: DDDR encode→parse 往返可用,键嗅探兼容手搓 dict 载荷Self-consistent serialization: DDDR encode→parse round-trips; key sniffing still accepts hand-built dict payloads
  • 回测无每根 bar 固定开销: 可选依赖 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)
10 / CAVEATS

11注意事项Caveats

  • 交易日历有边界: 内置日历目前覆盖至 2026-12-31,跨年前后请更新 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 working
  • 行情时间戳为 100ms 量化: 历史契约,依赖毫秒精度的策略需知悉100 ms timestamp quantization: a historical contract — millisecond-sensitive strategies should be aware
  • 大商所时间戳用本机日期: DCE 的 ActionDay 是交易日,引擎用 date.today() 拼接——请在北京时区主机上运行DCE uses the local date: DCE's ActionDay is the trading day, so the engine stitches date.today() — run on a Beijing-time host
  • 涨跌停单边行情: CTP 无价档位的哨兵值(极大浮点数)会原样进入 tick 字段,消费端自行过滤Limit-locked markets: CTP no-price sentinels (huge floats) pass through into tick fields — filter them downstream
  • exchange 类型兼容: 数据对象同时接受字符串与枚举;自定义构造时建议统一用 Exchange 枚举Exchange types: data objects accept both strings and enums; prefer the Exchange enum in your own code
  • INSTRUMENT_INDEPEND: 过滤比较 local_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)
11 / TESTS

12测试Tests

仓库自带独立脚本套件,共 161 项断言——不依赖 pytest、不连柜台、不需要真实 Redis。 The repo ships standalone script suites totalling 161 assertions — no pytest, no broker, no real Redis.

run_tests.sh
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.