### Trading Strategy Example Source: https://ptradeapi.com/index Demonstrates the basic structure of a trading strategy using Python, including initialization, pre-trading setup, and the main data handling loop. It shows how to set security, get index stocks, and log information. ```Python def initialize(context): g.security = '600570.SS' set_universe(g.security) def before_trading_start(context, data): # 获取当前所有沪深300的股票 g.stocks = get_index_stocks('000300.XBHS') log.info(g.stocks) # 获取2016年6月20日所有沪深300的股票, 设为股票池 g.stocks = get_index_stocks('000300.XBHS','20160620') set_universe(g.stocks) log.info(g.stocks) def handle_data(context, data): pass ``` -------------------------------- ### Basic Trading Strategy Example Source: https://ptradeapi.com/index An example Python script demonstrating how to initialize trading context, set security universe, and schedule daily orders using `run_daily` and `after_trading_order`. ```python def initialize(context): g.security = "300001.SZ" set_universe(g.security) # Use run_daily for after-hours fixed-price orders between 15:00-15:30 run_daily(context, order_test, time="15:15") g.flag = False def order_test(context): snapshot = get_snapshot(g.security) if snapshot is not None: last_px = snapshot[g.security].get("last_px", 0) if last_px > 0: after_trading_order(g.security, 200, float(last_px)) def handle_data(context, data): if not g.flag: snapshot = get_snapshot(g.security) if snapshot is not None: last_px = snapshot[g.security].get("last_px", 0) if last_px > 0: after_trading_order(g.security, 200, float(last_px)) g.flag = True ``` -------------------------------- ### Order Usage Example Source: https://ptradeapi.com/index Python example demonstrating how to place an order and retrieve all pending orders using get_orders(), then logging the order objects. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): order(g.security, 100) order_obj = get_orders() log.info(order_obj) ``` -------------------------------- ### Get ETF Stock Info Example Source: https://ptradeapi.com/index Python example demonstrating how to retrieve ETF component stock information using the get_etf_stock_info function for single and multiple constituent stocks. ```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) ``` -------------------------------- ### Trading Data Export Example Source: https://ptradeapi.com/index Provides a Python code example demonstrating how to initialize the context, set a security universe, place an order, and retrieve exported trade data files using get_trades_file(). ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): # Place an order order_obj = order(g.security, 100) log.info('Order ID: %s'% order_obj) def after_trading_end(context, data): # Get trade data saved to the default directory data_path = get_trades_file() log.info(data_path) # Get trade data saved to a specified directory under notebook user_data_path = get_trades_file('user_data/data') log.info(user_data_path) ``` -------------------------------- ### Set Email Information Example Source: https://ptradeapi.com/index Provides an example of setting email notification details using set_email_info. This includes specifying the QQ email address, SMTP authorization code, and a custom email subject for alerts. It also demonstrates raising an exception in before_trading_start to trigger an email alert. ```Python def initialize(context): g.security = "600570.SS" set_universe(g.security) # Set email information set_email_info("2222@qq.com", "AABB", "【PTrade量化-策略交易异常终止提醒】") def before_trading_start(context, data): raise BaseException("test send error email") def handle_data(context, data): pass ``` -------------------------------- ### Ptrade Initialization and Data Handling Source: https://ptradeapi.com/index Example of initializing Ptrade context with a security and handling data, including fetching margin assert and performing direct refunds. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): # 获取负债总额 fin_compact_balance = get_margin_assert().get('fin_compact_balance') # 还款 margincash_direct_refund(fin_compact_balance) ``` -------------------------------- ### Portfolio Usage Example Source: https://ptradeapi.com/index A Python example demonstrating how to access and log the portfolio's total value within a trading strategy's handle_data function. ```python def initialize(context): g.security = "600570.SS" set_universe([g.security]) def handle_data(context, data): log.info(context.portfolio.portfolio_value) ``` -------------------------------- ### get_user_name Example Source: https://ptradeapi.com/index Shows how to get the user's fund account name in the initialize function and use it in handle_data to conditionally place an order based on the account number and a flag. ```python def initialize(context): g.security = "600570.SS" set_universe(g.security) g.user_name = get_user_name() def before_trading_start(context, data): g.flag = False def handle_data(context, data): # Buy 100 shares if account is '123456789' and no order placed today if g.user_name == "123456789" and not g.flag: # Buy 100 shares order(g.security, 100) g.flag = True ``` -------------------------------- ### Run Daily Example Source: https://ptradeapi.com/index Illustrates the usage of run_daily to schedule a function, get_finance, to execute daily at 9:31 AM. The example defines the get_finance function which retrieves fundamental data for a given security. ```Python # Define a function to fetch financial data daily def initialize(context): run_daily(context, get_finance, time='9:31') g.security = '600570.SS' set_universe(g.security) def get_finance(context): re = get_fundamentals(g.security,'balance_statement','total_assets') log.info(re) def handle_data(context, data): pass ``` -------------------------------- ### Example Usage of get_price in Trading Strategy Source: https://ptradeapi.com/index Demonstrates how to use the get_price function within a trading strategy's initialization and data handling functions. Includes examples for fetching single stock data, multiple stock data, and data for industry sectors, specifying dates, frequencies, and counts. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): # Get daily 'open' price for a single stock price_open = get_price('600570.SS', start_date='20150101', end_date='20150131', frequency='1d')['open'] log.info(price_open) # Get index stocks and then fetch their daily data security_list = get_index_stocks('000300.XBHS', '20150101') price = get_price(security_list, start_date='20150101', end_date='20150131') log.info(price) # Get data for an industry sector industry_info = get_price("A01000.XBHS", end_date="20210315", frequency="daily", count=10) log.info(industry_info) ``` -------------------------------- ### Before Trading Start Function Source: https://ptradeapi.com/index The before_trading_start function is an optional function called once before the trading session begins each day. It's used for daily initializations. It can be omitted if no pre-trading setup is required. ```python def before_trading_start(context, data): log.info(g.security) ``` -------------------------------- ### ptradeapi Strategy Initialization and Data Handling Source: https://ptradeapi.com/index Provides a Python code example demonstrating the basic structure of a trading strategy, including initialization, setting the universe, and handling trading data. ```Python def initialize(context): # g is a global variable g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): order('600570.SS', 100) def after_trading_end(context, data): log.info(g.security) ``` -------------------------------- ### Basic Initialization and Data Handling Source: https://ptradeapi.com/index Demonstrates initializing trading context by setting security and handling incoming data by executing buy/sell orders. Includes examples for closing positions with and without specific limit prices. ```Python def initialize(context): g.security = ['IF1712.CCFX', 'CU1806.XSGE'] set_universe(g.security) def handle_data(context, data): #买入平仓 buy_close('IF1712.CCFX', 1) #买入平今仓(限定点数为52220) buy_close ('CU1806.XSGE', 1, limit_price=52220, close_today=False) #买入平仓(限定点数为52220) buy_close ('CU1806.XSGE', 1, limit_price=52220) ``` -------------------------------- ### Permission Test Example Source: https://ptradeapi.com/index Demonstrates the usage of the permission_test function, showing how to check authorization with and without parameters in a trading strategy's lifecycle. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): pass def after_trading_end(context, data): # 需要用授权模式下载功能的情况下不用入参 flag = permission_test() if not flag: raise RuntimeError('授权不通过,终止程序,抛出异常') # 不需要用授权模式下载功能的情况下通过入参来进行授权校验 flag = permission_test(account='10110922',end_date='20210101') if not flag: raise RuntimeError('授权不通过,终止程序,抛出异常') ``` -------------------------------- ### Position Usage Example Source: https://ptradeapi.com/index Python code snippet showing how to place an order, retrieve the position object for a security, and log its details. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): order(g.security,1000) position = get_position(g.security) log.info(position) ``` -------------------------------- ### get_deliver Example Source: https://ptradeapi.com/index Illustrates the usage of get_deliver to fetch historical delivery data between '20210101' and '20211117' and logs the retrieved information. ```python def initialize(context): g.security = "600570.SS" set_universe(g.security) def before_trading_start(context, data): h = get_deliver('20210101', '20211117') log.info(h) def handle_data(context, data): pass ``` -------------------------------- ### convert_position_from_csv Example Source: https://ptradeapi.com/index Demonstrates how to use the convert_position_from_csv function within the initialize method to load position data from 'Poslist.csv' and set the initial positions using set_yesterday_position. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) # Set initial positions poslist = convert_position_from_csv("Poslist.csv") set_yesterday_position(poslist) def handle_data(context, data): # Sell 100 shares order(g.security, -100) ``` -------------------------------- ### Run Interval Example Source: https://ptradeapi.com/index Shows how to use run_interval to execute a function, interval_handle, every 10 seconds. The interval_handle function retrieves and logs the snapshot data for a specified security. ```Python # Define a periodic processing function to execute every 10 seconds def initialize(context): run_interval(context, interval_handle, seconds = 10) g.security = '600570.SS' set_universe(g.security) def interval_handle(context): snapshot = get_snapshot(g.security) log.info(snapshot) def handle_data(context, data): pass ``` -------------------------------- ### Example Data Structure for ETF Information Source: https://ptradeapi.com/index Illustrates the typical data structure returned, which is a list of dictionaries containing various financial metrics for ETFs. Each dictionary represents an ETF with detailed trading and performance data. ```Python [ {'px_change': 3902, 'fall_first_grp': [{'prod_code': '002921', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': -9.99, 'last_px': 16.49, 'prod_name': '联诚精密'}, {'prod_code': '002238', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': -9.95, 'last_px': 9.96, 'prod_name': '天威视讯'}, {'prod_code': '605303', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': -7.6, 'last_px': 12.16, 'prod_name': '园林股份'}, {'prod_code': '605069', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': -7.01, 'last_px': 10.61, 'prod_name': '正和生态'}, {'prod_code': '600936', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': -5.06, 'last_px': 3.94, 'prod_name': '广西广电'}, {'prod_code': '002750', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': -4.97, 'last_px': 1.53, 'prod_name': '*ST龙津'}, {'prod_code': '603958', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': -3.71, 'last_px': 19.73, 'prod_name': '哈森股份'}, {'prod_code': '000851', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': 2.5, 'last_px': 2.46, 'prod_name': 'ST高鸿'}, {'prod_code': '603267', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': 2.55, 'last_px': 55.6, 'prod_name': '鸿远电子'}, {'prod_code': '002197', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': 4.94, 'last_px': 6.37, 'prod_name': 'ST证通'}], 'px_change_rate': 2.73, 'trade_status': 'ENDTR', 'last_px': 146618, 'member_count': 21, 'preclose_px': 142716, 'shares_per_hand': 1, 'amplitude': 253, 'total_shares': 12313513732, 'open_px': 145113, 'business_balance': 19208132000, 'high_px': 147705, 'time_stamp': 20250313152924000, 'prod_code': '031398.XBHS', 'wavg_px': 147422, 'circulation_value': 123558660317, 'rise_count': 14, 'rise_first_grp': [{'prod_code': '002105', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': 10.03, 'last_px': 11.3, 'prod_name': '信隆健康'}, {'prod_code': '000678', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': 10.02, 'last_px': 13.84, 'prod_name': '襄阳轴承'}, {'prod_code': '603716', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': 10.01, 'last_px': 14.62, 'prod_name': '塞力医疗'}, {'prod_code': '600539', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': 10, 'last_px': 15.84, 'prod_name': '狮头股份'}, {'prod_code': '603206', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': 9.99, 'last_px': 24.56, 'prod_name': '嘉环科技'}, {'prod_code': '000880', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': 9.99, 'last_px': 40.3, 'prod_name': '潍柴重机'}, {'prod_code': '002574', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': 9.97, 'last_px': 6.51, 'prod_name': '明牌珠宝'}, {'prod_code': '600967', 'hq_type_code': 'XSHG.ESA.M', 'px_change_rate': 8.2, 'last_px': 13.2, 'prod_name': '内蒙一机'}, {'prod_code': '000665', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': 7.41, 'last_px': 7.54, 'prod_name': '湖北广电'}, {'prod_code': '002052', 'hq_type_code': 'XSHE.ESA.M', 'px_change_rate': 5.1, 'last_px': 4.95, 'prod_name': '*ST同洲'}], 'low_px': 144101, 'fall_count': 7, 'trade_mins': 240, 'market_value': 123558660317, 'circulation_amount': 11663849671, 'hq_type_code': 'XBHS.GN', 'business_amount': 1647666828, 'prod_name': '昨日连板', 'vol_ratio': 0.8} ] ``` -------------------------------- ### Get Stock Ex-rights Information Source: https://ptradeapi.com/index Retrieves ex-rights and ex-dividend information for a given stock code. Returns None if no data is available for the specified date, otherwise returns a pandas DataFrame. ```APIDOC get_stock_exrights(stock_code: str) -> pandas.DataFrame or None Description: Fetches ex-rights and ex-dividend data for a stock. Returns None if no data is found for the input date. Returns a pandas DataFrame containing details like allotted shares, bonus shares, and rights issue prices if data exists. Parameters: stock_code: The stock code (e.g., '600570.SS'). Returns: A pandas DataFrame with columns: allotted_ps, rationed_ps, rationed_px, bonus_ps, exer_forward_a, exer_forward_b, exer_backward_a, exer_backward_b, and date (index). Returns None if no data is available. Example Usage: stock_exrights_data = get_stock_exrights('600570.SS') print(stock_exrights_data) ``` ```Python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): stock_exrights = get_stock_exrights(g.security) log.info('the stock exrights info of security %s:\n%s' % (g.security, stock_exrights)) ``` -------------------------------- ### Get ETF Stock Info Return Structure Source: https://ptradeapi.com/index Describes the structure and fields of the dictionary returned by functions providing ETF component stock information. Includes details on cash replacement flags and margin ratios. ```APIDOC Function: get_etf_stock_info Returns: A dictionary containing information about constituent stocks for each ETF code. An empty dictionary is returned on error. Return Fields: - code_num: Number of constituent stocks (str:float). - cash_replace_flag: Cash replacement flag (str:str). '0': No replacement allowed; '1': Replacement allowed; '2': Replacement mandatory; '3': Non-Shanghai market, replacement allowed; '4': Non-Shanghai market, replacement mandatory; '5': Non-Shenzhen market, replacement allowed; '6': Non-Shenzhen market, replacement mandatory. - replace_ratio: Margin ratio (premium ratio), valid for stocks allowing cash replacement (str:float). - replace_balance: Replacement amount, valid for stocks requiring cash replacement (str:float). - is_open: Suspension flag, 0-suspended, 1-not suspended (str:int). Example Return: {'600000.SS': {'cash_replace_flag': '1', 'replace_ratio': 0.1, 'is_open': 1, 'code_num': 4700.0, 'replace_balance': 0.0}} ``` -------------------------------- ### Get All Orders Source: https://ptradeapi.com/index Retrieves all orders for a specific security or all orders for the account on the current day. The function signature and detailed return structure are inferred from examples. ```Python def get_all_orders(security=None): """ 获取账户当日指定标的或全部订单。 Args: security (str, optional): 股票代码,如'600570.SS'。如果为None,则获取当日全部订单。 Returns: list[dict]: 包含多条订单记录的列表,每条记录包含以下字段: 'symbol': 股票代码(str) 'entrust_no': 委托编号(str) 'amount': 委托数量(int) 'entrust_bs': 委托方向(int, 1-买, 2-卖) 'price': 委托价格(float) 'status': 委托状态(str) 'filled_amount': 成交数量(int) 'entrust_time': 委托时间(str, optional) """ pass ``` -------------------------------- ### Python Trading Strategy Example Source: https://ptradeapi.com/index Demonstrates a basic Python trading strategy using market data. It shows how to initialize context, set a security, access tick data (like bid price), and place orders based on market conditions. ```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] # 最近一笔逐笔成交的成交量 # transcation = data[security]["transcation"] # business_amount = list(transcation["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 ``` -------------------------------- ### Basic Strategy Initialization and Data Handling Source: https://ptradeapi.com/index Illustrates a basic structure for a trading strategy, including initialization of global variables, setting security lists, and handling historical data within the backtesting framework. ```python def initialize(context): g.security = ['600570.SS','600571.SS'] # Set the stocks in g.security as the security pool set_universe(g.security) def handle_data(context, data): # Get historical data for the security pool set during initialization his = get_history(5, '1d', 'close', security_list=None) ``` -------------------------------- ### Core Backtesting Functions Source: https://ptradeapi.com/index Demonstrates the usage of initialize and handle_data functions for setting up a trading strategy and processing market data, including accessing context variables like previous_date and blotter timestamps. ```python def initialize(context): g.security = ['600570.SS', '000001.SZ'] set_universe(g.security) def handle_data(context, data): #获得当前回测相关时间 pre_date = context.previous_date log.info(pre_date) year = context.blotter.current_dt.year log.info(year) month = context.blotter.current_dt.month log.info(month) day = context.blotter.current_dt.day log.info(day) hour = context.blotter.current_dt.hour log.info(hour) minute = context.blotter.current_dt.minute log.info(minute) second = context.blotter.current_dt.second log.info(second) #得到"年-月-日"格式 date = context.blotter.current_dt.strftime("%Y-%m-%d") log.info(date) #得到周几 weekday = context.blotter.current_dt.isoweekday() log.info(weekday) ``` -------------------------------- ### Get Trading Day Source: https://ptradeapi.com/index Retrieves the trading day information. This function is available in research, backtesting, and trading modules. ```APIDOC get_trading_day(day: str) -> str - day: Specifies the trading day to query (e.g., 'today', 'yesterday', 'specific_date'). Returns: The trading day information. ``` -------------------------------- ### Basic Order Placement Source: https://ptradeapi.com/index Demonstrates a simple trading strategy that initializes a security and places an order to buy a fixed quantity when no order has been created yet. It highlights the use of global variables and the `order` API. ```Python def initialize(context): g.security = '600570.SS' # 是否创建订单标识 g.flag = False set_universe(g.security) def handle_data(context, data): if not g.flag: order(g.security, 1000) g.flag = True ``` -------------------------------- ### Persistence for Holding Days Tracking Source: https://ptradeapi.com/index This example shows how to persist a dictionary (`g.hold_days`) that tracks the number of days a security has been held. It uses `pickle` to save and load the dictionary, ensuring continuity of the holding period logic across strategy restarts. It also demonstrates using `defaultdict` and handling file operations within `initialize` and `handle_data`. ```Python import pickle from collections import defaultdict NOTEBOOK_PATH = get_research_path() ''' 持仓N日后卖出,仓龄变量每日pickle进行保存,重启策略后可以保证逻辑连贯 ''' def initialize(context): #尝试启动pickle文件 try: with open(NOTEBOOK_PATH+'hold_days.pkl','rb') as f: g.hold_days = pickle.load(f) #定义空的全局字典变量 except: g.hold_days = defaultdict(list) g.security = '600570.SS' set_universe(g.security) # 仓龄增加一天 def before_trading_start(context, data): if g.hold_days: g.hold_days[g.security] += 1 # 每天将存储仓龄的字典对象进行pickle保存 def handle_data(context, data): if g.security not in list(context.portfolio.positions.keys()) and g.security not in g.hold_days: order(g.security, 100) g.hold_days[g.security] = 1 if g.hold_days: if g.hold_days[g.security] > 5: order(g.security, -100) del g.hold_days[g.security] with open(NOTEBOOK_PATH+'hold_days.pkl','wb') as f: pickle.dump(g.hold_days,f,-1) ``` -------------------------------- ### Ptrade Download Links Source: https://ptradeapi.com/index Provides download links for various versions of the Ptrade software from different securities firms. Includes links for both live (实盘版) and testing (测试版) versions. ```text - [国金证券-Ptrade实盘版](https://download.gjzq.com.cn/gjty/organ/gjzqptd.rar) - [国金证券-Ptrade测试版](https://download.gjzq.com.cn/temp/organ/gjzqptrade_ceshi.rar) - [国盛证券-Ptrade实盘版](https://download.gszq.com/ptrade/PTrade1.0-Client-V201901-04-000.zip) - [国盛证券-Ptrade测试版](https://download.gszq.com/ptrade/PTrade1.0-Client-V201906-00-000.zip%20) - [湘财证券-Ptrade实盘版](http://wap.xcsc.com/file/Ptrade/Ptrade.exe) - [湘财证券-Ptrade测试版](https://pan.baidu.com/s/1ekrPh0Xk4UV7uC8oLSpRZw)(提取码:8jmg) - [东莞证券-Ptrade实盘版](https://media.dgzq.com.cn/app/file/get?group=group1&name=M00/00/95/rBQam2YKEXOACyPRCgyAaEJhSHs591.exe&fileName=PTrade1.0-Client-V202301-45(%E4%B8%9C%E8%8E%9E)) - [国泰君安-海通-Ptrade测试版](https://dl2.app.gtja.com/dzswem/softwareVersion/202504/07/PTrade1.0-Client-V202403-07-000%28PTrade-UAT%29.zip) - [国泰君安-海通-Ptrade实盘版](https://dl2.app.gtja.com/dzswem/softwareVersion/202504/07/PTrade1.0-Client-V202403-07-005%28PTrade%29.zip) - [长江证券-Ptrade实盘版](https://downcq.95579.com/jcj/zg/PTrade1.0-Client-V202308-15-000_CY.zip) ``` -------------------------------- ### Get Trading Name (get_trade_name) Source: https://ptradeapi.com/index Retrieves the name of the current trading session. This function is specifically designed for use within the trading module. ```APIDOC get_trade_name() -> str Description: Retrieves the name of the current trading session. Usage Scenarios: This function is only available in the trading module. Interface Description: This interface is used to obtain the name of the current trading session. Parameters: None Returns: A string representing the current trading session name. Example: name = get_trade_name() ``` -------------------------------- ### Get Index Constituent Stocks Source: https://ptradeapi.com/index Retrieves a list of constituent stocks for a given index on a specific date. Defaults to the current date if not provided. ```APIDOC get_index_stocks(index_code: str, date: str = None) -> list[str] Description: Fetches the list of stocks that are constituents of a specified index on a given date. Usage Scenarios: Available in research, backtesting, and trading modules. Notes: 1. In backtesting, if 'date' is not provided, it defaults to the historical date of the current backtesting period. 2. In research and trading, if 'date' is not provided, it defaults to the current date. Parameters: index_code: The index code, which must end with '.SS' (e.g., '000300.SS' for CSI 300). date: The date in 'YYYYMMDD' format (e.g., '20170620'). Defaults to the current date if not specified. Returns: A list of stock codes (strings) that are constituents of the index on the specified date. Example Output: ['000001.SZ', '000002.SZ', '000063.SZ', ..., '600521.SS', '600143.SS', '000800.SZ'] ``` -------------------------------- ### Backtesting Configuration Functions Source: https://ptradeapi.com/index This section details various functions used to configure backtesting environments within the ptradeapi. These functions allow users to set benchmarks, commission rates, slippage, volume ratios, limit modes, and initial positions, enabling more realistic simulation of trading strategies. ```APIDOC set_benchmark(sids) - Sets the benchmark for strategy evaluation. - Usage: Backtesting, Trading Module. - Description: Configures the benchmark security (stock, index, ETF) against which strategy performance metrics are calculated. The default benchmark is the CSI 300 Index (000300.SS). - Parameters: - sids: The security identifier (string) for the benchmark. - Returns: None. - Example: def initialize(context): g.security = '000001.SZ' set_universe(g.security) # Set SSE 50 Index (000016.SS) as the benchmark set_benchmark('000016.SS') set_commission(commission_ratio=0.0003, min_commission=5.0, type="STOCK") - Sets commission and handling fees for trades. - Usage: Backtesting Module. - Description: Configures the commission rate, minimum commission per trade, and transaction type (STOCK, ETF, LOF). Transaction costs include commission and handling fees. Commission is calculated as commission_ratio * total_transaction_amount, with a minimum fee applied. - Parameters: - commission_ratio: The commission rate per transaction (float). Defaults to 0.0003 (0.03%) for stocks, 0.0008 (0.08%) for ETFs/LOFs. - min_commission: The minimum commission charged per transaction (float). Defaults to 5.0. - type: The type of security for which to set commission (string). Supported values: "STOCK", "ETF", "LOF". Defaults to "STOCK". - Returns: None. - Example: def initialize(context): g.security = '600570.SS' set_universe(g.security) # Set commission rate to 0.03% and minimum commission to 3.0 set_commission(commission_ratio =0.0003, min_commission=3.0) set_fixed_slippage(fixedslippage=0.0) - Sets a fixed slippage value for trades. - Usage: Backtesting Module. - Description: Simulates fixed price difference between order price and execution price. This helps in making backtests more realistic by accounting for unavoidable slippage in real trading scenarios. - Parameters: - fixedslippage: The fixed price difference (float). The final execution price = order price +/- fixedslippage / 2. Defaults to 0.0. - Returns: None. - Example: def initialize(context): g.security = '600570.SS' set_universe(g.security) # Set slippage to a fixed 0.2 yuan set_fixed_slippage(fixedslippage=0.2) set_slippage(slippage=0.1) - Sets a slippage percentage based on the current price. - Usage: Backtesting Module. - Description: Simulates slippage as a percentage of the current price. This function accounts for price variations between the order price and the execution price, making backtests more representative of real market conditions. - Parameters: - slippage: The slippage percentage (float). The final execution price = order price +/- order price * slippage / 2. Defaults to 0.1 (10%). - Returns: None. - Example: def initialize(context): g.security = '600570.SS' set_universe(g.security) # Set slippage impact to 0.2 (20%) set_slippage(slippage = 0.2) set_volume_ratio(volume_ratio=0.25) - Sets the execution volume ratio for trades. - Usage: Backtesting Module. - Description: Controls the proportion of a single order that gets executed within a given period, simulating market liquidity constraints. If the order quantity exceeds the calculated execution quantity, the excess is not executed. - Parameters: - volume_ratio: The ratio of maximum executed volume to the total market tradable volume for the period (float). Defaults to 0.25 (25%). - Returns: None. - Example: def initialize(context): g.security = '600570.SS' set_universe(g.security) # Set maximum executed volume to 50% of total tradable volume set_volume_ratio(volume_ratio = 0.5) set_limit_mode(limit_mode='LIMIT') - Sets the transaction volume limit mode. - Usage: Backtesting Module. - Description: Determines whether transaction volume is restricted during backtesting. Setting to 'UNLIMITED' allows execution volume to exceed the actual market volume for the period, which can be useful for low-frequency strategies or simplifying backtests. - Parameters: - limit_mode: The mode for limiting transaction volume (str). 'LIMIT' enforces limits, 'UNLIMITED' removes them. Defaults to 'LIMIT'. - Returns: None. - Example: def initialize(context): g.security = '600570.SS' set_universe(g.security) # Disable transaction volume limits in backtesting set_limit_mode('UNLIMITED') set_yesterday_position(poslist) - Sets the initial positions (holdings) for backtesting. - Usage: Backtesting Module. - Description: Initializes the strategy with a predefined set of holdings, including security, quantity, available quantity, and cost basis. This function creates position objects at the start of the backtest. - Parameters: - poslist: A list of dictionaries, where each dictionary represents a holding. Each dictionary must contain: - 'sid': Security identifier (str). - 'amount': Total holding quantity (str). - 'enable_amount': Available quantity for trading (str). - 'cost_basis': Cost basis per share (str). - The parameter cannot be empty. Positions can also be loaded from a CSV file using convert_position_from_csv. - Returns: None. - Example: def initialize(context): g.security = '600570.SS' set_universe(g.security) # Set initial position pos = {} pos['sid'] = "600570.SS" pos['amount'] = "1000" pos['enable_amount'] = "600" pos['cost_basis'] = "55" set_yesterday_position([pos]) set_parameters(**kwargs) - Sets strategy configuration parameters. - Usage: Trading Module. - Description: A general function to set various strategy-specific parameters. The exact parameters depend on the trading module's implementation. - Parameters: - **kwargs: Arbitrary keyword arguments representing configuration parameters. - Returns: None. ``` -------------------------------- ### Get Frequency API Source: https://ptradeapi.com/index Retrieves the current business code's frequency (e.g., 'minute' or 'daily'). This function is available in backtesting and trading modules. ```APIDOC get_frequency() - Returns the current business code's frequency. - Available in backtesting and trading modules. - Returns: - 'minute' if the period is minute. - 'daily' if the period is daily. - Example Usage: def initialize(context): g.security = '600570.SS' set_universe(g.security) log.info(get_frequency()) ``` -------------------------------- ### Ptrade Strategy Structure Source: https://ptradeapi.com/index Demonstrates the basic structure of a Ptrade trading strategy using Python. It includes the essential `initialize` and `handle_data` functions. ```python def initialize(context): set_universe('600570.SS') def handle_data(context, data): pass ``` -------------------------------- ### Get Current Kline Count API Source: https://ptradeapi.com/index Retrieves the number of minute bars for the current time in the stock business. Available in backtesting, trading, and research modules. ```APIDOC get_current_kline_count() - Gets the number of minute bars for the current time. - Available in backtesting, trading, and research modules. - Notes: - Backtesting: Returns minute bar count for the backtest day. - Research: Returns minute bar count for the latest trading day; 0 for non-trading days. - Trading: Returns minute bar count for the latest trading day. - Returns (int): The number of minute bars at the current time. - Example Usage: def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): log.info(get_current_kline_count()) ``` -------------------------------- ### Set Strategy Parameters Example Source: https://ptradeapi.com/index Demonstrates how to use the set_parameters function to configure various strategy settings, including disabling execution on holidays, excluding tick data details, enabling specific response receptions, and managing behavior during server restarts. It also shows how to revert these settings. ```Python def initialize(context): # Initialize strategy g.security = "600570.SS" set_universe(g.security) # Set parameters: disable before_trading_start on holidays, exclude order/transaction in tick_data, # receive other and cancel responses, disable auto-restart and before_trading_start on server restart. set_parameters(holiday_not_do_before="1", tick_data_no_l2="1", receive_other_response="1", receive_cancel_response="1", not_restart_trade="1", server_restart_not_do_before="1") # Cancel server restart settings set_parameters(not_restart_trade="0", server_restart_not_do_before="0") def before_trading_start(context, data): log.info("do before_trading_start") # Cancel holiday and tick_data settings set_parameters(holiday_not_do_before="0", tick_data_no_l2="0", receive_other_response="0", receive_cancel_response="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 handle_data(context, data): pass ``` -------------------------------- ### Get Position Source: https://ptradeapi.com/index Retrieves position information for a specific asset or all positions if no asset is specified. This function is available only in backtesting and trading modules. It returns a Position object. ```APIDOC get_position(security) Usage: Only available in backtesting and trading modules. Description: Retrieves detailed position information for a specific asset. Parameters: security (str): The stock code, e.g., '600570.SS'. If not provided, it defaults to fetching all positions. Returns: Position: A Position object containing details of the holdings. ``` -------------------------------- ### Get Business Type API Source: https://ptradeapi.com/index Returns the current strategy's business type, such as 'stock', 'rzrq', 'future', 'option', or 'hks'. Available in backtesting and trading modules. ```APIDOC get_business_type() - Returns the current strategy's business type. - Available in backtesting and trading modules. - Returns (str): - 'stock': Stock - 'rzrq': Financing and Margin Trading - 'future': Futures - 'option': Options - 'hks': Hong Kong Stock Connect - Example Usage: def initialize(context): g.security = "600570.SS" set_universe(g.security) def before_trading_start(context, data): g.business_type = get_business_type() log.info("当前策略的业务类型为:%s" % g.business_type) def handle_data(context, data): if g.business_type == "stock": order("600570.SS", 100) elif g.business_type == "future": buy_open("IF2309.CCFX", 1, 3816.0) ```