Nuggets Quantification—Python SDK Documentation—5. API Introduction (1)

Python SDK Documentation

5. API introduction


5.1 Basic functions

init - initialization strategy

Initialize the strategy, which is automatically executed when the strategy starts. Policy configuration parameters can be initialized here.

Function prototype:

init(context)

parameter:

parameter name type illustrate
context context context, global variables can be stored here

Example:

def init(context):
    # 订阅bar
    subscribe(symbols='SHSE.600000,SHSE.600004', frequency='30s', count=5)
	# 增加对象属性,如:设置一个股票资金占用百分比
	context.percentage_stock = 0.8

Notice: 回测模式下init函数里不支持交易操作,仿真模式和实盘模式支持

schedule - timed task configuration

Automatically execute the strategy algorithm at a specified time, usually used for stock selection type strategies

Function prototype:

schedule(schedule_func, date_rule, time_rule)

parameter:

parameter name type illustrate
schedule_func function Policy Timing Execution Algorithm
date_rule str n + time unit, optional 'd/w/m' means n days/n weeks/n months
time_rule str The specific time to execute the algorithm (%H:%M:%S format)

return value:

None

Example:

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)




Notice:

1. The hours, minutes, and seconds of time_rule cannot only enter single digits, for example: '9:40:0'or'14:5:0'

1d2. At present , , 1w, are temporarily supported 1m, among which 1w, 1mare only used for backtesting

run - run policy

Function prototype:

run(strategy_id='', filename='', 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='', backtest_match_mode=0)

parameter:

parameter name type illustrate
strategy_id str policy id
filename str policy file name
mode int Strategy mode MODE_LIVE (real-time) = 1 MODE_BACKTEST (backtest) = 2
token str User ID
backtest_start_time str Backtest start time (%Y-%m-%d %H:%M:%S format)
backtest_end_time str Backtest end time (%Y-%m-%d %H:%M:%S format)
backtest_initial_cash double Backtest initial funds, default 1,000,000
backtest_transaction_ratio double Backtest transaction ratio, the default is 1.0, that is, 100% of the order is completed
backtest_commission_ratio double Backtest commission ratio, default 0
backtest_slippage_ratio double Backtest slippage ratio, default 0
backtest_adjust int Backtest recovery method (no recovery by default) ADJUST_NONE (no recovery) = 0 ADJUST_PREV (pre-recovery) = 1 ADJUST_POST (post-recovery) = 2
backtest_check_cache int Whether to use cache for backtest: 1 - use, 0 - not use; default use
serv_addr str Terminal service address, the default local address, you can leave it blank, if you need to specify, you should enter ip+port number, such as "127.0.0.1:7001"
backtest_match_mode int Backtest market price matching mode: 1-real-time matching: matching at the closing price of the current bar/the price of the current tick, 0-delay matching: matching at the opening price of the next bar/the price of the next tick, the default is mode 0

return value:

None

Example:

run(strategy_id='strategy_1', filename='main.py', mode=MODE_BACKTEST, token='token_id',
    backtest_start_time='2016-06-17 13:00:00', backtest_end_time='2017-08-21 15:00:00')

Notice: 

1.  In the run function, mode=1it can also be changed to mode=MODE_LIVE, the two are equivalent, backtest_adjustthe same reason

2.  For backtest_start_time and backtest_end_time, you can only enter single digits for month, day, hour, minute, and second, for example: '2016-6-7 9:55:0'or '2017-8-1 14:6:0', but if the corresponding position is zero, 0 cannot be omitted, for example, it cannot be entered"2017-8-1 14:6: "

3.  filename refers to the name of the running py file. If the strategy file name is Strategy.py, then "Strategy.py" should be filled here

stop - stop policy

stop policy, exit policy process

Function prototype:

stop()

return value:

None

Example:

#若订阅过的代码集合为空,停止策略
if not context.symbols:
   stop()

timer - set the timer

Set the interval seconds of the timer, and call the timer timer_func() every time the set number of seconds passes, until timer_stop() ends the timer. (Applicable to simulation and real disk scenarios, but not valid in backtest mode)

Function prototype:

timer(timer_func, period, start_delay)

parameter:

parameter name type illustrate
timer_func function Event function triggered when the time set by timer arrives
period int Timed event interval in milliseconds, set how many milliseconds to trigger a timer, the range is [1,43200000]
start_delay int Wait for seconds (milliseconds), set how many milliseconds to start the timer, the range is [0,43200000]

