Browse Source

Merge remote-tracking branch 'origin/master'

daniel 2 years ago
parent
commit
83af14b012
4 changed files with 633 additions and 1 deletions
  1. 3 1
      docker.start.txt
  2. 53 0
      his_money_flow.py
  3. 232 0
      real_time_order_MA_HLFX_1025.py
  4. 345 0
      real_time_update_qbh_hlfx_1025.py

+ 3 - 1
docker.start.txt

@@ -1,3 +1,5 @@
 docker run -itd --name mysql8 -p 3307:3306 -e MYSQL_ROOT_PASSWORD=r6kEwqWU9!v3 -v D:/MySQL/docker_mysql:/var/lib/mysql mysql:8.0.28-oracle
 
-docker run -itd --name mysql82 -p 3312:3306 -e MYSQL_ROOT_PASSWORD=r6kEwqWU9!v3 mysql:8.0.28-oracle
+docker run -itd --name mysql82 -p 3312:3306 -e MYSQL_ROOT_PASSWORD=r6kEwqWU9!v3 mysql:8.0.28-oracle
+
+# version order 1

+ 53 - 0
his_money_flow.py

@@ -0,0 +1,53 @@
+from jqdatasdk import *
+from datetime import datetime as dt
+import pandas as pd
+import pymysql
+from sqlalchemy import create_engine
+
+auth('18616891214', 'Ea?*7f68nD.dafcW34d!')
+stocks = list(get_all_securities(['stock'], date=dt.today().strftime('%Y-%m-%d')).index)
+engine = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/stocks?charset=utf8')
+engine_data = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/stocks_data?charset=utf8')
+# stocks_List = ','.join(set(stocks))
+
+# db_stocks_list = pymysql.connect(host='localhost',
+#                           user='root',
+#                           port=3307,
+#                           password='r6kEwqWU9!v3',
+#                           database='hlfx_pool')
+# cursor_stock_list = db_stocks_list.cursor()
+# sql = "INSERT INTO stocks_list (date,securities) VALUES('%s','%s')" % (dt.today().strftime('%Y-%m-%d'),  stocks_List)
+# cursor_stock_list.execute(sql)
+# db_stocks_list.commit()
+# db_stocks_list.close()
+
+fre = '1d'
+print('ready to write to mysql %s' % fre)
+for stock in stocks:
+    print(stock, fre)
+    starttime ='2010-01-04'
+    # endtime = pd.read_sql_table('stk%s_%s' % (stock, fre), con=engine).iloc[-1, 1]
+    df_stock = get_price(stock, start_date=starttime, end_date=dt.today().strftime('%Y-%m-%d %H:%M:%S'),
+                         frequency=fre, fields=['open', 'close', 'high', 'low', 'volume', 'money'],
+                         skip_paused=False,
+                         fq='pre', count=None, panel=False)
+    df_stock.index.name = 'date'
+
+    # print(df_stock)
+    # print(starttime,endtime)
+
+    df_money = get_money_flow(stock, start_date=starttime, end_date=dt.today().strftime('%Y-%m-%d %H:%M:%S'),
+                              fields=None, count=None)
+    df_money = df_money.drop(columns=['sec_code'])
+    # df_money.to_csv('/Users/daniel/Downloads/000002.csv')
+    # print(df_money)
+
+    df_stock = pd.merge(df_stock, df_money, how='outer', left_index=False , on='date')
+    # df_stock.to_csv('D:\001_QuantTrade\Result.csv')
+    df_stock = df_stock.dropna(axis=0)
+    df_stock.reset_index(inplace=True)
+    df_stock.rename(columns={'index': 'date'}, inplace=True)
+    df_stock.to_sql('stk%s_%s' % (stock, fre), con=engine_data, index=True, if_exists='replace')
+    # with engine.connect() as con:
+    #     con.execute("ALTER TABLE `stk%s_%s` ADD PRIMARY KEY (`date`);" % (stock, fre))
+    print(df_stock)

+ 232 - 0
real_time_order_MA_HLFX_1025.py

