### Example: Get All Orders Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Shows how to place an order and then retrieve all orders using get_orders. Available in backtesting and trading modules. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): _id = order(g.security, 100) order_obj = get_orders() log.info(order_obj) ``` -------------------------------- ### Example: Get Convertible Bond IPO Stocks Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Demonstrates how to retrieve convertible bond IPO subscription targets for the day and log them. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): # 当日可转债IPO申购标的 ipo_stocks = get_ipo_stocks().get('可转债代码') log.info('可转债IPO申购标的列表为%s' % ipo_stocks) ``` -------------------------------- ### Initialize Function Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md This is a basic example of the 'initialize' function, which is mandatory for Ptrade strategies. It sets up global variables and the trading universe. ```python def initialize(context): #g为全局对象 g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): order('600570.SS',100) ``` -------------------------------- ### Example: Get Marginable Securities List (Python) Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Demonstrates how to obtain and log the list of marginable securities for lending using the get_marginsec_stocks function. ```python def initialize(context): g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): # 获取最新的融券标的列表 marginsec_stocks = get_marginsec_stocks() log.info(marginsec_stocks) ``` -------------------------------- ### Example: Fetch and Log Margin Asset Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example of how to initialize the context, set a security, and log the retrieved margin asset information. ```python def initialize(context): g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): # 获取信用账户资产信息 margin_asset = get_margin_asset() log.info(margin_asset) ``` -------------------------------- ### Example: Get Position Information Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Shows how to get and log the position information for a given security. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): position = get_position(g.security) log.info(position) ``` -------------------------------- ### Example: Get Daily Trades Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Demonstrates how to fetch and log the daily trade information. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): #获取当日成交数据 trades_info = get_trades() log.info(trades_info) ``` -------------------------------- ### Example: Get Specific Order Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Demonstrates how to place an order and then retrieve its details using get_order. Available in backtesting and trading modules. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): order_id = order(g.security, 100) current_order = get_order(order_id) log.info(current_order) ``` -------------------------------- ### Example: Get Marginable Stocks List (Python) Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example of how to retrieve and log the list of marginable stocks for financing using the get_margincash_stocks function. ```python def initialize(context): g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): # 获取最新的融资标的列表 margincash_stocks = get_margincash_stocks() log.info(margincash_stocks) ``` -------------------------------- ### Basic Trading Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md A simple example demonstrating how to place an order and retrieve position information. ```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) ``` -------------------------------- ### Example: Get and Save Trades File Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Demonstrates placing an order and then retrieving trade reconciliation data, saving it to both the default directory and a specified subdirectory. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): # 委托 order_obj = order(g.security, 100) log.info('订单编号为:%s'% order_obj) def after_trading_end(context, data): # 获取对账数据,存放到默认目录 data_path = get_trades_file() log.info(data_path) # 获取对账数据,存放到notebook下的指定目录 user_data_path = get_trades_file('user_data/data') log.info(user_data_path) ``` -------------------------------- ### Initialize Strategy Setup Source: https://context7.com/kay-ou/ptradeapi/llms.txt Use `initialize` for one-time strategy setup at startup. Configure stock universe, benchmark, commission, slippage, and schedule recurring tasks. Ensure to call setting functions only within this callback. ```python def initialize(context): # Set stock universe for the strategy g.security = '600570.SS' set_universe(g.security) # Set performance benchmark (default: CSI 300) set_benchmark('000300.SS') # Configure backtest trading costs set_commission(commission_ratio=0.0003, min_commission=5.0, type="STOCK") set_slippage(0.001) # 0.1% proportional slippage # set_fixed_slippage(0.02) # or fixed 0.02 yuan slippage # Simulate realistic fill constraints set_limit_mode(True) set_volume_ratio(0.25) # Fill at most 25% of minute volume # Store strategy parameters in global object g.ma_short = 5 g.ma_long = 20 g.traded_today = False # Schedule a daily task at 09:30 run_daily(context, morning_task, time='9:30') def morning_task(context): log.info("Pre-market task running at 09:30") ``` -------------------------------- ### Ptrade API Initialization and Order Handling Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example demonstrating how to initialize the Ptrade API with a security universe and handle order responses. It includes placing an initial order and logging subsequent events. ```python def initialize(context): g.security =['600570.SS','002416.SZ'] set_universe(g.security) g.flag =0 ``` ```python def on_order_response(context, order_list): log.info(order_list) if(g.flag==0): order('600570.SS',100) g.flag =1 else: log.info("end") ``` ```python def handle_data(context, data): order('600570.SS',100) ``` -------------------------------- ### Basic Trading Strategy Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md A simple strategy example demonstrating initialization and order placement. Ensure necessary libraries are imported and context is properly set up. ```python def initialize(context): g.security ="600570.SS" set_universe(g.security) def handle_data(context, data): order(g.security,100) log.info(get_orders()) ``` -------------------------------- ### Order Retrieval Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Demonstrates how to place an order and then retrieve a list of all orders. ```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) ``` -------------------------------- ### Example: Query and Log Max Margin Buy Quantity for Repayment Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example of querying the maximum quantity for buying securities to repay margin short sells and logging the result. Handles cases where the result might be None. ```python def initialize(context): g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): security = g.security # 查询恒生电子最大可买券还款数量 marginsec_close_dict = get_marginsec_close_amount(security) if marginsec_close_dict isnotNone: log.info(marginsec_close_dict.get(security)) ``` -------------------------------- ### Profit Ability Data Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade财务数据东莞.md Example demonstrating how to fetch profit ability data, specifically 'roe' (Return on Equity), using a date query mode. ```python publ_date roe secu_abbr end_date 2013-03-31 2013-04-19 2.8127 恒生电子 2014-03-31 2014-04-29 3.3056 恒生电子 2015-03-31 2015-04-25 3.4869 恒生电子 ``` -------------------------------- ### Example: Query Real-time Margin Contract Flow (Python) Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example of retrieving and logging real-time margin contract flow data using the get_margin_contractreal function. ```python def initialize(context): g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): # 获取实时流水 df = get_margin_contractreal() log.info(df) ``` -------------------------------- ### Example: Query and Log Max Margin Short Sell Quantity Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example of querying the maximum quantity for margin short selling and logging the result. Handles cases where the result might be None. ```python def initialize(context): g.security ='600030.SS' set_universe(g.security) def handle_data(context, data): security = g.security # 查询中信证券最大可融券卖出数量 marginsec_open_dict = get_marginsec_open_amount(security) if marginsec_open_dict isnotNone: log.info(marginsec_open_dict.get(security)) ``` -------------------------------- ### Example: Query and Log Max Margin Cash Sell Quantity for Repayment Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example of querying the maximum quantity for selling securities to repay margin cash and logging the result. Handles cases where the result might be None. ```python def initialize(context): g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): security = g.security # 查询恒生电子最大可卖券还款数量 margincash_close_dict = get_margincash_close_amount(security) if margincash_close_dict isnotNone: log.info(margincash_close_dict.get(security)) ``` -------------------------------- ### Example: Query and Log Max Margin Cash Buy Quantity Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example of querying the maximum quantity for margin cash buy and logging the result. Handles cases where the result might be None. ```python def initialize(context): g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): security = g.security # 查询恒生电子最大可融资买入数量 margincash_open_dict = get_margincash_open_amount(security) if margincash_open_dict isnotNone: log.info(margincash_open_dict.get(security)) ``` -------------------------------- ### Example: Fetch ETF Constituents Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Demonstrates how to fetch and log the constituent stocks of an ETF using `get_etf_stock_list`. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def before_trading_start(context, data): #ETF成分券列表 stock_list = get_etf_stock_list('510020.SS') log.info(stock_list) def handle_data(context, data): pass ``` -------------------------------- ### Example: Log Convertible Bond IPO Stocks Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Retrieves and logs the list of convertible bonds available for IPO subscription today. This example specifically filters for '可转债代码' from the IPO stocks. ```python def handle_data(context, data): # 当日可转债IPO申购标的 ipo_stocks = get_ipo_stocks().get('可转债代码') log.info('可转债IPO申购标的列表为%s'% ipo_stocks) ``` -------------------------------- ### Initialize with Create Directory Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Initializes the security and sets the universe, then creates a directory using the security code as the user path. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) create_dir(user_path=g.security) def handle_data(context, data): pass ``` -------------------------------- ### Example: Get and Filter Tradable Convertible Bonds Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Demonstrates fetching the daily convertible bond list, getting their snapshots, and filtering for bonds that are currently tradable. It logs the list of tradable convertible bonds. ```python def initialize(context): g.security ="600570.SS" set_universe(g.security) run_daily(context, get_trade_cb_list,"9:25") def before_trading_start(context, data): # 每日清空,避免取到昨日市场代码表 g.trade_cb_list =[] def handle_data(context, data): pass # 获取当天可交易的可转债代码列表 def get_trade_cb_list(context): cb_list = get_cb_list() cb_snapshot = get_snapshot(cb_list) # 代码有行情快照并且交易状态不在暂停交易、停盘、长期停盘、退市状态的判定为可交易代码 g.trade_cb_list =[cb_code for cb_code in cb_list if cb_snapshot.get(cb_code,{}).get("trade_status")notin [None,"HALT","SUSP","STOPT","DELISTED"]] log.info("当天可交易的可转债代码列表为:%s"% g.trade_cb_list) ``` -------------------------------- ### Initialize and Handle Data with Persistence Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md This example demonstrates initializing a strategy, managing a 'hold_days' dictionary with persistence using pickle, and executing trades based on holding periods. It ensures continuity across strategy restarts. ```python import pickle from collections import defaultdict ''' 持仓N日后卖出,仓龄变量每日pickle进行保存,重启策略后可以保证逻辑连贯 ''' def initialize(context): g.notebook_path = get_research_path() #尝试启动pickle文件 try: with open(g.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 notin list(context.portfolio.positions.keys())and g.security notin 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(g.notebook_path+'hold_days.pkl','wb')as f: pickle.dump(g.hold_days,f,-1) ``` -------------------------------- ### Initialize with Multiple Parameter Settings Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Initializes the strategy and applies multiple configuration parameters using `set_parameters`. This example shows settings for holidays, tick data, response reception, and server restart behavior. ```python def initialize(context): # 初始化策略 g.security ="600570.SS" set_universe(g.security) # 设置非交易日不执行before_trading_start # 设置tick_data中data不包含order和transaction # 设置接收非本交易产生的主推 # 设置接收撤单委托产生的主推 # 设置交易时间段服务器重启不再拉起本交易 # 设置服务器重启重拉交易时不再执行before_trading_start函数 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") # 取消交易时间段服务器重启不再拉起本交易设置 # 取消服务器重启重拉交易时不再执行before_trading_start函数设置 set_parameters(not_restart_trade="0", server_restart_not_do_before="0") def before_trading_start(context, data): log.info("do before_trading_start") # 取消非交易日不执行before_trading_start设置 # 取消tick_data中data不包含order和transaction设置 # 取消接收非本交易产生的主推设置 # 取消接收撤单委托产生的主推设置 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 Historical Industry Data Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Retrieves historical daily closing prices for a specific industry code. This function is called before trading starts. ```python industry_info = get_history(10, frequency="1d", field="close", security_list="A01000.XBHS") log.info(industry_info) ``` -------------------------------- ### Get Trade Days within a Range with get_trade_days Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Retrieve trading days within a specified range using get_trade_days. You can define a start and end date, or specify a count of trading days prior to the end date. The earliest start date is 1990. ```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) ``` -------------------------------- ### initialize(context) Source: https://context7.com/kay-ou/ptradeapi/llms.txt This function is called once at strategy startup. It's used for initial setup, including configuring the stock universe, benchmark, commission, slippage, and scheduling recurring tasks. ```APIDOC ## initialize(context) — One-time strategy setup at startup ### Description Called once when the strategy starts; used to configure the stock universe, benchmark, commission, slippage, and schedule recurring tasks. This is the only place where setting functions like `set_universe`, `set_benchmark`, and `set_commission` may be called. ### Parameters * **context**: The context object containing strategy state and global variables. ### Example ```python def initialize(context): # Set stock universe for the strategy g.security = '600570.SS' set_universe(g.security) # Set performance benchmark (default: CSI 300) set_benchmark('000300.SS') # Configure backtest trading costs set_commission(commission_ratio=0.0003, min_commission=5.0, type="STOCK") set_slippage(0.001) # 0.1% proportional slippage # set_fixed_slippage(0.02) # or fixed 0.02 yuan slippage # Simulate realistic fill constraints set_limit_mode(True) set_volume_ratio(0.25) # Fill at most 25% of minute volume # Store strategy parameters in global object g.ma_short = 5 g.ma_long = 20 g.traded_today = False # Schedule a daily task at 09:30 run_daily(context, morning_task, time='9:30') def morning_task(context): log.info("Pre-market task running at 09:30") ``` ``` -------------------------------- ### Get Fund Flow Data Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Demonstrates how to call `get_fundjour` to retrieve historical fund flow data within the trading context. Requires `start_date` and `end_date`. ```python def initialize(context): g.security = "600570.SS" set_universe(g.security) def before_trading_start(context, data): h = get_fundjour('20210101', '20211117') log.info(h) def handle_data(context, data): pass ``` -------------------------------- ### Example: Fetch ETF Constituent Stock Information Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Shows how to get information for a single or multiple constituent stocks of an ETF. The function requires both the ETF code and the stock code(s). ```python 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) ``` -------------------------------- ### Get Cash Flow Statement Data Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/api-reference/financial-data.md Retrieve data from a company's cash flow statement using the `get_fundamentals` function. This example shows how to query for investment cash paid on a specific date. ```python get_fundamentals(security, 'cashflow_statement', fields, date=None, start_year=None, end_year=None, report_types=None, date_type=None, merge_type=None) ``` ```python # 按日期查询:获取回测日期前对应的投资支付现金数据 get_fundamentals('600570.SS', 'cashflow_statement', 'invest_cash_paid', '20160628') ``` -------------------------------- ### Initialize, Handle Data, and After Trading End in Ptrade Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md This comprehensive example demonstrates initializing a security, handling daily trading data, and performing post-trading logging. It covers the essential lifecycle of a trading strategy. ```python def initialize(context): #g为全局变量 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) ``` -------------------------------- ### Example: Fetch and Log Collateral Security List Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Demonstrates how to retrieve and log the list of collateral securities using get_assure_security_list(). ```python def initialize(context): g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): # 获取最新的担保券列表 assure_security = get_assure_security_list() log.info(assure_security) ``` -------------------------------- ### Get Individual Entrust Data Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Demonstrates how to fetch individual entrust data for the current stock pool, a specified list of stocks, and how to retrieve data in dictionary format. It also shows how to extract 'business_amount' from the returned data. ```python def initialize(context): g.security ="000001.SZ" set_universe(g.security) def before_trading_start(context, data): g.flag =False def handle_data(context, data): ifnot g.flag: # 获取当前股票池逐笔委托数据 entrust = get_individual_entrust() log.info(entrust) # 获取指定股票列表逐笔委托数据 entrust = get_individual_entrust(["000002.SZ","000032.SZ"]) log.info(entrust) # 获取委托量 if entrust isnotNone: business_amount = entrust.query('code in ["000002.SZ"]')["business_amount"] log.info("逐笔数据的委托量为:%s"% business_amount) # 返回字典类型数据 entrust = get_individual_entrust([g.security], is_dict=True) log.info("逐笔委托数据为:%s"% entrust) g.flag =True ``` -------------------------------- ### Get Lucky Info Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Fetches historical lottery (IPO/new stock subscription) information within a specified date range. This function is for the trading module and may return cached data if called multiple times within the same minute. ```python def initialize(context): # 初始化策略 g.security = "600570.SS" set_universe(g.security) def before_trading_start(context, data): pre_date = str(get_trading_day(-1)).replace("-", "") current_date = context.blotter.current_dt.strftime("%Y%m%d") # 获取上一交易日至今天中签信息 lucky_info = get_lucky_info(pre_date, current_date) log.info(lucky_info) def handle_data(context, data): pass ``` -------------------------------- ### Example: Conditional Order Based on User Name Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Initializes security and retrieves the user name. Before trading starts, a flag is reset. During data handling, if the user name matches '123456789' and no order has been placed today, it buys 100 shares and sets the 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): # 账号为123456789且当日未委托过,买入100股 if g.user_name == "123456789" and not g.flag: # 买入100股 order(g.security, 100) g.flag = True ``` -------------------------------- ### Example: Set Initial Position Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Demonstrates setting an initial position for a security ('600570.SS') with specific quantity, available amount, and cost basis. ```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) ``` -------------------------------- ### Basic Trading Strategy Initialization and Handling in Python Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Demonstrates how to initialize a trading strategy by setting a security universe and defining how to handle trade responses. This is a foundational example for strategy development. ```python def initialize(context): g.security =['600570.SS','002416.SZ'] set_universe(g.security) g.flag =0 def on_trade_response(context, trade_list): log.info(trade_list) if(g.flag==0): order('600570.SS',100) g.flag =1 else: log.info("end") def handle_data(context, data): order('600570.SS',100) ``` -------------------------------- ### IPO Stocks Order Result Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example of the return format for the ipo_stocks_order function, showing details of each subscription. ```json {"732116.SS":{"entrust_no":"205001","entrust_status":1,"redemption_amount":1000},"732100.SS":{"entrust_no":"205002","entrust_status":1,"redemption_amount":2000}} ``` -------------------------------- ### Strategy Framework and Setup Functions Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/api-classification.md Functions for defining the basic behavior and parameters of a strategy, including core callbacks, periodic execution, and environment settings. ```APIDOC ## Core Callback Functions ### initialize(context) **Description**: Required strategy initialization function, runs once at startup. ### handle_data(context, data) **Description**: Required main strategy logic function, executes on a daily or minute cycle. ### before_trading_start(context, data) **Description**: Optional pre-trading function, executes before the market opens each day. ### after_trading_end(context, data) **Description**: Optional post-trading function, executes after the market closes each day. ### tick_data(context, data) **Description**: Optional tick-level data processing function, available only in trading environments. ### on_order_response(context, order_list) **Description**: Optional main order response push function, available only in trading environments. ### on_trade_response(context, trade_list) **Description**: Optional main trade response push function, available only in trading environments. ## Periodic Functions ### run_daily(context, func, time) **Description**: Registers a function to run daily at a specified time. ### run_interval(context, func, seconds) **Description**: Registers a function to run at a specified interval in seconds. ## Environment Settings ### set_universe(security_list) **Description**: Sets the security pool for the strategy. ### set_benchmark(security) **Description**: Sets the benchmark for the strategy's performance. ### set_commission(commission_ratio, ...) **Description**: [Backtest] Sets commission rates. ### set_slippage(slippage) **Description**: [Backtest] Sets slippage as a ratio. ### set_fixed_slippage(fixedslippage) **Description**: [Backtest] Sets slippage as a fixed value. ### set_volume_ratio(volume_ratio) **Description**: [Backtest] Sets the volume ratio. ### set_limit_mode(limit_mode) **Description**: [Backtest] Sets the volume limit mode. ### set_yesterday_position(poslist) **Description**: [Backtest] Sets the initial position for backtesting. ### set_parameters(**kwargs) **Description**: [Trading] Sets specific behavior parameters for strategy execution. ``` -------------------------------- ### Get Bid/Ask Price Levels Source: https://context7.com/kay-ou/ptradeapi/llms.txt Retrieves full bid/ask price levels for specified securities. Use this to get real-time market depth. ```python def tick_data(context, data): gear = get_gear_price([g.security]) stock_gear = gear[g.security] bid_levels = stock_gear['bid_grp'] # list of {px, volume} ask_levels = stock_gear['offer_grp'] best_bid = bid_levels[0]['px'] best_ask = ask_levels[0]['px'] log.info("Best bid=%.3f ask=%.3f" % (best_bid, best_ask)) ``` -------------------------------- ### IPO Subscription Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Demonstrates how to subscribe to various types of IPO stocks using the ipo_stocks_order function with different market types. Includes a delay between each subscription. ```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 ``` -------------------------------- ### Debt Paying Ability Data Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade财务数据山西.md An example of the data structure returned for debt paying ability, including current ratio and publication date. ```text current_ratio publ_date secu_abbr end_date 2013-03-313.42342013-04-19恒生电子 2014-03-313.49412014-04-29恒生电子 2015-03-311.83322015-04-25恒生电子 ``` -------------------------------- ### Profitability Data Example Output Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade财务数据国盛.md Example output format for profitability financial data, showing return on equity (ROE), publication date, and security abbreviation. ```python publ_date roe secu_abbr end_date 2013-03-31 2013-04-19 2.8127 恒生电子 2014-03-31 2014-04-29 3.3056 恒生电子 2015-03-31 2015-04-25 3.4869 恒生电子 ``` -------------------------------- ### Initialize and Handle Data for ETF Components Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade国盛.md Initializes the security and sets the universe, then retrieves and logs ETF component information for single and multiple securities. ```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) ``` -------------------------------- ### Example: Query Margin Contracts (Python) Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Example of querying margin contracts and logging the resulting DataFrame. This function is available in the PTrade client's margin trading module. ```python def initialize(context): g.security ='600570.SS' set_universe(g.security) def handle_data(context, data): # 获取最新合约 df = get_margin_contract() log.info(df) ``` -------------------------------- ### Example: Set Initial Position from CSV Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Initializes security and then sets the yesterday's position using data loaded from a CSV file named 'Poslist.csv'. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) # 设置底仓 poslist= convert_position_from_csv("Poslist.csv") set_yesterday_position(poslist) def handle_data(context, data): # 卖出100股 order(g.security, -100) ``` -------------------------------- ### Example: Fetch Industry Stocks Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Demonstrates fetching stocks for a specific industry (e.g., agriculture) and setting them as the trading universe. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def before_trading_start(context, data): # 获取农业的股票, 设为股票池 stocks = get_industry_stocks('A01000.XBHS') set_universe(stocks) log.info(stocks) def handle_data(context, data): pass ``` -------------------------------- ### Initialize Backtest Environment Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Sets up the security and commission rates for backtesting. This function is typically called once at the beginning of a backtest. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) #将佣金费率设置为万分之三,将最低手续费设置为3元 set_commission(commission_ratio =0.0003, min_commission=3.0) def handle_data(context, data): pass ``` -------------------------------- ### Initialize and Handle Data with Security Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade东莞.md Initializes the security and sets the universe, then logs stock exrights information in the handle_data function. This is a common pattern for setting up and processing data in trading strategies. ```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)) ``` -------------------------------- ### After-Hours Order Cancellation Example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md Example demonstrating placing and then canceling an after-hours fixed price order. It uses run_daily to schedule the order and cancellation, with a 5-second delay between them. Includes a fallback in handle_data. ```python import time def initialize(context): g.security = "300001.SZ" set_universe(g.security) # 15:00-15:30期间使用run_daily进行盘后固定价委托、盘后固定价委托撤单 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: order_id = after_trading_order(g.security, 200, float(last_px)) time.sleep(5) after_trading_cancel_order(order_id) 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: order_id = after_trading_order(g.security, 200, float(last_px)) time.sleep(5) after_trading_cancel_order(order_id) g.flag = True ``` -------------------------------- ### Get ETF Information Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade山西.md Retrieves information for a single ETF or multiple ETFs. Use this function to get details like redemption code, IOPV publication status, report unit, and NAV. ```python get_etf_info('510020.SS') ``` ```python get_etf_info(['510020.SS','510050.SS']) ``` -------------------------------- ### Python dict data format example Source: https://github.com/kay-ou/ptradeapi/blob/main/docs/original/Ptrade社区.md An example of the dictionary format for transaction data, showing a stock code as the key and a list of transaction records as the value. Includes the 'fields' key describing the data columns. ```python {'600000.SS': [ [20250604133155710, 12.39, 600, 13838613, 1, 8654820, 8621141, 0, 0, 5], [20250604133155710, 12.39, 100, 13838614, 1, 8654820, 8622338, 0, 0, 5], [20250604133155710, 12.39, 200, 13838615, 1, 8654820, 8622921, 0, 0, 5], [20250604133155710, 12.39, 100, 13838616, 1, 8654820, 8623362, 0, 0, 5], [20250604133155830, 12.38, 100, 13838727, 0, 8484333, 8654902, 0, 0, 5], [20250604133155960, 12.38, 700, 13838864, 0, 8484333, 8654996, 0, 0, 5], [20250604133156200, 12.38, 900, 13839091, 0, 8484333, 8655131, 0, 0, 5], [20250604133158870, 12.38, 1100, 13841629, 0, 8484333, 8656738, 0, 0, 5], [20250604133200400, 12.39, 400, 13843209, 1, 8657686, 8623484, 0, 0, 5], [20250604133200400, 12.39, 100, 13843210, 1, 8657686, 8624349, 0, 0, 5], [20250604133200400, 12.39, 300, 13843211, 1, 8657686, 8624401, 0, 0, 5] ], 'fields': ['business_time', 'hq_px', 'business_amount', 'trade_index', 'business_direction', 'buy_no', 'sell_no', 'trans_flag', 'trans_identify_am', 'channel_num']} # 默认 search_direction =1, start = 0, 返回的数据list里最后一个是最新的一个逐笔 ```