demo.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #coding:utf-8
  2. import time, datetime, traceback, sys
  3. from xtquant import xtdata
  4. from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
  5. from xtquant.xttype import StockAccount
  6. from xtquant import xtconstant
  7. from sqlalchemy import create_engine
  8. import pandas as pd
  9. #定义一个类 创建类的实例 作为状态的容器
  10. class _a():
  11. pass
  12. A = _a()
  13. A.bought_list = []
  14. A.hsa = xtdata.get_stock_list_in_sector('沪深A股')
  15. def interact():
  16. """执行后进入repl模式"""
  17. import code
  18. code.InteractiveConsole(locals=globals()).interact()
  19. xtdata.download_sector_data()
  20. def f(data):
  21. now = datetime.datetime.now()
  22. for stock in data:
  23. if stock not in A.hsa:
  24. continue
  25. cuurent_price = data[stock]['lastPrice']
  26. pre_price = data[stock]['lastClose']
  27. ratio = cuurent_price / pre_price - 1 if pre_price > 0 else 0
  28. if ratio > 0.09 and stock not in A.bought_list:
  29. print(f"{now} 最新价 买入 {stock} 200股")
  30. async_seq = xt_trader.order_stock_async(acc, stock, xtconstant.STOCK_BUY, 200, xtconstant.LATEST_PRICE, -1, 'strategy_name', stock)
  31. A.bought_list.append(stock)
  32. xt_trader.query_stock_orders()
  33. class MyXtQuantTraderCallback(XtQuantTraderCallback):
  34. def on_disconnected(self):
  35. """
  36. 连接断开
  37. :return:
  38. """
  39. print(datetime.datetime.now(),'连接断开回调')
  40. def on_stock_order(self, order):
  41. """
  42. 委托回报推送
  43. :param order: XtOrder对象
  44. :return:
  45. """
  46. print(datetime.datetime.now(), '委托回调', order.order_remark)
  47. def on_stock_trade(self, trade):
  48. """
  49. 成交变动推送
  50. :param trade: XtTrade对象
  51. :return:
  52. """
  53. print(datetime.datetime.now(), '成交回调', trade.order_remark)
  54. def on_order_error(self, order_error):
  55. """
  56. 委托失败推送
  57. :param order_error:XtOrderError 对象
  58. :return:
  59. """
  60. # print("on order_error callback")
  61. # print(order_error.order_id, order_error.error_id, order_error.error_msg)
  62. print(f"委托报错回调 {order_error.order_remark} {order_error.error_msg}")
  63. def on_cancel_error(self, cancel_error):
  64. """
  65. 撤单失败推送
  66. :param cancel_error: XtCancelError 对象
  67. :return:
  68. """
  69. print(datetime.datetime.now(), sys._getframe().f_code.co_name)
  70. def on_order_stock_async_response(self, response):
  71. """
  72. 异步下单回报推送
  73. :param response: XtOrderResponse 对象
  74. :return:
  75. """
  76. print(f"异步委托回调 {response.order_remark}")
  77. def on_cancel_order_stock_async_response(self, response):
  78. """
  79. :param response: XtCancelOrderResponse 对象
  80. :return:
  81. """
  82. print(datetime.datetime.now(), sys._getframe().f_code.co_name)
  83. def on_account_status(self, status):
  84. """
  85. :param response: XtAccountStatus 对象
  86. :return:
  87. """
  88. print(datetime.datetime.now(), sys._getframe().f_code.co_name)
  89. if __name__ == '__main__':
  90. engine = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/qmt_stocks_tech?charset=utf8')
  91. df = pd.read_sql_table('601155.SH_1d', engine)
  92. df = df[df['HL'] != '-']
  93. print(df)
  94. df.to_csv(f"C:\Daniel\策略\601155.csv", index=True, encoding='utf_8_sig',
  95. mode='w')
  96. exit()
  97. print("start")
  98. #指定客户端所在路径
  99. path = r'c:\\qmt\\userdata_mini'
  100. # 生成session id 整数类型 同时运行的策略不能重复
  101. session_id = int(time.time())
  102. xt_trader = XtQuantTrader(path, session_id)
  103. # 创建资金账号为 800068 的证券账号对象
  104. acc = StockAccount('920000207040', 'SECURITY')
  105. # 创建交易回调类对象,并声明接收回调
  106. callback = MyXtQuantTraderCallback()
  107. xt_trader.register_callback(callback)
  108. # 启动交易线程
  109. xt_trader.start()
  110. # 建立交易连接,返回0表示连接成功
  111. connect_result = xt_trader.connect()
  112. print('建立交易连接,返回0表示连接成功', connect_result)
  113. # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
  114. subscribe_result = xt_trader.subscribe(acc)
  115. print('对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功', subscribe_result)
  116. asset = xt_trader.query_stock_asset(acc)
  117. cash = asset.cash
  118. positions = xt_trader.query_stock_positions(acc)
  119. print(cash, positions)
  120. # xt_trader.run_forever()
  121. print('run over')
  122. if '600362.SH' == positions[0].stock_code:
  123. print('aaa')
  124. exit()
  125. # xtdata.subscribe_whole_quote(["SH", "SZ"], callback=f)
  126. xtdata.run()
  127. #进入交互模式
  128. # interact()