1、之前提供了策略,是在回测进行模拟,现在需要在实际的实时交易进行验证
2、主程序如下:
def main():
global xt_trader, acc, strategy
try:
# 指定客户端所在路径, 券商端指定到 userdata_mini文件夹
path = r'D:\国金QMT交易端模拟\userdata_mini'
# 生成session id 整数类型 同时运行的策略不能重复
session_id = int(time.time())
xt_trader = XtQuantTrader(path, session_id)
# 创建资金账号为 40008446 的证券账号对象 股票账号为STOCK 信用CREDIT 期货FUTURE
acc = StockAccount('40008446', 'STOCK')
# 创建交易回调类对象,并声明接收回调
callback = MyXtQuantTraderCallback()
xt_trader.register_callback(callback)
# 启动交易线程
xt_trader.start()
# 建立交易连接,返回0表示连接成功
connect_result = xt_trader.connect()
print('建立交易连接,返回0表示连接成功', connect_result)
logging.info('建立交易连接,返回0表示连接成功', connect_result)
if (connect_result == -1) :
print('建立交易连接,连接失败!', connect_result)
logging.info('建立交易连接,连接失败!', connect_result)
return
# 初始化策略
stock_list = ['002127.SZ','600800.SH']
strategy = RealTimeStrategy(stock_list)
# 订阅实时行情
xtdata.subscribe_whole_quote(stock_list, callback=on_data)
# 启动守护线程
connection_thread = threading.Thread(target=maintain_connection, daemon=True)
connection_thread.start()
print("策略已启动,等待实时行情...")
logging.info("策略已启动,等待实时行情...")
except Exception as e:
print(f"初始化失败: {str(e)}")
traceback.print_exc()
sys.exit(1)
while True:
time.sleep(3600) # 防止主线程退出
if __name__ == '__main__':
main()
3、主要交易的回调函数如下:
class OrderManager:
def __init__(self):
self.active_orders = {}
def add_order(self, order_id, stock, direction):
self.active_orders[order_id] = {
'stock': stock,
'direction': direction,
'timestamp': time.time()
}
def remove_order(self, order_id):
if order_id in self.active_orders:
del self.active_orders[order_id]
order_manager = OrderManager()
class MyXtQuantTraderCallback(XtQuantTraderCallback):
def on_stock_order(self, order):
# 在回调中更新订单状态
if order.order_status == xtconstant.ORDER_CANCELLED:
order_manager.remove_order(order.order_id)
elif order.order_status == xtconstant.ORDER_UNREPORTED:
order_manager.add_order(order.order_id, order.stock_code, order.order_direction)
print(f"[{datetime.datetime.now()}] 订单更新: {order.stock_code} {order.order_status}")
logging.info(f"[{datetime.datetime.now()}] 订单更新: {order.stock_code} {order.order_status}")
def on_stock_trade(self, trade):
print(f"[{datetime.datetime.now()}] 成交: {trade.stock_code} {trade.offset_flag} {trade.traded_volume}@{trade.traded_price}")
logging.info(f"[{datetime.datetime.now()}] 成交: {trade.stock_code} {trade.offset_flag} {trade.traded_volume}@{trade.traded_price}")
def on_order_error(self, order_error):
print(f"[{datetime.datetime.now()}] 订单错误: {order_error.error_msg}")
logging.info(f"[{datetime.datetime.now()}] 订单错误: {order_error.error_msg}")
4、交易的数据处理
def on_data(data):
global strategy, xt_trader, acc
try:
with global_lock: # 在数据更新和信号生成处加锁
for stock in data:
tick = data[stock]
current_time = pd.to_datetime(tick['time'], unit='ms')
current_date = current_time.strftime('%Y-%m-%d')
strategy.update_realtime_data(stock, tick)
signal = strategy.generate_signal(stock, current_date)
if signal:
current_price = tick['lastPrice']
execute_trade(stock, signal, current_price, tick)
except Exception as e:
print(f"数据处理异常: {str(e)}")
logging.info(f"数据处理异常: {str(e)}")
traceback.print_exc()
5、效果图: