PythonSDK量化交易-API

  • 备注:本文档相当于字典,仅完善当前可用的API,并随时补充可能需要使用的API

基本函数

init

  • 初始化策略
    • 备注:回测模式下init函数里不支持交易操作,仿真模式和实盘模式支持
  • 初始化策略, 策略启动时自动执行。可以在这里初始化策略配置参数
  • 函数原型: init(context)
  • 参数:context,类型context,上下文,全局变量可存储在这里
  • 示例
def init(context):
    # 订阅 bar
    subscribe(
          symbols='SHSE.600000,SHSE.600004'
        , frequency='30s'
        , count=5
        , wait_group=True
        , wait_group_timeout='5s'
    )
    # 增加对象属性
    # 如: 设置一个股票资金占用百分比
    context.percentage_stock = 0.8

schedule

  • 定时任务配置
  • 在指定时间自动执行策略算法, 通常用于选股类型策略
  • 函数原型: schedule(schedule_func, date_rule, time_rule)
  • 参数:
参数名 类型 说明
schedule_func function 策略定时执行算法
date_rule str n + 时间单位, 可选’d/w/m’ 表示n天/n周/n月
time_rule str 执行算法的具体时间 (%H:%M:%S 格式)
  • 返回值: None
  • 示例
def init(context):      
    #每天的19:06:20执行策略 algo_1
    schedule(
          schedule_func=algo_1
        , date_rule='1d'
        , time_rule='19:06:20'
    )    
    #每月的第一个交易日的09:40:00执行策略 algo_2
    schedule(
          schedule_func=algo_2
        , date_rule='1m'
        , time_rule='9:40:00'
    )    

def algo_1(context):
    print(context.symbols)

def algo_2(context):
    order_volume(
          symbol='SHSE.600000'
        , volume=200
        , side=OrderSide_Buy
        , order_type=OrderType_Market
        , position_effect=PositionEffect_Open
    )
  • 备注
    • 1.time_rule的时,分,秒均可以只输入个位数,例:'9:40:0'或'14:5:0',但若对应位置为零,则0不可被省略,比如不能输入'14:5: '
    • 2.目前暂时支持1d、1w、1m,其中1w、1m仅用于回测

run

  • 运行策略
  • 函数原型:
    run(
        strategy_id=''
      , filename='main.py'
      , mode=MODE_UNKNOWN
      , token=''
      , backtest_start_time=''
      , backtest_end_time=''
      , backtest_initial_cash=1000000
      , backtest_transaction_ratio=1
      , backtest_commission_ratio=0
      , backtest_slippage_ratio=0
      , backtest_adjust=ADJUST_NONE
      , backtest_check_cache=1
      , serv_addr=''
    )
  • 参数
参数名 类型 说明
strategy_id str 策略id
filename str 策略文件名称
mode int 策略模式
MODE_LIVE(实时)=1
MODE_BACKTEST(回测) =2
token str 用户标识
backtest_start_time str 回测开始时间
(%Y-%m-%d %H:%M:%S格式)
backtest_end_time str 回测结束时间
(%Y-%m-%d %H:%M:%S格式)
backtest_initial_cash double 回测初始资金, 默认1000000
backtest_transaction_ratio double 回测成交比例, 默认1.0, 即下单100%成交
backtest_commission_ratio double 回测佣金比例, 默认0
backtest_slippage_ratio double 回测滑点比例, 默认0
backtest_adjust int 回测复权方式(默认不复权)
ADJUST_NONE(不复权)=0
ADJUST_PREV(前复权)=1
ADJUST_POST(后复权)=2
backtest_check_cache int 回测是否使用缓存:1 - 使用, 0 - 不使用;默认使用
serv_addr str 终端服务地址, 默认本地地址, 可不填,若需指定应输入ip+端口号,如”127.0.0.1:7001”

stop

  • 停止策略
  • 函数原型: stop()
  • 返回值: None
  • 示例
#若订阅过的代码集合为空,停止策略
if not context.symbols:
   stop()

数据订阅

