real_time.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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
  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. import gc
  19. # auth('18616891214', 'Ea?*7f68nD.dafcW34d!')
  20. engine_stock = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/qmt_stocks_whole?charset=utf8')
  21. auth('18616891214', 'Ea?*7f68nD.dafcW34d!')
  22. class MyXtQuantTraderCallback(XtQuantTraderCallback):
  23. def on_disconnected(self):
  24. """
  25. 连接断开
  26. :return:
  27. """
  28. print(datetime.datetime.now(), '连接断开回调')
  29. def on_stock_order(self, order):
  30. """
  31. 委托回报推送
  32. :param order: XtOrder对象
  33. :return:
  34. """
  35. print(datetime.datetime.now(), '委托回调', order.order_remark)
  36. def on_stock_trade(self, trade):
  37. """
  38. 成交变动推送
  39. :param trade: XtTrade对象
  40. :return:
  41. """
  42. print(datetime.datetime.now(), '成交回调', trade.order_remark)
  43. def on_order_error(self, order_error):
  44. """
  45. 委托失败推送
  46. :param order_error:XtOrderError 对象
  47. :return:
  48. """
  49. # print("on order_error callback")
  50. # print(order_error.order_id, order_error.error_id, order_error.error_msg)
  51. print(f"委托报错回调 {order_error.order_remark} {order_error.error_msg}")
  52. def on_cancel_error(self, cancel_error):
  53. """
  54. 撤单失败推送
  55. :param cancel_error: XtCancelError 对象
  56. :return:
  57. """
  58. print(datetime.datetime.now(), sys._getframe().f_code.co_name)
  59. def on_order_stock_async_response(self, response):
  60. """
  61. 异步下单回报推送
  62. :param response: XtOrderResponse 对象
  63. :return:
  64. """
  65. print(f"异步委托回调 {response.order_remark}")
  66. def on_cancel_order_stock_async_response(self, response):
  67. """
  68. :param response: XtCancelOrderResponse 对象
  69. :return:
  70. """
  71. print(datetime.datetime.now(), sys._getframe().f_code.co_name)
  72. def on_account_status(self, status):
  73. """
  74. :param response: XtAccountStatus 对象
  75. :return:
  76. """
  77. print(datetime.datetime.now(), sys._getframe().f_code.co_name)
  78. # 指定客户端所在路径
  79. path = r'c:\\qmt\\userdata_mini'
  80. # 生成session id 整数类型 同时运行的策略不能重复
  81. session_id = int(time.time())
  82. xt_trader = XtQuantTrader(path, session_id)
  83. # 创建资金账号为 800068 的证券账号对象
  84. acc = StockAccount('920000207040', 'SECURITY')
  85. # 创建交易回调类对象,并声明接收回调
  86. callback = MyXtQuantTraderCallback()
  87. xt_trader.register_callback(callback)
  88. # 启动交易线程
  89. xt_trader.start()
  90. # 建立交易连接,返回0表示连接成功
  91. connect_result = xt_trader.connect()
  92. print('建立交易连接,返回0表示连接成功', connect_result)
  93. # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
  94. subscribe_result = xt_trader.subscribe(acc)
  95. print('对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功', subscribe_result)
  96. def run(seq, pid):
  97. mor = datetime.datetime.strptime(
  98. str(dt.now().date()) + '11:30', '%Y-%m-%d%H:%M')
  99. afternoon = datetime.datetime.strptime(
  100. str(dt.now().date()) + '15:00', '%Y-%m-%d%H:%M')
  101. mor_1 = datetime.datetime.strptime(
  102. str(dt.now().date()) + '12:59', '%Y-%m-%d%H:%M')
  103. """阻塞线程接收行情回调"""
  104. import time
  105. client = xtdata.get_client()
  106. while True:
  107. time.sleep(3)
  108. now_date = dt.now()
  109. if not client.is_connected():
  110. xtdata.unsubscribe_quote(seq)
  111. raise Exception('行情服务连接断开')
  112. # if mor < dt.now() < mor_1:
  113. # xtdata.unsubscribe_quote(seq)
  114. # print(f'现在时间:{dt.now()},已休市')
  115. # sys.exit()
  116. # break
  117. # return 0
  118. elif dt.now() > afternoon:
  119. xtdata.unsubscribe_quote(seq)
  120. print(f'现在时间:{dt.now()},已收盘')
  121. sys.exit()
  122. break
  123. # return 0
  124. # return
  125. def real_price(datas):
  126. # i = '000001.SZ'
  127. for i in datas:
  128. if i == '000001.SZ':
  129. print(i, datas[i])
  130. # trader(datas)
  131. # return datas
  132. def ma(stock, num, data):
  133. global engine_stock
  134. try:
  135. i = (num - 1) * -1
  136. df = pd.read_sql_query(
  137. 'select close_front from `%s_1d`' % stock, engine_stock)
  138. except:
  139. return 9999999
  140. else:
  141. ma_num = (sum(df['close_front'][i:]) + data[stock]['lastPrice']) / num
  142. return ma_num
  143. def ma_1(stock, num):
  144. global engine_stock
  145. i = num * -1
  146. try:
  147. df = pd.read_sql_query(
  148. 'select close_front from `%s_1d`' % stock, engine_stock)
  149. except BaseException:
  150. return 9999999
  151. else:
  152. ma_num_1 = df['close_front'][i:].mean()
  153. return ma_num_1
  154. def his_vol(stock, num):
  155. global engine_stock
  156. num = num * -1
  157. try:
  158. df = pd.read_sql_query(
  159. 'select volume_front from `%s_1d`' % stock, engine_stock)
  160. except BaseException:
  161. return 9999999
  162. else:
  163. return df['volume_front'].iloc[num]
  164. def ma_judge(data, list_judge, rate, results):
  165. # print(f',收到的data数据为:{len(data.keys())},stock_pool长度为{len(stock_list)},now is {dt.now()}')
  166. print(f'这个ma_judge的PID为:{os.getpid()},本轮计算:{len(list_judge)}个股')
  167. for stock in list_judge:
  168. current_price, open_price = data[stock]['lastPrice'], data[stock]['open']
  169. MA5, MA10, MA20, MA30, MA60, MA120 = ma(stock, 5, data), ma(stock, 10, data), ma(stock, 20, data), ma(stock, 30,
  170. data), \
  171. ma(stock, 60, data), ma(stock, 120, data)
  172. MA5_1 = ma_1(stock, 5)
  173. # print(i, current_price, open_price, MA5, MA10, MA20, MA5_1)
  174. # 入交易池标准:阳线\大于MA5\MA5向上\MA20<MA10\离120线有距离
  175. if (current_price > open_price) & (current_price > MA5) & (MA5 > MA5_1) & (current_price < MA5 * 1.03) & (
  176. MA20 < MA10) & (current_price > MA120 or current_price < MA120 * rate):
  177. if his_vol(stock, -1) > his_vol(stock, -2):
  178. results.append(stock.replace('SH', 'XSHG').replace('SZ', 'XSHE'))
  179. def get_fundamentals(results):
  180. return results
  181. pass
  182. def sell_trader(data):
  183. print('卖出函数:', dt.now())
  184. positions = xt_trader.query_stock_positions(acc)
  185. positions_dict = {positions[x].stock_code: positions[x].can_use_volume for x in range(0, len(positions))}
  186. print(f'今日可卖出个股总数:{len([value for value in positions_dict.values() if value != 0])}')
  187. print(
  188. f'目前持仓总数为:{len([positions[x].stock_code for x in range(0, len(positions)) if positions[x].volume != 0])}')
  189. for stock, can_use_volume in positions_dict.items():
  190. if stock in data and can_use_volume != 0:
  191. current_price = data[stock]['lastPrice']
  192. open_price = data[stock]['open']
  193. MA5 = ma(stock, 5, data)
  194. MA5_1 = ma_1(stock, 5)
  195. print(f'{stock},持仓量为{can_use_volume}当前价:{current_price},MA5:{MA5},昨日MA5:{MA5_1},开始判断:')
  196. if 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)
  201. print(order_id, stock, can_use_volume)
  202. elif current_price > MA5 * 1.07:
  203. print('盈利乖离率超7%!!!!!!', stock, current_price)
  204. order_id = xt_trader.order_stock(acc, stock, xtconstant.STOCK_SELL, can_use_volume,
  205. xtconstant.LATEST_PRICE, 0, 'MA5策略', '盈利乖离率超7%')
  206. print('价格:', current_price, open_price, MA5, MA5_1)
  207. print(order_id, stock, can_use_volume)
  208. else:
  209. print(f'本轮没有持仓股票信息!')
  210. def buy_trader(data):
  211. print('买入函数:', dt.now(), f'接受到{len(data.keys())}个个股')
  212. results = mp.Manager().list()
  213. mp_list = []
  214. engine_hlfx_pool = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx_pool?charset=utf8')
  215. try:
  216. stock_pool = pd.read_sql_query(
  217. 'select value from `%s` order by `index` desc limit 10' % '1d', engine_hlfx_pool)
  218. stock_pool = stock_pool.iloc[0, 0].split(",")
  219. stock_pool.sort()
  220. print('stock_pool', len(stock_pool))
  221. except BaseException:
  222. pass
  223. '''
  224. for stock in data:
  225. if stock.replace('SH', 'XSHG').replace('SZ', 'XSHE') in stock_pool:
  226. # 真实买入策略
  227. current_price, open_price = data[stock]['lastPrice'], data[stock]['open']
  228. MA5, MA10, MA20 = ma(stock, 5), ma(stock, 10), ma(stock, 20)
  229. MA5_1 = ma_1(stock, 5)
  230. print(stock, current_price, open_price, MA5, MA10, MA20, MA5_1)
  231. if (current_price > open_price) & (current_price > MA5) & (MA5 > MA5_1) & (current_price < MA5 * 1.03) & (MA20 < MA10):
  232. if his_vol(stock, -1) > his_vol(stock, -2):
  233. results.append(stock.replace('SH', 'XSHG').replace('SZ', 'XSHE'))
  234. print('append')
  235. '''
  236. list_judge = list(set(data.keys()) & set(stock_pool))
  237. print(f'本轮有{len(data.keys())}条个股信息,而list_judge有:{len(list_judge)}')
  238. step = math.ceil(len(list_judge) / 2)
  239. print('step:', step)
  240. rate = 0.8
  241. for i in range(0, len(list_judge), step):
  242. p = mp.Process(target=ma_judge, args=(data, list_judge[i:i + step], rate, results))
  243. mp_list.append(p)
  244. p.start()
  245. for j in mp_list:
  246. j.join()
  247. results = list(set(results))
  248. print('results!!!!', len(results))
  249. # 选择板块
  250. if len(results) != 0:
  251. # 基本面过滤
  252. results = get_fundamentals(results)
  253. num_industry = get_industry(results)
  254. industry_list = []
  255. for key in num_industry.values():
  256. for key2 in key.values():
  257. industry_list.append(key2['industry_name'])
  258. industry_list = pd.value_counts(industry_list)
  259. # 最热集中的n个板块
  260. max_industry_list = list(industry_list[0:2].index)
  261. results_industry = []
  262. for key, value in num_industry.items():
  263. for key2 in value.values():
  264. if key2['industry_name'] in max_industry_list:
  265. results_industry.append(key)
  266. results_industry = ','.join(set(results_industry))
  267. print('1d', '\n', results_industry)
  268. db_pool = pymysql.connect(host='localhost',
  269. user='root',
  270. port=3307,
  271. password='r6kEwqWU9!v3',
  272. database='hlfx_pool')
  273. cursor_pool = db_pool.cursor()
  274. sql = "INSERT INTO MA5_%s (date,value) VALUES('%s','%s')" % ('1d', dt.now().strftime('%Y-%m-%d %H:%M:%S'),
  275. results_industry)
  276. cursor_pool.execute(sql)
  277. db_pool.commit()
  278. # print(len(results_industry), results_industry)
  279. print(dt.now(), '数据库数据已赋值!')
  280. cursor_pool.close()
  281. db_pool.close()
  282. # 取值交易
  283. keep_stocks = results_industry.split(",")
  284. new_keep_stock = [stock.replace('XSHG', 'SH').replace('XSHE', 'SZ') for stock in keep_stocks]
  285. print(f'new_keep_stock is:{len(new_keep_stock)}')
  286. # 进入购买程序
  287. max_pos = 7
  288. for stock in new_keep_stock:
  289. positions = xt_trader.query_stock_positions(acc)
  290. asset = xt_trader.query_stock_asset(acc)
  291. print('bbbb', positions, asset)
  292. cash = asset.cash
  293. positions_dict = {positions[x].stock_code: positions[x].volume for x in range(0, len(positions)) if
  294. positions[x].volume > 0}
  295. print(f'判断{stock}:cash={cash},持仓数量为{len(positions_dict)}')
  296. current_price = data[stock]['lastPrice']
  297. current_high = data[stock]['high']
  298. if cash > 5000 and len(positions_dict) < max_pos and current_price > 9 \
  299. and current_price > (current_high * 0.98):
  300. volume = int((cash / 3 / current_price) // 100 * 100)
  301. print('买入信号!!!!!!', stock, volume, current_price)
  302. order_id = xt_trader.order_stock(acc, stock, xtconstant.STOCK_BUY, volume, xtconstant.LATEST_PRICE,
  303. current_price, 'MA5策略', 'MA5趋势向上')
  304. print(order_id)
  305. else:
  306. print(f'Cash只有:{cash} 或者 现有持仓{len(positions_dict)} 超过了{max_pos}')
  307. engine_hlfx_pool.dispose()
  308. print('一轮结束了,现在时间是:', dt.now())
  309. def trader(data):
  310. # sell_trader(data)
  311. # 买入条件
  312. buy_trader(data)
  313. def bridge():
  314. pid = os.getpid()
  315. print(f'MyPid is {os.getpid()}, now is {dt.now()},开盘了')
  316. stocks = xtdata.get_stock_list_in_sector('沪深A股')
  317. seq = xtdata.subscribe_whole_quote(stocks, callback=trader)
  318. run(seq, pid)
  319. def job_func():
  320. print(f"Job started at {dt.now()}")
  321. # 创建子进程
  322. p = mp.Process(target=bridge)
  323. # 启动子进程
  324. p.start()
  325. # 等待子进程结束
  326. p.join()
  327. print(f"Job finished at {dt.now()}")
  328. if __name__ == '__main__':
  329. mp.freeze_support()
  330. print('cpu_count =', mp.cpu_count())
  331. pus = psutil.Process()
  332. pus.cpu_affinity([10, 11, 12, 13, 14, 15])
  333. # job_func()
  334. scheduler = BlockingScheduler()
  335. scheduler.add_job(func=job_func, trigger='cron', day_of_week='0-4', hour='09', minute='40',
  336. timezone="Asia/Shanghai")
  337. # scheduler.add_job(func=job_func, trigger='cron', day_of_week='0-4', hour='13', minute='05',
  338. # timezone="Asia/Shanghai")
  339. try:
  340. scheduler.start()
  341. except (KeyboardInterrupt, SystemExit):
  342. pass
  343. # xtdata.subscribe_quote('000001.SZ', '1d', '', '', count=1, callback=MA)