QMT Python API 参考手册
文档版本:3.2.9 | Python版本:3.6.8 | 更新整理:2026.07.18
1. 策略基本结构
1.1 编码声明(必须)
#coding:gbk
1.2 初始化函数 init()
def init(ContextInfo):
# 策略启动时调用一次,用于初始化
pass
- 参数:
ContextInfo - 策略运行环境对象
- 返回: 无
1.3 行情事件函数 handlebar()
def handlebar(ContextInfo):
# 每根K线调用一次;实时行情下每个tick调用一次
pass
- 参数:
ContextInfo - 策略运行环境对象
- 返回: 无
1.4 后初始化函数 after_init()
def after_init(ContextInfo):
# init执行完毕后调用,通常用于下载历史数据
pass
- 参数:
ContextInfo - 策略运行环境对象
- 返回: 无
- 用途: 在init函数执行完成后调用,适用于需要等待init完成后才能执行的操作,如下载历史数据
1.5 停止函数 stop()
def stop(ContextInfo):
print('strategy is stop!')
2. ContextInfo 对象属性与方法
2.1 设定与配置
| 函数 |
用法 |
说明 |
set_universe() |
ContextInfo.set_universe(stocklist) |
设定股票池,参数为list |
set_account() |
ContextInfo.set_account(account) |
设定交易账号,参数为string |
set_slippage() |
ContextInfo.set_slippage(slippageType, slippage) |
设定回测滑点(仅回测) |
set_commission() |
ContextInfo.set_commission(commissionType, commissionList) |
设定回测手续费率(仅回测) |
set_slippage 参数:
slippageType: 0=tick跳数, 1=固定值(价格), 2=价格比例
slippage: 滑点值
set_commission 参数:
commissionType: 0=按比例, 1=按每手(股)
commissionList: [open_tax, close_tax, open_commission, close_commission, close_tday_commission, min_commission]
2.2 只读属性
| 属性 |
说明 |
返回值 |
ContextInfo.period |
当前周期 |
string: '1d','1m','3m','5m','15m','30m','1h','1w','1mon','1q','1hy','1y' |
ContextInfo.barpos |
当前K线索引号(从0开始) |
number |
ContextInfo.time_tick_size |
当前图K线数目 |
number |
ContextInfo.stockcode |
当前图代码 |
string |
ContextInfo.market |
当前主图市场 |
string |
ContextInfo.dividend_type |
复权方式 |
string: 'none','front','back','front_ratio','back_ratio' |
ContextInfo.do_back_test |
是否回测模式 |
bool |
ContextInfo.benchmark |
回测基准(仅回测) |
string |
2.3 读写属性
| 属性 |
说明 |
默认值 |
ContextInfo.start |
回测开始时间 |
策略编辑器设定 |
ContextInfo.end |
回测结束时间 |
策略编辑器设定 |
ContextInfo.capital |
回测初始资金 |
1000000 |
ContextInfo.data_info_level |
日志级别(0信息/1警告/2错误/3致命) |
0 |
2.4 判定函数
| 函数 |
用法 |
返回 |
is_last_bar() |
ContextInfo.is_last_bar() |
bool |
is_new_bar() |
ContextInfo.is_new_bar() |
bool |
is_suspended_stock() |
ContextInfo.is_suspended_stock('600004.SH') |
bool |
is_sector_stock() |
is_sector_stock(sectorname, market, stockcode) |
bool |
is_typed_stock() |
is_typed_stock(stocktypenum, market, stockcode) |
1/0 |
2.5 其他方法
| 函数 |
用法 |
说明 |
get_universe() |
ContextInfo.get_universe() |
获取股票池 → list |
get_stock_name() |
ContextInfo.get_stock_name('000001.SZ') |
根据代码获取名称 → string |
get_open_date() |
get_open_date('000001.SZ') |
获取上市时间 → number |
get_industry_name_of_stock() |
get_industry_name_of_stock('SW','600000.SH') |
获取行业名 → string |
get_result_records() |
get_result_records(recordtype, index, ContextInfo) |
获取回测记录 → list |
run_time() |
ContextInfo.run_time(funcName, period, startTime, market) |
设置定时器 |
get_net_value() |
ContextInfo.get_net_value(index) |
获取回测净值(仅回测) |
run_time 参数:
funcName: 回调函数名
period: 如 '5nSecond', '5nDay', '500nMilliSecond'
startTime: 如 "2019-10-14 13:20:00"
market: 如 "SH"
3. 数据获取函数
3.1 行情数据
get_history_data() - 获取历史行情(需先set_universe)
ContextInfo.get_history_data(len, period, field, dividend_type=0, skip_paused=True)
| 参数 |
类型 |
说明 |
| len |
number |
数据长度 |
| period |
string |
周期: 'tick','1d','1m','3m','5m','15m','30m','1h','1w','1mon','1q','1hy','1y' |
| field |
string |
字段: 'open','high','low','close','quoter' |
| dividend_type |
number |
0=不复权,1=前复权,2=后复权,3=等比前,4=等比后 |
| skip_paused |
bool |
是否停牌填充 |
返回: dict, key为stockcode.market, value为价格list
get_market_data() - 获取行情数据
ContextInfo.get_market_data(fields, stock_code=[], start_time='', end_time='',
skip_paused=True, period='1d', dividend_type='none', count=-1)
| 参数 |
类型 |
说明 |
| fields |
list |
['open','high','low','close','volume','amount','settle','quoter'] |
| stock_code |
list |
合约代码列表,如['600000.SH'] |
| start_time |
string |
'20171209' 或 '20171209010101' |
| end_time |
string |
同上 |
| skip_paused |
bool |
True=填充停牌价, False=nan |
| period |
string |
周期类型 |
| dividend_type |
string |
'none','front','back','front_ratio','back_ratio' |
| count |
int |
-1=按时间取, >=0=取最近N条 |
返回: 根据参数组合返回 number / Series / DataFrame / Panel
get_full_tick() - 获取最新分笔数据
ContextInfo.get_full_tick(stock_code=[])
返回: dict,key为股票代码,value包含: lastPrice, amount, volume, pvolume, openInt, stockStatus, open, high, low, lastClose, askPrice[], bidPrice[], askVol[], bidVol[]
get_local_data() - 获取本地行情数据
ContextInfo.get_local_data(stock_code, start_time='', end_time='', period='1d', divid_type='none', count=-1)
get_market_data_ex() - 获取行情数据(替代get_market_data函数)
ContextInfo.get_market_data_ex(fields, stock_list, period='1d', start_time='', end_time='',
count=-1, dividend_type='none', fill_data=False, subscribe=False)
| 参数 |
类型 |
说明 |
| fields |
list |
字段列表,如['open','high','low','close','volume'],空列表则返回所有字段 |
| stock_list |
list |
合约代码列表,如['000001.SZ','600519.SH'] |
| period |
string |
周期: 'tick','1d','1m','3m','5m','15m','30m','1h','2h','1w','1mon','1q','1hy','1y' |
| start_time |
string |
开始时间,格式'YYYYMMDD'或'YYYYMMDDHHMMSS' |
| end_time |
string |
结束时间,格式同上 |
| count |
int |
-1=按时间范围取, >=0=取最近N条 |
| dividend_type |
string |
'none','front','back','front_ratio','back_ratio','follow' |
| fill_data |
bool |
是否填充停牌数据 |
| subscribe |
bool |
True=订阅模式(受500只股票限制,可获取动态行情), False=本地模式(不受限制,需提前下载数据) |
返回: dict,key为股票代码,value为DataFrame
- 提示1:
subscribe=True时有订阅股票数量限制,stock_list参数的数量不能超过500
- 提示2:
subscribe=False模式下,接口会从本地行情文件里获取数据,不会获取动态行情,且不受订阅数限制,但需要提前下载数据
- 提示3: 建议每天盘后增量补充对应周期的行情
subscribe_quote() - 订阅行情
ContextInfo.subscribe_quote(stock_code, period='1d', dividend_type='none',
result_type='dict', callback=None)
| 参数 |
类型 |
说明 |
| stock_code |
string |
股票代码,如'000001.SZ' |
| period |
string |
周期: '1d','1m','3m','5m','15m','30m','1h','2h','1w','1mon'等,也支持L2数据类型如'l2transaction','l2order','l2quote' |
| dividend_type |
string |
复权方式 |
| result_type |
string |
回调函数的行情数据格式,'dict'或'pandas' |
| callback |
function |
自定义回调函数,接收行情数据,只能有一个位置参数 |
返回: 订阅编号(int),用于取消订阅
unsubscribe_quote() - 取消订阅行情
ContextInfo.unsubscribe_quote(sub_num)
| 参数 |
类型 |
说明 |
| sub_num |
int |
订阅编号,由subscribe_quote返回 |
download_history_data() - 下载历史行情数据
download_history_data(stock_code, period, start_date='', end_date='')
| 参数 |
类型 |
说明 |
| stock_code |
string |
股票代码,如'000001.SZ' |
| period |
string |
周期: '1d','1m','5m','tick'等 |
| start_date |
string |
开始下载日期,格式'YYYYMMDD',为空时全量下载 |
| end_date |
string |
结束下载日期,格式'YYYYMMDD',为空时增量下载 |
- 提示1: 获取历史N分钟数据前,需要先下载历史数据
- 提示2: 1m以上,5m以下的数据,是通过1m数据合成的
- 提示3: 5m以上,1d以下的数据,是通过5m数据合成的
- 提示4: 1d以上的数据,是通过1d的数据合成的
3.2 时间相关
| 函数 |
用法 |
返回 |
get_bar_timetag() |
ContextInfo.get_bar_timetag(index) |
毫秒时间戳 |
get_tick_timetag() |
ContextInfo.get_tick_timetag() |
毫秒时间戳 |
timetag_to_datetime() |
timetag_to_datetime(timetag, '%Y%m%d%H:%M:%S') |
string |
get_date_location() |
ContextInfo.get_date_location('20170711') |
K线索引号 |
get_trading_dates() |
ContextInfo.get_trading_dates(stockcode, start_date, end_date, count, period) |
list |
3.3 板块与成份股
| 函数 |
用法 |
返回 |
get_sector() |
ContextInfo.get_sector('000300.SH', realtime) |
list(指数成份股) |
get_industry() |
ContextInfo.get_industry('CSRC采矿业') |
list(行业成份股) |
get_stock_list_in_sector() |
ContextInfo.get_stock_list_in_sector('沪深300', realtime) |
list(板块成份股) |
get_weight_in_index() |
ContextInfo.get_weight_in_index('000300.SH','000002.SZ') |
number(%) |
3.4 合约与股票信息
| 函数 |
用法 |
返回 |
get_last_volume() |
ContextInfo.get_last_volume('000002.SZ') |
流通股本 |
get_total_share() |
ContextInfo.get_total_share('600000.SH') |
总股数 |
get_contract_multiplier() |
ContextInfo.get_contract_multiplier('IF1707.IF') |
合约乘数 |
get_main_contract() |
ContextInfo.get_main_contract('IF00.IF') |
主力合约代码 |
get_contract_expire_date() |
ContextInfo.get_contract_expire_date('IF00.IF') |
到期日 |
get_instrumentdetail() |
ContextInfo.get_instrumentdetail('600000.SH') |
dict(合约详情) |
get_divid_factors() |
ContextInfo.get_divid_factors('600000.SH') |
dict(除权除息) |
get_risk_free_rate() |
ContextInfo.get_risk_free_rate(index) |
无风险利率 |
get_svol() |
ContextInfo.get_svol('000001.SZ') |
内盘成交量 |
get_bvol() |
ContextInfo.get_bvol('000001.SZ') |
外盘成交量 |
get_turnover_rate() |
ContextInfo.get_turnover_rate(stock_list, startTime, endTime) |
DataFrame(换手率) |
3.5 财务数据
用法1(推荐)
ContextInfo.get_financial_data(fieldList, stockList, startDate, endDate, report_type='announce_time')
| 参数 |
说明 |
| fieldList |
如 ['CAPITALSTRUCTURE.total_capital', 'ASHAREINCOME.net_profit_incl_min_int_inc'] |
| stockList |
如 ['600000.SH','000001.SZ'] |
| startDate |
如 '20171209' |
| endDate |
如 '20171212' |
| report_type |
'announce_time'(按公告期) / 'report_time'(按报告期) |
返回: 根据代码数×时间数返回 Series/DataFrame/Panel
用法2
ContextInfo.get_financial_data(tabname, colname, market, code, report_type='report_time', barpos)
返回: number
财务数据表名:
ASHAREBALANCESHEET - 资产负债表
ASHAREINCOME - 利润表
ASHARECASHFLOW - 现金流量表
CAPITALSTRUCTURE - 股本表
PERSHAREINDEX - 主要指标
3.6 其他数据
| 函数 |
用法 |
说明 |
get_longhubang() |
ContextInfo.get_longhubang(stock_list, startTime, endTime) |
龙虎榜数据 |
get_top10_share_holder() |
get_top10_share_holder(stock_list, data_name, start_time, end_time) |
十大股东 |
get_option_detail_data() |
ContextInfo.get_option_detail_data('10001506.SHO') |
期权详情 |
get_etf_info() |
get_etf_info('510050.SH') |
ETF申赎清单 |
get_etf_iopv() |
get_etf_iopv('510050.SH') |
ETF基金份额参考净值 |
load_stk_list() |
ContextInfo.load_stk_list(filePath, fileName) |
一篮子证券编码 |
load_stk_vol_list() |
ContextInfo.load_stk_vol_list(filePath, fileName) |
一篮子证券编码及数量 |
4. 交易函数
4.1 综合交易下单 passorder()
passorder(opType, orderType, accountid, orderCode, prType, modelprice, volume
[, strategyName, quickTrade, userOrderId], ContextInfo)
opType 操作类型
| 值 |
说明 |
值 |
说明 |
| 0 |
期货开多 |
23 |
股票买入 |
| 1 |
平昨多 |
24 |
股票卖出 |
| 2 |
平今多 |
27 |
融资买入 |
| 3 |
开空 |
28 |
融券卖出 |
| 4 |
平昨空 |
29 |
买券还券 |
| 5 |
平今空 |
30 |
直接还券 |
| 6 |
平多(优先平今) |
31 |
卖券还款 |
| 7 |
平多(优先平昨) |
32 |
直接还款 |
| 8 |
平空(优先平今) |
33 |
信用账号股票买入 |
| 9 |
平空(优先平昨) |
34 |
信用账号股票卖出 |
| 50 |
期权买入开仓 |
51 |
期权卖出平仓 |
| 52 |
期权卖出开仓 |
53 |
期权买入平仓 |
| 54 |
备兑开仓 |
55 |
备兑平仓 |
orderType 下单方式
| 值 |
说明 |
| 1101 |
单股、单账号、股/手方式 |
| 1102 |
单股、单账号、金额(元)方式(仅股票) |
| 1113 |
单股、单账号、总资产比例[0~1] |
| 1123 |
单股、单账号、可用比例[0~1] |
| 1201 |
单股、账号组、股/手方式 |
| 1202 |
单股、账号组、金额方式 |
prType 选价类型
| 值 |
说明 |
值 |
说明 |
| -1 |
无效(用面板设定) |
5 |
最新价 |
| 0~4 |
卖5~卖1价 |
6~10 |
买1~买5价 |
| 11 |
指定价(模型价) |
12 |
涨跌停价 |
| 13 |
挂单价 |
14 |
对手价 |
| 42 |
最优五档即成剩撤(上交所) |
44 |
对手方最优(深交所) |
| 49 |
科创板盘后定价 |
|
|
quickTrade 参数
| 值 |
说明 |
| 0 |
否(默认,下一根K线第一个tick下单) |
| 1 |
是(最后一根K线即可下单) |
| 2 |
强制(历史bar也能触发,谨慎使用) |
示例
# 股票最新价买入100股
passorder(23, 1101, 'test', '000001.SZ', 5, 0, 100, ContextInfo)
# 股票指定价7元买入100股
passorder(23, 1101, 'test', '000001.SZ', 11, 7, 100, ContextInfo)
# 期货最新价开多10手
passorder(0, 1101, 'test', 'IF1805.IF', 5, -1, 10, ContextInfo)
4.2 智能算法交易 smart_algo_passorder()
smart_algo_passorder(opType, orderType, accountid, orderCode, prType, modelprice,
volume, strategyName, quickTrade, userid, smartAlgoType,
limitOverRate, minAmountPerOrder, [targetPriceLevel],
[startTime, endTime], ContextInfo)
smartAlgoType 可选值: 'VWAP', 'TWAP', 'VP'(跟量), 'PINLINE'(跟价), 'DMA'(快捷), 'FLOAT'(盘口), 'SWITCH'(换仓), 'ICEBERG'(冰山), 'MOC'(尾盘)
4.3 算法交易下单 algo_passorder()
algo_passorder(opType, orderType, accountid, orderCode, prType, modelprice, volume
[, strategyName, quickTrade, userOrderId, userOrderParam], ContextInfo)
4.4 股票下单函数
| 函数 |
用法 |
说明 |
order_lots() |
order_lots(stockcode, lots[, style, price], ContextInfo[, accId]) |
指定手数(正买负卖) |
order_value() |
order_value(stockcode, value[, style, price], ContextInfo[, accId]) |
指定金额(正买负卖) |
order_percent() |
order_percent(stockcode, percent[, style, price], ContextInfo[, accId]) |
指定比例(正买负卖) |
order_target_value() |
order_target_value(stockcode, tar_value[, style, price], ContextInfo[, accId]) |
目标价值调仓 |
order_target_percent() |
order_target_percent(stockcode, tar_percent[, style, price], ContextInfo[, accId]) |
目标比例调仓 |
order_shares() |
order_shares(stockcode, shares[, style, price], ContextInfo[, accId]) |
指定股数(正买负卖) |
style 可选值: 'LATEST'(最新), 'FIX'(指定), 'HANG'(挂单), 'COMPETE'(对手), 'MARKET'(市价), 'SALE5'~'SALE1', 'BUY1'~'BUY5'
4.5 期货下单函数
| 函数 |
说明 |
buy_open(stockcode, amount[, style, price], ContextInfo[, accId]) |
买入开仓 |
sell_open(stockcode, amount[, style, price], ContextInfo[, accId]) |
卖出开仓 |
buy_close_tdayfirst(...) |
买入平仓(平今优先) |
buy_close_ydayfirst(...) |
买入平仓(平昨优先) |
sell_close_tdayfirst(...) |
卖出平仓(平今优先) |
sell_close_ydayfirst(...) |
卖出平仓(平昨优先) |
4.6 交易查询函数
get_trade_detail_data() - 获取交易明细
get_trade_detail_data(accountID, strAccountType, strDatatype[, strategyName])
| 参数 |
可选值 |
| strAccountType |
'FUTURE','STOCK','CREDIT','HUGANGTONG','SHENGANGTONG','STOCK_OPTION' |
| strDatatype |
'POSITION'(持仓),'ORDER'(委托),'DEAL'(成交),'ACCOUNT'(账号),'TASK'(任务) |
返回: list[PythonObj]
其他查询函数
| 函数 |
用法 |
返回 |
get_value_by_order_id() |
get_value_by_order_id(orderId, accountID, strAccountType, strDatatype) |
PythonObj |
get_last_order_id() |
get_last_order_id(accountID, strAccountType, strDatatype[, strategyName]) |
string(委托号) |
can_cancel_order() |
can_cancel_order(orderId, accountID, strAccountType) |
bool |
get_debt_contract() |
get_debt_contract(accId) |
list(负债合约) |
get_assure_contract() |
get_assure_contract(accId) |
list(担保标的) |
get_assure_contract 返回对象属性:
m_strInstrumentID - 证券代码
m_strExchangeID - 交易所代码
m_eFinStatus - 融资状态(48=可融资买入)
m_eSecStatus - 融券状态
|
get_enable_short_contract() |
get_enable_short_contract(accId) |
list(可融券明细) |
get_ipo_data() |
get_ipo_data([type]) |
dict(新股新债信息) |
get_new_purchase_limit() |
get_new_purchase_limit(accid) |
dict(申购额度) |
4.7 撤单与任务管理
| 函数 |
用法 |
返回 |
cancel() |
cancel(orderId, accountId, accountType, ContextInfo) |
bool |
cancel_task() |
cancel_task(taskId, accountId, accountType, ContextInfo) |
bool |
pause_task() |
pause_task(taskId, accountId, accountType, ContextInfo) |
bool |
resume_task() |
resume_task(taskId, accountId, accountType, ContextInfo) |
bool |
do_order() |
do_order(ContextInfo) |
无(触发前一根bar信号) |
4.8 止损/止盈
# 限价止损/止盈
stoploss_limitprice(mode, accountid, stockcode, stopprice, limitprice, volume, orderderction)
# 市价止损/止盈
stoploss_marketprice(mode, accountid, stockcode, stopprice, volume, orderderction)
mode: 0=止损, 1=止盈
orderderction: 期货填"short"(平空)/"long"(平多),股票填""
5. 成交回报回调函数(仅实盘生效)
def account_callback(ContextInfo, accountInfo):
"""资金账号状态变化"""
pass
def order_callback(ContextInfo, orderInfo):
"""委托状态变化"""
pass
def deal_callback(ContextInfo, dealInfo):
"""成交状态变化"""
pass
def position_callback(ContextInfo, positonInfo):
"""持仓状态变化"""
pass
def orderError_callback(ContextInfo, orderArgs, errMsg):
"""下单异常"""
pass
6. 引用函数
| 函数 |
用法 |
说明 |
ext_data() |
ext_data(extdataname, stockcode, deviation, ContextInfo) |
获取扩展数据 |
ext_data_rank() |
ext_data_rank(extdataname, stockcode, deviation, ContextInfo) |
扩展数据排名 |
ext_data_range() |
ext_data_range(extdataname, stockcode, begintime, endtime, ContextInfo) |
时间区间扩展数据 |
ext_data_rank_range() |
ext_data_rank_range(extdataname, stockcode, begintime, endtime, ContextInfo) |
时间区间排名 |
get_ext_all_data() |
ContextInfo.get_ext_all_data(extdataname, start_time, end_time) |
全部扩展数据(建议init中调用) |
get_factor_value() |
get_factor_value(factorname, stockcode, deviation, ContextInfo) |
获取因子数据 |
get_factor_rank() |
get_factor_rank(factorname, stockcode, deviation, ContextInfo) |
因子排名 |
call_vba() |
call_vba(factorname, stockcode, [period, dividend_type, barpos,] ContextInfo) |
引用VBA模型结果 |
call_formula() |
call_formula(formulaName, code, period, divideType, basket, argsDict, ...) |
调用VBA组合模型 |
7. 绘图函数
| 函数 |
用法 |
说明 |
paint() |
ContextInfo.paint(name, value, index, line_style, color='white', limit='') |
画线(0=曲线,42=柱状) |
draw_text() |
ContextInfo.draw_text(condition, position, text) |
显示文字 |
draw_number() |
ContextInfo.draw_number(cond, height, number, precision) |
显示数字 |
draw_vertline() |
ContextInfo.draw_vertline(cond, number1, number2, color='', limit='') |
绘垂直线 |
draw_icon() |
ContextInfo.draw_icon(cond, height, type) |
绘图标(0=矩形,1=椭圆) |
颜色可选: blue, brown, cyan, green, magenta, red, white, yellow
8. 交易对象属性速查
8.1 Account 资金账号对象(常用)
| 属性 |
说明 |
m_dAvailable |
可用金额 |
m_dBalance |
总资产 |
m_dInstrumentValue |
总市值 |
m_dCommission |
手续费 |
m_dPositionProfit |
持仓盈亏 |
m_dFetchBalance |
可取金额 |
m_strStatus |
状态 |
m_dStockValue |
股票总市值 |
m_dAssureAsset |
净资产 |
m_dTotalDebit |
总负债 |
8.2 Order 委托对象(常用)
| 属性 |
说明 |
m_strInstrumentID |
证券代码 |
m_strInstrumentName |
证券名称 |
m_strOrderSysID |
委托号 |
m_nOrderStatus |
委托状态 |
m_dLimitPrice |
委托价格 |
m_nVolumeTotalOriginal |
委托量 |
m_nVolumeTraded |
已成交量 |
m_nVolumeTotal |
委托剩余量 |
m_nTaskId |
任务号 |
m_strRemark |
投资备注 |
8.3 Deal 成交对象(常用)
| 属性 |
说明 |
m_strInstrumentID |
证券代码 |
m_strTradeID |
成交编号 |
m_strOrderSysID |
委托号 |
m_dPrice |
成交均价 |
m_nVolume |
成交量 |
m_dTradeAmount |
成交额 |
m_strTradeDate |
成交日期 |
m_strTradeTime |
成交时间 |
8.4 Position 持仓对象(常用)
| 属性 |
说明 |
m_strInstrumentID |
证券代码 |
m_strInstrumentName |
证券名称 |
m_nVolume |
持仓量 |
m_dOpenPrice |
持仓成本 |
m_dLastPrice |
最新价 |
m_dFloatProfit |
浮动盈亏 |
m_dMarketValue |
市值 |
m_nCanUseVolume |
可用持仓 |
m_nFrozenVolume |
冻结数量 |
m_dProfitRate |
盈亏比例 |
9. 枚举值速查
9.1 委托状态 (EEntrustStatus)
| 值 |
说明 |
值 |
说明 |
| 48 |
未报 |
53 |
部撤 |
| 49 |
待报 |
54 |
已撤 |
| 50 |
已报 |
55 |
部成 |
| 51 |
已报待撤 |
56 |
已成 |
| 52 |
部成待撤 |
57 |
废单 |
9.2 买卖方向 (EEntrustBS)
9.3 市场代码
| 市场 |
代码 |
市场 |
代码 |
| 上证所 |
SH |
上期所 |
SF |
| 深交所 |
SZ |
中金所 |
IF |
| 大商所 |
DF |
沪港通 |
HGT |
| 郑商所 |
ZF |
深港通 |
SGT |
10. 完整策略示例
10.1 获取Lv1行情数据示例
#coding:gbk
import time
def init(ContextInfo):
ContextInfo.stock = ContextInfo.stockcode + '.' + ContextInfo.market
price = ContextInfo.get_market_data_ex(['open','high','low','close'], [ContextInfo.stock],
start_time='', end_time='', period='1d', subscribe=False)
print(price[ContextInfo.stock].head())
def handlebar(ContextInfo):
bar_timetag = ContextInfo.get_bar_timetag(ContextInfo.barpos)
bar_date = timetag_to_datetime(bar_timetag, '%Y%m%d%H%M%S')
print('获取截至到%s为止前5根k线的开高低收等字段:'%(bar_date))
price = ContextInfo.get_market_data_ex(
[], [ContextInfo.stock],
end_time=bar_date,
period=ContextInfo.period,
subscribe=True,
count=5,
)
print(price[ContextInfo.stock].to_dict('dict'))
10.2 获取N分钟周期K线数据示例
#coding:gbk
import pandas as pd
import numpy as np
def init(ContextInfo):
start_date = '20231001'
end_date = ''
period = "3m"
need_download = 1
code_list = ["000001.SZ", "600519.SH"]
if need_download:
my_download(code_list, period, start_date, end_date)
data = ContextInfo.get_market_data_ex([], code_list, period=period,
start_time=start_date, end_time=end_date,
dividend_type="back_ratio")
print(data)
print(ContextInfo.get_instrumentdetail(code_list[0]))
def handlebar(ContextInfo):
return
def my_download(stock_list, period, start_date='', end_date=''):
if "d" in period:
period = "1d"
elif "m" in period:
if int(period[0]) < 5:
period = "1m"
else:
period = "5m"
elif "tick" == period:
pass
else:
raise KeyboardInterrupt("周期传入错误")
n = 1
num = len(stock_list)
for i in stock_list:
print(f"当前正在下载{n}/{num}")
download_history_data(i, period, start_date, end_date)
n += 1
print("下载任务结束")
10.3 获取2小时行情数据示例
#coding:gbk
def after_init(ContextInfo):
stock = '000012.SZ'
download_history_data(stock, '5m', '20260101', '')
def handlebar(ContextInfo):
if not ContextInfo.is_last_bar():
return
stock = '000012.SZ'
data = ContextInfo.get_market_data_ex(
['open', 'high', 'low', 'close', 'volume'], [stock],
period='2h', start_time='20260101', end_time='',
count=-1, dividend_type='follow', fill_data=False, subscribe=True
)
print(data)
10.4 获取融资融券账户可融资买入标的示例
#coding:gbk
def init(ContextInfo):
r = get_assure_contract('123456789')
if len(r) == 0:
print('未取到担保明细')
else:
finable = [o.m_strInstrumentID+'.'+o.m_strExchangeID for o in r if o.m_eFinStatus==48]
print('可融资买入标的:', finable)
11. 注意事项
- 回测模式:交易函数使用虚拟账号,
can_cancel_order/cancel/do_order无实际意义
- 实盘模式:需将策略加入"模型交易"才能发送真实委托
- 模拟模式:交易函数无效
- 数据补充:回测前需在"数据管理"中下载对应品种和周期的历史数据
- quickTrade=1:可实现当日下单(不等下一根K线)
- get_history_data vs get_market_data:前者只能获取股票池数据,后者可获取任意股票