import AlgoPlus.CTPV6315 as ctp


@ctp.marketdata_callback_wraps
def marketdata_callback1(event_id, field):
    global my_strategy

    print("=======my marketdata callback1 decode response by wraps")
    print(event_id)
    print(field)
    standard_id = ctp.bytes_to_str(field.StandardID)
    my_strategy.lower_limit_price_map[standard_id] = field.LowerLimitPrice
    print(field.StandardID, field.LowerLimitPrice)
    print("=======")


def marketdata_callback2(event_id, field):
    global my_strategy

    print("=======my marketdata callback2 decode response by function")
    print(event_id)
    field = ctp.decode_marketdata_field(field)
    print(field)
    my_strategy.lower_limit_price_map[field.StandardID] = field.LowerLimitPrice
    print("=======")


@ctp.order_callback_wraps
def order_callback1(event_id, order):
    print("=======my order callback1 decode response by wraps")
    print(event_id)
    print(order)
    print("=======")


def order_callback2(event_id, order):
    print("=======my order callback2 decode response by function")
    print(event_id)
    order = ctp.decode_order_field(order)
    print(order)
    print("=======")


def loop_callback():
    global my_strategy

    step = 100
    my_strategy.count += 1

    if my_strategy.count % step == 0:
        print(f'||Count||,Count:{my_strategy.count}')

    if my_strategy.count == step * 1:
        for standard_id in my_strategy.standard_id_list:
            for _ in range(2):
                new_order = ctp.buyOpen(my_strategy.trader, standard_id, 100, ctp.ENUM_OrderType_LimitAndWait, my_strategy.lower_limit_price_map[standard_id])
                my_strategy.order_map[new_order.OrderID] = new_order
                my_strategy.order_list.append(new_order)
    elif my_strategy.count == step * 2:
        the_order = my_strategy.order_list[0]
        ctp.cancelOrder(my_strategy.trader, the_order.ExchangeID, the_order.StandardID, the_order.OrderSysID, the_order.OrderID, the_order.FrontID, the_order.SessionID)
    elif my_strategy.count == step * 3:
        the_order = my_strategy.order_list[2]
        ctp.cancelOrderByOrderID(my_strategy.trader, the_order.OrderID)
    elif my_strategy.count == step * 4:
        the_order = my_strategy.order_list[4]
        ctp.cancelOrderByStandardID(my_strategy.trader, the_order.ExchangeID, the_order.StandardID)
    elif my_strategy.count == step * 5:
        ctp.cancelOrderByStandardID(my_strategy.trader, ctp.ENUM_ExchangeID_INE, None)
    elif my_strategy.count == step * 6:
        ctp.cancelOrderByStandardID(my_strategy.trader)


class MyStrategy:
    def __init__(self, standard_id_list):
        self.count = 0
        self.login_field = ctp.CAPLoginField()
        self.standard_id_list = standard_id_list
        self.trader = None
        self.lower_limit_price_map = {}
        self.order_map = {}
        self.order_list = []


if __name__ == '__main__':

    print(f"||Version||,Version:{ctp.getVersion()}")

    my_strategy = MyStrategy(['ag2112', 'au2112', 'sc2110'])

    my_strategy.login_field.UserType = ctp.ENUM_UserType_SIMNOWFuture
    my_strategy.login_field.UserID = ""
    my_strategy.login_field.Password = ""

    # Simnow仿真交易环境（http://simnow.com.cn）
    my_strategy.login_field.BrokerID = "9999"
    my_strategy.login_field.TraderFrontAddress = "tcp://180.168.146.187:10201"
    my_strategy.login_field.MdFrontAddress = "tcp://180.168.146.187:10211"
    my_strategy.login_field.AppID = "simnow_client_test"
    my_strategy.login_field.AuthCode = "0000000000000000"

    # # NSight期货仿真交易环境（http://n-sight.com.cn）
    # my_strategy.login_field.BrokerID = "10010"
    # my_strategy.login_field.TraderFrontAddress = "tcp://210.14.72.15:4600"
    # my_strategy.login_field.MdFrontAddress = "tcp://210.14.72.15:4602"
    # my_strategy.login_field.AppID = ""
    # my_strategy.login_field.AuthCode = ""

    my_strategy.trader = ctp.init(1, my_strategy.login_field, None, None, loop_callback, marketdata_callback1)

    if my_strategy.trader is not None:
        print("||init||,Succeed")
        ctp.subscribe(my_strategy.trader, my_strategy.standard_id_list)
        ctp.loop()
    else:
        error_id = ctp.getInitError()
        message = ctp.getMessageByErrorID(error_id)
        print(f"||init||,ErrorID:{error_id},Message:{message}")
