Skip to content

Repository files navigation

CTP (China Futures)

CTP exchange plugin for bt_api, supporting Chinese futures market trading.

PyPI VersionPython VersionsLicenseCIDocs


English | 中文

Overview

This package provides the CTP (China Futures) exchange plugin for the bt_api framework. It offers a unified interface for interacting with Chinese futures exchanges via the CTP protocol.

Supported Exchanges

ExchangeCodeDescription
Shanghai Futures ExchangeSHFEmetals, energy
Dalian Commodity ExchangeDCEagricultural, chemicals
Zhengzhou Commodity ExchangeCZCEagricultural, chemicals
China Financial Futures ExchangeCFFEXequity index futures
Shanghai International Energy ExchangeINEcrude oil, iron ore
Guangzhou Futures ExchangeGFEXindustrial, agricultural

Features

  • Futures trading via CTP protocol (v6.x)
  • Support for all Chinese futures exchanges
  • Real-time market data via market data API
  • Order placement and cancellation via trade API
  • Position and margin tracking
  • Auto-selection between SimNow environments (set1 / set2 / 7x24)
  • SimNow simulated trading support

Installation

pip install bt_api_ctp

Or install from source:

git clone https://github.com/cloudQuant/bt_api_ctp
cd bt_api_ctp
pip install -e .

Quick Start

frombt_api_pyimportBtApi# Configure CTP futures exchangeexchange_kwargs= {
"CTP___FUTURE": {
"user_id": "your_user_id",
"password": "your_password",
"broker_id": "your_broker_id",
"md_front": "tcp://182.254.243.31:30011",
"td_front": "tcp://182.254.243.31:30001",
}
}
api=BtApi(exchange_kwargs=exchange_kwargs)
# Connect and subscribeapi.connect()
api.subscribe("CTP___FUTURE___rb2401", [{"topic": "tick", "symbol": "rb2401"}])
# Get data from queuedata_queue=api.get_data_queue("CTP___FUTURE")
msg=data_queue.get(timeout=10)
print(type(msg).__name__, msg)

CtpGatewayAdapter API

The CtpGatewayAdapter provides direct access to CTP futures:

frombt_api_ctp.gateway.adapterimportCtpGatewayAdapter# Initialize adapteradapter=CtpGatewayAdapter(
md_front="tcp://182.254.243.31:30011", # market data fronttd_front="tcp://182.254.243.31:30001", # trade frontuser_id="your_user_id",
password="your_password",
broker_id="your_broker_id",
gateway_startup_timeout_sec=10.0,
)
# Connectadapter.connect()
# Subscribe to symbolsadapter.subscribe_symbols(["rb2401.SHFE", "IF2404.CFFEX"])
# Get balance and positionsbalance=adapter.get_balance()
positions=adapter.get_positions()
# Place an orderorder=adapter.place_order({
"symbol": "rb2401.SHFE",
"side": "buy",
"size": 1,
"price": 4000.0,
"offset": "open",
})
# Cancel an orderadapter.cancel_order({
"symbol": "rb2401.SHFE",
"order_id": order["order_id"],
"front_id": order["front_id"],
"session_id": order["session_id"],
"order_ref": order["order_ref"],
})
# Disconnectadapter.disconnect()

Constructor Parameters

