m = 0
# def mm(m):
#     while True:
#         print('m=', m)
#         m = m + 1
#         if m == 10:
#             break
#     return
# print(mm(m))

import pandas as pd
import pymysql
from sqlalchemy import create_engine, text
import threading
from datetime import datetime as dt
import datetime
from jqdatasdk.technical_analysis import *
from xtquant import xtdata, xtconstant
from xtquant.xttype import StockAccount
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
import time
import math
import multiprocessing as mp
import os
import psutil
import traceback
from apscheduler.schedulers.blocking import BlockingScheduler
import sys

# p = xtdata.get_instrument_detail('000001.sz')
# print(p.get('UpStopPrice'))


# stock = '000001.SZ'
# engine_stock = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/qmt_stocks_whole?charset=utf8',
#                              pool_size=5000, pool_recycle=50, max_overflow=-1)
# df = pd.read_sql_query(text(
#                 'select close_front, high_front from `%s_1d`' % stock), engine_stock.connect())
#
# print(df['close_front'].iloc[-1])
# print(df['close_front'].iloc[-2])


def sell_trader(data):
    stock = '002645.SZ'
    # print(data[stock][0]['close'])
    print(xtdata.get_instrument_detail(stock).get('UpStopPrice'))

    current_price = data[stock]['lastPrice']
    print('aaa', current_price, data[stock]['time'])
    print(data[stock])

'''
    if stock in data and can_use_volume != 0:
        current_price = data[stock]['lastPrice']
        open_price = data[stock]['open']
        MA5 = ma(stock, 5, data)
        MA5_1 = ma_1(stock, 5)
        df = pd.read_sql_query(text(
            'select close_front, high_front from `%s_1d`' % stock), engine_stock.connect())
        print(f'{stock},持仓量为{can_use_volume}当前价:{current_price},MA5:{MA5},昨日MA5：{MA5_1},开始判断:')
        if current_price == xtdata.get_instrument_detail(stock).get('UpStopPrice') \
                or (df['close_front'].iloc[-1] == df['high_front'].iloc[-1]
                    and df['close_front'].iloc[-1] / df['close_front'].iloc[-2] > 1.08):
            continue
        elif current_price < MA5 or MA5 < MA5_1:
            print('卖出信号！！！！！！', stock, current_price)
            order_id = xt_trader.order_stock(acc, stock, xtconstant.STOCK_SELL, can_use_volume,
                                             xtconstant.LATEST_PRICE, 0, 'MA5策略', '低于MA5趋势向下')
            print('价格：', current_price, open_price, MA5, MA5_1, '低于MA5趋势向下')
            print(order_id, stock, can_use_volume)
        elif current_price > MA5 * 1.07:
            print('盈利乖离率超7%！！！！！！', stock, current_price)
            order_id = xt_trader.order_stock(acc, stock, xtconstant.STOCK_SELL, can_use_volume,
                                             xtconstant.LATEST_PRICE, 0, 'MA5策略', '盈利乖离率超7%')
            print('价格：', current_price, open_price, MA5, MA5_1, '盈利乖离率超7%')
            print(order_id, stock, can_use_volume)
    else:
        print(f'本轮没有持仓股票信息！')
'''




# xtdata.subscribe_quote('301125.SZ',callback=sell_trader)
stocks = xtdata.get_stock_list_in_sector('沪深A股')
xtdata.download_history_data2(stock_list=stocks, period='30m', start_time='', end_time='')
print(stocks)
seq = xtdata.subscribe_whole_quote(stocks, callback=sell_trader)
xtdata.run()
