### Python Example: ETF Fund Subscription and Redemption Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Illustrates how to use `etf_purchase_redemption` for both subscribing to and redeeming ETF funds. Examples include a simple subscription and a redemption with a specified limit price. ```python def initialize(context): g.security = '510050.SS' set_universe(g.security) def handle_data(context, data): #ETF申购 etf_purchase_redemption('510050.SS',900000) #ETF赎回 etf_purchase_redemption('510050.SS',-900000,limit_price = 2.9995) ``` -------------------------------- ### Python Example: Get Sector/Industry Ranking Data Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This Python example demonstrates how to initialize the trading context, set the universe, and then use `get_sort_msg` to retrieve the top 100 ranking information for the 'XBHS.DY' sector based on `preclose_px`. It also shows how to access the first item in the returned sorted data. ```python def initialize(context): g.security = '000001.SZ' set_universe(g.security) def handle_data(context, data): #获取XBHS.DY板块的涨幅排名信息 sort_data = get_sort_msg(sort_type_grp='XBHS.DY', sort_field_name='preclose_px', sort_type=1, data_count=100) log.info(sort_data) #获取sort_data排序第一条代码的数据 sort_data_first = sort_data[0] log.info(sort_data_first) ``` -------------------------------- ### Python Example: Get ETF Information Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This Python example demonstrates how to retrieve ETF information using `get_etf_info`. It shows calls for both a single ETF code ('510020.SS') and a list of ETF codes (['510020.SS', '510050.SS']), logging the results. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): #ETF信息 etf_info = get_etf_info('510020.SS') log.info(etf_info) etfs_info = get_etf_info(['510020.SS','510050.SS']) log.info(etfs_info) ``` -------------------------------- ### Python Example: Placing Orders with Tick Data Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Demonstrates how to use `order_tick` within the `tick_data` module to place orders based on real-time tick prices. Examples include placing orders at specific bid/ask levels and at a designated limit price. ```python def initialize(context): g.security = "600570.SS" set_universe(g.security) def tick_data(context,data): security = g.security current_price = eval(data[security]['tick']['bid_grp'][0])[1][0] if current_price > 56 and current_price < 57: # 以买一档下单 order_tick(g.security, -100, "1") # 以卖二档下单 order_tick(g.security, 100, "-2") # 以指定价格下单 order_tick(g.security, 100, limit_price=56.5) def handle_data(context, data): pass ``` -------------------------------- ### Python Example: Get ETF Component Stock Information Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This Python example demonstrates how to retrieve ETF component stock information using `get_etf_stock_info`. It shows calls for both a single component stock ('600000.SS') and a list of component stocks (['600000.SS', '600036.SS']) for a given ETF ('510050.SS'), logging the results. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): #ETF成分券信息 stock_info = get_etf_stock_info('510050.SS','600000.SS') log.info(stock_info) stocks_info = get_etf_stock_info('510050.SS',['600000.SS','600036.SS']) log.info(stocks_info) ``` -------------------------------- ### Python Example: Processing Tick Data and Placing Orders Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Illustrates a Python strategy that initializes a security, processes real-time tick data to extract price information (e.g., bid prices, high price), and conditionally places an order using `order_tick` based on a price threshold. Includes commented-out examples for accessing other data points like transaction volume and order type. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def tick_data(context,data): # 获取买一价 security = g.security current_price = eval(data[security]['tick']['bid_grp'][0])[1][0] log.info(current_price) # 获取买二价 # current_price = eval(data[security]['tick']['bid_grp'][0])[2][0] # 获取买三量 # current_amount = eval(data[security]['tick']['bid_grp'][0])[3][1] # 获取tick最高价 # current_high_price = data[security]['tick']['high_px'][0] # 最近一笔逐笔成交的成交量 # transaction = data[security]["transcation"] # business_amount = list(transaction["business_amount"]) # if len(business_amount) > 0: # log.info("最近一笔逐笔成交的成交量:%s" % business_amount[0]) # 最近一笔逐笔委托的委托类别 # order = data[security]["order"] # trans_kind = list(order["trans_kind"]) # if len(trans_kind) > 0: # log.info("最近一笔逐笔委托的委托类别:%s" % trans_kind[0]) if current_price > 38.19: # 按买一档价格下单 order_tick(security, 100, 1) def handle_data(context, data): pass ``` -------------------------------- ### Example: Get Tick-by-Tick Transaction Data Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This example demonstrates how to use `get_tick_direction` to retrieve tick-by-tick transaction data for a specific stock or a list of stocks. It also shows how to access specific fields like `business_amount` from the returned OrderedDict. ```python def initialize(context): g.security = '000001.SZ' set_universe(g.security) def handle_data(context, data): # Get tick-by-tick transaction data for 000001.SZ direction_data = get_tick_direction(g.security) log.info(direction_data) # Get tick-by-tick transaction data for specified stock list direction_data = get_tick_direction(['000002.SZ','000032.SZ']) log.info(direction_data) # Get transaction volume business_amount = direction_data['000002.SZ']['business_amount'] log.info('分时成交的成交量为:%s' % business_amount) ``` -------------------------------- ### Python Example: Retrieve and Log Convertible Bond Info Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Demonstrates how to initialize a security and use get_cb_info within a handle_data function to retrieve and log convertible bond information. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): df = get_cb_info() log.info(df) ``` -------------------------------- ### Example: Get Individual Transaction Data Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This example demonstrates how to use `get_individual_transaction` to retrieve individual transaction data for the current stock pool or specified stock lists. It also shows how to access specific fields like `business_amount` from the returned Pandas.panel object. ```python def initialize(context): g.security = "000001.SZ" set_universe(g.security) def handle_data(context, data): # Get individual transaction data for the current stock pool transaction = get_individual_transaction() log.info(transaction) # Get individual transaction data for specified stock list transaction = get_individual_transaction(["000002.SZ", "000032.SZ"]) log.info(transaction) # Get transaction volume if transaction is not None: business_amount = transaction["000002.SZ"]["business_amount"] log.info("逐笔数据的成交量为:%s" % business_amount) ``` -------------------------------- ### Python Example: Filter Stocks by ST Status Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Demonstrates how to use get_stock_status to check if stocks are ST, halted, or delisted, and provides an example of filtering out ST stocks from a list. ```python ``` -------------------------------- ### Python Example: Using get_price for Stock Data Retrieval Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This example demonstrates various ways to use the `get_price` function to retrieve historical stock data. It covers fetching daily, minute, and weekly data for single stocks, retrieving specific fields, and querying data for multiple stocks (e.g., from an index like CSI 300) or an industry sector. It also shows how to access specific data points from the returned DataFrame or Panel. ```Python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): # 获得600570.SS(恒生电子)的2015年01月的天数据,只获取open字段 price_open = get_price('600570.SS', start_date='20150101', end_date='20150131', frequency='1d')['open'] log.info(price_open) # 获取指定结束日期前count天到结束日期的所有开盘数据 # price_open = get_price('600570.SS', end_date='20150131', frequency='daily', count=10)['open'] # log.info(price_open) # 获取股票指定结束时间前count分钟到指定结束时间的所有数据 # stock_info = get_price('6005 ``` -------------------------------- ### Python Example: Cancelling an Order Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Illustrates how to place an order and then immediately cancel it using `cancel_order`, followed by checking its status to confirm cancellation. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): _id = order(g.security, 100) cancel_order(_id) log.info(get_order(_id)) ``` -------------------------------- ### Python Example: Retrieve Single and Multiple Stock Basic Info Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Shows how to use get_stock_info to obtain basic information for a single stock and a list of stocks, including specific fields like stock_name and listed_date. ```python def initialize(context): g.security = ['600570.SS', '600571.SS'] set_universe(g.security) def handle_data(context, data): #获取单支股票的基础信息 stock_info = get_stock_info(g.security[0]) log.info(stock_info) #获取多支股票的基础信息 stock_infos = get_stock_info(g.security, ['stock_name','listed_date','de_listed_date']) log.info(stock_infos) ``` -------------------------------- ### Python Example: ETF Basket Order Placement Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Demonstrates how to use `etf_basket_order` for placing ETF component basket orders. It shows two scenarios: one with default price style and position, and another with cash/position replacement flags and a specific price style. ```python def initialize(context): g.security = get_Ashares() set_universe(g.security) def handle_data(context, data): #ETF成分券篮子下单 etf_basket_order('510050.SS' ,1, price_style='S3',position=True) stock_info = {'600000.SS':{'cash_replace_flag':1,'position_replace_flag':1,'limit_price':12}} etf_basket_order('510050.SS' ,1, price_style='S2',position=False, info=stock_info) ``` -------------------------------- ### Python Example: Retrieve Single and Multiple Stock Names Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Illustrates how to use get_stock_name to fetch the name of a single stock and a list of stocks within an initialize and handle_data context. ```python def initialize(context): g.security = ['600570.SS', '600571.SS'] set_universe(g.security) def handle_data(context, data): #获取600570.SS股票名称 stock_name = get_stock_name(g.security[0]) log.info(stock_name) #获取股票池所有的股票名称 stock_names = get_stock_name(g.security) log.info(stock_names) ``` -------------------------------- ### Python Example: Convertible Bond to Stock Conversion Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Shows how to use `debt_to_stock_order` to convert a specified amount of a convertible bond into stock and then check the order status. This operation is performed once at the beginning of trading. ```python def initialize(context): g.security = "600570.SS" set_universe(g.security) def before_trading_start(context, data): g.count = 0 def handle_data(context, data): if g.count == 0: # 对持仓内的国贸转债进行转股操作 debt_to_stock_order("110033.SS", -1000) g.count += 1 # 查看委托状态 log.info(get_orders()) g.count += 1 ``` -------------------------------- ### Python Example: Retrieving Stock Positions Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Shows various ways to use `get_positions` to retrieve stock holdings, including for specific securities (single or list) or all current positions when no argument is provided. ```python def initialize(context): g.security = ['600570.SS','600000.SS'] set_universe(g.security) def handle_data(context, data): log.info(get_positions('600570.SS')) log.info(get_positions(g.security)) log.info(get_positions()) ``` -------------------------------- ### Python Example: Cancelling Orders from get_all_orders Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Demonstrates how to iterate through all daily orders and cancel those in 'reported' or 'partially filled' status using `cancel_order_ex`. It also shows how to check the order status after cancellation. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) g.count = 0 def handle_data(context, data): if g.count == 0: log.info("当日全部订单为:%s" % get_all_orders()) # 遍历账户当日全部订单,对已报、部成状态订单进行撤单操作 for _order in get_all_orders(): if _order['status'] in ['2', '7']: cancel_order_ex(_order) if g.count == 1: # 查看撤单是否成功 log.info("当日全部订单为:%s" % get_all_orders()) g.count += 1 ``` -------------------------------- ### API: get_stock_info - Get Stock Basic Information Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Documents the get_stock_info interface for retrieving basic information about stocks, convertible bonds, and ETFs. Users can specify fields to retrieve, with stock_name being the default. ```APIDOC get_stock_info(stocks, field=None) Usage Scenarios: This function is available in research, backtesting, and trading modules. Interface Description: This interface can obtain basic information about stocks, convertible bonds, and ETFs. Notes: If 'field' is not provided as a parameter, only the 'stock_name' field is returned by default. Parameters: stocks: Stock code (list[str]/str) field: Specifies the supported output fields in the data result set (list[str]/str). Output fields include: stock_name -- Company name corresponding to stock code (str:str) listed_date -- Stock listing date (str:str) de_listed_date -- Stock delisting date; if not delisted, returns 2900-01-01 (str:str) Returns: Nested dict type, containing content specified in 'field'. If field=None, the returned stock basic information only includes the corresponding company name (dict[str:dict[str:str,...],...]). Example Return: {'600570.SS': {'stock_name': '恒生电子', 'listed_date': '2003-12-16', 'de_listed_date': '2900-01-01'}} ``` -------------------------------- ### Get Trade Days Within a Specified Range Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function retrieves trading days within a specified date range or a count of days prior to an end date. It is available in research, backtesting, and live trading modules. Users must choose between providing a start date or a count, but not both. ```APIDOC get_trade_days(start_date=None, end_date=None, count=None) start_date: Start date, mutually exclusive with 'count'. E.g., '2016-02-13' or '20160213'. Earliest date is 1990 (str). end_date: End date, e.g., '2016-02-13' or '20160213'. If greater than current year, returns data up to current year (str). count: Number of days, mutually exclusive with 'start_date'. Must be > 0. Gets 'count' trade days before 'end_date', including 'end_date'. Recommended not to exceed 3000 (int). Returns: A numpy.ndarray containing trade days within the specified range. Notes: 1. In backtesting, 'end_date' defaults to context.blotter.current_dt. 2. In research, 'end_date' defaults to the current day. 3. In live trading, 'end_date' defaults to the current day. ``` ```python def initialize(context): # 获取指定范围内交易日 trade_days = get_trade_days('2016-01-01', '2016-02-01') log.info(trade_days) g.security = ['600570.SS', '000001.SZ'] set_universe(g.security) def handle_data(context, data): # 获取回测日期往前10天的所有交易日,包含历史回测日期 trading_days = get_trade_days(count=10) log.info(trading_days) ``` -------------------------------- ### API: get_stock_status - Get Stock Status Information Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Documents the get_stock_status interface for querying the ST, halt, or delisting status of stocks on a specified date. It supports different query types. ```APIDOC get_stock_status(stocks, query_type='ST', query_date=None) Usage Scenarios: This function is available in research, backtesting, and trading modules. Interface Description: This interface is used to obtain the ST, halt, or delisting attributes of specified stocks on a given date. Notes: Stocks in the delisting reorganization period are not included in the delisting status. You can confirm delisting reorganization codes by checking if the stock name contains '【退】' using the get_stock_name function. Parameters: stocks: E.g., ['000001.SZ','000003.SZ']. This field must be entered, otherwise returns None (list[str]/str). query_type: Supports querying the following three types of attributes, defaults to 'ST' (str). Specific supported input fields include: 'ST' – Query whether it is an ST stock 'HALT' – Query whether it is halted 'DELISTING' – Query whether it is delisted query_date: Format is YYYYmmdd, defaults to None, meaning current date (current period for backtesting, system current time for research and trading) (str). Returns: Returns a dict type, where the value for each stock is True or False. If no relevant data is found or input is incorrect, returns None (dict[str:bool,...]). Example Return: {'600570': None} ``` -------------------------------- ### API: get_stock_name - Get Stock Name Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Documents the get_stock_name interface for retrieving names of stocks, convertible bonds, and ETFs. It supports single or multiple stock codes as input. ```APIDOC get_stock_name(stocks) Usage Scenarios: This function is available in research, backtesting, and trading modules. Interface Description: This interface can obtain names of stocks, convertible bonds, and ETFs. Notes: None Parameters: stocks: Stock code (list[str]/str) Returns: A dictionary of stock names, dict type, where key is stock code and value is stock name. If no relevant data is found or input is incorrect, value is None (dict[str:str]). Example Return: {'600570.SS': '恒生电子'} ``` -------------------------------- ### Get Detailed Information for a Specific Market Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function returns detailed information for a market corresponding to a given market code. It is available in research, backtesting, and live trading, with usage restricted to `before_trading_start` and `after_trading_end` in backtesting and live trading. ```APIDOC get_market_detail(finance_mic) finance_mic: Market code, refer to get_market_list for valid codes (str). Returns: A pandas.DataFrame object with fields: prod_code: Product code (str) prod_name: Product name (str) hq_type_code: Type code (str) trade_time_rule: Time rule (numpy.int64) ``` ```python # 获取上海证券交易所相关信息 'XSHG'/'SS' get_market_detail('XSHG') ``` -------------------------------- ### Get All Trading Days Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function is available in the research, backtesting, and trading modules. It is used to retrieve all trading dates. ```APIDOC get_all_trades_days(date=None) Usage Scenario: This function is available in the research, backtesting, and trading modules. ``` -------------------------------- ### Get A-Share Stock Code List with get_Ashares Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md The `get_Ashares` function retrieves a list of all A-share stock codes for a specified date. It is available in research, backtesting, and trading modules. The `date` parameter defaults to the current backtest date, research date, or trading date depending on the environment. ```APIDOC get_Ashares(date=None) 使用场景 该函数在研究、回测、交易模块可用 接口说明 该接口用于获取指定日期沪深市场的所有A股代码列表 注意事项: 1、在回测中,date不入参默认取回测日期,默认值会随着回测日期变化而变化,等于context.current_dt 2、在研究中,date不入参默认取当天日期 3、在交易中,date不入参默认取当天日期 参数 date:格式为YYYYmmdd 返回 股票代码列表,list类型(list[str,...]) ['000001.SZ', '000002.SZ', '000004.SZ', '000005.SZ', '000006.SZ', '000007.SZ', '000008.SZ', '000009.SZ', '000010.SZ', '000011.SZ', '000012.SZ', '000014.SZ', '000016.SZ', '000017.SZ', '000018.SZ', '000019.SZ', '000020.SZ', '000021.SZ', '000023.SZ', '000024.SZ', '000025.SZ', '000026.SZ', '000027.SZ',..., '603128.SS', '603167.SS', '603333.SS', '603366.SS', '603399.SS', '603766.SS', '603993.SS'] ``` ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): #沪深A股代码 ashares = get_Ashares() log.info('%s A股数量为%s' % (context.blotter.current_dt,len(ashares))) ashares = get_Ashares('20130512') log.info('20130512 A股数量为%s'%len(ashares)) ``` -------------------------------- ### Get Trading Day Date Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function is available in the research, backtesting, and trading modules. It is used to get the trading date a certain number of days before or after the current time. Notes: 1. By default, in backtesting, the current time is the backtest date when this interface is called (context.blotter.current_dt). 2. By default, in research, the current time is the date of the call. 3. By default, in trading, the current time is the date of the call. ```APIDOC get_trading_day(day) Usage Scenario: This function is available in the research, backtesting, and trading modules. Parameters: day (int): Represents the number of days. Positive for days after, negative for days before. 'day' = 0 means getting the current trading day; if the current date is a non-trading day, it returns the date of the previous trading day. The default value for 'day' is 0. It is not recommended to get trading dates that the exchange has not yet announced. Returns: date (datetime.date): Date object. ``` ```Python def initialize(context): g.security = ['600670.SS', '000001.SZ'] set_universe(g.security) def handle_data(context, data): # 获取后一天的交易日期 previous_trading_date = get_trading_day(1) log.info(previous_trading_date) # 获取前一天的交易日期 next_trading_date = get_trading_day(-1) log.info(next_trading_date) ``` -------------------------------- ### Set Strategy Configuration Parameters Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function is only available in the backtesting and trading modules. It is used to set configuration parameters within the strategy. Note: The input parameters for this function must be in 'a=b' format. ```APIDOC set_parameters(**kwargs) Usage Scenario: This function is only available in the backtesting and trading modules. Supported Parameters: holiday_not_do_before: Whether to execute before_trading_start on holidays in trading. Default: execute; 1: do not execute. tick_data_no_l2: Whether tick_data includes order and transaction data. Default: include; 1: do not include. receive_other_response: Whether the strategy receives push messages not generated by its own trades. Default: do not receive; 1: receive. receive_cancel_response: Whether the strategy receives push messages generated by order cancellations. Default: do not receive; 1: receive. Returns: None ``` ```Python def initialize(context): # 初始化策略 g.security = "600570.SS" set_universe(g.security) # 设置非交易日不执行before_trading_start # 设置tick_data中data不包含order和transaction # 设置接收非本交易产生的主推 # 设置接收撤单委托产生的主推 set_parameters(holiday_not_do_before="1", tick_data_no_l2="1", receive_other_response="1", receive_cancel_response="1") def before_trading_start(context, data): log.info("do before_trading_start") g.count = 0 def on_order_response(context, order_list): log.info("委托主推:%s" % order_list) def on_trade_response(context, trade_list): log.info("成交主推:%s" % trade_list) def tick_data(context, data): if g.count == 0: log.info(data[g.security]) g.count += 1 def handle_data(context, data): pass ``` -------------------------------- ### Retrieve List of Available Markets Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function returns a directory of currently available markets. It is supported in research, backtesting, and live trading modules, but in backtesting and live trading, it should only be used within `before_trading_start` and `after_trading_end`. ```APIDOC get_market_list() Parameters: None. Returns: A pandas.DataFrame object with fields: finance_mic: Market code (str) finance_name: Market name (str) ``` ```python get_market_list() ``` -------------------------------- ### One-Click IPO Subscription (ipo_stocks_order) Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function allows for one-click subscription of all new stocks available on the current day. It is only available within the trading module. Users can specify the market type and exclude certain stocks using a blacklist. The function returns a dictionary containing details like order code, order number, status, and quantity. ```APIDOC ipo_stocks_order(market_type=None, black_stocks=None) market_type: int - Market type for subscription (0: SSE common, 1: SSE STAR, 2: SZSE common, 3: SZSE ChiNext, 4: Convertible bonds). Default subscribes all new stocks. black_stocks: str/list - Blacklist of stock codes (e.g., '787001' or '787001.SS'). Stocks in this list will not be subscribed. Default subscribes all new stocks. Returns: dict[str:dict[str:str,str:int,str:float],...] - Dictionary containing order code, order number, order status (0 for failure, 1 for success), order quantity, etc. ``` ```Python import time def initialize(context): g.security = "600570.SS" set_universe(g.security) g.flag = False def before_trading_start(context, data): g.flag = False def handle_data(context, data): if not g.flag: # 上证普通代码 log.info("申购上证普通代码:") ipo_stocks_order(market_type=0) time.sleep(5) # 上证科创板代码 log.info("申购上证科创板代码:") ipo_stocks_order(market_type=1) time.sleep(5) # 深证普通代码 log.info("申购深证普通代码:") ipo_stocks_order(market_type=2) time.sleep(5) # 深证创业板代码 log.info("申购深证创业板代码:") ipo_stocks_order(market_type=3) time.sleep(5) # 可转债代码 log.info("申购可转债代码:") ipo_stocks_order(market_type=4) time.sleep(5) g.flag = True ``` -------------------------------- ### Python `get_gear_price` Return Data Structure Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Illustrates the dictionary structure returned by `get_gear_price` for single and multiple securities, detailing bid and offer group information. Each entry includes price, order volume, and number of orders. ```python 单只代码返回: {'bid_grp': {1: [价格, 委托量,委托笔数], 2: [价格, 委托量,委托笔数], 3: [价格, 委托量,委托笔数], 4: [价格, 委托量,委托笔数], 5: [价格, 委托量,委托笔数]}, 'offer_grp': {1: [价格, 委托量,委托笔数], 2: [价格, 委托量,委托笔数], 3: [价格, 委托量,委托笔数], 4: [价格, 委托量,委托笔 ``` -------------------------------- ### API Reference: on_order_response Callback Function Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Documents the `on_order_response` callback, an optional function available in the trading module. It provides faster order status updates than polling methods, making it suitable for high-frequency strategies. Includes important notes on handling external trades, infinite loops, and specific parameters for receiving different types of push data. ```APIDOC on_order_response(context, order_list) Usage Scenario: This function is only available in the trading module. Interface Description: This function responds to order push callbacks, updating Order status faster than engine, get_order(), and get_orders() functions, making it suitable for strategies requiring high speed. Notes: 1. Currently supports push data for stocks, convertible bonds, ETFs, LOFs, and futures. 2. When receiving pushes generated by trades outside the strategy (requires broker configuration, default is not to push), the order_id field in the push information will be "" as there is no corresponding Order object. 3. When calling order interfaces within the push callback, judgment processing is required to avoid infinite iteration loop issues. 4. When the broker is configured to receive pushes generated by trades outside the strategy AND the strategy calls set_parameters() with receive_other_response="1", the strategy will receive pushes not generated by its own trades. 5. When the strategy calls set_parameters() with receive_cancel_response="1", and receives a cancellation trade push, the order_id in the push information will be the order_id of the buy or sell Order object, and entrust_no will be the entrust number of the cancellation order. 6. The traded quantity in cancellation order push information is always processed as a positive number. ``` -------------------------------- ### Send email notifications via QQ Mail in Python Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function sends email content using QQ Mail. It is exclusively available in the trading module. It requires sender and receiver email addresses, and an SMTP authorization code. Optional parameters include email content, attachment path, and subject. Note that server connectivity to the external network and attachment sending capabilities depend on the brokerage's configuration. ```APIDOC send_email(send_email_info: str, get_email_info: Union[str, List[str]], smtp_code: str, info: str = '', path: str = '', subject: str = '') Usage: Available only in the trading module. Description: Sends email content via QQ Mail. Notes: 1. Requires server connectivity to external network, determined by brokerage. 2. Attachment sending (path parameter) depends on brokerage configuration. 3. Attachments received in email are filenames, not paths. Parameters: send_email_info: str - Required. Sender's email address (e.g., 'sender@qq.com'). get_email_info: Union[str, List[str]] - Required. Receiver's email address(es) (e.g., 'receiver@qq.com' or ['r1@qq.com', 'r2@qq.com']). smtp_code: str - Required. SMTP authorization code (not email password). info: str - Optional. Email content (default: empty string). path: str - Optional. Attachment path (e.g., '/home/fly/notebook/stock.csv') (default: empty string). subject: str - Optional. Email subject (default: empty string). Returns: None ``` ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): #发送文字信息 send_email('sender@qq.com', ['receiver1@qq.com', 'receiver2@qq.com'], 'phfxxxxxxxxxxcd', info='今天的股票池信息') ``` -------------------------------- ### API Return Format: Sector/Industry Ranking Data Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Describes the structure of the list and dictionary returned by the API for sector and industry ranking information. Each item in the list represents a code's ranking data, including various financial metrics and details about leading stocks. ```APIDOC Return Type: List[Dict[str, Any]] Each dictionary in the list contains the following fields: * prod_code: Industry code (str) * prod_name: Industry name (str) * hq_type_code: Industry sector code (str) * time_stamp: Millisecond timestamp (int) * trade_mins: Trading minutes (int) * trade_status: Trading status (str) * preclose_px: Yesterday's closing price (float) * open_px: Today's opening price (float) * last_px: Latest price (float) * high_px: Highest price (float) * low_px: Lowest price (float) * wavg_px: Weighted average price (float) * business_amount: Total trading volume (int) * business_balance: Total trading value (int) * px_change: Price change amount (float) * amplitude: Amplitude (int) * px_change_rate: Price change rate (float) * circulation_amount: Circulating shares (int) * total_shares: Total shares (int) * market_value: Market capitalization (int) * circulation_value: Circulating market capitalization (int) * vol_ratio: Volume ratio (float) * shares_per_hand: Shares per hand (int) * rise_count: Number of rising stocks (int) * fall_count: Number of falling stocks (int) * member_count: Number of members (int) * rise_first_grp: Leading rising stocks (List[Dict[str, Any]]) * prod_code: Stock code (str) * prod_name: Security name (str) * hq_type_code: Type code (str) * last_px: Latest price (float) * px_change_rate: Price change rate (float) * fall_first_grp: Leading falling stocks (List[Dict[str, Any]]) * prod_code: Stock code (str) * prod_name: Security name (str) * hq_type_code: Type code (str) * last_px: Latest price (float) * px_change_rate: Price change rate (float) ``` -------------------------------- ### Get All Trade Days Before a Specific Date Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function retrieves all trading days prior to a given date. It is applicable in backtesting, research, and live trading environments. By default, in backtesting, the date refers to the current backtest date; in research and live trading, it refers to the current day. ```APIDOC get_all_trades_days(date=None) date: The reference date, e.g., '2016-02-13' or '20160213' (str). Returns: A numpy.ndarray containing all trade days before the specified date. Notes: 1. In backtesting, 'date' defaults to context.blotter.current_dt. 2. In research, 'date' defaults to the current day. 3. In live trading, 'date' defaults to the current day. ``` ```python def initialize(context): # 获取当前回测日期之前的所有交易日 all_trades_days = get_all_trades_days() log.info(all_trades_days) all_trades_days_date = get_all_trades_days('20150312') log.info(all_trades_days_date) g.security = ['600570.SS', '000001.SZ'] set_universe(g.security) def handle_data(context, data): pass ``` -------------------------------- ### API Reference: Tick Data Callback Parameters and Structure Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Defines the `context` and `data` parameters for market data callbacks. The `data` parameter is a dictionary containing `order`, `tick`, and `transcation` DataFrames for each security, detailing their respective fields and data types. ```APIDOC Parameters: context: Context object, contains current account and position information. data: A dictionary where keys are security codes (e.g., '600570.SS') and values are dictionaries containing 'order' (latest per-order), 'tick' (current tick data), and 'transcation' (latest per-transaction) information. Data Structure for 'data' parameter: { 'Security Code': { 'order(latest per-order)': DataFrame/None, 'tick(current tick data)': DataFrame, 'transcation(latest per-transaction)': DataFrame/None, } } DataFrame Fields: order - Per-order DataFrame fields: business_time: Timestamp in milliseconds hq_px: Price business_amount: Order quantity order_no: Order number business_direction: Order direction 0 – Sell; 1 – Buy; 2 – Borrow; 3 – Lend; trans_kind: Order type 1 -- Market order; 2 -- Limit order; 3 -- Best bid/offer; tick - Tick data DataFrame fields: amount: Holding quantity avg_px: Average price bid_grp: Bid levels, dict type, e.g., {1:[42.71,200,0],2:[42.74,200,0],3:[42.75,700,...}, key is level, value is list: [price, quantity, number of orders]; business_amount: Traded quantity; business_amount_in: Inner market traded volume; business_amount_out: Outer market traded volume business_balance: Traded amount; business_count: Number of trades; circulation_amount: Circulating shares; close_px: Today's closing price current_amount: Latest traded quantity (current hand); down_px: Limit down price; end_trade_date: Last trading date entrust_diff: Entrust difference; entrust_rate: Entrust ratio; high_px: Highest price; hsTimeStamp: Timestamp, format YYYYMMDDHHMISS, e.g., 20170711141612; issue_date: Listing date last_px: Latest traded price; low_px: Lowest price; offer_grp: Offer levels, dict type, e.g., {1:[42.71,200,0],2:[42.74,200,0],3:[42.75,700,...}, key is level, value is list: [price, quantity, number of orders]; open_px: Today's opening price; pb_rate: Price-to-book ratio; pe_rate: Dynamic price-to-earnings ratio; preclose_px: Yesterday's closing price; prev_settlement: Yesterday's settlement px_change_rate: Price change rate settlement: Settlement price start_trade_date: First trading date tick_size: Minimum quote unit total_bid_turnover: Total bid amount total_bidqty: Total bid quantity total_offer_turnover: Total offer amount total_offerqty: Total offer quantity trade_mins: Trading time, minutes passed since market open, e.g., 100 for 100th minute of 240 min trading day; trade_status: Trading status; START -- Market start (after initialization, before call auction) PRETR -- Pre-market OCALL -- Start call auction TRADE -- Trading (continuous matching) HALT -- Trading halt SUSP -- Suspension BREAK -- Market break POSTR -- Post-market ENDTR -- Trading end STOPT -- Long-term suspension, n days, n>=1 DELISTED -- Delisted POSMT -- Post-market trading PCALL -- Post-market call auction INIT -- Before post-market fixed price start ENDPT -- Post-market fixed price closing phase POSSP -- Post-market fixed price suspension turnover_ratio: Turnover ratio up_px: Limit up price; vol_ratio: Volume ratio; wavg_px: Weighted average price; transcation - Per-transaction DataFrame fields: business_time: Timestamp in milliseconds; hq_px: Price; business_amount: Traded quantity; trade_index: Trade number; business_direction: Trade direction; 0 – Sell; 1 – Buy; buy_no: Buyer number; sell_no: Seller number; trans_flag: Trade flag; 0 – Normal trade; 1 – Cancellation trade; trans_identify_am: Post-market per-transaction sequence identifier; 0 – During market hours; 1 – Post-market; channel_num: Trade channel information; Returns: None ``` -------------------------------- ### API: get_cb_info - Convertible Bond Information Structure Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md Describes the DataFrame structure returned by the get_cb_info function, detailing each column related to convertible bond information such as code, name, stock details, dates, and conversion rates. ```APIDOC Returns: A DataFrame containing information for each convertible bond. Includes the following information: bond_code: Convertible bond code (str) bond_name: Convertible bond name (str) stock_code: Stock code (str) stock_name: Stock name (str) list_date: Listing date (str) premium_rate: Premium rate (float) convert_date: Conversion start date (str) maturity_date: Maturity date (str) convert_rate: Conversion ratio (float) convert_price: Conversion price (float) convert_value: Conversion value (float) ``` -------------------------------- ### Place ETF Component Basket Order (etf_basket_order) Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function is used to place ETF component basket orders. It is only available in the Ptrade client and within the stock trading module. It allows specifying the ETF code, basket quantity, order price style, and whether to use existing holdings for substitution. Detailed component stock information can be provided for cash or position replacement settings. ```APIDOC etf_basket_order(etf_code, amount, price_style=None, position=True, info=None) etf_code: str - Single ETF code (required). amount: int - Number of basket units to order (positive for buy, negative for sell) (required). price_style: str - Set order price ('B1'-'B5' for buy, 'S1'-'S5' for sell, 'new' for latest price). Defaults to latest price. position: bool - Use existing holdings for subscription (True) or not (False). Only for basket buy orders. Defaults to True. info: dict - Component stock information. Key is component stock code, value is dict with fields: cash_replace_flag: int - Set cash replacement flag (1 for replace, 0 for no replace). Only valid for replaceable targets. position_replace_flag: int - Set position replacement flag (1 for replace, 0 for no replace). Calculated based on 'position' parameter if not provided. limit_price: float - Set order price. Calculated based on 'price_style' parameter if not provided. Returns: dict[str:str] - Dictionary where key is stock code and value is Order object ID if successful, empty dict {} otherwise. ``` -------------------------------- ### Set Initial Backtest Positions Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This function is only available in the backtesting module. It is used to set the initial base positions for backtesting. Note: This function will cause the strategy to create a position object containing the set position information upon initialization. ```APIDOC set_yesterday_position(poslist) Usage Scenario: This function is only available in the backtesting module. Parameters: poslist (list[dict[str:str],...]): A list of dictionary elements, cannot be empty. Data format and parameter fields are as follows: [ { 'sid': Stock code, 'amount': Position quantity, 'enable_amount': Available quantity, 'cost_basis': Cost price per share } ] Parameters can also be passed via a CSV file, refer to convert_position_from_csv. Returns: None ``` ```Python def initialize(context): g.security = '600570.SS' set_universe(g.security) # 设置底仓 pos={} pos['sid'] = "600570.SS" pos['amount'] = "1000" pos['enable_amount'] = "600" pos['cost_basis'] = "55" set_yesterday_position([pos]) def handle_data(context, data): #卖出100股 order(g.security,-100) ``` -------------------------------- ### APIDOC: debt_to_stock_order - Convertible Bond to Stock Conversion Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md API for performing convertible bond to stock conversion operations. This function is only available in the trading module. ```APIDOC debt_to_stock_order(security, amount) Usage Scenario: This function is only available in the trading module. Description: This interface is used for convertible bond to stock conversion operations. Notes: None Parameters: security: Convertible bond code (str) amount: Entrustment quantity (int) Returns: The id from [Order object](#Order) or None. If order creation is successful, returns the Order object's id; otherwise, returns None (str). ``` -------------------------------- ### APIDOC: order_tick - Tick Data Triggered Trading Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md API for placing stock buy/sell orders triggered by tick data. It allows setting price levels for entrustment and is only usable within the `tick_data` module. ```APIDOC order_tick(sid, amount, priceGear='1', limit_price=None) Usage Scenario: This function is only available in the trading module. Description: This interface is used for placing buy/sell stock orders in the `tick_data` module, allowing price level settings for entrustment. Notes: This function can only be used in the `tick_data` module. Parameters: sid: Stock code (str) amount: Trading quantity, positive for buy, negative for sell (int) priceGear: Order book level, level1: 1~5 buy levels/-1~-5 sell levels, level2: 1~10 buy levels/-1~-10 sell levels (str) limit_price: Buy/sell limit price; when `priceGear` is also included in the input parameters, the order price will be based on `limit_price` (float). Returns: Returns an order transaction number (str). ``` -------------------------------- ### API: get_etf_info - Retrieve ETF Information Source: https://github.com/kaykouo/ptradeapi/blob/main/README.md This interface is used to retrieve information for a single or multiple ETFs. It is only available within the Ptrade client's stock trading module. The function returns a dictionary where keys are ETF codes and values are dictionaries containing ETF details. ```APIDOC Function Signature: get_etf_info(etf_code) Usage Scenario: Available only in Ptrade client, within the stock trading module. Parameters: * etf_code: Single ETF code or a list of ETF codes (list[str]/str), required. Return Type: * Normal return: dict[str:dict[...]] - A dictionary where keys are ETF codes and values are dictionaries containing ETF information. * Abnormal return: {} (empty dict). Return Fields: * etf_redemption_code: Subscription/Redemption code (str) * publish: Whether IOPV needs to be published (int) - 1: Yes, 0: No * report_unit: Minimum subscription/redemption unit (int) * cash_balance: Cash balance (float) * max_cash_ratio: Maximum cash substitute ratio (float) * pre_cash_component: T-1 day subscription base unit cash balance (float) * nav_percu: T-1 day subscription base unit net value (float) * nav_pre: T-1 day fund unit net value (float) * allot_max: Subscription limit (float) * redeem_max: Redemption limit (float) Example Return: {'510020.SS': {'nav_percu': 206601.39, 'redeem_max': 0.0, 'nav_pre': 0.207, 'report_unit': 1000000, 'max_cash_ratio': 0.4, 'cash_balance': -813.75, 'etf_redemption_code': '510021', 'pre_cash_component': 598.39, 'allot_max': 0.0, 'publish': 1}} ```