ParameterTypeDefaultDescription
md_frontstr""Market data front address (tcp://host:port)
td_frontstr""Trade front address (tcp://host:port)
user_idstr""CTP user ID / investor ID
passwordstr""CTP password
broker_idstr""Broker ID
auth_codestr"0000000000000000"Auth code (for production)
app_idstr"simnow_client_test"App ID
gateway_startup_timeout_secfloat10.0Connection timeout

Supported Operations

OperationMethodStatus
Connectconnect()
Disconnectdisconnect()
Subscribe Symbolssubscribe_symbols(symbols)
Get Balanceget_balance()
Get Positionsget_positions()
Place Orderplace_order(payload)
Cancel Ordercancel_order(payload)

Order Payload Format

{
"symbol": "rb2401.SHFE", # instrument.exchange or just instrument"side": "buy", # "buy" or "sell""size": 1, # order volume"price": 4000.0, # limit price (required for limit orders)"offset": "open", # "open", "close", "close_today""client_order_id": "...", # optional, client-side order ref"exchange_id": "SHFE", # optional, exchange code
}

Order Response Format

{
"id": "...",
"order_id": "...",
"external_order_id": "...",
"order_ref": "...",
"front_id": 1,
"session_id": 123456,
"exchange_id": "SHFE",
"details": {"bt_order_ref": "..."},
}

Environment Configuration

CTP supports three environments via CTP_ENV or env parameter:

EnvironmentDescriptionTrading Hours
auto (default)Auto-select based on timeMatches production
set1Production-like environmentTrading session only
set27x24 environmentNon-trading hours

For SimNow test accounts, leave md_front/td_front empty to auto-select the appropriate SimNow environment.

Online Documentation

ResourceLink
English Docshttps://bt-api-ctp.readthedocs.io/
Chinese Docshttps://bt-api-ctp.readthedocs.io/zh/latest/
GitHub Repositoryhttps://github.com/cloudQuant/bt_api_ctp
Issue Trackerhttps://github.com/cloudQuant/bt_api_ctp/issues

Requirements

  • Python 3.9+
  • bt_api_base >= 0.15

Architecture

bt_api_ctp/
├── src/bt_api_ctp/ # Source code
│ ├── containers/ctp/ # Data containers (CtpTicker, CtpOrder, etc.)
│ ├── feeds/ # Feed implementations (live_ctp_feed.py)
│ ├── gateway/ # Gateway adapter (CtpGatewayAdapter)
│ ├── ctp/ # CTP protocol (structs, client, trader/md API)
│ ├── errors/ # Error translators
│ ├── exchange_data.py # Exchange metadata
│ └── ctp_env_selector.py # SimNow environment selector
├── tests/ # Unit tests
└── docs/ # Documentation

License

MIT License - see LICENSE for details.

Support


中文

概述

本包为 bt_api 框架提供 CTP(中国期货) 交易所插件。通过 CTP 协议与中国期货交易所进行交互的统一接口。

支持的交易所

交易所代码描述
上海期货交易所SHFE金属、能源
大连商品交易所DCE农产品、化工
郑州商品交易所CZCE农产品、化工
中国金融期货交易所CFFEX股指期货
上海国际能源交易中心INE原油、铁矿石
广州期货交易所GFEX工业品、农产品

功能特点

  • 通过 CTP 协议(v6.x)进行期货交易
  • 支持所有中国期货交易所
  • 通过行情 API 获取实时市场数据
  • 通过交易 API 下单和撤单
  • 持仓和保证金跟踪
  • 自动选择 SimNow 环境(set1 / set2 / 7x24)
  • SimNow 模拟交易支持

安装

pip install bt_api_ctp

或从源码安装:

git clone https://github.com/cloudQuant/bt_api_ctp
cd bt_api_ctp
pip install -e .

快速开始

frombt_api_pyimportBtApi# 配置 CTP 期货交易所exchange_kwargs= {
"CTP___FUTURE": {
"user_id": "your_user_id",
"password": "your_password",
"broker_id": "your_broker_id",
"md_front": "tcp://182.254.243.31:30011", # 行情前置"td_front": "tcp://182.254.243.31:30001", # 交易前置
}
}
api=BtApi(exchange_kwargs=exchange_kwargs)
# 连接并订阅api.connect()
api.subscribe("CTP___FUTURE___rb2401", [{"topic": "tick", "symbol": "rb2401"}])
# 从队列获取数据data_queue=api.get_data_queue("CTP___FUTURE")
msg=data_queue.get(timeout=10)
print(type(msg).__name__, msg)

CtpGatewayAdapter API

CtpGatewayAdapter 提供对 CTP 期货的直接访问:

frombt_api_ctp.gateway.adapterimportCtpGatewayAdapter# 初始化适配器adapter=CtpGatewayAdapter(
md_front="tcp://182.254.243.31:30011", # 行情前置地址td_front="tcp://182.254.243.31:30001", # 交易前置地址user_id="your_user_id",
password="your_password",
broker_id="your_broker_id",
gateway_startup_timeout_sec=10.0,
)
# 连接adapter.connect()
# 订阅合约adapter.subscribe_symbols(["rb2401.SHFE", "IF2404.CFFEX"])
# 获取资金和持仓balance=adapter.get_balance()
positions=adapter.get_positions()
# 下单order=adapter.place_order({
"symbol": "rb2401.SHFE",
"side": "buy",
"size": 1,
"price": 4000.0,
"offset": "open",
})
# 撤单adapter.cancel_order({
"symbol": "rb2401.SHFE",
"order_id": order["order_id"],
"front_id": order["front_id"],
"session_id": order["session_id"],
"order_ref": order["order_ref"],
})
# 断开连接adapter.disconnect()