subcribe

  • 订阅行情, 可以指定symbol, 数据滑窗大小, 以及是否需要等待全部代码的数据到齐再触发事件。
  • 函数原型
  subscribe(
        symbols
      , frequency='1d'
      , count=1
      , wait_group=False
      , wait_group_timeout='10s'
      , unsubscribe_previous=False
  )
  • 参数
参数名 类型 说明
symbols str or list 订阅标的代码, 支持字串格式,如有多个代码, 中间用 , (英文逗号) 隔开, 也支持 ['symbol1', 'symbol2'] 这种列表格式
frequency str 频率, 支持 ‘tick’, ‘60s’, ‘300s’, ‘900s’ 等, 默认’1d’, 详情见股票行情数据和期货行情数据, 实时行情支持的频率
count int 订阅数据滑窗大小, 默认1 ,详情见数据滑窗
wait_group bool 是否需要等待全部代码的数据到齐再触发事件, 默认False不到齐。设置为True则等待订阅标的eob相同的bar全部到齐再被调用。该参数只对Bar数据有效。
wait_group_timeout str 超时时间设定, 支持s结尾表示单位秒, 默认10s
unsubscribe_previous bool 是否取消过去订阅的symbols, 默认False不取消, 输入True则取消所有原来的订阅。
  • 备注
    • subscribe支持多次调用,并可以重复订阅同一代码
      • 订阅后的数据储存在本地
      • 需要通过 context.data 接口调用或是直接在 on_tickon_bar 中获取。
    • 在实时模式下,最新返回的数据是不复权的。

unsubscribe

  • 取消行情订阅, 默认取消所有已订阅行情
  • 函数原型: unsubscribe(symbols='*', frequency='60s')
  • 示例:unsubscribe(symbols='SHSE.600000,SHSE.600004', frequency='60s')
    • 取消SHSE.600000,SHSE.600004两只代码60s行情的订阅
    • 若SHSE.600000同时还订阅了"300s"频度的行情,该代码不会取消该标的此频度的订阅

数据事件

  • 数据事件是阻塞回调事件函数,通过 subscribe 函数订阅, 主动推送

on_tick

  • 接收tick分笔数据, 通过subscribe订阅tick行情,行情服务主动推送tick数据
  • 函数原型: on_tick(context, tick)
  • 参数
参数名 类型 说明
context context对象 上下文
tick tick对象 当前被推送的tick
  • 示例
def on_tick(context, tick):
    print(tick)
  • 输出
{'symbol': 'SHSE.600519', 'created_at': datetime.datetime(2020, 9, 2, 14, 7, 23, 620000, tzinfo=tzfile('PRC')), 'price': 1798.8800048828125, 'open': 1825.0, 'high': 1828.0, 'low': 1770.0, 'cum_volume': 2651191, 'cum_amount': 4760586491.0, 'cum_position': 0, 'last_amount': 179888.0, 'last_volume': 100, 'trade_type': 0, 'receive_local_time': 1602751345.262745}

on_bar

  • 接收固定周期bar数据, 通过subscribe订阅bar行情,行情服务主动推送bar数据
  • 函数原型: on_bar(context, bars)
  • 参数
参数名 类型 说明
context context对象 上下文对象
bars list(bar) 当前被推送的bar列表
  • 示例
