from xtquant import xtdata, xtconstant
from xtquant.xttype import StockAccount
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
import pandas as pd
import datetime
from datetime import datetime as dt
import sys

pd.set_option('display.max_columns', None)


class MyXtQuantTraderCallback(XtQuantTraderCallback):
    def on_disconnected(self):
        """
        连接断开
        :return:
        """
        print(datetime.datetime.now(), '连接断开回调')

    def on_stock_order(self, order):
        """
        委托回报推送
        :param order: XtOrder对象
        :return:
        """
        print(datetime.datetime.now(), '委托回调', order.order_remark)

    def on_stock_trade(self, trade):
        """
        成交变动推送
        :param trade: XtTrade对象
        :return:
        """
        print(datetime.datetime.now(), '成交回调', trade.order_remark)

    def on_order_error(self, order_error):
        """
        委托失败推送
        :param order_error:XtOrderError 对象
        :return:
        """
        # print("on order_error callback")
        # print(order_error.order_id, order_error.error_id, order_error.error_msg)
        print(f"委托报错回调 {order_error.order_remark} {order_error.error_msg}")

    def on_cancel_error(self, cancel_error):
        """
        撤单失败推送
        :param cancel_error: XtCancelError 对象
        :return:
        """
        print(datetime.datetime.now(), sys._getframe().f_code.co_name)

    def on_order_stock_async_response(self, response):
        """
        异步下单回报推送
        :param response: XtOrderResponse 对象
        :return:
        """
        print(f"异步委托回调 {response.order_remark}")

    def on_cancel_order_stock_async_response(self, response):
        """
        :param response: XtCancelOrderResponse 对象
        :return:
        """
        print(datetime.datetime.now(), sys._getframe().f_code.co_name)

    def on_account_status(self, status):
        """
        :param response: XtAccountStatus 对象
        :return:
        """
        print(datetime.datetime.now(), sys._getframe().f_code.co_name)


def p(data):
    print(data)


if __name__ == '__main__':
    hszs = xtdata.get_stock_list_in_sector('中金所')
    print(hszs)
    print(dt.now().strftime('%Y%m%d'))

    # print(xtdata.get_sector_list())

    field = ['time', 'open', 'close', 'high', 'low', 'volume', 'amount']
    stock_list = hszs
    stock = '000001.SH'

    xtdata.download_history_data2(stock_list=['000001.SZ'], period='1m', start_time='20230801', end_time='')
    df = xtdata.get_market_data(field, ['000001.SZ'], '1m', start_time='20230804', end_time='', count=-1,
                                dividend_type='front')
    df = pd.concat([df[i].T for i in ['time', 'open', 'high', 'low', 'close', 'volume',
                                      'amount']], axis=1)
    df.columns = ['time', 'open_front', 'high_front', 'low_front', 'close_front', 'volume_front',
                  'amount_front']
    df['time'] = df['time'].apply(lambda x: dt.fromtimestamp(x / 1000.0))
    daily_avg_price = []
    print(len(df))
    for i in range(1, len(df) + 1):
        daily_avg_price.append(round(sum(df['amount_front'][:i]) / sum(df['volume_front'][:i]) / 100, 2))
    df['daily_avg_price'] = daily_avg_price
    print(df)
    # xtdata.subscribe_whole_quote(['000001.SZ'], callback=p)