return value:  dict

field type illustrate
timer_status int Whether the timer setting is successful, success = 0, failure = non-zero error code (timer_id is invalid).
timer_id int The set timer id

#timer_stop  - stop timer

Stop the timer that has been set

Function prototype:

timer_stop(timer_id)

copy successfully

parameter:

field type illustrate
timer_id int The timer id to stop

return value:

field type illustrate
is_stop bool Whether to stop successfully, True or False

Example:

def init(context):
    # 每隔1分钟执行ontime_1, 即时启动
    context.timerid_1 = timer(timer_func=ontimer_1, period=60000, start_delay=0)
    context.counter_1 = 0

    # 每隔半小时执行ontime_2, 5分钟之后启动
    context.timerid_2 = timer(timer_func=ontimer_2, period=300000, start_delay=0)
    print('启动定时器2:', context.now)
    context.counter_2 = 0


def ontimer_1(context):
    # 定时器执行次数计数
    context.counter_1 += 1
    # 定时器执行逻辑
    print('定时器1:', context.now)


def ontimer_2(context):
    # 定时器执行次数计数
    context.counter_2 += 1
    # 定时器执行逻辑(如查询账户资金)
    cash = context.account().cash

    print('定时器2:', context.now)

    # 按执行次数条件停止定时器
    if context.counter_1 >= 5:
        ret1 = timer_stop(context.timerid_1['timer_id'])
        if ret1:
            print("结束1分钟定时器")

    if context.counter_2 >= 10:
        ret2 = timer_stop(context.timerid_2['timer_id'])

Notice:

  1. Applicable to simulation and real disk scenarios, but not effective in backtest mode
  2. The period is counted from the time when the previous event function started to execute. If the next event function needs to be executed, the previous event function has not finished running, and the next event will be executed after the previous event is executed.

5.2 Data Subscription

subscribe - Quote Subscription

To subscribe to the market, you can specify the symbol, the size of the data sliding window, and whether you need to wait for the data of all codes to arrive before triggering the event.

Function prototype:

subscribe(symbols, frequency='1d', count=1, unsubscribe_previous=False)

parameter:

parameter name type illustrate
symbols str or list Subscribe to the target code , pay attention to uppercase and lowercase, support string format, if there are multiple codes,  , separate them with (English commas), and also support  ['symbol1', 'symbol2'] this list format
frequency str Frequency, supports 'tick', '60s', '300s', '900s', etc., the default is '1d', see stock market data and futures market data for details ,  frequency supported by real-time market
count int Subscription data sliding window size, default 1 , see data sliding window for details
unsubscribe_previous bool 是否取消过去订阅的 symbols, 默认False不取消, 输入True则取消所有原来的订阅。

返回值:

None

示例:

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. subscribe 支持多次调用,并可以重复订阅同一代码。订阅后的数据储存在本地,需要通过 context.data 接口调用或是直接在 on_tick 或 on_bar 中获取。

  2. 在实时模式下,最新返回的数据是不复权的。

unsubscribe - 取消订阅

取消行情订阅, 默认取消所有已订阅行情

函数原型:

unsubscribe(symbols='*', frequency='60s')

参数:

参数名 类型 说明
symbols str or list 订阅标的代码, 支持字串格式,如有多个代码, 中间用 , (英文逗号) 隔开, 也支持 ['symbol1', 'symbol2'] 这种列表格式
frequency str 频率, 支持 'tick', '60s', '300s', '900s' 等, 默认'1d', 详情见股票行情数据期货行情数据实时行情支持的频率

返回值:

None

示例:

unsubscribe(symbols='SHSE.600000,SHSE.600004', frequency='60s')

注意: 如示例所示代码,取消SHSE.600000,SHSE.600004两只代码60s行情的订阅,若SHSE.600000同时还订阅了"300s"频度的行情,该代码不会取消该标的此频度的订阅


5.3数据事件

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

on_tick - 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 数据推送事件

接收固定周期 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_l2transaction(context, transaction)

参数:

参数名 类型 说明
context context 对象 上下文对象
transaction L2Transaction 对象 收到的逐笔成交行情

示例:

def on_l2transaction(context, transaction):
    print(transaction)