构造函数参数

参数类型默认值描述
md_frontstr""行情前置地址(tcp://host:port)
td_frontstr""交易前置地址(tcp://host:port)
user_idstr""CTP 用户 ID / 投资者 ID
passwordstr""CTP 密码
broker_idstr""经纪公司 ID
auth_codestr"0000000000000000"认证码(生产环境用)
app_idstr"simnow_client_test"App ID
gateway_startup_timeout_secfloat10.0连接超时时间

支持的操作

操作方法状态
连接connect()
断开disconnect()
订阅合约subscribe_symbols(symbols)
获取资金get_balance()
获取持仓get_positions()
下单place_order(payload)
撤单cancel_order(payload)

下单 Payload 格式

{
"symbol": "rb2401.SHFE", # 合约代码.交易所或仅合约代码"side": "buy", # "buy" 或 "sell""size": 1, # 委托数量"price": 4000.0, # 限价(限价单必须)"offset": "open", # "open", "close", "close_today""client_order_id": "...", # 可选,客户端订单引用"exchange_id": "SHFE", # 可选,交易所代码
}

订单响应格式

{
"id": "...",
"order_id": "...",
"external_order_id": "...",
"order_ref": "...",
"front_id": 1,
"session_id": 123456,
"exchange_id": "SHFE",
"details": {"bt_order_ref": "..."},
}

环境配置

CTP 支持通过 CTP_ENVenv 参数配置三种环境:

环境描述交易时段
auto(默认)根据时间自动选择与生产一致
set1类生产环境仅交易时段
set27x24 环境非交易时段

使用 SimNow 测试账户时,留空 md_front/td_front 可自动选择合适的 SimNow 环境。

在线文档

资源链接
英文文档https://bt-api-ctp.readthedocs.io/
中文文档https://bt-api-ctp.readthedocs.io/zh/latest/
GitHub 仓库https://github.com/cloudQuant/bt_api_ctp
问题反馈https://github.com/cloudQuant/bt_api_ctp/issues

系统要求

  • Python 3.9+
  • bt_api_base >= 0.15

架构

bt_api_ctp/
├── src/bt_api_ctp/ # 源代码
│ ├── containers/ctp/ # 数据容器 (CtpTicker, CtpOrder 等)
│ ├── feeds/ # Feed 实现 (live_ctp_feed.py)
│ ├── gateway/ # 网关适配器 (CtpGatewayAdapter)
│ ├── ctp/ # CTP 协议 (structs, client, trader/md API)
│ ├── errors/ # 错误翻译器
│ ├── exchange_data.py # 交易所元数据
│ └── ctp_env_selector.py # SimNow 环境选择器
├── tests/ # 单元测试
└── docs/ # 文档

许可证

MIT 许可证 - 详见 LICENSE

技术支持

About

Exchange adapter package for bt_api

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages