阅读:212回复:0
移仓换月代码编写
在量化交易中,自动移仓换月是指在主力合约切换时,自动将持仓从旧主力合约转移到新主力合约。以下是一个简单的Python示例,展示了如何在天勤量化(TqSdk)中实现自动移仓换月:
from tqsdk import TqApi, TqAuth, TqAccount # 初始化天勤API api = TqApi(auth=TqAuth("your_account", "your_password")) # 定义合约代码前缀 symbol_prefix = "SHFE.cu" # 获取当前主力合约 current_dominant_symbol = api.get_dominant_symbol(symbol_prefix) # 定义一个函数来检查主力合约是否发生变化 def check_dominant_change(): global current_dominant_symbol new_dominant_symbol = api.get_dominant_symbol(symbol_prefix) if new_dominant_symbol != current_dominant_symbol: print("主力合约发生变化,从", current_dominant_symbol, "变为", new_dominant_symbol) current_dominant_symbol = new_dominant_symbol return True return False # 定义一个函数来进行移仓换月操作 def switch_to_new_dominant(): global current_dominant_symbol old_symbol = current_dominant_symbol new_symbol = api.get_dominant_symbol(symbol_prefix) # 获取当前持仓 old_position = api.get_position(old_symbol) # 平掉旧合约仓位 if old_position.pos_long > 0: # 如果有多头持仓 old_order = api.insert_order(symbol=old_symbol, direction="SELL", offset="CLOSE", volume=old_position.pos_long) elif old_position.pos_short > 0: # 如果有空头持仓 old_order = api.insert_order(symbol=old_symbol, direction="BUY", offset="CLOSE", volume=old_position.pos_short) # 等待旧合约订单成交 while old_order.status != "FINISHED": api.wait_update() print("旧合约平仓完成") # 开新合约仓位 if old_position.pos_long > 0: # 如果有多头持仓 new_order = api.insert_order(symbol=new_symbol, direction="BUY", offset="OPEN", volume=old_position.pos_long) elif old_position.pos_short > 0: # 如果有空头持仓 new_order = api.insert_order(symbol=new_symbol, direction="SELL", offset="OPEN", volume=old_position.pos_short) # 等待新合约订单成交 while new_order.status != "FINISHED": api.wait_update() print("新合约开仓完成") # 主循环 while True: # 检查主力合约是否发生变化 if check_dominant_change(): switch_to_new_dominant() # 等待更新 api.wait_update() # 关闭API api.close() |
|
|