输出:

{'symbol': 'SZSE.300003', 'volume': 300, 'created_at': datetime.datetime(2020, 11, 24, 9, 38, 16, 50, tzinfo=tzfile('PRC')), 'exec_type': '4', 'side': '', 'price': 0.0}

on_l2order - 逐笔委托事件

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

on_l2order(context, l2order)

参数:

参数名 类型 说明
context context 对象 上下文对象
l2order L2Order 对象 收到的逐笔委托行情

示例:

def on_l2order(context, l2order):
    print(l2order)

输出:

{'symbol': 'SZSE.300003', 'side': '1', 'price': 29.350000381469727, 'volume': 2400, 'created_at': datetime.datetime(2020, 11, 24, 9, 38, 16, 80, tzinfo=tzfile('PRC')), 'order_type': '2'}


5.4行情数据查询函数

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

2. 若输入代码正确,但查询字段中包括错误字段,返回的列表仍包含对应数量的dict,但每个dict中除有效字段外,其他字段的值均为空字符串/0

3. 回测只返回 symbol、price 和 created_at 字段,实时模式返回全部字段

4. 实时模式无法获取集合竞价的数据,可使用 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 or list 标的代码, 如有多个代码, 中间用 , (英文逗号) 隔开, 也支持 ['symbol1', 'symbol2'] 这种列表格式 ,使用参考symbol
frequency str 频率, 支持 'tick', '1d', '60s' 等, 默认 '1d', 详情见股票行情数据期货行情数据实时行情支持的频率
start_time str or datetime.datetime 开始时间 (%Y-%m-%d %H:%M:%S 格式), 也支持 datetime.datetime 格式
end_time str or datetime.datetime 结束时间 (%Y-%m-%d %H:%M:%S 格式), 也支持 datetime.datetime 格式
fields str 指定返回对象字段, 如有多个字段, 中间用, 隔开, 默认所有, 具体字段见:tick 对象 和 bar 对象
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 tick 的 dataframe 或者 bar 的 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)

输出:

          open      close        low       high                       eob
0     2796.4829  2863.7241  2784.1550  2866.4041 2010-07-28 00:00:00+08:00
1     2866.7720  2877.9761  2851.9961  2888.5991 2010-07-29 00:00:00+08:00
2     2871.4810  2868.8459  2844.6819  2876.1360 2010-07-30 00:00:00+08:00
3     2868.2791  2917.2749  2867.4500  2922.6121 2010-08-02 00:00:00+08:00
4     2925.2539  2865.9709  2865.7610  2929.6140 2010-08-03 00:00:00+08:00

当 df = False 时, 返回

类型 说明
list tick 列表 或者 bar 列表

注意:

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)

输出:

[{'open': 3722.42822265625, 'close': 3737.873291015625, 'low': 3713.655029296875, 'high': 3746.520751953125, 'eob': datetime.datetime(2017, 7, 31, 0, 0, tzinfo=tzfile('PRC'))}]

1. 返回的list/DataFrame是以参数eob/bob的升序来排序的,若要获取多标的的数据,通常需进一步的数据处理来分别提取出每只标的的历史数据

2. start_time 和 end_time 中月,日,时,分,秒均可以只输入个位数,例:'2010-7-8 9:40:0''2017-7-30 12:3:0',但若对应位置为零,则0不可被省略,如不可输入'2017-7-30 12:3: ' 获取数据目前采用前后闭区间的方式,即会获取前后两个时间节点的数据,使用时务必注意这点

3. 若输入无效标的代码,返回空列表/空DataFrame

4. 若输入代码正确,但查询字段包含无效字段,返回的列表、DataFrame 只包含 eob、symbol和输入的其他有效字段

5. skip_suspended 和 fill_missing 参数暂不支持

6. 单次返回数据量最大返回 33000, 超出部分不返回

7. 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)

参数:

参数名 类型 说明
symbol str 标的代码(只允许单个标的的代码字符串),使用时参考symbol
frequency str 频率, 支持 'tick', '1d', '60s' 等, 默认 '1d', 详情见股票行情数据期货行情数据实时行情支持的频率
count int 数量(正整数)
end_time str or datetime.datetime 结束时间 (%Y-%m-%d %H:%M:%S 格式), 也支持 datetime.datetime 格式,默认 None 时,用了实际当前时间,非回测当前时间
fields str 指定返回对象字段, 如有多个字段, 中间用, 隔开, 默认所有, 具体字段见:tick 对象 和 bar 对象
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 tick 的 dataframe 或者 bar 的 dataframe

