### Backtesting Setup Guide on how to set up and initiate a backtest for a trading strategy. This includes defining parameters such as start and end times, capital, benchmark, and frequency. ```APIDOC ## Create New Backtest After creating a strategy, you can start the backtesting process. Before backtesting, you need to set the start time, end time, backtest capital, backtest benchmark, and backtest frequency. After completing the settings, click save. Then, click the backtest button, and the system will start running the backtest. The evaluation metrics, profit and loss curve, and logs will be displayed on the interface. ``` -------------------------------- ### Python: Pre-Trading Start Logic - ptrade The `before_trading_start` function in ptrade is optional and runs once daily before the trading session begins. It's used for any pre-market data initialization or setup. The function receives `context` and `data` objects. Be cautious with real-time data calls within this function before the market opens. ```python def initialize(context): #g为全局变量 g.security = '600570.SS' set_universe(g.security) def before_trading_start(context, data): log.info(g.security) def handle_data(context, data): order('600570.SS',100) ``` -------------------------------- ### Trading Setup Instructions for setting up and initiating a live trade. This covers selecting a strategy, naming the trading session, and monitoring its progress. ```APIDOC ## Create New Trade In the trading interface, click the 'Add' button to add a new trade. The strategy object in the strategy plan refers to the strategies in the strategy list. After setting a name for this trade and clicking confirm, the system will start running the trade. Once the trade starts running, you can view the total assets and available funds in real-time. You can also check the trade status in the trade list. After the trade starts running, you can click on the trade details to view the strategy evaluation metrics, trade details, position details, and trade logs. ``` -------------------------------- ### Python: Initialize Strategy - ptrade The `initialize` function is mandatory for ptrade strategies and is executed once at the beginning of backtesting or trading. It's used to set up global variables and define the initial trading universe. Dependencies include the `context` object and various setup interfaces like `set_universe`. ```python def initialize(context): #g为全局对象 g.security = '600570.SS' set_universe(g.security) ``` -------------------------------- ### Python: Example of Handling Non-Serializable Objects with Persistence This Python example demonstrates how to manage non-serializable objects within a persistent trading strategy. It defines a 'Test' class with a method that modifies a count. In 'initialize', a private global variable '__test_class' is created to hold an instance of 'Test'. This ensures that the object is not persisted, preventing errors, while its methods can still be called in 'handle_data'. ```python class Test(object): count = 5 def print_info(self): self.count += 1 log.info("a" * self.count) def initialize(context): g.security = "600570.SS" set_universe(g.security) # 初始化无法被序列化类对象,并赋值为私有变量,落地持久化信息时跳过保存该变量 g.__test_class = Test() def handle_data(context, data): # 调用私有变量中定义的方法 g.__test_class.print_info() ``` -------------------------------- ### Get Gear Price Retrieves the gear market price for specified stock codes. This provides real-time quote snapshot information. ```APIDOC ## GET /websites/59_53_49_216_hub_help_api/get_gear_price ### Description This interface is used to retrieve the gear market price for specified stock codes. It is available only in the trading module. ### Method GET ### Endpoint /websites/59_53_49_216_hub_help_api/get_gear_price ### Parameters #### Query Parameters - **sids** (str/list[str]) - Required - The stock code(s) for which to retrieve gear price information. ### Response #### Success Response (200) - **dict** - A dictionary containing bid and offer group information. - **bid_grp** (dict) - Bid group information. - **offer_grp** (dict) - Offer group information. *Note: If the real-time quote snapshot fails, an empty dictionary `{"bid_grp": {}, "offer_grp": {}}` will be returned. If L2 quotes are unavailable, the entrustment number field will return 0.* #### Response Example ```json { "bid_grp": { "10.00": 100, "9.99": 200 }, "offer_grp": { "10.01": 150, "10.02": 250 } } ``` ``` -------------------------------- ### Python: Initialize and Handle Data for a Basic Strategy This Python snippet demonstrates the basic structure of a trading strategy. It includes the 'initialize' function to set up the trading universe and the 'handle_data' function, which is called for each data point to execute trading logic. The 'set_universe' function is used to define the securities the strategy will operate on. ```python def initialize(context): set_universe('600570.SS') def handle_data(context, data): pass ``` -------------------------------- ### 策略初始化函数 策略初始化函数,用于设置策略的基本参数和环境。这是策略运行的入口,所有策略都必须包含此函数。 ```python def initialize(context): # 初始化代码 ``` -------------------------------- ### Get ETF Information Retrieves detailed information for a specified ETF or a list of ETFs. This includes redemption codes, publication status, and various financial metrics. ```APIDOC ## GET /websites/59_53_49_216_hub_help_api/get_etf_info ### Description This interface is used to retrieve information for one or multiple ETFs. It is only available on the Ptrade client and within the stock trading module. ### Method GET ### Endpoint /websites/59_53_49_216_hub_help_api/get_etf_info ### Parameters #### Query Parameters - **etf_code** (str/list[str]) - Required - A single ETF code or a list of ETF codes. ### Response #### Success Response (200) - **dict[str:dict]** - A dictionary where keys are ETF codes and values are dictionaries containing ETF information. - **etf_redemption_code** (str) - Redemption code. - **publish** (int) - Indicates if IOPV needs to be published (1 for yes, 0 for no). - **report_unit** (int) - Minimum subscription and redemption unit. - **cash_balance** (float) - Cash difference. - **max_cash_ratio** (float) - Maximum cash alternative ratio. - **pre_cash_componet** (float) - T-1 day's subscription benchmark unit cash balance. - **nav_percu** (float) - T-1 day's subscription benchmark unit Net Asset Value (NAV). - **nav_pre** (float) - T-1 day's fund unit NAV. - **allot_max** (float) - Subscription limit. - **redeem_max** (float) - Redemption limit. #### Response Example ```json { "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_componet": 598.39, "allot_max": 0.0, "publish": 1 } } ``` ``` -------------------------------- ### get_margincash_stocks - Get list of marginable cash stocks Retrieves the latest list of securities eligible for margin financing from the Shanghai and Shenzhen stock exchanges. Available for Ptrade clients. ```APIDOC ## GET /api/margincash/stocks ### Description Fetches the most recent list of eligible securities for margin financing. This function is specific to Ptrade clients and the margin trading module. ### Method GET ### Endpoint /api/margincash/stocks ### Parameters None ### Response #### Success Response (200) - **list** (array) - An array of strings, where each string is a stock code eligible for margin financing. #### Response Example ```json [ "600570.SS", "000001.SZ" ] ``` ``` -------------------------------- ### 股票按市价进行委托API 以当前市价立即进行股票买卖委托。适用于需要快速成交的场景。 ```python order_market(security, quantity) ``` -------------------------------- ### Get Stock Ranking Information Retrieves ranking information for stocks or industries based on specified criteria. This includes details such as price changes, trading volume, and leading stocks. ```APIDOC ## GET /websites/59_53_49_216_hub_help_api/sort_data ### Description Returns a list of dictionaries containing ranking information for stocks and industries, including their price change and other market data. ### Method GET ### Endpoint /websites/59_53_49_216_hub_help_api/sort_data ### Parameters #### Query Parameters - **sort_type_grp** (str) - Optional - The group type for sorting (e.g., 'XBHS.DY'). - **sort_field_name** (str) - Optional - The field to sort by (e.g., 'preclose_px'). - **sort_type** (int) - Optional - The type of sorting (1 for ascending, other values may apply). - **data_count** (int) - Optional - The number of data entries to retrieve. ### Response #### Success Response (200) - **list[dict]** - A list of dictionaries, where each dictionary contains detailed information about a stock or industry's market performance. - **prod_code** (str) - Stock or industry code. - **prod_name** (str) - Stock or industry name. - **hq_type_code** (str) - Market type code. - **time_stamp** (int) - Millisecond timestamp. - **trade_mins** (int) - Trading minutes. - **trade_status** (str) - Trading status. - **preclose_px** (float) - Previous day's closing price. - **open_px** (float) - Today's opening price. - **last_px** (float) - Latest price. - **high_px** (float) - Highest price. - **low_px** (float) - Lowest price. - **wavg_px** (float) - Weighted average price. - **business_amount** (int) - Total trading volume. - **business_balance** (int) - Total trading turnover. - **px_change** (float) - Price change. - **amplitude** (int) - Amplitude. - **px_change_rate** (float) - Percentage change in price. - **circulation_amount** (int) - Circulating shares. - **total_shares** (int) - Total shares. - **market_value** (int) - Market value. - **circulation_value** (int) - Circulating market value. - **vol_ratio** (float) - Volume ratio. - **shares_per_hand** (int) - Shares per lot. - **rise_count** (int) - Number of rising stocks. - **fall_count** (int) - Number of falling stocks. - **member_count** (int) - Number of members. - **rise_first_grp** (list[dict]) - Leading rising stocks (list of dictionaries, each with prod_code, prod_name, hq_type_code, last_px, px_change_rate). - **fall_first_grp** (list[dict]) - Leading falling stocks (list of dictionaries, each with prod_code, prod_name, hq_type_code, last_px, px_change_rate). #### Response Example ```json [ { "prod_code": "000001.SZ", "prod_name": "平安银行", "hq_type_code": "RB", "time_stamp": 1678886400000, "trade_mins": 240, "trade_status": "-", "preclose_px": 10.50, "open_px": 10.60, "last_px": 10.70, "high_px": 10.80, "low_px": 10.45, "wavg_px": 10.65, "business_amount": 50000000, "business_balance": 532500000, "px_change": 0.20, "amplitude": 3, "px_change_rate": 1.90, "circulation_amount": 1000000000, "total_shares": 1500000000, "market_value": 16050000000, "circulation_value": 10700000000, "vol_ratio": 1.2, "shares_per_hand": 100, "rise_count": 100, "fall_count": 50, "member_count": 200, "rise_first_grp": [ { "prod_code": "000002.SZ", "prod_name": "万科A", "hq_type_code": "RB", "last_px": 15.00, "px_change_rate": 5.00 } ], "fall_first_grp": [ { "prod_code": "600519.SH", "prod_name": "贵州茅台", "hq_type_code": "RB", "last_px": 1800.00, "px_change_rate": -2.00 } ] } ] ``` -------------------------------- ### 期货开多API 执行期货的多头开仓交易。 ```python buy_open(instrument, quantity, price) ``` -------------------------------- ### get_marginsec_stocks - Get list of marginable securities for short selling Retrieves the latest list of securities eligible for short selling from the Shanghai and Shenzhen stock exchanges. Available for Ptrade clients. ```APIDOC ## GET /api/marginsec/stocks ### Description Fetches the most recent list of eligible securities for short selling. This function is specific to Ptrade clients and the margin trading module. ### Method GET ### Endpoint /api/marginsec/stocks ### Parameters None ### Response #### Success Response (200) - **list** (array) - An array of strings, where each string is a stock code eligible for short selling. #### Response Example ```json [ "600570.SS", "000001.SZ" ] ``` ``` -------------------------------- ### 债转股委托API 执行债转股的交易委托。 ```python debt_to_stock_order(security, quantity, price) ``` -------------------------------- ### Get ETF Constituent Securities Information Retrieves information about the constituent securities of a specified ETF. This includes details like the number of components, cash replacement flags, and trading status. ```APIDOC ## GET /websites/59_53_49_216_hub_help_api/get_etf_stock_info ### Description This interface is used to retrieve information about the constituent securities of an ETF. It is only available on the Ptrade client and within the stock trading module. ### Method GET ### Endpoint /websites/59_53_49_216_hub_help_api/get_etf_stock_info ### Parameters #### Query Parameters - **etf_code** (str) - Required - The code of the ETF. - **security** (str/list[str]) - Required - The code of a single stock or a list of stock codes. ### Response #### Success Response (200) - **dict[str:dict]** - A dictionary where keys are ETF codes and values are dictionaries containing constituent security information. - **code_num** (float) - Number of constituent securities. - **cash_replace_flag** (str) - Cash replacement flag: - '0': No replacement allowed. - '1': Replacement allowed. - '2': Must be replaced. - '3': Non-Shanghai stock, refund cash alternative. - '4': Non-Shanghai stock, must use cash alternative. - '5': Non-Shanghai/Shenzhen stock, refund cash alternative. - '6': Non-Shanghai/Shenzhen stock, must use cash alternative. - **replace_ratio** (float) - Margin ratio (premium ratio), valid for cash-substitutable securities. - **replace_balance** (float) - Replacement amount, valid for securities that must use cash alternative. - **is_open** (int) - Trading status flag (0: suspended, 1: active). #### Response Example ```json { "600000.SS": { "cash_replace_flag": "1", "replace_ratio": 0.1, "is_open": 1, "code_num": 4700.0, "replace_balance": 0.0 } } ``` ``` -------------------------------- ### Strategy API - Setting Functions Details on functions used to configure strategy parameters, including setting stock pools, benchmarks, commissions, slippage, and position limits. ```APIDOC ## Strategy API Introduction - Setting Functions ### `set_universe(stock_pool)` - **Description**: Sets the stock universe (pool of stocks) for the strategy. - **Parameters**: - `stock_pool` (list or string) - Required - A list of stock codes or a predefined stock pool name. ### `set_benchmark(benchmark_stock)` - **Description**: Sets the benchmark for performance comparison. - **Parameters**: - `benchmark_stock` (string) - Required - The stock code to be used as the benchmark. ### `set_commission(rate, auto_adjust=False, commission_type='')` - **Description**: Sets the commission rate for trades. - **Parameters**: - `rate` (float) - Required - The commission rate (e.g., 0.001 for 0.1%). - `auto_adjust` (bool) - Optional - Whether to automatically adjust commission for different trade types. - `commission_type` (string) - Optional - Specifies the type of commission (e.g., 'buy', 'sell'). ### `set_fixed_slippage(amount)` - **Description**: Sets a fixed slippage amount for trades. - **Parameters**: - `amount` (float) - Required - The fixed slippage amount. ### `set_slippage(slippage_model)` - **Description**: Sets a dynamic slippage model for trades. - **Parameters**: - `slippage_model` (object) - Required - An object defining the slippage model. ### `set_volume_ratio(ratio)` - **Description**: Sets the volume ratio for trades, limiting the trade size relative to market volume. - **Parameters**: - `ratio` (float) - Required - The volume ratio (e.g., 0.1 for 10%). ### `set_limit_mode(mode)` - **Description**: Sets the backtest transaction quantity limitation mode. - **Parameters**: - `mode` (string) - Required - The mode for limiting transaction quantity. ### `set_yesterday_position(stock_codes)` - **Description**: Sets the initial position (stocks) for the start of the backtest based on yesterday's holdings. - **Parameters**: - `stock_codes` (dict) - Required - A dictionary where keys are stock codes and values are the quantities to hold. ``` -------------------------------- ### Python: Persistent Strategy for Holding Days Tracking with Pickle This Python code implements a trading strategy that tracks the holding days of a security and uses pickling for persistence. The 'initialize' function attempts to load holding days data from a pickle file; otherwise, it initializes a defaultdict. 'before_trading_start' increments the holding day count for the security. 'handle_data' places buy orders if the security is not held, sells if holding days exceed 5, and persistently saves the holding days data using pickle. ```python import pickle from collections import defaultdict NOTEBOOK_PATH = '/home/fly/notebook/' # 持仓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) ``` -------------------------------- ### GET /websites/59_53_49_216_hub_help_api Retrieves historical stock market data based on specified parameters. Supports fetching data for single or multiple securities, with options for frequency, fields, and data复权 (data adjustment). ```APIDOC ## GET /websites/59_53_49_216_hub_help_api ### Description Retrieves historical stock market data with various customization options. ### Method GET ### Endpoint /websites/59_53_49_216_hub_help_api ### Parameters #### Query Parameters - **count** (int) - Required - Number of historical K-lines to return (greater than 0). - **frequency** (str) - Optional - K-line period. Supported values: '1m', '5m', '15m', '30m', '60m', '120m', '1d', '1w', 'weekly', 'mo', 'monthly', '1q', 'quarter', '1y', 'yearly'. Defaults to '1d'. - **field** (list[str] or str) - Optional - Specifies the market data fields to include in the result. Defaults to ['open','high','low','close','volume','money','price']. Available fields: 'open', 'high', 'low', 'close', 'volume', 'money', 'price', 'preclose' (daily only), 'high_limit' (daily only), 'low_limit' (daily only), 'unlimited' (daily only). - **security_list** (list[str] or str) - Optional - List of stock codes to fetch data for. If None, uses all stocks selected in the context's universe. Defaults to None. - **fq** (str) - Optional - Data adjustment option. Supported values: 'pre' (pre-adjustment), 'post' (post-adjustment), 'dypre' (dynamic pre-adjustment), None (no adjustment). Defaults to None. - **include** (bool) - Optional - Whether to include the current period. Defaults to False. - **fill** (str) - Optional - How to fill missing minute data. 'pre' to use the previous minute's data, 'nan' to use NaN. Defaults to 'nan'. ### Request Example (No request body for GET requests. Parameters are passed as query parameters) ### Response #### Success Response (200) - **Data**: The structure of the returned data depends on the `security_list` and `field` parameters: - **Single security, single/multiple fields**: Returns a pandas.DataFrame with datetime index and market fields as columns. - **Multiple securities, single field**: Returns a pandas.DataFrame with datetime index and security codes as columns. - **Multiple securities, multiple fields**: Returns a pandas.Panel object where items are market fields, and each item contains a DataFrame with datetime index and security codes as columns. #### Response Example **Example for single security, single field:** ```json { "data": { "2017-04-11": {"open": 40.30}, "2017-04-12": {"open": 40.08}, "2017-04-13": {"open": 40.03}, "2017-04-14": {"open": 40.04}, "2017-04-17": {"open": 39.90} } } ``` **Example for multiple securities, single field:** ```json { "data": { "2017-04-11": {"600570.SS": 40.30, "600571.SS": 17.81}, "2017-04-12": {"600570.SS": 40.08, "600571.SS": 17.56}, "2017-04-13": {"600570.SS": 40.03, "600571.SS": 17.42}, "2017-04-14": {"600570.SS": 40.04, "600571.SS": 17.40}, "2017-04-17": {"600570.SS": 39.90, "600571.SS": 17.49} } } ``` ``` -------------------------------- ### 股票指定持仓市值买卖API 将股票持仓调整到指定的市值。如果当前持仓市值不等于目标市值,则会发出市价委托来达到目标市值。 ```python order_target_value(security, target_value) ``` -------------------------------- ### Get Marginable Cash Stocks List (Ptrade Client) Retrieves a list of securities eligible for margin financing from the Shanghai and Shenzhen stock exchanges. This function requires no parameters and returns a list of stock codes. It is only 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): # 获取最新的融资标的列表 margincash_stocks = get_margincash_stocks() log.info(margincash_stocks) ``` -------------------------------- ### 直接还券API 直接归还融券欠券。 ```python marginsec_direct_refund(security, quantity) ``` -------------------------------- ### Python: Implement a Practical Strategy with Moving Average Crossover This Python code implements a practical trading strategy based on a 5-day moving average. It uses 'get_history' to fetch historical closing prices, calculates the average price, and compares the current price to the average. It then places buy orders using 'order_value' if the current price is 1% above the average, or sell orders using 'order_target' if the current price is below the average and the security is held. ```python def initialize(context): g.security = '600570.SS' set_universe(g.security) def handle_data(context, data): security = g.security sid = g.security # 取得过去五天的历史价格 df = get_history(5, '1d', 'close', security, fq=None, include=False) # 取得过去五天的平均价格 average_price = round(df['close'][-5:].mean(), 3) # 取得上一时间点价格 current_price = data[sid]['close'] # 取得当前的现金 cash = context.portfolio.cash # 如果上一时间点价格高出五天平均价1%, 则全仓买入 if current_price > 1.01*average_price: # 用所有 cash 买入股票 order_value(g.security, cash) log.info('buy %s' % g.security) # 如果上一时间点价格低于五天平均价, 则空仓卖出 elif current_price < average_price and get_position(security).amount > 0: # 卖出所有股票,使这只股票的最终持有量为0 order_target(g.security, 0) log.info('sell %s' % g.security) ``` -------------------------------- ### Get Marginable Securities List (Ptrade Client) Retrieves a list of securities eligible for short selling on margin from the Shanghai and Shenzhen stock exchanges. This function requires no parameters and returns a list of stock codes. It is exclusively 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): # 获取最新的融券标的列表 marginsec_stocks = get_marginsec_stocks() log.info(marginsec_stocks) ``` -------------------------------- ### Get Market Ranking Information with get_sort_msg Retrieves market ranking information for sectors or industries, such as stock price changes. It returns a list of dictionaries, each containing details about a specific financial instrument. This function is useful for identifying top-performing or lagging assets within a specified market segment. Dependencies include the 'set_universe' and 'log' functions. ```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) ``` -------------------------------- ### 获取对账数据文件API 获取交易对账单数据文件,用于核对交易记录。 ```python get_trades_file(start_date, end_date) ``` -------------------------------- ### Get ETF Information with get_etf_info Fetches information for one or multiple ETFs. It returns a dictionary where keys are ETF codes and values are dictionaries containing ETF details like redemption code, publication status, minimum subscription/redemption units, and net asset value. This function is exclusive to the Ptrade client and the stock trading module. Input can be a single ETF code or a list of codes. ```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) ``` -------------------------------- ### 盘后固定价委托API 在收盘后以指定价格进行股票委托。适用于盘后交易。 ```python after_trading_order(security, quantity, price) ``` -------------------------------- ### Get ETF Constituent Securities with get_etf_stock_info Retrieves information about the constituent stocks of a specific ETF. It returns a dictionary keyed by ETF code, with values containing details for each component security, such as the number of constituents, cash replacement flags, replacement ratios, and trading status (open/suspended). This function is available only on the Ptrade client within the stock trading module. Both ETF code and security code(s) are required parameters. ```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) ``` -------------------------------- ### 设置底仓(股票)API 在策略开始运行时设置初始持仓,支持股票等品种。用于模拟已有仓位的情况。 ```python set_yesterday_position(positions) ``` -------------------------------- ### 买券还券API 通过买入证券来偿还融券欠券。 ```python marginsec_close(security, quantity, price) ``` -------------------------------- ### Get Level Quote Price with get_gear_price Fetches the level quote price for specified stock codes, including bid and offer groups. This function is available in the trading module. It handles real-time quote snapshots and returns empty dictionaries for bid/offer groups if the snapshot fails. If Level 2 data is unavailable, the number of委托笔 (order entries) will be reported as 0. Input can be a single stock code or a list of codes. ```python get_gear_price(sids) ``` -------------------------------- ### 股票指定目标数量买卖API 将股票持仓调整到指定的数量。如果当前持仓不等于目标数量,则会发出市价委托来达到目标数量。 ```python order_target(security, target_quantity) ``` -------------------------------- ### 新股一键申购API 对指定股票进行一键申购操作。简化新股申购流程。 ```python ipo_stocks_order(security, quantity) ``` -------------------------------- ### 获取行业成份股API 获取指定行业下的股票代码列表。 ```python get_industry_stocks(industry_code) ``` -------------------------------- ### 设置基准API 设置策略的回测基准,用于衡量策略的相对表现。通常选择一个市场指数作为基准。 ```python set_benchmark(benchmark_stock) ``` -------------------------------- ### 期货多平API 执行期货的多头平仓交易。 ```text ``` -------------------------------- ### 获取行情快照API 获取指定证券的实时行情快照,包括最新价、涨跌幅、成交量等关键信息。 ```python get_snapshot(securities) ``` -------------------------------- ### Python: Add Basic Order Functionality to a Strategy This Python code extends a basic trading strategy by adding order placement functionality. The 'initialize' function sets a global security and a flag to control order execution. The 'handle_data' function checks the flag and places a buy order for a specified quantity of the security if the flag is false, then sets the flag to true to prevent further orders. ```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 ``` -------------------------------- ### 融资买入API 执行融资买入操作,即借入资金购买证券。 ```python margincash_open(security, quantity, price) ``` -------------------------------- ### 获取市场列表API 获取系统支持的市场列表,例如A股、港股等。用于了解可交易的市场。 ```python get_market_list() ``` -------------------------------- ### 直接还款API 直接使用现金偿还融资欠款。 ```python margincash_direct_refund(amount) ``` -------------------------------- ### 获取融资标的API 查询当前可用于融资的证券标的列表。 ```python get_margincash_stocks() ``` -------------------------------- ### 设置股票池API 设置策略的股票池,指定哪些股票将被纳入策略的分析和交易范围。此函数对于定义策略的投资标的至关重要。 ```python set_universe(stocks) ``` -------------------------------- ### 按设定周期处理函数 定义一个函数,该函数将按照设定的时间间隔(例如,每分钟、每5分钟)被调用,用于执行更频繁的策略逻辑。 ```python run_interval(callback, interval_seconds) ``` -------------------------------- ### 股票指定目标价值买卖API 根据指定的金额(价值)买入或卖出股票。可用于制定固定金额的交易指令。 ```python order_value(security, target_value) ``` -------------------------------- ### 设置固定滑点API 设置固定的滑点,用于模拟交易执行价格与订单申报价格之间的差异。 ```python set_fixed_slippage(slippage_value) ``` -------------------------------- ### 融券卖出API 执行融券卖出操作,即借入证券卖出。 ```python marginsec_open(security, quantity, price) ``` -------------------------------- ### 获取融券标的API 查询当前可用于融券的证券标的列表。 ```python get_marginsec_stocks() ``` -------------------------------- ### 获取逐笔委托行情API 获取指定证券在指定时间段内的逐笔委托(买卖盘)行情数据。 ```python get_individual_entrust(security, start_time, end_time) ``` -------------------------------- ### 设置回测成交数量限制模式API 设置回测时成交数量的限制模式,例如限制为订单数量的百分比。 ```python set_limit_mode(mode) ``` -------------------------------- ### POST /ipo_stocks_order One-click subscription for all new stocks of the day. Allows specifying market type and a blacklist of stocks to exclude. ```APIDOC ## POST /ipo_stocks_order ### Description This interface is used for one-click subscription of all new stocks on the current day. ### Method POST ### Endpoint /ipo_stocks_order ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **market_type** (int) - Optional - The market to which the subscription code belongs. Defaults to subscribing to all new stocks if not provided. * 0: Shanghai Stock Exchange ordinary code * 1: Shanghai Stock Exchange STAR Market code * 2: Shenzhen Stock Exchange ordinary code * 3: Shenzhen Stock Exchange ChiNext code * 4: Convertible bond code - **black_stocks** (str/list) - Optional - Blacklist of stocks. Stocks in the blacklist will not be subscribed. Defaults to subscribing to all new stocks if not provided. Stock codes can be 6 digits (without suffix) or with a suffix (e.g., '787001' or '787001.SS'). ### Request Example ```python import time def handle_data(context, data): if not g.flag: # Subscribe to Shanghai Stock Exchange ordinary code log.info("Subscribing to Shanghai Stock Exchange ordinary code:") ipo_stocks_order(market_type=0) time.sleep(5) # Subscribe to Shanghai Stock Exchange STAR Market code log.info("Subscribing to Shanghai Stock Exchange STAR Market code:") ipo_stocks_order(market_type=1) time.sleep(5) # Subscribe to Shenzhen Stock Exchange ordinary code log.info("Subscribing to Shenzhen Stock Exchange ordinary code:") ipo_stocks_order(market_type=2) time.sleep(5) # Subscribe to Shenzhen Stock Exchange ChiNext code log.info("Subscribing to Shenzhen Stock Exchange ChiNext code:") ipo_stocks_order(market_type=3) time.sleep(5) # Subscribe to convertible bond code log.info("Subscribing to convertible bond code:") ipo_stocks_order(market_type=4) time.sleep(5) g.flag = True ``` ### Response #### Success Response (200) - A dictionary containing order codes, order numbers, order status (0 for failure, 1 for success), and order quantities. (dict[str:dict[str:str,str:int,str:float],...]) #### Response Example ```json { "order_results": { "600570.SS": { "order_id": "123456789", "status": 1, "quantity": 1000, "price": 10.50 } } } ``` ``` -------------------------------- ### 设置策略配置参数API 允许用户自定义策略的配置参数,这些参数可以在策略运行中被调整,用于参数优化或动态调整策略逻辑。 ```python set_parameters(**params) ``` -------------------------------- ### 获取逐笔成交行情API 获取指定证券在指定时间段内的逐笔成交行情数据。 ```python get_individual_transcation(security, start_time, end_time) ``` -------------------------------- ### 股票按数量买卖API 根据指定的数量买入或卖出股票。可用于制定固定数量的交易指令。 ```python order(security, quantity) ``` -------------------------------- ### 获取指数成份股API 获取指定指数的成份股列表及其权重。 ```python get_index_stocks(index_code) ``` -------------------------------- ### 获取未完成订单API 查询当前所有未成交的订单列表。 ```python get_open_orders() ``` -------------------------------- ### 卖券还款API 通过卖出持有的证券来偿还融资欠款。 ```python margincash_close(security, quantity, price) ``` -------------------------------- ### Strategy Creation Instructions on how to create a new trading strategy within the platform. This involves selecting a business type, naming the strategy, and writing the code based on provided templates. ```APIDOC ## Create New Strategy Before starting backtesting and trading, you need to create a new strategy. Click the icon in the upper left corner of the image to add a strategy. You can choose different business types (e.g., stocks) and set a name for the strategy. After successful addition, you can start writing your strategy based on the default strategy template. ``` -------------------------------- ### 设置滑点API 设置根据交易量或其他因素动态调整的滑点模型,更精确地模拟滑点影响。 ```python set_slippage(slippage_model) ```