@@ -0,0 +1,232 @@
+from future.types import newint
+from jqdatasdk import *
+from datetime import datetime as dt
+import pandas as pd
+import pymysql
+from sqlalchemy import create_engine
+import time
+from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
+from xtquant.xttype import StockAccount
+from xtquant import xtconstant
+from xtquant import xtdata
+
+
+
+auth('18616891214', 'Ea?*7f68nD.dafcW34d!')
+
+#启动交易系统
+path = 'D:\\安信证券QMT实盘_交易终端\\userdata_mini'
+# session_id为会话编号,策略使用方对于不同的Python策略需要使用不同的会话编号
+session_id = 20221123
+#后续的所有示例将使用该实例对象
+xt_trader = XtQuantTrader(path, session_id)
+xt_trader.start()
+connect_result = xt_trader.connect()
+if connect_result == 0:
+    print('QMTmini 已连接')
+else:
+    print('连接失败')
+
+account = StockAccount('920000207040', 'SECURITY')  # xt_trader为XtQuant API实例对象
+positions = xt_trader.query_stock_positions(account)
+
+
+
+
+fre = '1d'
+
+engine_hlfx_pool = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx_pool?charset=utf8')
+# engine_stock = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/stocks?charset=utf8')
+
+db_pool = pymysql.connect(host='localhost',
+                              user='root',
+                              port=3307,
+                              password='r6kEwqWU9!v3',
+                              database='hlfx_pool')
+cursor_pool = db_pool.cursor()
+
+
+
+fut = locals()
+print(dt.now(), '开始寻找MA5趋势!')
+
+
+def XtTrader(new_keep_stock):
+    # 获取账号信息
+    # account = StockAccount('888824600221', 'CREDIT') #xt_trader为XtQuant API实例对象
+    account = StockAccount('920000207040', 'SECURITY')  # xt_trader为XtQuant API实例对象
+    # print('acc:', account.account_type, account.account_id)
+    # print("query asset:")
+    asset = xt_trader.query_stock_asset(account)
+    positions = xt_trader.query_stock_positions(account)
+    if asset:
+        print("asset:")
+        print(asset.account_type, asset.account_id, asset.cash, asset.frozen_cash, asset.market_value,
+              asset.total_asset)
+    # 开始交易
+    for i in new_keep_stock:
+        print(i)
+        price = get_bars(i.replace('SH', 'XSHG').replace('SZ', 'XSHE'), count=1, unit=fre, fields=['close'],
+                         include_now=True).iloc[-1].at['close']
+        print('price:', price)
+        print(asset.cash / price)
+        if asset.cash > 2000:
+            volume = int((asset.cash / 2 / price) // 100 * 100)
+            print('volume:', volume)
+            order_id = xt_trader.order_stock(account, i, xtconstant.STOCK_BUY, volume, xtconstant.LATEST_PRICE, price, 'strategy1', 'order_test')
+            print(order_id)
+    # for i in positions:
+    #     price = get_bars(i.replace('SH', 'XSHG').replace('SZ', 'XSHE'), count=1, unit=fre, fields=['close'],
+    #                      include_now=True).iloc[-1].at['close']
+    #     if Sell_Trader(i):
+    #         print('yao maihu de gupiao !!!!!!!!!!!', i.stock_code)
+    #         order_id = xt_trader.order_stock(account, i, xtconstant.STOCK_SELL,
+    #                                              1000, xtconstant.FIX_PRICE, 10.90, 'strategy1', 'order_test')
+    # print(positions[1].stock_code, positions[1].volume)
+
+    print('今日成交:')
+    for trades in xt_trader.query_stock_trades(account):
+        print(trades.stock_code, trades.traded_volume, trades.traded_price)
+
+    positions = xt_trader.query_stock_positions(account)
+    print("positions:", len(positions))
+    if len(positions) != 0:
+        print("last position:")
+        print("{0} {1} {2}".format(positions[-1].account_id, positions[-1].stock_code, positions[-1].volume))
+
+    print(positions)
+    xt_trader.stop()
+
+def Sell_Trader(stock, account, positions, volume):
+    price = get_bars(stock, count=1, unit=fre, fields=['close'],
+                     include_now=True).iloc[-1].at['close']
+    print(type(stock.replace('XSHG', 'SH').replace('XSHE', 'SZ')),stock.replace('XSHG', 'SH').replace('XSHE', 'SZ') )
+    order_id = xt_trader.order_stock(account, stock.replace('XSHG', 'SH').replace('XSHE', 'SZ'), xtconstant.STOCK_SELL,
+                                     volume, xtconstant.LATEST_PRICE, 0,  'strategy1', 'order_test')
+    print(order_id, i)
+
+
+while True:
+
+    now_date = dt.now()
+    date_morning_begin = now_date.replace(hour=9, minute=25, second=0)
+    date_morning_end = now_date.replace(hour=11, minute=31, second=0)
+    date_afternooe_begin = now_date.replace(hour=13, minute=0, second=0)
+    date_afternooe_end = now_date.replace(hour=15, minute=0, second=0)
+    # if True:
+    if date_morning_begin < now_date < date_morning_end or date_afternooe_begin < now_date < date_afternooe_end:
+        # time.sleep(1800)
+        try:
+            account = StockAccount('920000207040', 'SECURITY')  # xt_trader为XtQuant API实例对象
+            positions = xt_trader.query_stock_positions(account)
+            print(positions)
+        except BaseException:
+            continue
+        for i in positions:
+            # print(i.stock_code, i.volume)
+            volume = i.volume
+            stock = i.stock_code.replace('SH', 'XSHG').replace('SZ', 'XSHE')
+            df_stock = get_bars(stock, count=60, unit=fre,
+                                     fields=['date', 'open', 'close', 'high', 'low', 'volume'],
+                                     include_now=True, df=True)
+
+            price = df_stock.iloc[-1].at['close']
+            MA5_1 = df_stock['close'][-7:-2].mean()
+            MA5 = df_stock['close'][-6:-1].mean()
+            MA10 = df_stock['close'][-11:-1].mean()
+            MA20 = df_stock['close'][-21:-1].mean()
+            if price < MA5 or MA5 < MA5_1 or price > MA5 * 1.12:
+                print(MA5, MA5_1)
+                Sell_Trader(stock, account, positions, volume)
+
+
+        for fre in ['1d']:
+            print('开始:', fre)
+            results = []
+            try:
+                stock_pool = pd.read_sql_query(
+                    'select value from `%s`' % fre, engine_hlfx_pool)
+                stock_pool = stock_pool.iloc[-1, 0].split(",")
+                print(stock_pool)
+            except BaseException:
+                continue
+            for stock in stock_pool:
+                # print(stock)
+                try:
+                    df_stock = get_bars(stock, count=60, unit=fre, fields=['date', 'open', 'close', 'high', 'low','volume'],
+                                           include_now=True, df=True)
+                    price = df_stock.iloc[-1].at['close']
+                    price_open = df_stock.iloc[-1].at['open']
+                    MA5_1 = df_stock['close'][-7:-2].mean()
+                    MA5 = df_stock['close'][-6:-1].mean()
+                    MA10 = df_stock['close'][-11:-1].mean()
+                    MA20 = df_stock['close'][-21:-1].mean()
+                    # print(price,price_open, 'ma5_1:',MA5_1, 'ma5:', MA5,MA10)
+                    if (price > price_open) & (price > MA5) & (MA5 > MA5_1) & (price < MA5 * 1.03) & (MA20 < MA10)  \
+                            & (df_stock.iloc[-1].at['volume'] > df_stock.iloc[-2].at['volume']):
+                        print(stock)
+                        results.append(stock)
+                    elif price < MA5 or MA5<MA5_1 or price > MA5*1.09:
+                        stock_pool.remove(stock)
+                        print(stock, '已失败!')
+                except BaseException:
+                    continue
+            results = list(set(results))
+            print(results)
+            now_time = dt.now().strftime('%Y-%m-%d %H:%M:%S')
+            # results_list =','.join(results)
+            # print(fre, '\n', results_list)
+
+
+
+            if len(results) == 0:
+                continue
+            else:
+                num_industry = get_industry(results)
+                print(num_industry)
+                industry_list = []
+                for key in num_industry.values():
+                    for key2 in key.values():
+                        industry_list.append(key2['industry_name'])
+                industry_list = pd.value_counts(industry_list)
+                # 最热集中的n个板块
+                max_industry_list = list(industry_list[0:3].index)
+                results_industry = []
+                for key, value in num_industry.items():
+                    for key2 in value.values():
+                        if key2['industry_name'] in max_industry_list:
+                            results_industry.append(key)
+                print('suoyou:', set(results_industry))
+                results_industry = ','.join(set(results_industry))
+                print(fre, '\n', results_industry)
+
+                sql = "INSERT INTO MA5_%s (date,value) VALUES('%s','%s')" % (fre, dt.now().strftime('%Y-%m-%d %H:%M:%S'),
+                                                                             results_industry)
+                cursor_pool.execute(sql)
+                db_pool.commit()
+
+                print(len(results_industry), results_industry)
+                print(dt.now(), '数据库数据已赋值!')
+
+                # 取值交易
+                engine_hlfx_pool = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx_pool?charset=utf8')
+
+                # stocks = xtdata.get_stock_list_in_sector('沪深A股')
+                keep_stocks = pd.read_sql_query(
+                    'select value from `MA5_%s`' % fre, engine_hlfx_pool)
+                keep_stocks = keep_stocks.iloc[-1, 0].split(",")
+                new_keep_stock = [stock.replace('XSHG', 'SH').replace('XSHE', 'SZ') for stock in keep_stocks]
+                print(new_keep_stock)
+                price = get_bars(keep_stocks, count=1, unit=fre, fields=['close'])
+
+                XtTrader(new_keep_stock)
+        time.sleep(1800)
+    elif now_date > date_afternooe_end:
+        pass
+        # print("MA5_收盘了", now_date)
+        # break
+
+
+
+
+

+ 345 - 0
real_time_update_qbh_hlfx_1025.py

@@ -0,0 +1,345 @@
+from jqdatasdk import *
+import pandas as pd
+import pymysql
+from sqlalchemy import create_engine
+import threading
+from datetime import datetime as dt
+from jqdatasdk.technical_analysis import *
+
+auth('18616891214', 'Ea?*7f68nD.dafcW34d!')
+stocks = list(get_all_securities(['stock'], date=dt.today().strftime('%Y-%m-%d')).index)
+# stocks = stocks[0:200]
+
+def hlfx(stocks, engine_stock, engine_hlfx):
+    for thd.stock in stocks:
+        print(thd.stock)
+        if ('stk%s_%s' % (thd.stock, fre)) in table_list:
+            # 有历史数据
+            index_len = pd.read_sql_table('stk%s_%s' % (thd.stock, fre), con=engine_hlfx).iloc[-1, 0]
+            startdate = pd.read_sql_table('stk%s_%s' % (thd.stock, fre), con=engine_hlfx).iloc[-1, 1]
+
+            # thd.get_price = pd.read_sql_query(
+            #     'select date,open,close,high,low,volume,money from `stk%s_%s`' % (thd.stock, fre), engine_stock)
+            # thd.get_price = thd.get_price.loc[thd.get_price['date'] > startdate]
+            thd.get_price = df.loc[thd.stock]
+
+            thd.df_day = pd.read_sql_query(
+                'select date,open,close,high,low,volume,money,HL from `stk%s_%s`' % (thd.stock, fre), engine_hlfx)
+
+            # 先处理去包含
+            for i in thd.get_price.index:
+                # 不包含
+                if (thd.df_day.iloc[-1, 3] > thd.get_price.loc[i, 'high']
+                    and thd.df_day.iloc[-1, 4] > thd.get_price.loc[i, 'low']) \
+                        or (thd.df_day.iloc[-1, 3] < thd.get_price.loc[i, 'high']
+                            and thd.df_day.iloc[-1, 4] < thd.get_price.loc[i, 'low']):
+                    thd.df_day = pd.concat([thd.df_day, thd.get_price.loc[[i]]], ignore_index=True)
+
+                # 包含
+                else:
+                    # (new_df.iloc[-1,3]>=df_day.loc[i,'high'] and new_df.iloc[-1,4]<= df_day.loc[i,'low']):
+                    # 左高,下降
+                    if thd.df_day.iloc[-2, 3] > thd.df_day.iloc[-1, 3]:
+                        thd.df_day.iloc[-1, 3] = min(thd.df_day.iloc[-1, 3], thd.get_price.loc[i, 'high'])
+                        thd.df_day.iloc[-1, 4] = min(thd.df_day.iloc[-1, 4], thd.get_price.loc[i, 'low'])
+                    else:
+                        # 右高,上升
+                        thd.df_day.iloc[-1, 3] = max(thd.df_day.iloc[-1, 3], thd.get_price.loc[i, 'high'])
+                        thd.df_day.iloc[-1, 4] = max(thd.df_day.iloc[-1, 4], thd.get_price.loc[i, 'low'])
+
+            # 寻找顶底分型
+            if len(thd.df_day.index) > 2:
+                x = len(thd.df_day.index)-1
+                m = x - 1
+                # 底
+                if ((thd.df_day.loc[x, 'high'] > thd.df_day.loc[x - 1, 'high']) and (
+                        thd.df_day.loc[x - 2, 'high'] > thd.df_day.loc[x - 1, 'high'])):
+                    # if ((stk.df_day.loc[i-2, 'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-3,'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-1,'date'] != stk.fxdf.iloc[-1,0])):
+                    # stk.fxdf = pd.concat([stk.fxdf, stk.df_day.iloc[[i]]], ignore_index=True)
+                    thd.df_day.loc[x, 'HL'] = 'L*'
+                    while m:
+                        if thd.df_day.loc[m, 'HL'] == 'H':
+                            if (x - m) > 3:
+                                thd.df_day.loc[x, 'HL'] = 'L'
+                                # 此处可以获得MACD指标
+                                # pre-macd_dif, pre-macd_dea, pre-macd_macd = MACD(thd.stock,check_date=thd.df_day.loc[m, 'datetime'], SHORT = 12, LONG = 26, MID = 9)
+                                    # pass
+                                print(thd.stock, '$$$$$$$', '\n', thd.df_day.loc[x, 'date'], '\n',
+                                      '笔形成————买买买买买!!')
+                                results.append(thd.stock)
+                                print('222')
+                            # break
+                        elif (thd.df_day.loc[m, 'HL'] == 'L'):
+                            if thd.df_day.loc[x - 1, 'low'] < thd.df_day.loc[m - 1, 'low']:
+                                # 前一个为底,且中间存在不包含 or 更低的底
+                                thd.df_day.loc[x, 'HL'] = 'L'
+                                x_macd_dif, x_macd_dea, x_macd_macd = MACD(thd.stock,
+                                                                           check_date=thd.df_day.loc[x, 'date'],
+                                                                           SHORT=12, LONG=26, MID=9, unit=fre)
+                                m_macd_dif, m_macd_dea, m_macd_macd = MACD(thd.stock,
+                                                                           check_date=thd.df_day.loc[m, 'date'],
+                                                                           SHORT=12, LONG=26, MID=9, unit=fre)
+                                if x_macd_dif[thd.stock] > m_macd_dif[thd.stock]:
+                                    # pass
+                                    # print(thd.df_day.loc[m, 'date'], thd.df_day.loc[m, 'low'],
+                                    #       m_macd_dif[thd.stock])
+                                    # print(thd.df_day.loc[x, 'date'], thd.df_day.loc[x, 'low'],
+                                    #       x_macd_dif[thd.stock])
+                                    print(thd.stock, '$$$$$$$', '\n', thd.df_day.loc[x, 'date'], 'MACD背驰————买吗?!')
+                                    results.append(thd.stock)
+                                    print('333')
+                                break
+                            else:
+                                # 底更低但没有背驰
+                                break
+                        m = m - 1
+                        if m == 0:
+                            # 第一个底
+                            thd.df_day.loc[x, 'HL'] = 'L'
+                            results.append(thd.stock)
+                            print('444')
+                # 顶
+                elif ((thd.df_day.loc[x, 'high'] < thd.df_day.loc[x - 1, 'high']) and (
+                        thd.df_day.loc[x - 2, 'high'] < thd.df_day.loc[x - 1, 'high'])):
+                    # if ((stk.df_day.loc[i-2, 'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-3,'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-1,'date'] != stk.fxdf.iloc[-1,0])):
+                    #     stk.fxdf = pd.concat([stk.fxdf, stk.df_day.iloc[[i]]], ignore_index=True)
+                    thd.df_day.loc[x, 'HL'] = 'H*'
+                    while m:
+                        if thd.df_day.loc[m, 'HL'] == 'L':
+                            if x - m > 3:
+                                thd.df_day.loc[x, 'HL'] = 'H'
+                                print(thd.stock, '!!!!!!!', '\n', thd.df_day.loc[x, 'date'], '笔形成————卖卖卖卖卖卖卖!')
+                                # pass
+                                results_short.append(thd.stock)
+                                if thd.stock in results:
+                                    results.remove(thd.stock)
+                            # break
+                        elif (thd.df_day.loc[m, 'HL'] == 'H'):
+                            if thd.df_day.loc[x - 1, 'high'] > thd.df_day.loc[m - 1, 'high']:
+                                # 前一个为顶,且中间存在不包含 or 更高的顶
+                                thd.df_day.loc[x, 'HL'] = 'H'
+                                x_macd_dif, x_macd_dea, x_macd_macd = MACD(thd.stock,
+                                                                           check_date=thd.df_day.loc[x, 'date'],
+                                                                           SHORT=12, LONG=26, MID=9, unit=fre)
+                                m_macd_dif, m_macd_dea, m_macd_macd = MACD(thd.stock,
+                                                                           check_date=thd.df_day.loc[m, 'date'],
+                                                                           SHORT=12, LONG=26, MID=9, unit=fre)
+                                if x_macd_dif[thd.stock] < m_macd_dif[thd.stock]:
+                                    # pass
+                                    print(thd.stock, '/\/\/\/\/\/\/', '顶背离了!!!!')
+                                    results_short.append(thd.stock)
+                                    if thd.stock in results:
+                                        results.remove(thd.stock)
+                                break
+                            break
+                        m = m - 1
+                        if m == 0:
+                            thd.df_day.loc[x, 'HL'] = 'H'
+                            results_short.append(thd.stock)
+                            if thd.stock in results:
+                                results.remove(thd.stock)
+                else:
+                    thd.df_day.loc[x, 'HL'] = '-'
+
+            # 更新数据库
+            # 可以使用normalize_code(code) 方法 改变代码格式
+            # thd.df_day[index_len + 1:].to_sql('stk%s_%s' % (thd.stock, fre), con=engine_hlfx, index=True, if_exists='append')
+        else:
+            # 没有历史数据表
+            thd.df_day = pd.DataFrame(columns=('date', 'open', 'close', 'high', 'low', 'volume', 'money', 'HL'))
+            thd.get_price = pd.read_sql_query(
+                'select date,open,close,high,low,volume,money from `stk%s_%s`' % (thd.stock, fre), engine_stock)
+            # 先处理去包含
+            for i in thd.get_price.index:
+                if i == 0 or i == 1:
+                    thd.df_day = pd.concat([thd.df_day, thd.get_price.iloc[[i]]], ignore_index=True)
+                # 不包含
+                elif (thd.df_day.iloc[-1, 3] > thd.get_price.loc[i, 'high']
+                      and thd.df_day.iloc[-1, 4] > thd.get_price.loc[i, 'low']) \
+                        or (thd.df_day.iloc[-1, 3] < thd.get_price.loc[i, 'high']
+                            and thd.df_day.iloc[-1, 4] < thd.get_price.loc[i, 'low']):
+                    thd.df_day = pd.concat([thd.df_day, thd.get_price.loc[[i]]], ignore_index=True)
+                # 包含
+                else:
+                    # 左高,下降
+                    if thd.df_day.iloc[-2, 3] > thd.df_day.iloc[-1, 3]:
+                        thd.df_day.iloc[-1, 3] = min(thd.df_day.iloc[-1, 3], thd.get_price.loc[i, 'high'])
+                        thd.df_day.iloc[-1, 4] = min(thd.df_day.iloc[-1, 4], thd.get_price.loc[i, 'low'])
+                    else:
+                        # 右高,上升
+                        thd.df_day.iloc[-1, 3] = max(thd.df_day.iloc[-1, 3], thd.get_price.loc[i, 'high'])
+                        thd.df_day.iloc[-1, 4] = max(thd.df_day.iloc[-1, 4], thd.get_price.loc[i, 'low'])
+            if len(thd.df_day.index) > 2:
+                # 寻找顶底分型
+                x = len(thd.df_day.index)-1
+                m = x - 1
+                # 底
+                if ((thd.df_day.loc[x, 'high'] > thd.df_day.loc[x - 1, 'high']) and (
+                        thd.df_day.loc[x - 2, 'high'] > thd.df_day.loc[x - 1, 'high'])):
+                    # if ((stk.df_day.loc[i-2, 'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-3,'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-1,'date'] != stk.fxdf.iloc[-1,0])):
+                    # stk.fxdf = pd.concat([stk.fxdf, stk.df_day.iloc[[i]]], ignore_index=True)
+                    thd.df_day.loc[x, 'HL'] = 'L*'
+                    while m:
+                        if thd.df_day.loc[m, 'HL'] == 'H':
+                            if (x - m) > 3:
+                                thd.df_day.loc[x, 'HL'] = 'L'
+                                # 此处可以获得MACD指标
+                                # pre-macd_dif, pre-macd_dea, pre-macd_macd = MACD(thd.stock,check_date=thd.df_day.loc[m, 'datetime'], SHORT = 12, LONG = 26, MID = 9)
+                                # pass
+                                print(thd.stock, '$$$$$$$', '\n', thd.df_day.loc[x, 'date'], '买买买买买!!')
+                                results.append(thd.stock)
+                            # break
+                        elif (thd.df_day.loc[m, 'HL'] == 'L'):
+                            if thd.df_day.loc[x - 1, 'low'] < thd.df_day.loc[m - 1, 'low']:
+                                # 前一个为底,且中间存在不包含 or 更低的底
+                                thd.df_day.loc[x, 'HL'] = 'L'
+                                x_macd_dif, x_macd_dea, x_macd_macd = MACD(thd.stock,
+                                                                           check_date=thd.df_day.loc[x, 'date'],
+                                                                           SHORT=12, LONG=26, MID=9, unit=fre)
+                                m_macd_dif, m_macd_dea, m_macd_macd = MACD(thd.stock,
+                                                                           check_date=thd.df_day.loc[m, 'date'],
+                                                                           SHORT=12, LONG=26, MID=9, unit=fre)
+                                if x_macd_dif[thd.stock] > m_macd_dif[thd.stock]:
+                                    # pass
+                                    # print(thd.df_day.loc[m, 'date'], thd.df_day.loc[m, 'low'],
+                                    #       m_macd_dif[thd.stock])
+                                    # print(thd.df_day.loc[x, 'date'], thd.df_day.loc[x, 'low'],
+                                    #       x_macd_dif[thd.stock])
+                                    print(thd.stock, '$$$$$$$', '\n', thd.df_day.loc[x, 'date'],
+                                          'MACD背驰————买吗?!')
+                                    results.append(thd.stock)
+
+                                break
+                            else:
+                                break
+                        m = m - 1
+                        if m == 0:
+                            thd.df_day.loc[x, 'HL'] = 'L'
+                            results.append(thd.stock)
+                # 顶
+                elif ((thd.df_day.loc[x, 'high'] < thd.df_day.loc[x - 1, 'high']) and (
+                        thd.df_day.loc[x - 2, 'high'] < thd.df_day.loc[x - 1, 'high'])):
+                    # if ((stk.df_day.loc[i-2, 'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-3,'date'] != stk.fxdf.iloc[-1,0]) and (stk.df_day.loc[i-1,'date'] != stk.fxdf.iloc[-1,0])):
+                    #     stk.fxdf = pd.concat([stk.fxdf, stk.df_day.iloc[[i]]], ignore_index=True)
+                    thd.df_day.loc[x, 'HL'] = 'H*'
+                    while m:
+                        if thd.df_day.loc[m, 'HL'] == 'L':
+                            if x - m > 3:
+                                thd.df_day.loc[x, 'HL'] = 'H'
+                                print(thd.stock, '!!!!!!!', '\n', '卖卖卖卖卖卖卖!')
+                                # pass
+                                results.remove(thd.stock)
+                            # break
+                        elif (thd.df_day.loc[m, 'HL'] == 'H'):
+                            if thd.df_day.loc[x - 1, 'high'] > thd.df_day.loc[m - 1, 'high']:
+                                # 前一个为顶,且中间存在不包含 or 更高的顶
+                                thd.df_day.loc[x, 'HL'] = 'H'
+                                x_macd_dif, x_macd_dea, x_macd_macd = MACD(thd.stock,
+                                                                           check_date=thd.df_day.loc[x, 'date'],
+                                                                           SHORT=12, LONG=26, MID=9, unit=fre)
+                                m_macd_dif, m_macd_dea, m_macd_macd = MACD(thd.stock,
+                                                                           check_date=thd.df_day.loc[m, 'date'],
+                                                                           SHORT=12, LONG=26, MID=9, unit=fre)
+                                if x_macd_dif[thd.stock] < m_macd_dif[
+                                    thd.stock]:
+                                    # pass
+                                    print(thd.stock, '/\/\/\/\/\/\/', '顶背离了!!!!')
+                                    results.remove(thd.stock)
+                                break
+                            break
+                        m = m - 1
+                        if m == 0:
+                            thd.df_day.loc[x, 'HL'] = 'H'
+                            results.remove(thd.stock)
+                else:
+                    thd.df_day.loc[x, 'HL'] = '-'
+            # print(thd.df_day[-20:])
+            # 更新数据库
+            # thd.df_day.to_sql('stk%s_%s' % (thd.stock, fre), con=engine_hlfx, index=True, if_exists='append')
+
+start = dt.now()
+while True:
+    now_date = dt.now()
+    date_morning_begin = now_date.replace(hour=9, minute=25, second=0)
+    date_morning_end = now_date.replace(hour=11, minute=31, second=0)
+    date_afternooe_begin = now_date.replace(hour=13, minute=0, second=0)
+    date_afternooe_end = now_date.replace(hour=15, minute=0, second=0)
+    # print(now_date,date_morning_begin,date_morning_end,date_afternooe_begin,date_afternooe_end)
+    if date_morning_begin < now_date < date_afternooe_end:
+    # if True:
+        for fre in ['1d']:
+            start = dt.now()
+            print(fre)
+            # 连接数据库
+            db = pymysql.connect(host='localhost',
+                                 user='root',
+                                 port=3307,
+                                 password='r6kEwqWU9!v3',
+                                 database='hlfx')
+            cursor = db.cursor()
+            cursor.execute("show tables like '%%%s%%' " % fre)
+            table_list = [tuple[0] for tuple in cursor.fetchall()]
+            print('取得 table_list %s' % fre)
+
+            db_pool = pymysql.connect(host='localhost',
+                                      user='root',
+                                      port=3307,
+                                      password='r6kEwqWU9!v3',
+                                      database='hlfx_pool')
+            cursor_pool = db_pool.cursor()
+
+            stk = locals()
+            thd = threading.local()
+            # 进程准备
+            step = 600
+            thread_list = []
+            engine_stock = []
+            engine_hlfx = []
+            times_engine = 0
+            engine_hlfx_pool = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx_pool?charset=utf8')
+
+            # 获得hlfx_pool池子
+            # results = pd.read_sql_query(
+            #                 'select value from `%s`' % fre, engine_hlfx_pool)
+            # for i in range(0, len(results)):
+            #     print(len(results.iloc[i, 0].split(",")))
+
+            results = pd.read_sql_query(
+                            'select value from `%s`' % fre, engine_hlfx_pool).iloc[-1, 0].split(",")
+            results_short = []
+            print('数据库读取', len(results))
+
+            df = get_bars(stocks, count=20, unit=fre,
+                          fields=['date', 'open', 'close', 'high', 'low', 'volume', 'money'], include_now=True, df=True)
+            print(dt.now(), 'get_bars 成功')
+
+            for i in range(0, len(stocks), step):
+                engine_stock.append(create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/stocks?charset=utf8'))
+                engine_hlfx.append(create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx?charset=utf8'))
+                thread = threading.Thread(target=hlfx, args=(stocks[i:i + step], engine_stock[times_engine], engine_hlfx[times_engine]))
+                times_engine = times_engine + 1
+                thread.start()
+                thread_list.append(thread)
+
+            for thread in thread_list:
+                thread.join()
+            db.close()
+
+
+
+            time = dt.now().strftime('%Y-%m-%d %H:%M:%S')
+            results_list =','.join(set(results))
+            print(set(results))
+            sql = "INSERT INTO %s (date,value) VALUES('%s','%s')" % (fre, dt.now().strftime('%Y-%m-%d %H:%M:%S'), results_list)
+            cursor_pool.execute(sql)
+            db_pool.commit()
+            print(fre, '\n', '做多:', len(set(results)),  set(results))
+            print('做空', len(set(results_short)), set(results_short))
+
+
+            end= dt.now()
+            print('总时长:', (end - start).seconds)
+    elif now_date>date_afternooe_end:
+        pass
+        # print("HLFX_收盘了",now_date)
+        # break