示例:

history_n_data = history_n(symbol='SHSE.600519', frequency='1d', count=100, end_time='2020-10-20 15:30:00', fields='symbol, open, close, low, high, eob', adjust=ADJUST_PREV, df=True)

输出:

 symbol       open  ...       high                       eob
0   SHSE.600519  1350.2278  ...  1350.3265 2020-05-22 00:00:00+08:00
1   SHSE.600519  1314.6434  ...  1350.8010 2020-05-25 00:00:00+08:00
2   SHSE.600519  1354.0629  ...  1354.1321 2020-05-26 00:00:00+08:00
3   SHSE.600519  1343.3086  ...  1344.2970 2020-05-27 00:00:00+08:00
4   SHSE.600519  1322.5214  ...  1331.3878 2020-05-28 00:00:00+08:00

当 df = False 时, 返回

类型 说明
list tick 列表 或者 bar 列表

示例:

history_n_data = history_n(symbol='SHSE.600519', frequency='1d', count=2, end_time='2020-10-20 15:30:00', fields='symbol, open, close, low, high, eob', adjust=ADJUST_PREV, df=False)

输出:

[{'symbol': 'SHSE.600519', 'open': 1725.0, 'close': 1699.0, 'low': 1691.9000244140625, 'high': 1733.97998046875, 'eob': datetime.datetime(2020, 10, 19, 0, 0, tzinfo=tzfile('PRC'))}, {'symbol': 'SHSE.600519', 'open': 1699.989990234375, 'close': 1734.0, 'low': 1695.0, 'high': 1734.969970703125, 'eob': datetime.datetime(2020, 10, 20, 0, 0, tzinfo=tzfile('PRC'))}]

注意:

1. 返回的list/DataFrame是以参数eob/bob的升序来排序的

2. 若输入无效标的代码,返回空列表/空DataFrame

3. 若输入代码正确,但查询字段包含无效字段,返回的列表、DataFrame 只包含 eob、symbol和输入的其他有效字段

4. end_time 中月,日,时,分,秒均可以只输入个位数,例:'2017-7-30 20:0:20',但若对应位置为零,则0不可被省略,如不可输入'2017-7-30 20: :20'

5. skip_suspended 和 fill_missing 参数暂不支持

6. 单次返回数据量最大返回 33000, 超出部分不返回

7. end_time 输入不存在日期时,会报错 details = "Can't parse string as time: 2020-10-40 15:30:00"


context.data - 查询订阅数据

函数原型:

context.data(symbol, frequency, count)

参数:

参数名 类型 说明
symbol str 标的代码(只允许单个标的的代码字符串),使用时参考symbol
frequency str 频率, 支持 'tick', '1d', '60s' 等, 默认 '1d', 详情见股票行情数据期货行情数据实时行情支持的频率
count int 滑窗大小(正整数),需小于等于 subscribe 函数中 count 值
fields str 指定返回对象字段, 如有多个字段, 中间用, 隔开, 默认所有, 具体字段见:tick 对象 和 bar 对象

返回值:参考tick 对象 和 bar 对象

类型 说明
dataframe tick 的 dataframe 或者 bar 的 dataframe

示例:

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)

输出:

        symbol	         eob	                           bob	          open	 close	 high	     low	     amount    pre_close	position	frequency	volume
0	SHSE.600519	2020-12-21 09:31:00+08:00	2020-12-21 09:30:00+08:00	1840	1845.5	1845.5	1838.199951	210503484	  0	        0	      60s	  114365

注意:

1. 只有在订阅后,此接口才能取到数据,如未订阅数据,则返回值为空。 

2. symbols 参数只支持输入一个标的。 

3. count 参数必须小于或等于订阅函数里面的 count 值

get_history_l2ticks - 查询历史 L2 Tick 行情

仅特定券商版本可用

函数原型:

 get_history_l2ticks(symbols, start_time, end_time, fields=None,skip_suspended=True, fill_missing=None,adjust=ADJUST_NONE, adjust_end_time='', df=False)

参数:

