### Example of Research Trade with Live API and Specific Recovery Source: https://quant.10jqka.com.cn/view/help/10/index This example demonstrates initializing a TradeAPI object with a specific account and order policy, then using it with the research_trade function. It specifies a 'MINUTE' frequency, sets signal_mode to False for direct broker interaction, and uses 'today' for recover_dt to resume from the current day's trading session. ```python from tick_trade_api import TradeAPI # Initialize TradeAPI with an order policy trade_api=TradeAPI('69271711',order_policy=MarketPolicy) source_code=""" # Stock Strategy Template def init(context): pass # Execute before trading hours def before_trading(context): pass # Function to run at market open def handle_bar(context, bar_dict): order_id = order('000001.SZ', 100) print(get_orders()) try: cancel_order(order_id) except: print('Cancel order failed') 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' ) ``` -------------------------------- ### Backtesting vs. Live Trading Differences Source: https://quant.10jqka.com.cn/view/help/10/index Highlights key differences between backtesting (simulation) and live trading environments, and provides solutions to potential issues. ```APIDOC ## Backtesting vs. Live Trading Differences ### Description This section outlines the discrepancies between backtesting (simulation) and live trading environments (simulation counter, real trading) and offers solutions to common problems that may arise when a strategy performs differently in live trading compared to backtesting. ### Key Differences Table: | Feature | Backtesting (Simulation) | Live Trading (Simulation Counter) |---|---|--- | Initial Holdings | Generally none | May have initial holdings | Order Execution | Usually immediate | Not immediate; depends on price and market trends | Position Days (`position_days`) | Records holding days | Always 0 | External Trades | Not applicable | Can affect strategy performance | Order Cancellation | Rare scenario | Should be considered | Reporting Lag | No lag | Has reporting lag ### Potential Issues and Solutions: #### Issue 1: Initial Holdings in Account - **Problem**: Live accounts often have initial holdings, unlike simulation environments. This can cause conflicts if the strategy internally tracks holdings and doesn't account for pre-existing positions, especially when using `sync_trade_api()` or `signal_mode=False`. - **Example**: A strategy that records bought stocks in a dictionary might fail if it tries to delete information for an initial holding that wasn't added by the strategy itself. - **User-side Solutions**: - Initialize the strategy's internal holdings tracker with existing positions. - Avoid trading outside the strategy in live environments. - Use `dict.pop()` instead of `del` for safer dictionary key removal. - **Long-term Solution (SuperMind Feature Optimization)**: - Implement asset units per strategy to isolate strategy-specific funds, holdings, orders, and trades (Expected July-August). #### Issue 2: Delayed Order Execution in Live Trading - **Problem**: Orders in live trading do not execute immediately, unlike in backtesting. Strategies that assume instant execution for recording trades or updating positions may encounter data inaccuracies or errors. - **Example**: A strategy that places an order and immediately records the purchase might miss data if the order hasn't been filled yet. Later, when the order finally executes, the recorded data might be incorrect or missing. - **User-side Solutions**: - Refactor holding tracking code to consolidate updates after market close based on actual holdings and trades. - Use `dict.get()` for safer dictionary value retrieval. - **Long-term Solution (SuperMind Feature Optimization)**: - Add events for trade execution reports and order status updates (Planned by end of June). ``` -------------------------------- ### Managing Order Execution Delays in Live Trading Source: https://quant.10jqka.com.cn/view/help/10/index Unlike backtesting where orders are often matched instantly, live trading involves delays between placing an order and its execution. Strategies that assume immediate order matching can lead to data discrepancies. The provided example illustrates how assuming immediate updates to `g.information` after placing an order can fail. Solutions include consolidating position updates after market close or using more robust data retrieval methods. ```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 # Incorrect assumption: immediate position update for symbol in list(context.portfolio.positions): g.information[symbol] = 1 time.sleep(3) # Simulate delay # Now positions might have changed, but g.information is based on earlier state for symbol in list(context.portfolio.positions): print(g.information.get(symbol, 'Position not recorded')) # Use .get() for safety ``` -------------------------------- ### TradeAPI Enhancements Source: https://quant.10jqka.com.cn/view/help/10/index New functionalities added to the TradeAPI and strategy framework for improved trading management. ```APIDOC ## TradeAPI Enhancements ### Description This section details new features added to the strategy framework and the `TradeAPI` for enhanced control over trading operations, including order management and retrieval. ### New Strategy Framework Features: - **`cancel_order_all()`**: Cancels all outstanding orders. - **`get_tradelogs()`**: Retrieves all executed orders for the current day. - **`get_orders()`**: Retrieves current orders (functionally equivalent to `get_order()`, aligned with `tradeapi` naming). ### New TradeAPI Features: - **`get_open_orders()`**: Retrieves all pending (unfilled) orders for the current day. - **`cancel_order_all()`**: Cancels all outstanding orders. ``` -------------------------------- ### TradeAPI Initialization with Order Policy Source: https://quant.10jqka.com.cn/view/help/10/index This snippet shows how to initialize the TradeAPI object, which is crucial for live trading. It requires specifying the account ID and an order policy, such as MarketPolicy for market orders or LimitPolicy for limit orders. Proper initialization prevents potential issues with order execution due to price precision. ```python from tick_trade_api import TradeAPI # Initialize TradeAPI with an order policy, MarketPolicy for market orders, LimitPolicy for limit orders trade_api=TradeAPI('69271711',order_policy=MarketPolicy) ``` -------------------------------- ### Initialize TradeAPI for Simulation Counter Source: https://quant.10jqka.com.cn/view/help/10/index This Python snippet demonstrates how to initialize the TradeAPI for use with the simulation counter. It requires your account ID and is used within the research environment to connect to the trading interface. ```python from tick_trade_api.api import TradeAPI trade_api = TradeAPI(account_id='84728199') #填入已登录的资金账号 ``` -------------------------------- ### POST /research_trade Source: https://quant.10jqka.com.cn/view/help/10/index Initiates a simulated or live trading session for a given strategy. ```APIDOC ## POST /research_trade ### Description Initiates a simulated or live trading session for a given strategy. This function allows users to backtest strategies in a simulated environment or execute them in a live trading environment using a provided TradeAPI object. ### Method POST ### Endpoint /research_trade ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (str) - Required - The name of the strategy. A directory with this name will be created under ./persist/ to store strategy information. - **source_code** (str) - Required - The strategy code, which can be copied directly from the strategy research module. The code should be enclosed in triple quotes (\"\"). - **capital_base** (float) - Optional - The initial capital amount. Defaults to 100000. This parameter is ignored if a TradeAPI object is provided and `signal_mode` is set to `False`. - **frequency** (str) - Optional - The strategy frequency. Can be 'DAILY' or 'MINUTE'. Defaults to 'DAILY'. - **stock_market** (str) - Optional - The type of strategy. Defaults to 'STOCK'. - **benchmark** (str) - Optional - The benchmark index for performance comparison. - **trade_api** (TradeAPI object) - Optional - A TradeAPI object for live trading. If `None`, the trading is simulated. If provided, it's live trading. - **signal_mode** (bool) - Optional - Controls the trading mode. Defaults to `True`. - `True`: Simulated trading using `capital_base`. Context and order-related methods return data from the simulation. Orders are placed to the broker only after simulation matching. - `False`: Live trading using the provided `trade_api`. Context and order-related methods return data directly from the broker. Orders are placed directly to the broker. - **dry_run** (bool) - Optional - If `True`, the function runs a dry run and returns immediately. Defaults to `False`. - **recover_dt** (bool or str) - Optional - Controls breakpoint recovery. Defaults to `False`. - `False`: Executes from the current time point, without breakpoint recovery. - `True`: Resumes execution from the last strategy end time point. - `'today'`: Resumes from the beginning of the current day. Only `before_trading` and `open_auction` will be re-executed; `handle_bar` will start from the current time. - `'yyyyMMdd HH:mm'`: Resumes execution from the specified date and time. ### Request Example ```json { "name": "MyStrategy", "source_code": "\"\n# Strategy code goes here\n\"", "capital_base": 100000, "frequency": "MINUTE", "trade_api": "", "signal_mode": false, "recover_dt": "today" } ``` ### Response #### Success Response (200) - **RealtimeService** (object) - An instance of the RealtimeService class, which provides methods to interact with the trading environment. #### Response Example ```json { "instance": "" } ``` ### Notes - Strategies should be started before 9:00 AM to ensure execution of `before_trading` and other steps, unless `recover_dt` is set. - When initializing `TradeAPI`, specify an `order_policy` (e.g., `MarketPolicy` for market orders, `LimitPolicy` for limit orders). Failure to do so might result in invalid orders due to price precision issues. - When `signal_mode=True`, use `sync_trade_api()` to get simulation account's holdings and fund data within the context. ``` -------------------------------- ### Strategy Framework and TradeAPI Enhancements Source: https://quant.10jqka.com.cn/view/help/10/index This section highlights new functionalities added to both the strategy framework and the TradeAPI. Key additions include cancel_order_all() for immediate cancellation of all orders, get_tradelogs() to retrieve all executed orders for the day, and get_open_orders() to fetch pending orders from the TradeAPI. ```python # Strategy framework additions: cancel_order_all() # Cancel all get_tradelogs() # Get all executed orders for the day get_orders() # Get pending orders (consistent with tradeapi) # TradeAPI additions: get_open_orders() # Get pending orders for the day cancel_order_all() # Cancel all ``` -------------------------------- ### Handle Position Days Data in Python Source: https://quant.10jqka.com.cn/view/help/10/index This Python code snippet demonstrates a strategy to sell stocks after holding them for 5 days. It highlights a limitation where `positions_days` data, crucial for this logic, might be unavailable in simulation or live trading environments due to broker limitations. The solution involves manually tracking holding days. ```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) ``` -------------------------------- ### Simulated and Live Trading with research_trade Source: https://quant.10jqka.com.cn/view/help/10/index The research_trade function allows for both simulated and live trading of strategies. It takes strategy code, capital base, frequency, and various trading parameters. When trade_api is None, it performs simulated trading; otherwise, it engages in live/simulated trading through the provided TradeAPI object. The signal_mode parameter controls whether context data reflects simulated trades or actual broker data. ```python research_trade( name, source_code, capital_base=100000, frequency='DAILY', stock_market='STOCK', benchmark=None, trade_api=None, signal_mode=True, dry_run=False, recover_dt=False, ) ``` -------------------------------- ### Handling Initial Holdings in Live Trading Source: https://quant.10jqka.com.cn/view/help/10/index Strategies may encounter issues if they don't account for initial holdings in live trading accounts, which are typically absent in backtesting. This can lead to errors if the strategy's internal state management (e.g., tracking positions in a dictionary) conflicts with pre-existing holdings. The solution involves initializing the strategy's internal state with current holdings or using safer dictionary access methods like pop(). ```python def init(context): # Example: Initialize context.information with initial holdings if available # Or handle potential KeyError when deleting items pass def handle_bar(context, bar_dict): # Example: Use dict.pop() for safer deletion symbol_to_remove = '000001.SZ' context.information.pop(symbol_to_remove, None) # Safely remove if key exists pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.