### Install TqSdk using pip Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/ai_editor/tqsdk_trae.md Install the TqSdk library in your Python environment using pip. Ensure your Python interpreter is correctly configured in Trae or that your virtual environment is activated in the integrated terminal. ```bash pip install tqsdk ``` -------------------------------- ### Automated Trading Based on Target Positions Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/quickstart.md This example shows how to use `TargetPosTask` to automatically manage positions. You set a desired target volume, and TqSdk handles the orders to reach it. This is useful for spread trading strategies. ```python from tqsdk import TqApi, TqAuth, TargetPosTask api = TqApi(auth=TqAuth("快期账户", "账户密码")) quote_near = api.get_quote("SHFE.ni2010") quote_deferred = api.get_quote("SHFE.ni2011") # 创建 ni2010 的目标持仓 task,该 task 负责调整 ni2010 的仓位到指定的目标仓位 target_pos_near = TargetPosTask(api, "SHFE.ni2010") # 创建 ni2011 的目标持仓 task,该 task 负责调整 ni2011 的仓位到指定的目标仓位 target_pos_deferred = TargetPosTask(api, "SHFE.ni2011") while True: api.wait_update() if api.is_changing(quote_near) or api.is_changing(quote_deferred): spread = quote_near.last_price - quote_deferred.last_price print("当前价差:", spread) if spread > 200: print("目标持仓: 空近月,多远月") # 设置目标持仓为正数表示多头,负数表示空头,0表示空仓 target_pos_near.set_target_volume(-1) target_pos_deferred.set_target_volume(1) elif spread < 150: print("目标持仓: 空仓") target_pos_near.set_target_volume(0) target_pos_deferred.set_target_volume(0) ``` -------------------------------- ### Configure Strategy Backtesting Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/quickstart.md To perform backtesting, initialize `TqApi` with a `TqBacktest` instance, specifying the start and end dates for the simulation. This allows you to test your trading strategies on historical data. ```python from datetime import date from tqsdk import TqApi, TqAuth, TqBacktest api = TqApi(backtest=TqBacktest(start_dt=date(2018, 5, 1), end_dt=date(2018, 10, 1)), auth=TqAuth("快期账户", "账户密码")) ``` -------------------------------- ### Cancel and Manage TargetPosTask Instances Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/advanced/targetpostask2.md This example demonstrates how to cancel an active TargetPosTask, wait for it to finish, and then create a new instance to close positions. Use cancel() to stop pending orders and is_finished() to confirm task completion. ```python from datetime import datetime, time from tqsdk import TqApi, TargetPosTask api = TqApi(auth=TqAuth("快期账户", "账户密码")) quote = api.get_quote("SHFE.rb2110") target_pos_passive = TargetPosTask(api, "SHFE.rb2110", price="PASSIVE") while datetime.strptime(quote.datetime, "%Y-%m-%d %H:%M:%S.%f").time() < time(14, 50): api.wait_update() # ... 策略代码 ... # 取消 TargetPosTask 实例 target_pos_passive.cancel() while not target_pos_passive.is_finished(): # 此循环等待 target_pos_passive 处理 cancel 结束 api.wait_update() # 调用wait_update(),会对已经发出但还是未成交的委托单撤单 # 创建新的 TargetPosTask 实例 target_pos_active = TargetPosTask(api, "SHFE.rb2110", price="ACTIVE") target_pos_active.set_target_volume(0) # 平所有仓位 while True: api.wait_update() # ... 策略代码 ... api.close() ``` -------------------------------- ### Configure Live Trading Account Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/quickstart.md To enable live trading, provide a `TqAccount` instance to `TqApi`, including your futures company, account number, and password, along with your TqSdk account credentials. ```python from tqsdk import TqApi, TqAuth, TqAccount # 如果要更换为徽商期货,只需要改为 H徽商期货 api = TqApi(TqAccount("H宏源期货", "412432343", "123456"), auth=TqAuth("快期账户", "账户密码")) ``` -------------------------------- ### Configure Simulated Trading with TqKq Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/quickstart.md Use `TqKq` when initializing `TqApi` to log in to a persistent simulated trading account. This account's data is synchronized across various TqSdk clients. ```python from tqsdk import TqApi, TqAuth, TqKq api = TqApi(TqKq(), auth=TqAuth("快期账户", "账户密码")) ``` -------------------------------- ### Use Temporary Simulated Trading Account Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/quickstart.md If no account instance is provided to `TqApi`, a temporary `TqSim` account is automatically created. This account is local to the program and its data is lost upon program termination. ```python api = TqApi(auth=TqAuth("快期账户", "账户密码")) ``` -------------------------------- ### Build an Automated Trading Program Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/quickstart.md This snippet demonstrates a simple automated trading strategy that buys when the latest price exceeds the 15-minute moving average. It uses `api.wait_update()` to wait for new data and `api.is_changing()` to check for updates. ```python klines = api.get_kline_serial("DCE.m2105", 60) while True: api.wait_update() if api.is_changing(klines): ma = sum(klines.close.iloc[-15:])/15 print("最新价", klines.close.iloc[-1], "MA", ma) if klines.close.iloc[-1] > ma: print("最新价大于MA: 市价开仓") api.insert_order(symbol="DCE.m2105", direction="BUY", offset="OPEN", volume=5) ``` -------------------------------- ### Clone TqSdk Python Source Code Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/ai_editor/tqsdk_trae.md Clone the TqSdk Python source code repository from GitHub or Gitee. This allows Trae to deeply understand the library's implementation details when added to the workspace. ```bash git clone https://github.com/shinnytech/tqsdk-python.git git clone https://gitee.com/tianqin_quantification_tqsdk/tqsdk-python.git ``` -------------------------------- ### Backtest Completion Handling Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/demo/strategy.md This snippet demonstrates how to handle the completion of a backtest. It includes closing the API connection after the backtest has finished. ```python except BacktestFinished as e: print("回测结束") api.close() ``` -------------------------------- ### Trading Strategy Logic for Long and Short Positions Source: https://github.com/shinnytech/tqsdk-python/blob/master/doc/demo/strategy.md This snippet shows the core logic for managing long and short positions, including stop-loss, take-profit, and exit conditions based on HMA crossovers. It handles updating entry prices, tracking minimum/maximum prices since entry, and calculating dynamic stop-loss levels. ```python print(f"多头止盈: 价格={current_price}, 盈亏={profit_pct:.2f}%") # 空头持仓 - 检查平仓条件 elif current_direction == -1: # 更新入场后的最低价 if current_price < lowest_since_entry or lowest_since_entry == 0: lowest_since_entry = current_price # 计算固定止损 fixed_stop_loss = entry_price * (1 + STOP_LOSS_ATR) # 更新追踪止损(只下移不上移) new_stop = current_short_hma + STOP_LOSS_ATR * current_atr if new_stop < stop_loss_price or stop_loss_price == 0: stop_loss_price = new_stop print(f"更新空头止损: {stop_loss_price:.2f}") # 平仓条件1: 短期HMA上穿长期HMA if prev_short_hma <= prev_long_hma and current_short_hma > current_long_hma: profit_pct = (entry_price - current_price) / entry_price * 100 target_pos.set_target_volume(0) current_direction = 0 print(f"空头平仓: 价格={current_price}, 盈亏={profit_pct:.2f}%") # 平仓条件2: 价格突破止损 elif current_price > stop_loss_price or current_price > fixed_stop_loss: profit_pct = (entry_price - current_price) / entry_price * 100 target_pos.set_target_volume(0) current_direction = 0 print(f"空头止损: 价格={current_price}, 盈亏={profit_pct:.2f}%") # 平仓条件3: 价格达到止盈价格 elif current_price <= take_profit_price: profit_pct = (entry_price - current_price) / entry_price * 100 target_pos.set_target_volume(0) current_direction = 0 print(f"空头止盈: 价格={current_price}, 盈亏={profit_pct:.2f}%") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.