参数名 类型 说明
symbols str 标的代码,使用时参考symbol
start_time str 开始时间 (%Y-%m-%d %H:%M:%S 格式)
end_time str 结束时间 (%Y-%m-%d %H:%M:%S 格式)
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

返回值:参考Tick 对象

当 df = True 时, 返回dataframe

当 df = Falst, 返回list 示例:

history_l2tick=get_history_l2ticks('SHSE.600519', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None,
                        skip_suspended=True, fill_missing=None,
                        adjust=ADJUST_NONE, adjust_end_time='', df=False)
print(history_l2tick[0])

输出:

{'symbol': 'SHSE.600519', 'open': 1771.010009765625, 'high': 1809.9000244140625, 'low': 1771.010009765625, 'price': 1791.0999755859375, 'quotes': [{'bid_p': 1790.8800048828125, 'bid_v': 100, 'ask_p': 1794.760009765625, 'ask_v': 200}, {'bid_p': 1790.80004882812
5, 'bid_v': 123, 'ask_p': 1794.800048828125, 'ask_v': 100}, {'bid_p': 1790.699951171875, 'bid_v': 100, 'ask_p': 1794.8800048828125, 'ask_v': 416}, {'bid_p': 1790.68994140625, 'bid_v': 200, 'ask_p': 1794.8900146484375, 'ask_v': 300}, {'bid_p': 1790.630004882812
5, 'bid_v': 300, 'ask_p': 1794.9000244140625, 'ask_v': 1000}, {'bid_p': 1790.6199951171875, 'bid_v': 500, 'ask_p': 1794.949951171875, 'ask_v': 300}, {'bid_p': 1790.6099853515625, 'bid_v': 300, 'ask_p': 1794.9599609375, 'ask_v': 300}, {'bid_p': 1790.59997558593
75, 'bid_v': 200, 'ask_p': 1794.97998046875, 'ask_v': 100}, {'bid_p': 1790.510009765625, 'bid_v': 314, 'ask_p': 1794.989990234375, 'ask_v': 200}, {'bid_p': 1790.5, 'bid_v': 4200, 'ask_p': 1795.0, 'ask_v': 9700}], 'cum_volume': 5866796, 'cum_amount': 1049949547
1.0, 'last_amount': 1973854.0, 'last_volume': 1100, 'created_at': datetime.datetime(2020, 11, 23, 14, 0, 2, tzinfo=tzfile('PRC')), 'cum_position': 0, 'trade_type': 0}

注意:get_history_l2ticks接口每次只能提取一天的数据, 如果取数时间超过一天,则返回按照结束时间的最近有一个交易日数据, 如果取数时间段超过 1 个自然月(31)天,则获取不到数据

get_history_l2bars - 查询历史 L2 Bar 行情

仅特定券商版本可用

函数原型:

 get_history_l2bars(symbols, frequency, start_time, end_time, fields=None,skip_suspended=True, fill_missing=None,adjust=ADJUST_NONE, adjust_end_time='', df=False)

参数:

参数名 类型 说明
symbols str 标的代码,使用时参考symbol
frequency str 频率, 支持 '1d', '60s'等
start_time str 开始时间 (%Y-%m-%d %H:%M:%S 格式)
end_time str 结束时间 (%Y-%m-%d %H:%M:%S 格式)
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

返回值:参考Bar 对象

当 df = True 时, 返回dataframe

当 df = Falst, 返回list

示例:

history_l2bar=get_history_l2bars('SHSE.600000', '60s', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None,
								skip_suspended=True, fill_missing=None,
								adjust=ADJUST_NONE, adjust_end_time='', df=False)
print(history_l2bar[0])

输出:

{'symbol': 'SHSE.600000', 'frequency': '60s', 'open': 9.90999984741211, 'high': 9.90999984741211, 'low': 9.890000343322754, 'close': 9.899999618530273, 'volume': 1270526, 'amount': 12574276.0, 'bob': datetime.datetime(2020, 11, 23, 14, 0, tzinfo=tzfile('PRC'))
, 'eob': datetime.datetime(2020, 11, 23, 14, 1, tzinfo=tzfile('PRC')), 'position': 0, 'pre_close': 0.0}

Note:  1. get_history_l2bars The interface can extract the data of 1 natural month (31) days at most at a time, such as: 2015.1.1-2015.1.31 Wrong setting: (2015.1.1-2015.2.1) If it exceeds 31 days, no data can be obtained

