real_time_order_MA_HLFX_1025.py 10 KB

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