sell_real_time.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # coding:utf-8
  2. from datetime import datetime as dt
  3. import os
  4. import pandas as pd
  5. from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
  6. from xtquant.xttype import StockAccount
  7. from xtquant import xtdata, xtconstant
  8. import time
  9. from sqlalchemy import create_engine, text
  10. from jqdatasdk import *
  11. import pymysql
  12. import multiprocessing as mp
  13. import math
  14. import psutil
  15. import datetime
  16. from apscheduler.schedulers.blocking import BlockingScheduler
  17. import sys
  18. # 指定客户端所在路径
  19. path = r'c:\\qmt\\userdata_mini'
  20. # 创建资金账号为 800068 的证券账号对象
  21. acc = StockAccount('920000207040', 'SECURITY')
  22. # 生成session id 整数类型 同时运行的策略不能重复
  23. session_id = 123456
  24. xt_trader = None
  25. order_list = []
  26. engine_stock = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/qmt_stocks_whole?charset=utf8',
  27. pool_size=5000, pool_recycle=50, max_overflow=-1)
  28. class MyXtQuantTraderCallback(XtQuantTraderCallback):
  29. def on_disconnected(self):
  30. """
  31. 连接断开
  32. :return:
  33. """
  34. print(datetime.datetime.now(), '连接断开回调')
  35. def on_stock_order(self, order):
  36. """
  37. 委托回报推送
  38. :param order: XtOrder对象
  39. :return:
  40. """
  41. print(datetime.datetime.now(), '委托回调', order.order_remark)
  42. def on_stock_trade(self, trade):
  43. """
  44. 成交变动推送
  45. :param trade: XtTrade对象
  46. :return:
  47. """
  48. print(datetime.datetime.now(), '成交回调', trade.order_remark)
  49. def on_order_error(self, order_error):
  50. """
  51. 委托失败推送
  52. :param order_error:XtOrderError 对象
  53. :return:
  54. """
  55. # print("on order_error callback")
  56. # print(order_error.order_id, order_error.error_id, order_error.error_msg)
  57. print(f"委托报错回调 {order_error.order_remark} {order_error.error_msg}")
  58. def on_cancel_error(self, cancel_error):
  59. """
  60. 撤单失败推送
  61. :param cancel_error: XtCancelError 对象
  62. :return:
  63. """
  64. print(datetime.datetime.now(), sys._getframe().f_code.co_name)
  65. def on_order_stock_async_response(self, response):
  66. """
  67. 异步下单回报推送
  68. :param response: XtOrderResponse 对象
  69. :return:
  70. """
  71. print(f"异步委托回调 {response.order_remark}")
  72. def on_cancel_order_stock_async_response(self, response):
  73. """
  74. :param response: XtCancelOrderResponse 对象
  75. :return:
  76. """
  77. print(datetime.datetime.now(), sys._getframe().f_code.co_name)
  78. def on_account_status(self, status):
  79. """
  80. :param response: XtAccountStatus 对象
  81. :return:
  82. """
  83. print(datetime.datetime.now(), sys._getframe().f_code.co_name)
  84. def run(seq, pid):
  85. mor = datetime.datetime.strptime(
  86. str(dt.now().date()) + '11:30', '%Y-%m-%d%H:%M')
  87. afternoon = datetime.datetime.strptime(
  88. str(dt.now().date()) + '15:00', '%Y-%m-%d%H:%M')
  89. mor_1 = datetime.datetime.strptime(
  90. str(dt.now().date()) + '12:59', '%Y-%m-%d%H:%M')
  91. """阻塞线程接收行情回调"""
  92. import time
  93. client = xtdata.get_client()
  94. while True:
  95. time.sleep(3)
  96. now_date = dt.now()
  97. if not client.is_connected():
  98. xtdata.unsubscribe_quote(seq)
  99. raise Exception('行情服务连接断开')
  100. # if mor < dt.now() < mor_1:
  101. # xtdata.unsubscribe_quote(seq)
  102. # print(f'现在时间:{dt.now()},已休市')
  103. # sys.exit()
  104. # break
  105. # return 0
  106. elif dt.now() > afternoon:
  107. xtdata.unsubscribe_quote(seq)
  108. print(f'现在时间:{dt.now()},已收盘')
  109. sys.exit()
  110. break
  111. # return 0
  112. return
  113. def get_fundamentals(results):
  114. return results
  115. pass
  116. def ma(stock, num, data):
  117. global engine_stock
  118. try:
  119. i = (num - 1) * -1
  120. df = pd.read_sql_query(text(
  121. 'select close_front from `%s_1d`' % stock), engine_stock.connect())
  122. except BaseException as e:
  123. print(e)
  124. return 9999999
  125. else:
  126. ma_num = (sum(df['close_front'][i:]) + data[stock]['lastPrice']) / num
  127. return ma_num
  128. def ma_1(stock, num):
  129. global engine_stock
  130. i = num * -1
  131. try:
  132. df = pd.read_sql_query(text(
  133. 'select close_front from `%s_1d`' % stock), engine_stock.connect())
  134. except BaseException as e:
  135. print(e)
  136. return 9999999
  137. else:
  138. ma_num_1 = df['close_front'][i:].mean()
  139. return ma_num_1
  140. def his_vol(stock, num):
  141. global engine_stock
  142. num = num * -1
  143. try:
  144. df = pd.read_sql_query(text(
  145. 'select volume_front from `%s_1d`' % stock), engine_stock.connect())
  146. except BaseException:
  147. return 9999999
  148. else:
  149. return df['volume_front'].iloc[num]
  150. def ma_judge(data, list_judge, rate, results):
  151. # print(f'这个ma_judge的PID为:{os.getpid()},本轮计算:{len(list_judge)}个股')
  152. for stock in list_judge:
  153. current_price, open_price = data[stock]['lastPrice'], data[stock]['open']
  154. MA5, MA10, MA20, MA30, MA60, MA120 = ma(stock, 5, data), ma(stock, 10, data), ma(stock, 20, data), ma(stock, 30,
  155. data), \
  156. ma(stock, 60, data), ma(stock, 120, data)
  157. MA5_1 = ma_1(stock, 5)
  158. # print(i, current_price, open_price, MA5, MA10, MA20, MA5_1)
  159. # 入交易池标准:阳线\大于MA5\MA5向上\MA20<MA10\离120线有距离
  160. if (current_price > open_price) & (current_price > MA5) & (MA5 > MA5_1) & (current_price < MA5 * 1.05) \
  161. & (current_price > MA120 or current_price < MA120 * rate):
  162. if his_vol(stock, -1) > his_vol(stock, -2):
  163. results.append(stock.replace('SH', 'XSHG').replace('SZ', 'XSHE'))
  164. def sell_trader(data):
  165. # print('卖出函数:', dt.now())
  166. positions = xt_trader.query_stock_positions(acc)
  167. positions_dict = {positions[x].stock_code: positions[x].can_use_volume for x in range(0, len(positions))}
  168. print(
  169. f'目前持仓总数为:{len([positions[x].stock_code for x in range(0, len(positions)) if positions[x].volume != 0])}')
  170. # orders = xt_trader.query_stock_orders(acc, False)
  171. # print(orders)
  172. # if orders is not None:
  173. # for order_id in order_list:
  174. # cancel_result = xt_trader.cancel_order_stock(acc, order_id)
  175. # print(f'{order_id}撤单结果:{cancel_result}')
  176. # else:
  177. # print(f'今日没有委托单!')
  178. for stock, can_use_volume in positions_dict.items():
  179. # if stock in data and can_use_volume != 0:
  180. if stock in data:
  181. current_price = data[stock]['lastPrice']
  182. open_price = data[stock]['open']
  183. MA5 = ma(stock, 5, data)
  184. MA5_1 = ma_1(stock, 5)
  185. print(
  186. f"{data[stock]['time']}, {stock}\n当前时间为:{dt.now().strftime('%Y-%m-%d %H:%M:%S')},"
  187. f"信号时间:{dt.fromtimestamp((data[stock]['time']) / 1000.0)}\n"
  188. f"持仓量为{can_use_volume}当前价:{current_price},开盘价:{open_price},"f"MA5:{MA5},昨日MA5:{MA5_1},开始判断:")
  189. df = pd.read_sql_query(text(
  190. 'select close_front, high_front from `%s_1d`' % stock), engine_stock.connect())
  191. if current_price == xtdata.get_instrument_detail(stock).get('UpStopPrice') \
  192. or (df['close_front'].iloc[-1] == df['high_front'].iloc[-1]
  193. and df['close_front'].iloc[-1] / df['close_front'].iloc[-2] > 1.08):
  194. print(f"{stock}涨停或昨日涨幅超过8%,持股观察!{data[stock]['time']}")
  195. continue
  196. elif current_price < MA5 or MA5 < MA5_1:
  197. print('卖出信号!!!!!!', stock, current_price)
  198. order_id = xt_trader.order_stock(acc, stock, xtconstant.STOCK_SELL, can_use_volume,
  199. xtconstant.LATEST_PRICE, 0, 'MA5策略', '低于MA5趋势向下')
  200. print('价格:', current_price, open_price, MA5, MA5_1, '低于MA5趋势向下')
  201. print(order_id, stock, can_use_volume)
  202. order_list.append(order_id)
  203. elif current_price > MA5 * 1.07:
  204. print('盈利乖离率超7%!!!!!!', stock, current_price)
  205. order_id = xt_trader.order_stock(acc, stock, xtconstant.STOCK_SELL, can_use_volume,
  206. xtconstant.LATEST_PRICE, 0, 'MA5策略', '盈利乖离率超7%')
  207. print('价格:', current_price, open_price, MA5, MA5_1, '盈利乖离率超7%')
  208. print(order_id, stock, can_use_volume)
  209. order_list.append(order_id)
  210. else:
  211. # print(f'本轮没有持仓股票信息!')
  212. pass
  213. engine_stock.dispose()
  214. def bridge():
  215. global session_id, xt_trader
  216. pid = os.getpid()
  217. connect_result = -1
  218. subscribe_result = -1
  219. while True:
  220. if connect_result != 0 or subscribe_result != 0:
  221. session_id = int(time.time())
  222. xt_trader = XtQuantTrader(path, session_id)
  223. # 创建交易回调类对象,并声明接收回调
  224. callback = MyXtQuantTraderCallback()
  225. xt_trader.register_callback(callback)
  226. # 启动交易线程
  227. xt_trader.start()
  228. # 建立交易连接,返回0表示连接成功
  229. connect_result = xt_trader.connect()
  230. print('建立交易连接,返回0表示连接成功', connect_result)
  231. # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
  232. subscribe_result = xt_trader.subscribe(acc)
  233. print('对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功', subscribe_result)
  234. # 建立交易连接,返回0表示连接成功
  235. connect_result = xt_trader.connect()
  236. print('建立交易连接,返回0表示连接成功', connect_result)
  237. # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
  238. subscribe_result = xt_trader.subscribe(acc)
  239. print('对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功', subscribe_result)
  240. time.sleep(3)
  241. else:
  242. break
  243. print(f'MyPid is {os.getpid()}, now is {dt.now()},开盘了,session_id = {session_id}, \n')
  244. positions = xt_trader.query_stock_positions(acc)
  245. positions_dict = {positions[x].stock_code: positions[x].can_use_volume for x in range(0, len(positions))}
  246. print(f'今日可卖出个股总数:{len([value for value in positions_dict.values() if value != 0])}')
  247. stocks = xtdata.get_stock_list_in_sector('沪深A股')
  248. seq_s = xtdata.subscribe_whole_quote(stocks, callback=sell_trader)
  249. # seq_b = xtdata.subscribe_whole_quote(stocks, callback=buy_trader)
  250. run(seq_s, pid)
  251. # run(seq_b, pid)
  252. def job_func():
  253. print(f"Job started at {dt.now()}")
  254. # 创建子进程
  255. p = mp.Process(target=bridge)
  256. # 启动子进程
  257. p.start()
  258. # 等待子进程结束
  259. p.join()
  260. print(f"Job finished at {dt.now()}")
  261. if __name__ == '__main__':
  262. mp.freeze_support()
  263. # print('cpu_count =', mp.cpu_count())
  264. pus = psutil.Process()
  265. # pus.cpu_affinity([16, 17, 18, 19])
  266. print('sell real time start at', dt.now())
  267. job_func()
  268. scheduler = BlockingScheduler()
  269. scheduler.add_job(func=job_func, trigger='cron', day_of_week='0-4', hour='09', minute='40',
  270. timezone="Asia/Shanghai", max_instances=5)
  271. # scheduler.add_job(func=job_func, trigger='cron', day_of_week='0-4', hour='12', minute='35',
  272. # timezone="Asia/Shanghai")
  273. try:
  274. scheduler.start()
  275. except (KeyboardInterrupt, SystemExit):
  276. pass