get_history_l2transactions - Query historical L2 transaction by transaction

Available only for specific brokerage versions

Function prototype:

 get_history_l2transactions(symbols, start_time, end_time, fields=None, df=False)

parameter:

parameter name type illustrate
symbols str The target code, refer to symbol when using
start_time str Start time (%Y-%m-%d %H:%M:%S format)
end_time str End time (%Y-%m-%d %H:%M:%S format)
fields str Specify the field of the returned object. If there are multiple fields, separate them with , and default to all
df bool Whether to return dataframe format, default False

Return value: refer to level2 transaction data

When df = True, returnsdataframe

When df = Falst, returnslist

Example:

history_transactions=get_history_l2transactions('SHSE.600000', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None, df=False)
print(history_transactions[0])

output:

{'symbol': 'SHSE.600000', 'side': 'B', 'price': 9.90999984741211, 'volume': 100, 'created_at': datetime.datetime(2020, 11, 23, 14, 0, 0, 820000, tzinfo=tzfile('PRC')), 'exec_type': ''}

Note:  1. get_history_l2transactions The interface can only fetch data of one day at a time, if the fetching time exceeds one day, the data of the latest trading day according to the start time will be returned

get_history_l2orders - Query historical L2 order by order

Only available for specific brokerage versions  Note:  only available for SZSE targets

Function prototype:

 get_history_l2orders(symbols, start_time, end_time, fields=None, df=False)

parameter:

parameter name type illustrate
symbols str The target code, refer to symbol when using
start_time str Start time (%Y-%m-%d %H:%M:%S format)
end_time str End time (%Y-%m-%d %H:%M:%S format)
fields str Specify the field of the returned object. If there are multiple fields, separate them with , and default to all
df bool Whether to return dataframe format, default False

Return value: Refer to level2 entrusted data one by one

When df = True, returnsdataframe

When df = Falst, returnslist

Example:

history_order=get_history_l2orders('SZSE.000001', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None, df=False)
print(history_order[0])

output:

{'symbol': 'SZSE.000001', 'side': '1', 'price': 19.520000457763672, 'volume': 200, 'created_at': datetime.datetime(2020, 11, 23, 14, 0, 0, 110000, tzinfo=tzfile('PRC')), 'order_type': '2'}

Note:  1. get_history_l2orders The interface can only fetch data of one day at a time, if the fetching time exceeds one day, the data of the latest trading day according to the start time will be returned

get_history_l2orders_queue - Query the historical L2 delegation queue

Available only for specific brokerage versions

Function prototype:

 get_history_l2orders_queue(symbols, start_time, end_time, fields=None, df=False)

parameter:

parameter name type illustrate
symbols str The target code, refer to symbol when using
start_time str Start time (%Y-%m-%d %H:%M:%S format)
end_time str End time (%Y-%m-%d %H:%M:%S format)
fields str Specify the field of the returned object. If there are multiple fields, separate them with , and default to all
df bool Whether to return dataframe format, default False

Return value: Refer to level2 delegate queue data

When df = True, returnsdataframe

When df = Falst, returnslist

Example:

history_order_queue=get_history_l2orders_queue('SHSE.600000', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None, df=False)
print(history_order_queue[0])

output:

{'symbol': 'SHSE.600000', 'price': 9.90999984741211, 'total_orders': 155, 'queue_orders': 50, 'queue_volumes': [52452, 600, 1200, 3200, 10000, 1800, 1000, 300, 10000, 2000, 500, 500, 2000, 1000, 2000, 300, 1200, 1400, 1000, 200, 1000, 100, 500, 1000, 500, 2380
0, 25400, 1000, 2000, 200, 500, 1200, 5000, 2000, 17600, 5000, 1000, 1300, 1000, 1200, 1000, 3000, 1000, 1000, 15000, 400, 15000, 5000, 2000, 10000], 'created_at': datetime.datetime(2020, 11, 23, 14, 0, 1, tzinfo=tzfile('PRC')), 'side': '', 'volume': 0}

Note:  1. get_history_l2orders_queue The interface can only fetch data of one day at a time, if the fetching time exceeds one day, the data of the latest trading day according to the start time will be returned

Guess you like

Origin blog.csdn.net/weixin_42219751/article/details/131783496