### SuperMind 1-Minute Quick Live Trading Tutorial Source: https://quant.10jqka.com.cn/view/help/14/index A step-by-step guide for users to quickly set up and run live trading using the SuperMind platform. It covers downloading the client, logging in, accessing the research environment, and configuring the trading API with account details. The tutorial also directs users to resources for template strategies. ```APIDOC ## SuperMind 1-Minute Quick Live Trading Tutorial ### Prerequisites 1. **Download Client:** Ensure you have downloaded and updated the SuperMind client to the latest version. A trial version is available for simulated live trading. 2. **Login:** Use your TongHuiShun (同花顺) account to log in. ### Setup Steps 1. **Open Research Environment:** Click the "Research" (研究一下) button to open the web-based research environment. Copy the provided research file directly into the root directory of the environment. It is recommended to select the Python 3.8 environment if prompted. 2. **Access Client Environment:** Open the research environment within the client application. You should see the copied file and can proceed with execution. ### Live Trading Execution 1. **Obtain Funding Account:** Navigate to the client's homepage to get your funding account number. 2. **Configure `TradeAPI`:** Update the first parameter of the `TradeAPI` initialization with your strategy's corresponding funding account number. 3. **Start Strategy:** Select the code cell containing your strategy and click the "▶" (Play) button to start the strategy. **Template Strategy:** Find template strategies at the bottom of the linked post: [https://quant.10jqka.com.cn/view/article/2358](https://quant.10jqka.com.cn/view/article/2358) **Note:** Clicking "Research" (研究一下) will copy the relevant file to your research environment's root directory. ``` -------------------------------- ### Python Factor Analysis Setup and Configuration Source: https://quant.10jqka.com.cn/view/help/14/index This Python code defines a `FactorAnalyse` class to set up parameters for factor analysis and backtesting. It includes configurations for backtesting dates, benchmark indices, stock pools, quantiles, rebalancing periods and frequency, factor names, factor composition (direction and weight), and data processing options (fillna, winsorize, neutralize, standardize). ```python import alphalens import pandas as pd import numpy as np import time import statsmodels.api as sm import scipy as sp class FactorAnalyse(object): #==========================================因子检测参数设置============================================================== start_date = '2021-05-22' #回测开始时间 end_date = '2021-06-21' #回测结束时间 benchindex = '000300.SH' #基准指数设置 stockpool = '000905.SH' #股票池设置 quantiles=3 #因子分组数量 periods=1 #调仓周期 frequency='daily' #调仓频率'daily','weekly','monthly'一周按5个交易日计算,一月按21个交易日计算 #==========================================添加因子============================================================== #添加因子名称,保持list形式,系统因子对应字段参照 http://quant.10jqka.com.cn/platform/html/help-api.html?t=data#222/436 factor_input=['weighted_roe'] #==========================================因子合成参数设置============================================================== # 因子合成参数 #direct表示因子方向,weight表示因子权重 #因子方向:一共有两种1和-1。1表示正序,从小到大排列,因子值越大的股票会分组至前几组;-1表示倒序,效果反之 factor_set={"weighted_roe":{"direct":1,"weight":1}} #==========================================因子数据处理参数设置============================================================== #对应的因子数据处理选项 #缺失值处理 fillna:0—不处理,1—均值法,2—回归填充法 #极值处理 winsorize:0—不处理,1—中位数法,2—三倍标准差,3—四分位 #正交化处理 neutralize:0—不处理,1—申万一级正交化,2—市值正交化,3—申万行业市值正交化 #标准化处理 standardize:0—不处理,1—标准化法,2—rank值标准化,3—极差正规化 factor_dp={"weighted_roe":{"fillna":0,"winsorize":0,"neutralize":0,"standardize":0}} #==========================================合成因子数据处理参数设置============================================================== #合成因子数据处理选项 dataprcess={"fillna":0,"winsorize":0,"neutralize":0,"standardize":0} ``` -------------------------------- ### Place Limit Price Order Source: https://quant.10jqka.com.cn/view/help/14/index This Python code example shows how to place a limit price order using the trade_api. It allows specifying a desired price for the transaction, in addition to the symbol, amount, and side. This provides more control over the execution price compared to market orders. ```python trade_api.order(symbol='000001.SZ', amount=100, price=10, side=SIDE.BUY) # 限价单 ``` -------------------------------- ### Basket Trading Setup and Order Placement (Python) Source: https://quant.10jqka.com.cn/view/help/14/index Demonstrates how to use the NEW_BASKET API to group multiple orders together for simultaneous execution. Orders are added to the basket using the add method, specifying symbol, amount, and an algorithmic API (like NEW_RECHASE). The basket.order method then places the combined trades, with an option to specify the balance to be used. ```python basket_api = trade_api.NEW_BASKET() rechase_api = trade_api.NEW_RECHASE(reprice=None, spread=0, entrustcnt=3, revoke=True, timeout=60) basket_api.add(symbol='000001.SZ', amount=100, algo_api=rechase_api) basket_api.add(symbol='000001.SZ', amount=100, algo_api=rechase_api) basket_api.add(symbol='000001.SZ', amount=100, algo_api=rechase_api) basket_api.order(balance=1000) ``` -------------------------------- ### Deploy Backtest Code to Live Trading (1-Minute Setup) Source: https://quant.10jqka.com.cn/view/help/14/index This section details the groundbreaking feature that allows users to deploy their existing backtest code directly into live trading with minimal effort. It explains the background, purpose, and the streamlined process, emphasizing the reduction in time and complexity for users transitioning from backtesting to live execution. New APIs that facilitate live trading are also highlighted. ```APIDOC ## Deploy Backtest Code to Live Trading (1-Minute Setup) ### Background and Purpose Previously, deploying backtested strategies to live trading involved familiarizing oneself with live trading APIs, writing new code, and extensive debugging, often taking 1-2 weeks. This new feature significantly reduces that time, allowing users to use their backtest code directly for live trading, lowering the barrier to entry for beginners. ### Process 1. **Utilize Existing Backtest Code:** Leverage your tested backtesting strategies. 2. **Simplified Transition:** The `research_trade` function enables direct deployment. ### `research_trade` Function Example ```python from tick_trade_api import TradeAPI, LimitPolicy # Initialize TradeAPI with account ID and order policy (e.g., LimitPolicy for limit orders) trade_api = TradeAPI('YOUR_ACCOUNT_ID', order_policy=LimitPolicy) source_code = """ # Example Stock Strategy Template def init(context): pass def before_trading(context): pass def handle_bar(context, bar_dict): # Example order placement and management order_id = order('000001.SZ', 100) print(get_orders()) try: cancel_order(order_id) except Exception as e: print(f'Cancel order failed: {e}') print(get_open_orders()) print(get_tradelogs()) print(context.portfolio.stock_account) print(context.portfolio.positions) """ rtrade = research_trade( 'Research Environment Strategy', source_code, frequency='MINUTE', trade_api=trade_api, signal_mode=False, recover_dt='today' ) ``` **Note:** The account ID in `TradeAPI('YOUR_ACCOUNT_ID', ...)` can be a simulated or live trading account ID. ### Additional Updates **Strategy Framework Enhancements:** * `cancel_order_all()`: Cancel all open orders. * `get_tradelogs()`: Retrieve all executed orders for the current day. * `get_orders()`: Get pending orders (consistent with `TradeAPI` function names). **`TradeAPI` Enhancements:** * `get_open_orders()`: Retrieve pending orders for the current day. * `cancel_order_all()`: Cancel all open orders. ``` -------------------------------- ### Python Real-time Trading Strategy using run_daily Source: https://quant.10jqka.com.cn/view/help/14/index This Python example demonstrates implementing a trading strategy that executes at a specific frequency using the 'run_daily' function. It initializes the TradeAPI and defines a 'test_day' function to be executed. The 'run_daily' function is configured to trigger 'test_day' every second ('every_bar') for a reference security, suitable for high-frequency trading scenarios. ```python from tick_trade_api import TradeAPI #初始化TradeAPI时需要指定下单策略,MarketPolicy为最新价下单;LimitPolicy为限价下单 trade_api=TradeAPI('69271711',order_policy=LimitPolicy) source_code=""" # tick股票策略模版 def init(context): # 每个交易日开盘每秒执行一次 run_daily(func=test_day, time_rule='every_bar', reference_security='300033.SZ') def test_day(context, bar_dict): log.info('定时运行') """ rtrade = research_trade( '研究环境策略rundaily', source_code, frequency='TICK', trade_api=trade_api, signal_mode=False, recover_dt='today' ) ``` -------------------------------- ### Auto-Chasing Order Setup and Execution (Python) Source: https://quant.10jqka.com.cn/view/help/14/index Configures and uses the NEW_RECHASE API for automatically chasing orders. This involves setting parameters like reprice, spread, and entrust count. The order method is then used to place trades with specified symbol, amount, and price. An optional repricetype parameter can be used for advanced price control. ```python rechase_api = trade_api.NEW_RECHASE(reprice=82, spread=0.15, entrustcnt=3, revoke=True, timeout=5) rechase_api.order('601012.SH',amount=100, price=79) ``` ```python rechase_api = trade_api.NEW_RECHASE(reprice=0.01, spread=0.15, entrustcnt=3, revoke=True, timeout=5, repricetype=10) rechase_api.order('601012.SH', amount=200, price=79) ``` -------------------------------- ### Python Real-time Trading Strategy using handle_tick Source: https://quant.10jqka.com.cn/view/help/14/index This Python example showcases how to implement a tick-level trading strategy using the 'handle_tick' function within the research environment. It initializes the TradeAPI with a specified order policy and subscribes to market data for a given security. The 'handle_tick' function is triggered upon receiving tick data updates, allowing for high-frequency trading decisions. ```python from tick_trade_api import TradeAPI #初始化TradeAPI时需要指定下单策略,MarketPolicy为最新价下单;LimitPolicy为限价下单 trade_api=TradeAPI('69271711',order_policy=LimitPolicy) source_code=""" # tick股票策略模版 def init(context): #设定标的代码 context.symbol = ['300033.SZ'] subscribe(context.symbol) # 开盘时运行函数 def handle_tick(context, tick): log.info('定时运行') """ rtrade = research_trade( '研究环境策略handletick', source_code, frequency='TICK', trade_api=trade_api, signal_mode=False, recover_dt='today' ) ``` -------------------------------- ### TWAP Algorithm Order Execution (Python) Source: https://quant.10jqka.com.cn/view/help/14/index Implements the Time-Weighted Average Price (TWAP) trading algorithm using the NEW_TWAP API. This allows for orders to be broken down and executed over a specified time period with configurable intervals for placing and revising orders. Parameters include start and end times, order and re-chase intervals, and minimum/maximum order sizes. Optional randprice allows for price fluctuation. ```python twap_api = trade_api.NEW_TWAP(start_time='09:30', end_time='15:00', order_interval=60, rechase_interval=30, min_order_number=100, max_order_number=10000,randprice=1) twap_api.order(symbol='000001.SZ', amount=100, price=0.01,pricetype=3) ``` -------------------------------- ### Iceberg Algorithm Order Execution (Python) Source: https://quant.10jqka.com.cn/view/help/14/index Implements the Iceberg algorithm for trading using the NEW_ICEBERG API. This strategy breaks down large orders into smaller child orders, revealing only a portion of the total quantity at a time. Parameters control the start and end times, the percentage of the order to reveal per child order, and the re-chase interval. Various entrustment types and conditions (like entrusttraderatio and entrusttimeout) can be specified. ```python iceberg_api = trade_api.NEW_ICEBERG(start_time='09:30', end_time='15:00', order_percent=0.05, rechase_interval=30) iceberg_api.order(symbol='000001.SZ', amount=100) ``` -------------------------------- ### Python Custom Factor Generation Function Source: https://quant.10jqka.com.cn/view/help/14/index This Python function `factor_gen` within the `FactorAnalyse` class allows users to define their custom factor calculation logic. It accepts start date, end date, and an optional list of stocks. The function is expected to return a Pandas DataFrame where columns represent dates and the index represents stock codes. The example fetches 'trix' factor data. ```python #用户自定义因子算法 #用户可在此函数下编译因子计算方式,返回的结果需为DataFrame,列名(columns)为时间,行名(index)为股票代码 def factor_gen(self, start_date, end_date,stocks=None): stocks=stocks or self.get_stocks() #此行代码用于更新因子时获取股票代码,请勿更改 factor_df = get_sfactor_data(start_date, end_date, stocks, ['trix']) #样例数据,可获取行情数据及财务数据构建新的因子 return factor_df['trix'] ``` -------------------------------- ### Get Stock Pool - Python Source: https://quant.10jqka.com.cn/view/help/14/index Retrieves a list of stock codes based on the specified stock pool. If the stock pool is 'stock', it fetches all securities; otherwise, it gets stocks from a specified index. This function is useful for defining the universe for trading strategies. ```python def get_stocks(self): if self.stockpool=='stock': self.stocks=list(get_all_securities('stock',self.start_date).index) else: self.stocks = get_index_stocks(self.stockpool, self.start_date) ``` -------------------------------- ### Research Environment and Live Trading Overview Source: https://quant.10jqka.com.cn/view/help/14/index Introduction to the SuperMind research environment, its foundation on Jupyter Notebook/Lab, and its support for live trading. It highlights the benefits of using JupyterLab for enhanced IDE features and file format support. The section also provides crucial preliminary information for live trading, such as variable pickling, API rate limits, and trading restrictions during settlement times. ```APIDOC ## Supermind Research Environment and Live Trading ### Description SuperMind provides a powerful research environment based on Jupyter Notebook (Python 3.5) and JupyterLab (Python 3.8). This environment supports real-time code, mathematical equations, and Markdown, making it suitable for data exploration, statistical modeling, and machine learning. JupyterLab offers a comprehensive IDE experience with support for various file formats including code files (.py, .ipynb), CSV, JSON, Markdown, and PDF. The platform seamlessly integrates live trading capabilities, allowing users to deploy their strategies directly from the research environment. This section outlines the essential prerequisites and considerations for live trading, including: * **Global Variables:** Ensure variables are pickle-able (e.g., lists, dictionaries). * **API Rate Limits:** Be mindful of potential frequency limitations on brokerage APIs for positions, funds, and orders; reduce usage frequency in code. * **Settlement Time:** From 22:05 to 22:15 daily, backend settlement occurs, during which new orders are not accepted, and trading instructions cannot be processed. ### Key Features * **Jupyter Notebook/Lab:** A familiar and robust environment for quantitative analysis. * **Live Trading Integration:** Deploy and manage trading strategies directly. * **Community Support:** Access to forums and email for assistance. ### Community Contact * **Official Community Forum:** Post questions and share insights. * **Email Support:** SuperMind@myhexin.com ``` -------------------------------- ### Differences Between Simulation/Live Trading and Backtesting Source: https://quant.10jqka.com.cn/view/help/14/index This section addresses common issues encountered when transitioning from backtesting to live or simulated trading. It details the key differences between backtesting and live trading environments, such as initial holdings, order execution timing, position data, and handling of out-of-strategy trades, and provides potential solutions for these discrepancies. ```APIDOC ## Differences Between Simulation/Live Trading and Backtesting This section outlines common issues encountered in live trading compared to backtesting and provides solutions. ### Backtesting (Simulation) vs. Counter (Simulation, Live) Environment Differences | Feature | Backtesting (Simulation) | Counter (Simulation, Live) | | :---------------- | :------------------------------------------- | :--------------------------------------------- | | Initial Holdings | Generally none | May have initial holdings | | Order Execution | Usually immediate | Not immediate; depends on price and market | | Position Days | `position_days` may be available | `position_days` is often 0 | | Trades | Only within strategy | Trades outside strategy can affect strategy | | Order Cancellation| Rare scenario | Should be considered | | Report Delay | No delay | Reports may have delay | | Paused Data | Can be backfilled (`skip_paused=False`) | Cannot be backfilled for paused stocks | ### Potential Issues and Solutions #### Issue 1: Initial Holdings in Funding Account * **Problem:** Live accounts often have initial holdings, unlike backtesting environments. This can cause conflicts if the strategy relies on internal tracking of holdings and assumes no initial positions. * **Example Case:** Strategies that record bought stocks in a dictionary (`context.information`). If the account has initial holdings, attempting to delete these from the dictionary when selling can lead to errors if they weren't recorded as part of the strategy's buys. * **User-Side Solutions:** * Initialize `context.information` with existing holdings. * Avoid external trading outside the strategy. * Use `dict.pop()` instead of `del` for safer dictionary key removal. * **Long-Term Solution (SuperMind Feature):** Asset unit construction per strategy to isolate funds, holdings, orders, and trades (expected July-August). #### Issue 2: Orders Not Immediately Executed in Live Trading * **Problem:** In backtesting, orders are often executed immediately within the strategy's execution flow. In live trading, order confirmation and execution are asynchronous, leading to potential data discrepancies if the strategy assumes immediate execution and updates internal records. * **Example Case:** A strategy that places orders and immediately updates an internal record (`g.information`) based on current positions. If the order hasn't executed yet, the `g.information` might be inaccurate, leading to errors when subsequent logic relies on it. ```python import time def init(context): g.information = {} g.symbols = ['000001.SZ','600519.SH'] def handle_bar(context): for symbol in g.symbols: order(symbol, 100) # Place order # Immediately try to update based on current positions, which might not reflect the new order yet for symbol in list(context.portfolio.positions): g.information[symbol] = 1 time.sleep(3) # Simulate delay # Later logic might fail if g.information was incorrectly populated earlier for symbol in list(context.portfolio.positions): print(g.information[symbol]) ``` * **User-Side Solutions:** * Refactor holding information logic. Consider updating records after market close based on confirmed positions and trades. * Use `dict.get()` for safer dictionary value retrieval. * **Long-Term Solution (SuperMind Feature):** Implement events for trade confirmations and order status updates (planned before end of June). ``` -------------------------------- ### Initialize TradeAPI Account Source: https://quant.10jqka.com.cn/view/help/14/index Imports the TradeAPI library and initializes the API with a given account ID. This is the first step before performing any trading operations. ```python from tick_trade_api.api import TradeAPI trade_api = TradeAPI(account_id='84728199') #填入已登录的资金账号 ``` -------------------------------- ### Margin Trading API Initialization (Python) Source: https://quant.10jqka.com.cn/view/help/14/index Initializes the TradeCredit API for margin trading operations. It requires importing the TradeCredit class and the SIDE enum from the tick_trade_api.api module. An account ID must be provided to establish the connection. ```python from tick_trade_api.api import TradeCredit as TradeAPI, SIDE trade_api = TradeAPI(account_id='18771019820') ``` -------------------------------- ### Order Placement and Cancellation Source: https://quant.10jqka.com.cn/view/help/14/index Details on how to place various types of orders (market, limit, intelligent) and how to cancel them. ```APIDOC ## Order Placement and Cancellation ### Description Details on how to place various types of orders (market, limit, intelligent) and how to cancel them. ### Market Price Order To place a sell order, set `amount` to a negative value. Upon successful order placement, an order ID ('order_id') will be returned, which can be used for cancellation. ```python trade_api.order(symbol='300033.SZ', amount=100) ``` ### Limit Price Order To place a sell order, set `amount` to a negative value. Upon successful order placement, an order ID ('order_id') will be returned, which can be used for cancellation. ```python trade_api.order(symbol='000001.SZ', amount=100, price=13.4) ``` ### Intelligent Order Placement Intelligent orders allow for more diverse trading needs by specifying `pricetype`. | `pricetype` | Meaning | `pricetype` | Meaning | |-------------|---------------|-------------|---------------| | 0 | Limit Price | 1 | Upper Limit Price | | 2 | Lower Limit Price| 3 | Market Price | | 4 | Bid 1 Price | 5 | Bid 2 Price | | 6 | Bid 3 Price | 7 | Bid 4 Price | | 8 | Bid 5 Price | 9 | Ask 1 Price | | 10 | Ask 2 Price | 11 | Ask 3 Price | | 12 | Ask 4 Price | 13 | Ask 5 Price | | 17 | Market Price | 21 | Hitch Price | - When `pricetype` is 0, the order is placed at the specified `price`. - When `pricetype` is 1-13, `price` represents a floating price relative to the `pricetype` specified. The final order price is `pricetype` + `price`. If the final price exceeds the upper or lower limit price, it will be capped at the respective limit. - When `pricetype` is 17 (Market Price), the meaning of `price` differs for Shanghai and Shenzhen markets: - Shanghai: 1-5 ticks immediate or cancel, 2-5 ticks immediate or transfer to limit, 3-Best bid, 4-Best offer. - Shenzhen: 1-Best offer, 2-Best bid, 3-Immediate or cancel, 4-5 ticks immediate or cancel, 5-Full fill or kill. - When `pricetype` is 21 (Hitch Price), buy orders will be placed at the upper bound of the price band, and sell orders will be placed at the lower bound. **Example:** Place a buy order for 100 shares of 002109.SZ at Bid 5 price plus 0.3 yuan. ```python trade_api.order(symbol='002109.SZ', amount=100, price=0.3, pricetype=8) ``` ### Cancel Order Cancel a specific unfilled order by providing its order ID. ```python trade_api.cancel_order('11591') ``` If the order has already been executed or canceled, an error will be raised. This can be handled using try-except blocks: ```python try: trade_api.cancel_order('11591') except Exception as e: print(f"Order cancellation failed: {e}") ``` ### Cancel All Orders ```python trade_api.cancel_order_all() ``` ``` -------------------------------- ### Query Account Portfolio Source: https://quant.10jqka.com.cn/view/help/14/index Retrieves and prints the user's account portfolio, including available cash, market value, and total value. This provides a summary of the account's financial status. ```python portfolio = trade_api.portfolio print(portfolio) ``` -------------------------------- ### VWAP Algorithm Order Execution (Python) Source: https://quant.10jqka.com.cn/view/help/14/index Utilizes the Volume-Weighted Average Price (VWAP) trading algorithm via the NEW_VWAP API. This strategy aims to execute trades close to the average price based on volume over a specified period. Key parameters include start and end times, order intervals, minimum and maximum order quantities, order cycle (k-line interval), and sample days for calculation. It can place orders at the latest price. ```python vwap_api = trade_api.NEW_VWAP(start_time='09:30', end_time='15:00', order_interval=60, rechase_interval=30, min_order_number=100, max_order_number=10000, ordercycle=1, sampledays=30) vwap_api.order(symbol='000001.SZ', amount=100) ``` -------------------------------- ### Order Placement API Source: https://quant.10jqka.com.cn/view/help/14/index This section covers functions for placing orders in the market. It includes placing orders at the latest market price and at a specified limit price. ```APIDOC ## Order Placement API ### Description Provides functions to place buy or sell orders in the market. Orders can be placed at the current market price or at a specific limit price. ### Method POST (Implicit for function calls) ### Endpoints - `trade_api.order(...)` ### Parameters #### Request Body Parameters - **symbol** (string) - Required - The trading symbol of the stock (e.g., '000001.SZ'). - **amount** (integer) - Required - The quantity of shares to trade. - **side** (enum) - Required - The type of order. Accepted values are: `SIDE.BUY`, `SIDE.SALE`, `SIDE.FINANCE_BUY`, `SIDE.STOCK_SALE`, `SIDE.PURCHASE`, `SIDE.REDEEM`, `SIDE.SALE_REPAY`, `SIDE.BUY_REPAY`, `SIDE.STOCK_REPAY_TRANSFER`, `SIDE.STOCK_LEFT_TRANSFER`. - **price** (float) - Optional - The limit price for the order. Required for limit price orders. ### Request Example ```python # Market price order (buy using collateral) trade_api.order(symbol='000001.SZ', amount=100, side=SIDE.BUY) # Market price order (buy using financing) trade_api.order(symbol='000001.SZ', amount=100, side=SIDE.FINANCE_BUY) # Market price order (sell using collateral) trade_api.order(symbol='000001.SZ', amount=100, side=SIDE.SALE) # Market price order (sell using stock shorting) trade_api.order(symbol='000001.SZ', amount=100, side=SIDE.STOCK_SALE) # Limit price order (buy using collateral) trade_api.order(symbol='000001.SZ', amount=100, price=10.50, side=SIDE.BUY) ``` ### Response #### Success Response (200) - The response typically indicates the success or failure of the order placement and may include an order ID. #### Response Example ```json { "order_id": "123456789", "status": "success" } ``` ``` -------------------------------- ### Query Trade Records Source: https://quant.10jqka.com.cn/view/help/14/index Instructions on how to query executed trade records and set up push notifications for order status updates. ```APIDOC ## Query Trade Records ### Description Instructions on how to query executed trade records and set up push notifications for order status updates. ### Query Order Records from SuperMind Backend Order results can be queried using the `trade_api.get_orders` function. These records are also visible in the intelligent trading terminal. **Method:** `trade_api.get_orders(order_id=None, start_time=None, end_time=None, symbol=None)` **Parameters:** - `order_id` (string): The order ID to query. - `start_time` (string): The start time for historical queries (e.g., 'YYYY-MM-DD HH:MM:SS'). - `end_time` (string): The end time for historical queries (e.g., 'YYYY-MM-DD HH:MM:SS'). - `symbol` (string): The security code to filter orders by. **Note:** By default, this function queries all orders for the current day. ### Order Execution Push Callback By registering the following callback function, you can receive active push notifications for order execution status whenever an order is placed. ```python def order_push(order): print("Received order push: ", order) trade_api.register_push(orderpush=order_push) ``` ``` -------------------------------- ### Initialize TradeAPI with Reconnection Source: https://quant.10jqka.com.cn/view/help/14/index Initializes the TradeAPI with parameters to handle potential disconnections and automatically retry connection. This ensures strategy continuity during network interruptions. ```python trade_api = TradeAPI(account_id='84728199', retry_query_exception=6, delay_query_exception=10)#设置每隔10秒尝试重连,尝试6次 ``` -------------------------------- ### Register Order Push Callback Source: https://quant.10jqka.com.cn/view/help/14/index Sets up a callback function to receive real-time notifications for order executions and updates. This allows for immediate feedback on trade status without active polling. ```python def order_push(order): print("接收到订单推送: ", order) trade_api.register_push(orderpush=order_push) ``` -------------------------------- ### Place Market Price Orders Source: https://quant.10jqka.com.cn/view/help/14/index This Python code illustrates how to place market price orders for various trading scenarios using the trade_api. It covers buying and selling for collateral, financing purchases, and securities lending. The `SIDE` enum is used to specify the transaction type. Ensure correct symbol, amount, and side are provided. ```python trade_api.order(symbol='000001.SZ', amount=100, side=SIDE.BUY) # 最新价下单,担保品买入 trade_api.order(symbol='000001.SZ', amount=100, side=SIDE.FINANCE_BUY) # 最新价下单,融资买入 trade_api.order(symbol='000001.SZ', amount=100, side=SIDE.SALE) # 最新价下单,担保品卖出 trade_api.order(symbol='000001.SZ', amount=100, side=SIDE.STOCK_SALE) # 最新价下单,融券卖出 ``` -------------------------------- ### Query Account Assets and Orders Source: https://quant.10jqka.com.cn/view/help/14/index This Python code snippet demonstrates how to query various account asset and order-related information using the trade_api. This includes portfolio details, positions, trade logs, open orders, secondary market orders, and available stock offerings. The outputs provide a comprehensive view of the user's financial status and trading activities. ```python print("账号信息:", trade_api.portfolio) print("持仓信息:", trade_api.positions) print("成交信息:", trade_api.get_tradelogs()) print("委托信息:", trade_api.get_orders()) # 可传入order_id查询指定委托信息 print("柜台委托信息:", trade_api.secondary_orders()) print("可融资标的券:", trade_api.get_stocks()) ``` -------------------------------- ### Place Smart Order with Pricetype Source: https://quant.10jqka.com.cn/view/help/14/index Executes an order using various pricing types beyond simple market or limit orders. This allows for flexible order placement based on real-time market conditions or predefined strategies. ```python #以卖五价上浮0.3元挂100股002109的买单 trade_api.order(symbol='002109.SZ', amount=100, price=0.3, pricetype=8) ``` -------------------------------- ### Python Factor Analysis Data Preparation and Calculation Source: https://quant.10jqka.com.cn/view/help/14/index This Python method `calc` within the `FactorAnalyse` class handles the data preparation and initial processing for factor analysis. It logs the backtesting period, fetches market price data, determines trade days based on the specified frequency and period, retrieves industry classification data, and obtains the specified factor data. ```python #==========================================因子检测前进行数据准备及数据处理======================================================== def calc(self): log.info("回测区间: %s / %s" % (self.start_date, self.end_date)) log.info("开始时间: %s " % time.strftime("%H:%M:%S")) if self.frequency=='daily': period=self.periods elif self.frequency=='weekly': period=self.periods*5 elif self.frequency=='monthly': period=self.periods*21 # 获取股票池 self.get_stocks() # 价格数据price_df log.info("正在获取行情数据......: %s " % time.strftime("%H:%M:%S")) price_df = get_price(self.stocks, self.start_date, self.end_date, str(period) + 'd', ['close'], bar_count=0, skip_paused=False, fq='pre', is_panel=1)['close'] days = get_trade_days(self.start_date, self.end_date) day_index=pd.Index((days[min(i+period-1, len(days)-1)] for i in range(0, len(days), period))) price_df=price_df.loc[day_index,:] log.info("行情数据提取完成: %s " % time.strftime("%H:%M:%S")) #==========================================获取行业分类============================================================== # 获取行业分类哑变量,行业分类数据groupby log.info("正在获取行业分类数据......: %s " % time.strftime("%H:%M:%S")) industry_data, ind_dict = get_sfactor_industry(self.start_date, self.end_date, self.stocks, industry='s_industryid1') log.info("行业分类数据提取完毕: %s " % time.strftime("%H:%M:%S")) # ==========================================根据参数选择生成因子========================================================== # 获取因子数据 log.info("正在获取因子数据......: %s " % time.strftime("%H:%M:%S")) factor_df = get_sfactor_data(self.start_date, self.end_date, self.stocks, self.factor_input) log.info("获取因子数据完毕: %s 因子名称: %s" % (time.strftime("%H:%M:%S"), self.factor_input)) #==========================================因子合成========================================================= factors = factor_df[self.factor_input[0]].copy() factors.iloc[:, :] = 0 for ia in self.factor_input: factors = factors + self.factor_set[ia]['direct'] * self.factor_set[ia]['weight'] * factor_df[ia] log.info("因子数据合成完成: %s " % time.strftime("%H:%M:%S")) #==========================================根据用户自定义因子算法生成因子========================================================= # factors = self.factor_gen(self.start_date, self.end_date,self.stocks) ``` -------------------------------- ### Account Information Inquiry Source: https://quant.10jqka.com.cn/view/help/14/index This section details how to query account information, including available cash, market value, and transfer history. ```APIDOC ## Account Information Inquiry ### Description This section details how to query account information, including available cash, market value, and transfer history. ### Initialize TradeAPI ```python from tick_trade_api.api import TradeAPI trade_api = TradeAPI(account_id='84728199') # Replace with your logged-in fund account ID ``` ### Query Account Funds ```python portfolio = trade_api.portfolio print(portfolio) ``` **Output:** ```json { "available_cash": 10350203.22, "market_value": 1168, "total_value": 10351371.22, "frozen_cash": 0 } ``` **Field Descriptions:** - `available_cash` (float): Available cash balance. - `market_value` (float): Market value of securities. - `frozen_cash` (float): Frozen cash balance. - `total_value` (float): Total account value. ### Query Fund Transfer Records ```python transfer = trade_api.get_transfers(start_date=None, end_date=None) print(transfer) ``` **Output:** ```json { "transfer_id": "20241213003359", "transfer_type": "转入", "transfer_status": "", "cash": 100000.0, "bank_name": "存管招商人民币", "currency": "人民币", "total_cash": 0.0, "datetime": "2024-12-13 09:51:09" } ``` **Field Descriptions:** - `transfer_id` (string): Transfer record ID. - `transfer_type` (string): Type of transfer (e.g., deposit, withdrawal). - `transfer_status` (string): Status of the transfer. - `cash` (float): Amount transferred. - `bank_name` (string): Name of the bank. - `currency` (string): Currency of the transfer. - `datetime` (string): Timestamp of the transfer. ### Query Holdings Information ```python positions = trade_api.positions print(positions) ``` **Output:** A dictionary where keys are security codes and values are Namedict objects containing security information. ```json { "000001.SZ": { "symbol": "000001.SZ", "name": "平安银行", "amount": 100, "frozen_amount": 100, "available_amount": 0, "market_value": 1164, "cost_basis": 11.644, "last_price": 11.64, "pnl": -0.37, "profit_rate": -0.0003 } } ``` **Field Descriptions:** - `name` (string): Security name. - `available_amount` (integer): Available quantity of the security. - `cost_basis` (float): Cost basis of the security. - `last_price` (float): Last traded price. - `amount` (integer): Total quantity of the security held. - `profit_rate` (float): Profit rate. - `frozen_amount` (integer): Frozen quantity of the security. - `market_value` (float): Market value of the security. - `symbol` (string): Security code. - `pnl` (float): Profit and loss amount. ### Convert Holdings to DataFrame ```python import pandas as pd positions_df = pd.DataFrame() for symbol, info in positions.items(): temp = pd.DataFrame([[info[vb] for vb in ['symbol', 'name', 'amount', 'available_amount', 'frozen_amount', 'cost_basis', 'last_price', 'market_value', 'pnl', 'profit_rate']]], columns=['symbol', 'name', 'amount', 'available_amount', 'frozen_amount', 'cost_basis', 'last_price', 'market_value', 'pnl', 'profit_rate'], index=[0]) positions_df = pd.concat([positions_df, temp], ignore_index=True) print(positions_df) ``` ``` -------------------------------- ### Python实盘交易持仓信息记录延迟问题示例 Source: https://quant.10jqka.com.cn/view/help/14/index 此Python代码示例演示了在实盘交易中,由于订单撮合与策略执行不同步可能导致持仓信息记录延迟或错误。代码尝试在下单后记录持仓信息,但由于实盘中委托不会立即成交,可能导致信息丢失或出错。解决方案包括优化持仓记录逻辑或使用`dict.get()`。 ```python import time def init(context): g.information = {} g.symbols = ['000001.SZ','600519.SH'] def handle_bar(context): for symbol in g.symbols: order(symbol,100) for symbol in list(context.portfolio.positions): g.information[symbol] = 1 time.sleep(3) for symbol in list(context.portfolio.positions): print(g.infomation[symbol]) ``` -------------------------------- ### Python Strategy with Position Days Logic Source: https://quant.10jqka.com.cn/view/help/14/index This Python code demonstrates a trading strategy that aims to sell stocks after holding them for a specific number of days. It initializes with a list of symbols and a status flag. The 'handle_bar' function attempts to calculate 'positions_days' and sell if held for more than 5 days. This logic fails in simulation/live trading due to the absence of 'positions_days' data from the broker. ```python from datetime import timedelta as td def init(context): g.symbols = ['000001.SZ','600519.SH'] g.status = True def handle_bar(context): if g.status: for symbol in g.symbols: order(symbol,100) g.status = False else: for k,v in context.portfolio.positions: trade_days = get_datetime() - td(v.positions_days) tdays = len(get_trade_days( trade_days.strftime('%Y%m%d'), get_datetime().strftime('%Y%m%d') )) if tdays>5: order_target(k,0) ``` -------------------------------- ### Strategy Backtesting with research_strategy Source: https://quant.10jqka.com.cn/view/help/14/index Conducts backtesting for a trading strategy. It takes the strategy's source code, date range, initial capital, frequency, market type, and benchmark as input. The function returns a result object containing analysis data like portfolio and trades. ```python research_strategy( source_code, start_date=None, end_date=None, capital_base=100000, frequency='DAILY', stock_market='STOCK', benchmark=None ) ``` ```python source_code=r""" # 股票策略模版 def init(context): pass ## 开盘时运行函数 def handle_bar(context, bar_dict): order('000001.SZ', 100) """ btest = research_strategy(source_code, start_date='20210601', end_date='20210815', capital_base=float(10000000), frequency='DAILY', stock_market='STOCK', benchmark=None) btest['analyser']['portfolio']#查询历史持仓 btest['analyser']['trades']#查询交易明细 ``` -------------------------------- ### Account Asset and Order Queries Source: https://quant.10jqka.com.cn/view/help/14/index This section details functions for querying account-related information such as portfolio, positions, trade logs, and orders. It also includes functions for querying secondary orders and available stocks for financing. ```APIDOC ## Account Asset and Order Queries ### Description Provides functions to retrieve various account-related data including portfolio details, current positions, executed trades, pending orders, counterparty orders, and available stocks for financing. ### Method GET (Implicit for property access and function calls) ### Endpoints - `trade_api.portfolio` - `trade_api.positions` - `trade_api.get_tradelogs()` - `trade_api.get_orders()` - `trade_api.secondary_orders()` - `trade_api.get_stocks()` ### Parameters #### Query Parameters - `order_id` (string) - Optional - Used with `trade_api.get_orders()` to query a specific order. ### Request Example ```python # Get account information print("Account Info:", trade_api.portfolio) print("Position Info:", trade_api.positions) # Get order and trade logs print("Trade Logs:", trade_api.get_tradelogs()) print("Order Info:", trade_api.get_orders()) print("Counterparty Order Info:", trade_api.secondary_orders()) # Get available stocks for financing print("Stocks for Financing:", trade_api.get_stocks()) ``` ### Response #### Success Response (200) - `portfolio` (object) - Contains account summary fields like `available_cash`, `market_value`, `total_value`, `frozen_cash`, `finance_debt`, `stock_debt`, `total_debt`, `net_assets`, `finance_available`, `available_margin`. - `positions` (list) - List of current stock positions. - `get_tradelogs()` (list) - List of executed trades. - `get_orders()` (list) - List of pending orders. - `secondary_orders()` (list) - List of counterparty orders. - `get_stocks()` (list) - List of stocks available for financing. #### Response Example ```json { "portfolio": { "available_cash": 100000.00, "market_value": 500000.00, "total_value": 600000.00, "frozen_cash": 10000.00, "finance_debt": 50000.00, "stock_debt": 0.00, "total_debt": 50000.00, "net_assets": 550000.00, "finance_available": 200000.00, "available_margin": 100000.00 } } ``` ``` -------------------------------- ### Query Stock Positions Source: https://quant.10jqka.com.cn/view/help/14/index Retrieves and prints the user's current stock holdings. The output is a dictionary where keys are stock symbols and values are Namedict objects containing detailed information about each holding. ```python positions= trade_api.positions print(positions) ```