import AlgoPlus.CTPV6315 as ctp


@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 * 1:
        new_order = ctp.buyOpen(my_strategy.trader, my_strategy.standard_id, 100000, ctp.ENUM_OrderType_HomeBestLimitAndWait, 0)
        my_strategy.order_map[new_order.OrderID] = new_order


class MyStrategy:
    def __init__(self, standard_id):
        self.login_field = ctp.CAPLoginField()
        self.trader = None
        self.standard_id = standard_id
        self.count = 0
        self.order_map = {}


if __name__ == '__main__':

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

    my_strategy = MyStrategy('000001')

    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, None)

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