def on_bar(context, bars):
    for bar in bars:
        print(bar)
  • `输出
{'symbol': 'SHSE.600519', 'eob': datetime.datetime(2020, 9, 30, 15, 15, 1, tzinfo=tzfile('PRC')), 'bob': datetime.datetime(2020, 9, 30, 0, 0, tzinfo=tzfile('PRC')), 'open': 1660.0, 'close': 1668.5, 'high': 1691.9000244140625, 'low': 1660.0, 'volume': 2708781, 'amount': 4536012540.0, 'pre_close': 1652.2999267578125, 'position': 0, 'frequency': '1d', 'receive_local_time': 1602751647.923199}
  • 备注
    • 1.若在subscribe函数中订阅了多个标的的bar,但wait_group参数值为False,则多次触发On_bar,每次返回只包含单个标的list长度为1的bars;
      • 若参数值为True,则只会触发一次On_bar,返回包含多个标的的bars。
    • 2.bar在本周期结束时间后才会推送,标的在这个周期内无交易则不推送bar。

on_l2transaction

  • 接收逐笔成交数据(L2行情时有效)
  • 仅特定券商版本可用

on_l2order

  • 接收逐笔委托数据(深交所L2行情时有效)
  • 仅特定券商版本可用

on_l2order_queue

  • 接收委托队列, L2行情时有效,最优价最大50笔委托量
  • 仅特定券商版本可用

数据查询函数

current

  • 查询当前行情快照,返回tick数据
  • 回测时,返回回测当前时间点的tick数据
  • 函数原型: current(symbols, fields='')
参数名 类型 说明
symbols str or list 查询代码,如有多个代码, 中间用 , (英文逗号) 隔开,也支持 ['symbol1', 'symbol2'] 这种列表格式 ,使用参考symbol
fields str 查询字段, 默认所有字段。具体字段见:Tick
  • 返回值: list[dict]
  • 示例:current_data = current(symbols='SZSE.000001')
  • 输出:

    [{'symbol': 'SZSE.000001', 'open': 16.200000762939453, 'high': 16.920000076293945, 'low': 16.149999618530273, 'price': 16.559999465942383, 'quotes': [{'bid_p': 16.549999237060547, 'bid_v': 209200, 'ask_p': 16.559999465942383, 'ask_v': 296455}, {'bid_p': 16.540000915527344, 'bid_v': 188900, 'ask_p': 16.56999969482422, 'ask_v': 374405}, {'bid_p': 16.530000686645508, 'bid_v': 44900, 'ask_p': 16.579999923706055, 'ask_v': 187220}, {'bid_p': 16.520000457763672, 'bid_v': 20800, 'ask_p': 16.59000015258789, 'ask_v': 102622}, {'bid_p': 16.510000228881836, 'bid_v': 37700, 'ask_p': 16.600000381469727, 'ask_v': 337002}], 'cum_volume': 160006232, 'cum_amount': 2654379585.66, 'last_amount': 14153832.0, 'last_volume': 854700, 'trade_type': 7, 'created_at': datetime.datetime(2020, 10, 15, 15, 0, 3, tzinfo=tzfile('PRC'))}]
    
  • 注意:

      1. 若输入包含无效标的代码,则返回的列表只包含有效标的代码对应的dict
      1. 若输入代码正确,但查询字段中包括错误字段,返回的列表仍包含对应数量的dict,但每个dict中除有效字段外,其他字段的值均为空字符串/0
      1. 回测只返回symbol、price和created_at字段,实时模式返回全部字段
      1. 实时模式无法获取集合竞价的数据,可使用history_n

history

  • 查询历史行情
  • 函数原型:

    history(
      symbol
      , frequency
      , start_time
      , end_time
      , fields=None
      , skip_suspended=True
      , fill_missing=None
      , adjust=ADJUST_NONE
      , adjust_end_time=''
      , df=True
    )
  • 参数

参数名 类型 说明
symbol str 标的代码,若要获取多个标的的历史数据,可以采用中间用 , (英文逗号) 隔开的方法,但不能是list类型的输入参数,使用时参考symbol
frequency str 频率, 支持 ‘tick’, ‘1d’, ‘15s’, ‘30s’ 等, 默认 ‘1d’, 详情见股票行情数据和期货行情数据
start_time str or datetime.datetime 开始时间 (%Y-%m-%d %H:%M:%S 格式), 也支持datetime.datetime格式, 其中日线包含start_time数据, 非日线不包含start_time数据
end_time str or datetime.datetime 结束时间 (%Y-%m-%d %H:%M:%S 格式), 也支持datetime.datetime格式
fields str 指定返回对象字段, 如有多个字段, 中间用, 隔开, 默认所有, 具体字段见:股票字段 ,期货字段
skip_suspended bool 是否跳过停牌, 默认跳过
fill_missing str or None 填充方式, None - 不填充, 'NaN' - 用空值填充, 'Last' - 用上一个值填充, 默认None
adjust int ADJUST_NONE or 0: 不复权, ADJUST_PREV or 1: 前复权, ADJUST_POST or 2: 后复权 默认不复权 , 目前只支持股票
adjust_end_time str 复权基点时间, 默认当前时间
df bool 是否返回 dataframe格式, 默认 False, 返回list[dict]
  • 返回值:参考Tick对象或者Bar对象

    • 当df = True时, 返回 dataframe
      • 示例
        • history_data = history(symbol='SHSE.000300', frequency='1d', start_time='2010-07-28', end_time='2017-07-30', fields='open, close, low, high, eob', adjust=ADJUST_PREV, df= True)
    • 当df = False时, 返回 list
      • 示例
        • history_data = history(symbol='SHSE.000300', frequency='1d', start_time='2017-07-30', end_time='2017-07-31', fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=False)
  • 备注

      1. 返回的list/DataFrame是以参数eob/bob的升序来排序的,若要获取多标的的数据,通常需进一步的数据处理来分别提取出每只标的的历史数据
      1. start_time和end_time中月,日,时,分,秒均可以只输入个位数,例:'2010-7-8 9:40:0'或'2017-7-30 12:3:0',但若对应位置为零,则0不可被省略,如不可输入'2017-7-30 12:3: '获取数据目前采用前后闭区间的方式,即会获取前后两个时间节点的数据,使用时务必注意这点
      1. 若输入无效标的代码,返回空列表/空DataFrame
      1. 若输入代码正确,但查询字段包含无效字段,返回的列表、DataFrame只包含eob、symbol和输入的其他有效字段
      1. skip_suspended 和 fill_missing 参数暂不支持
      1. 单次返回数据量最大返回33000, 超出部分不返回
      1. start_time和end_time输入不存在日期时,会报错details = “failed to parse datetime”

history_n

  • 查询历史行情最新n条
  • 函数原型:
    history_n(
      symbol
      , frequency
      , count
      , end_time=None
      , fields=None
      , skip_suspended=True
      , fill_missing=None
      , adjust=ADJUST_NONE
      , adjust_end_time=''
      , df=False
    )
  • 返回值: 参考Tick对象或者Bar对象

context.data

  • 查询订阅数据
  • 函数原型: context.data(symbol, frequency, count)
  • 返回值: 参考Tick对象或者Bar对象
  • 示例
def init(context):
    subscribe(symbols='SHSE.600519', frequency='60s', count=2)

def on_bar(context,bars):
    data = context.data(
          symbol='SHSE.600519'
        , frequency='60s'
        , count=1
    )
  • 注意:
      1. 只有在订阅后,此接口才能取到数据,如未订阅数据,则返回值为空。
      1. symbols参数只支持输入一个标的。
      1. count参数必须小于或等于订阅函数里面的count值

get_history_l2ticks

  • 仅特定券商版本可用

get_history_l2bars

  • 仅特定券商版本可用

get_history_l2transactions

  • 仅特定券商版本可用

get_history_l2orders

  • 仅特定券商版本可用

get_history_l2orders_queue

  • 仅特定券商版本可用

get_fundamentals

  • 查询基本面数据
  • 函数原型:
get_fundamentals(
      table
    , symbols
    , start_date
    , end_date
    , fields=None
    , filter=None
    , order_by=None
    , limit=1000
    , df=False
)
参数名 类型 说明
table str 表名,只支持单表查询. 具体表名及fields字段名及filter可过滤的字段参考 财务数据文档
symbols str or list 标的代码, 多个代码可用 ,(英文逗号)分割, 也支持 ['symbol1', 'symbol2'] 这种列表格式,使用时参考symbol
start_date str 开始时间, (%Y-%m-%d 格式)
end_date str 结束时间, (%Y-%m-%d 格式)
fields str 查询字段 (必填)
filter str 查询过滤,使用方法参考例3、例4
order_by str or None 排序方式, 默认 None. TCLOSE 表示按 TCLOSE 升序排序. -TCLOSE 表示按 TCLOSE 降序排序. TCLOSE, -NEGOTIABLEMV 表示按 TCLOSE 升序, NEGOTIABLEMV 降序综合排序
limit int 数量. 默认是1000, 为保护服务器, 单次查询最多返回 40000 条记录
df bool 是否返回dataframe格式, 默认False, 返回list[dict]
  • 返回值:
key value类型 说明
symbol str 标的代码
pub_date datetime.datetime 公司发布财报的日期.
end_date datetime.datetime 财报统计的季度的最后一天.
fields dict 相应指定查询 fields 字段的值. 字典key值请参考 财务数据文档

get_fundamentals_n

  • 查询基本面数据最新n条
  • 函数原型:
    get_fundamentals_n(
        table
      , symbols
      , end_date
      , fields=None
      , filter=None
      , order_by=None
      , count=1
      , df=False
    )

get_instruments

  • 查询最新交易标的信息, 有基本数据及最新日频数据
  • 函数原型:
    get_instruments(
        symbols=None
      , exchanges=None
      , sec_types=None
      , names=None
      , skip_suspended=True
      , skip_st=True
      , fields=None
      , df=False
    )
  • 参数:
参数名 类型 说明
symbols str or list or None 标的代码 多个代码可用 ,(英文逗号)分割, 也支持 ['symbol1', 'symbol2'] 这种列表格式,默认None表示所有,使用时参考symbol
exchanges str or list or None 见交易所代码,。多个交易所代码可用 ,(英文逗号)分割, 也支持 ['exchange1', 'exchange2'] 这种列表格式,默认None表示所有
sec_types list 指定类别, 默认所有, 其他类型见sec_type 类型
names str or None 查询代码, 默认None 表示所有
skip_suspended bool 是否跳过停牌, 默认True 跳过停牌
skip_st bool 是否跳过ST, 默认True 跳过ST
fields str or None 查询字段 默认None 表示所有,参考返回值。
df bool 是否返回dataframe格式, 默认False, 返回list[dict]
  • 返回值:
key 类型 说明
symbol str 标的代码
sec_type int 1: 股票, 2: 基金, 3: 指数, 4: 期货, 5: 期权, 8:可转债,10: 虚拟合约
exchange str 见交易所代码
sec_id str 代码
sec_name str 名称
sec_abbr str 拼音简称
price_tick float 最小变动单位
listed_date datetime.datetime 上市日期
delisted_date datetime.datetime 退市日期
trade_date datetime.datetime 交易日期
sec_level int 1-正常,2-ST 股票,3-*ST 股票,4-股份转让,5-处于退市整理期的证券,6-上市开放基金LOF,7-交易型开放式指数基金(ETF),8-非交易型开放式基金(暂不交易,仅揭示基金净值及开放申购赎回业务),9-仅提供净值揭示服务的开放式基金;,10-仅在协议交易平台挂牌交易的证券,11-仅在固定收益平台挂牌交易的证券,12-风险警示产品,13-退市整理产品,99-其它
is_suspended int 是否停牌. 1: 是, 0: 否
multiplier float 合约乘数
margin_ratio float 保证金比率
settle_price float 结算价
position int 持仓量
pre_close float 昨收价
upper_limit float 涨停价 (可转债没有涨停价)
lower_limit float 跌停价 (可转债没有跌停价)
adj_factor float 复权因子.基金跟股票才有
conversion_price float 可转债转股价
conversion_start_date datetime.datetime 可转债开始转股时间
underlying_symbol str 可转债正股标的

get_history_instruments

  • 查询交易标的历史信息数据
  • 返回指定symbols的标的日频历史数据

get_instrumentinfos

  • 查询交易标的基本信息(与时间无关)
  • 函数原型
    get_instrumentinfos(
        symbols=None
      , exchanges=None
      , sec_types=None
      , names=None
      , fields=None
      , df=False
    )

get_constituents

  • 查询指数最新成份股
  • 函数原型: get_constituents(index, fields=None, df=False)
  • 参数
参数名 类型 说明
index str 指数代码
fields str or None 若要有返回权重字段, 可以设置为 ‘symbol, weight’
df bool 是否返回dataframe 格式, 默认False, 返回list[dict]
  • 返回值:
    • 参数 fields 为 None时, 返回 list[str] , 成分股列表
    • 参数 fields 指定为 'symbol, weight', 返回 list[dict]
    • 当df = True时,返回 dataframe
    • 当df = False时,返回 list[dict()]

get_history_constituents

  • 查询指数成份股的历史数据
  • 函数原型: get_history_constituents(index, start_date=None, end_date=None)
  • 返回值:
    • list[constituent]
    • constituent 为 dict,包含key值 constituents 和 trade_date

get_continuous_contracts

  • 获取主力合约
  • 函数原型:(获取主力合约和次主力合约)
    • get_continuous_contracts(csymbol, start_date=None, end_date=None)

get_industry

  • 查询行业股票列表
  • 函数原型: get_industry(code)

get_dividend

  • 查询分红送配
  • 函数原型: get_dividend(symbol, start_date, end_date=None)

get_trading_dates

  • 查询交易日列表
  • 函数原型: get_trading_dates(exchange, start_date, end_date)

get_previous_trading_date

  • 返回指定日期的上一个交易日
  • 函数原型: get_previous_trading_date(exchange, date)

get_next_trading_date

  • 返回指定日期的下一个交易日
  • 函数原型: get_next_trading_date(exchange, date)

ipo_get_quota

  • 查询新股申购额度
  • 仅在实盘中可以使用

ipo_get_instruments

  • 查询当日新股清单
  • 仅在实盘中可以使用

ipo_get_match_number

  • 查询配号
  • 仅在实盘中可以使用

ipo_get_lot_info

  • 中签查询
  • 仅在实盘中可以使用

交易函数

order_volume

  • 按指定量委托
    order_volume(
        symbol
      , volume
      , side
      , order_type
      , position_effect
      , price=0
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account=''
    )

order_value

  • 按指定价值委托
    order_value(
        symbol
      , value
      , side
      , order_type
      , position_effect
      , price=0
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account=''
    )

order_percent

  • 按总资产指定比例委托
    order_percent(
        symbol
      , percent
      , side,order_type
      , position_effect
      , price=0
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account=''
    )

order_target_volume

  • 调仓到目标持仓量
    order_target_volume(
        symbol
      , volume
      , position_side
      , order_type
      , price=0
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account=''
    )

order_target_value

  • 调仓到目标持仓额
    order_target_value(
        symbol
      , value
      , position_side
      , order_type
      , price=0
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account=''
    )

order_target_percent

  • 调仓到目标持仓比例(总资产的比例)
    order_target_percent(
      symbol
      , percent
      , position_side
      , order_type
      , price=0
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account=''
    )

order_batch

  • 批量委托接口
    order_batch(
        orders
      , combine=False
      , account=''
    )

order_cancel

  • 撤销委托
    order_cancel(wait_cancel_orders)

order_cancel_all

  • 撤销所有委托
    order_cancel_all()

order_close_all

  • 平当前所有可平持仓
    • 注意:不支持市价委托类型的委托,会被柜台拒绝
      order_close_all()

get_unfinished_orders

  • 查询日内全部未结委托
    get_unfinished_orders()

get_orders

  • 查询日内全部委托
    get_orders()

get_execution_reports

  • 查询日内全部执行回报
    get_execution_reports()

ipo_buy

  • 新股申购
    ipo_buy(symbol, volume, price, account_id='')

fund_etf_buy

  • ETF申购
    fund_etf_buy(symbol, volume, price, account_id='')

fund_etf_redemption

  • ETF赎回
    fund_etf_redemption(symbol, volume, price, account_id='')

fund_subscribing

  • 基金认购
    fund_subscribing(symbol, volume, account_id='')

fund_buy

  • 基金申购
    fund_buy(symbol, volume, account_id='')

fund_redemption

  • 基金赎回
    fund_redemption(symbol, volume, account_id='')

bond_reverse_repurchase_agreement

  • 国债逆回购
    bond_reverse_repurchase_agreement(
        symbol
      , volume
      , price
      , order_type=OrderType_Limit
      , order_duration=OrderQualifier_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account_id=''
    )

bond_convertible_call

  • 可转债转股
    bond_convertible_call(symbol, volume, price=0.0, account_id='')

bond_convertible_put

  • 可转债回售
    bond_convertible_put(symbol, volume, price=0.0, account_id='')

bond_convertible_put_cancel

  • 可转债回售撤销
    bond_convertible_put_cancel(symbol, volume, account_id='')

交易查询函数

context.account().positions()

  • 查询当前账户全部持仓
    context.account(account_id=None).positions()

context.account().position(symbol, side)

  • 查询当前账户指定持仓
    # 指定持仓
    Account_position = context.account().position(
                                   symbol='SHSE.600519'
                                  ,side = PositionSide_Long
                           )

context.account().cash

  • 查询当前账户资金
    context.account(account_id=None).cash

两融交易函数

  • python两融SDK包含在gm3.0.126版本及以上版本,不需要引入新库
  • 融资融券暂时仅支持实盘委托不支持仿真交易

credit_buying_on_margin

  • 融资买入
    credit_buying_on_margin(
        position_src
      , symbol
      , volume
      , price
      , order_type=OrderType_Limit
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account_id=''
    )

credit_short_selling

  • 融券卖出
    credit_short_selling(
        position_src
      , symbol
      , volume
      , price
      , order_type=OrderType_Limit
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account_id=''
    )

credit_repay_cash_directly

  • 直接还款
    credit_repay_cash_directly(amount, account_id='')

credit_repay_share_directly

  • 直接还券
    credit_repay_share_directly(symbol, volume, account_id='')

credit_get_collateral_instruments

  • 查询担保证券
    credit_get_collateral_instruments(account_id='', df=False)

credit_get_borrowable_instruments

  • 查询可融标的证券,可做融券标的股票列表
    credit_get_borrowable_instruments(
        position_src
      , account_id=''
      , df=False
    )

credit_get_borrowable_instruments_positions

  • 查询券商融券账户头寸,可用融券的数量
    credit_get_borrowable_instruments_positions(position_src, account_id='', df=False)

credit_get_contracts

  • 查询融资融券合约
    credit_get_contracts(position_src, account_id='', df=False)

credit_get_cash

  • 查询融资融券资金
    credit_get_cash(account_id='')

credit_repay_share_by_buying_share

  • 买券还券
    credit_repay_share_by_buying_share(
        symbol
      , volume
      , price
      , order_type=OrderType_Limit
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account_id=''
    )

credit_repay_cash_by_selling_share

  • 卖券还款
    credit_repay_cash_by_selling_share(
        symbol
      , volume
      , price
      , order_type=OrderType_Limit
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account_id=''
    )

credit_buying_on_collateral

  • 担保品买入
    credit_buying_on_collateral(
        symbol
      , volume
      , price
      , order_type=OrderType_Limit
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account_id=''
    )

credit_selling_on_collateral

  • 担保品卖出
    credit_selling_on_collateral(
        symbol
      , volume
      , price
      , order_type=OrderType_Limit
      , order_duration=OrderDuration_Unknown
      , order_qualifier=OrderQualifier_Unknown
      , account_id=''
    )

credit_collateral_in

  • 担保品转入
    credit_collateral_in(symbol, volume, account_id='')

credit_collateral_out

  • 担保品转出
    credit_collateral_out(symbol, volume, account_id='')

算法交易函数

  • python算法SDK包含在gm3.0.126版本及以上版本,不需要引入新库
  • 仅支持实时模式,部分券商版本可用

algo_order

  • 算法交易委托

algo_order(symbol, volume, side, order_type,position_effect, price, algo_name, algo_param)

algo_order_cancel

  • 撤销算法委托
algo_order_cancel(wait_cancel_orders)

get_algo_orders

  • 查询算法委托
algo_order_cancel(account)

algo_order_pause

  • 暂停或重启或者撤销算法委托
algo_order_pause(alorders)

get_algo_child_orders

  • 查询算法委托的所有子单
get_algo_child_orders(cl_ord_id, account='')

on_algo_order_status

  • 算法单状态事件
on_algo_order_status(context, algo_order)

交易事件

on_order_status

  • 委托状态更新事件
on_order_status(context, order)

on_execution_report

  • 委托执行回报事件
on_execution_report(context, execrpt)

on_account_status

  • 交易账户状态更新事件
def on_account_status(context, account):
    print(account)

动态参数

  • 动态参数仅在仿真交易和实盘交易下生效, 可在终端设置和修改

add_parameter

  • 增加动态参数
add_parameter(key, value, min=0, max=0, name='', intro='', group='', readonly=False)

set_parameter

  • 修改已经添加过的动态参数
set_parameter(key, value, min=0, max=0, name='', intro='', group='', readonly=False)

on_parameter

  • 动态参数修改事件推送
on_parameter(context, parameter)

context.parameters

  • 获取所有动态参数
print(context.parameters)

其他函数

set_token

  • 设置token
set_token(token)

log

  • 日志函数
log(level, msg, source)

get_strerror

  • 查询错误码的错误描述信息
get_strerror(error_code)

get_version

  • 查询api版本
get_version()

set_mfp

  • 设置留痕信息
set_mfp(mfp)

其他事件

on_backtest_finished

  • 回测结束事件
on_backtest_finished(context, indicator)

on_error

  • 错误事件: 当发生异常情况,比如断网时、终端服务崩溃是会触发
on_error(context, code, info)

on_market_data_connected

  • 实时行情网络连接成功事件
on_market_data_connected(context)

on_trade_data_connected

  • 交易通道网络连接成功事件
on_trade_data_connected(context)

on_market_data_disconnected

  • 实时行情网络连接断开事件
on_market_data_disconnected(context)

on_trade_data_disconnected

  • 交易通道网络连接断开事件
on_trade_data_disconnected(context)

枚举常量

OrderStatus

  • 委托状态

OrderSide

  • 委托方向

OrderType

  • 委托类型

OrderDuration

  • 委托时间属性

OrderQualifier

  • 委托成交属性

OrderBusiness

  • 委托业务类型

ExecType

  • 执行回报类型

PositionEffect

  • 开平仓类型

PositionSide

  • 持仓方向

OrderRejectReason

  • 订单拒绝原因

CancelOrderRejectReason

  • 取消订单拒绝原因

OrderStyle

  • 委托风格

CashPositionChangeReason

  • 仓位变更原因

SecType

  • 标的类别
    • SEC_TYPE_STOCK = 1 # 股票
    • SEC_TYPE_FUND = 2 # 基金
    • SEC_TYPE_INDEX = 3 # 指数
    • SEC_TYPE_FUTURE = 4 # 期货
    • SEC_TYPE_OPTION = 5 # 期权
    • SEC_TYPE_CREDIT = 6 # 信用交易
    • SEC_TYPE_BOND = 7 # 债券
    • SEC_TYPE_BOND_CONVERTIBLE = 8 # 可转债
    • SEC_TYPE_CONFUTURE = 10 # 虚拟合约

AccountStatus

  • 交易账户状态

PositionSrc

  • 头寸来源(仅适用融券融券)

AlgoOrderStatus

  • 算法单状态,暂停/恢复算法单时有效

错误码

错误码 描述 解决方法
0 成功
1000 错误或无效的token 检查下token是否有误
1001 无法连接到终端服务 检查是否开启了掘金终端
1010 无法获取掘金服务器地址列表 检查是否开启了掘金终端
1013 交易服务调用错误 检查终端是否正常或重启掘金终端
1014 历史行情服务调用错误 在微信群或者QQ群通知技术支持
1015 策略服务调用错误 检查终端是否正常或重启掘金终端
1016 动态参数调用错误 检查动态参数设置
1017 基本面数据服务调用错误 在微信群或者QQ群通知技术支持
1018 回测服务调用错误 重启掘金终端、重新运行策略
1019 交易网关服务调用错误 检查终端是否正常或重启掘金终端
1020 无效的ACCOUNT_ID 检查账户id是否填写正确
1021 非法日期格式 对照帮助文档修改日期格式, 检查run()回测日期是否正确
1100 交易消息服务连接失败 检查终端是否正常或重启掘金终端
1101 交易消息服务断开 一般不用处理,等待自动重连
1200 实时行情服务连接失败 一般不用处理,等待自动重连
1201 实时行情服务连接断开 一般不用处理,等待自动重连
1202 实时行情订阅失败 订阅代码标的数量超过账户权限,联系商务咨询权限
1300 初始化回测失败 检查终端是否启动或策略是否连接到终端
1301 回测时间区间错误 检查回测时间是否超出范围