real_time_order_MA_HLFX_1025.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. from jqdatasdk import *
  2. from datetime import datetime as dt
  3. import pandas as pd
  4. import pymysql
  5. from sqlalchemy import create_engine
  6. import time
  7. from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
  8. from xtquant.xttype import StockAccount
  9. from xtquant import xtconstant
  10. from xtquant import xtdata
  11. auth('18616891214', 'Ea?*7f68nD.dafcW34d!')
  12. # auth('18521506014', 'Abc123!@#')
  13. #启动交易系统
  14. path = 'c:\\qmt\\userdata_mini'
  15. # session_id为会话编号,策略使用方对于不同的Python策略需要使用不同的会话编号
  16. session_id = 20221123
  17. # connect_result = xt_trader.connect()
  18. # if connect_result == 0:
  19. # print('QMTmini 已连接')
  20. # else:
  21. # print('连接失败')
  22. # account = StockAccount('920000207040', 'SECURITY') # xt_trader为XtQuant API实例对象
  23. # positions = xt_trader.query_stock_positions(account)
  24. fre = '1d'
  25. engine_hlfx_pool = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx_pool?charset=utf8')
  26. # engine_stock = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/stocks?charset=utf8')
  27. db_pool = pymysql.connect(host='localhost',
  28. user='root',
  29. port=3307,
  30. password='r6kEwqWU9!v3',
  31. database='hlfx_pool')
  32. cursor_pool = db_pool.cursor()
  33. fut = locals()
  34. print(dt.now(), '开始寻找MA5趋势!')
  35. def XtTrader(new_keep_stock):
  36. # 获取账号信息
  37. # account = StockAccount('888824600221', 'CREDIT') #xt_trader为XtQuant API实例对象
  38. account = StockAccount('920000207040', 'SECURITY') # xt_trader为XtQuant API实例对象
  39. # print('acc:', account.account_type, account.account_id)
  40. # print("query asset:")
  41. asset = xt_trader.query_stock_asset(account)
  42. positions = xt_trader.query_stock_positions(account)
  43. if asset:
  44. print("asset:")
  45. print(asset.account_type, asset.account_id, asset.cash, asset.frozen_cash, asset.market_value,
  46. asset.total_asset)
  47. # 开始交易
  48. for i in new_keep_stock:
  49. print(i)
  50. price = get_bars(i.replace('SH', 'XSHG').replace('SZ', 'XSHE'), count=1, unit=fre, fields=['close'],
  51. include_now=True).iloc[-1].at['close']
  52. print('price:', price)
  53. print(asset.cash / price)
  54. if asset.cash > 2000:
  55. volume = int((asset.cash / 2 / price) // 100 * 100)
  56. print('volume:', volume)
  57. order_id = xt_trader.order_stock(account, i, xtconstant.STOCK_BUY, volume, xtconstant.LATEST_PRICE, price, 'strategy1', 'order_test')
  58. print(order_id)
  59. # for i in positions:
  60. # price = get_bars(i.replace('SH', 'XSHG').replace('SZ', 'XSHE'), count=1, unit=fre, fields=['close'],
  61. # include_now=True).iloc[-1].at['close']
  62. # if Sell_Trader(i):
  63. # print('yao maihu de gupiao !!!!!!!!!!!', i.stock_code)
  64. # order_id = xt_trader.order_stock(account, i, xtconstant.STOCK_SELL,
  65. # 1000, xtconstant.FIX_PRICE, 10.90, 'strategy1', 'order_test')
  66. # print(positions[1].stock_code, positions[1].volume)
  67. print('今日成交:')
  68. for trades in xt_trader.query_stock_trades(account):
  69. print(trades.stock_code, trades.traded_volume, trades.traded_price)
  70. positions = xt_trader.query_stock_positions(account)
  71. print("positions:", len(positions))
  72. if len(positions) != 0:
  73. print("last position:")
  74. print("{0} {1} {2}".format(positions[-1].account_id, positions[-1].stock_code, positions[-1].volume))
  75. print(positions)
  76. xt_trader.stop()
  77. def Sell_Trader(stock, account, positions, volume):
  78. price = get_bars(stock, count=1, unit=fre, fields=['close'],
  79. include_now=True).iloc[-1].at['close']
  80. print(type(stock.replace('XSHG', 'SH').replace('XSHE', 'SZ')),stock.replace('XSHG', 'SH').replace('XSHE', 'SZ') )
  81. order_id = xt_trader.order_stock(account, stock.replace('XSHG', 'SH').replace('XSHE', 'SZ'), xtconstant.STOCK_SELL,
  82. volume, xtconstant.LATEST_PRICE, 0, 'strategy1', 'order_test')
  83. print(order_id, i)
  84. while True:
  85. # print('进入循环')
  86. now_date = dt.now()
  87. date_morning_begin = now_date.replace(hour=9, minute=25, second=0)
  88. date_morning_end = now_date.replace(hour=11, minute=31, second=0)
  89. date_afternooe_begin = now_date.replace(hour=13, minute=0, second=0)
  90. date_afternooe_end = now_date.replace(hour=15, minute=0, second=0)
  91. if True:
  92. # if date_morning_begin < now_date < date_morning_end or date_afternooe_begin < now_date < date_afternooe_end:
  93. # time.sleep(1800)
  94. # 后续的所有示例将使用该实例对象
  95. xt_trader = XtQuantTrader(path, session_id)
  96. xt_trader.start()
  97. connect_result = xt_trader.connect()
  98. try:
  99. if connect_result == 0:
  100. print('QMTmini 已连接')
  101. else:
  102. print('连接失败')
  103. account = StockAccount('920000207040', 'SECURITY') # xt_trader为XtQuant API实例对象
  104. positions = xt_trader.query_stock_positions(account)
  105. print(positions)
  106. except BaseException:
  107. continue
  108. for i in positions:
  109. # print(i.stock_code, i.volume)
  110. volume = i.volume
  111. stock = i.stock_code.replace('SH', 'XSHG').replace('SZ', 'XSHE')
  112. df_stock = get_bars(stock, count=60, unit=fre,
  113. fields=['date', 'open', 'close', 'high', 'low', 'volume'],
  114. include_now=True, df=True)
  115. price = df_stock.iloc[-1].at['close']
  116. MA5_1 = df_stock['close'][-7:-2].mean()
  117. MA5 = df_stock['close'][-6:-1].mean()
  118. MA10 = df_stock['close'][-11:-1].mean()
  119. MA20 = df_stock['close'][-21:-1].mean()
  120. if price < MA5 or MA5 < MA5_1 or price > MA5 * 1.12:
  121. print(MA5, MA5_1)
  122. Sell_Trader(stock, account, positions, volume)
  123. for fre in ['1d']:
  124. print('开始:', fre)
  125. results = []
  126. try:
  127. stock_pool = pd.read_sql_query(
  128. 'select value from `%s`' % fre, engine_hlfx_pool)
  129. stock_pool = stock_pool.iloc[-1, 0].split(",")
  130. print(stock_pool)
  131. except BaseException:
  132. continue
  133. for stock in stock_pool:
  134. # print(stock)
  135. try:
  136. df_stock = get_bars(stock, count=60, unit=fre, fields=['date', 'open', 'close', 'high', 'low','volume'],
  137. include_now=True, df=True)
  138. print('time=', df_stock.iloc[-1].at['date'])
  139. price = df_stock.iloc[-1].at['close']
  140. price_open = df_stock.iloc[-1].at['open']
  141. MA5_1 = df_stock['close'][-7:-2].mean()
  142. MA5 = df_stock['close'][-6:-1].mean()
  143. MA10 = df_stock['close'][-11:-1].mean()
  144. MA20 = df_stock['close'][-21:-1].mean()
  145. # print(price,price_open, 'ma5_1:',MA5_1, 'ma5:', MA5,MA10)
  146. if (price > price_open) & (price > MA5) & (MA5 > MA5_1) & (price < MA5 * 1.03) & (MA20 < MA10) \
  147. & (df_stock.iloc[-1].at['volume'] > df_stock.iloc[-2].at['volume']):
  148. print(stock)
  149. results.append(stock)
  150. elif price < MA5 or MA5<MA5_1 or price > MA5*1.09:
  151. stock_pool.remove(stock)
  152. print(stock, '已失败!')
  153. except BaseException:
  154. continue
  155. results = list(set(results))
  156. print(results)
  157. now_time = dt.now().strftime('%Y-%m-%d %H:%M:%S')
  158. # results_list =','.join(results)
  159. # print(fre, '\n', results_list)
  160. if len(results) == 0:
  161. continue
  162. else:
  163. num_industry = get_industry(results)
  164. print(num_industry)
  165. industry_list = []
  166. for key in num_industry.values():
  167. for key2 in key.values():
  168. industry_list.append(key2['industry_name'])
  169. industry_list = pd.value_counts(industry_list)
  170. # 最热集中的n个板块
  171. max_industry_list = list(industry_list[0:3].index)
  172. results_industry = []
  173. for key, value in num_industry.items():
  174. for key2 in value.values():
  175. if key2['industry_name'] in max_industry_list:
  176. results_industry.append(key)
  177. print('suoyou:', set(results_industry))
  178. results_industry = ','.join(set(results_industry))
  179. print(fre, '\n', results_industry)
  180. sql = "INSERT INTO MA5_%s (date,value) VALUES('%s','%s')" % (fre, dt.now().strftime('%Y-%m-%d %H:%M:%S'),
  181. results_industry)
  182. cursor_pool.execute(sql)
  183. db_pool.commit()
  184. print(len(results_industry), results_industry)
  185. print(dt.now(), '数据库数据已赋值!')
  186. # 取值交易
  187. engine_hlfx_pool = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx_pool?charset=utf8')
  188. # stocks = xtdata.get_stock_list_in_sector('沪深A股')
  189. keep_stocks = pd.read_sql_query(
  190. 'select value from `MA5_%s`' % fre, engine_hlfx_pool)
  191. keep_stocks = keep_stocks.iloc[-1, 0].split(",")
  192. new_keep_stock = [stock.replace('XSHG', 'SH').replace('XSHE', 'SZ') for stock in keep_stocks]
  193. print(new_keep_stock)
  194. price = get_bars(keep_stocks, count=1, unit=fre, fields=['close'])
  195. XtTrader(new_keep_stock)
  196. xt_trader.run_forever()
  197. time.sleep(1800)
  198. elif now_date > date_afternooe_end:
  199. pass
  200. # print("MA5_收盘了", now_date)
  201. # break