from pyda.api.td_constant import (
    DERIVATIVE_BID,
    DERIVATIVE_ASK
)

from future_demo import MyFutureApi


def show_future_help():
    """显示期货接口帮助信息"""
    print("\n------ 测试期货接口 ------")
    print("  A 连接并登录期货交易账号")
    print("  B 查询合约")
    print("  C 查询交易所")
    print("  D 查询资金")
    print("  E 查询持仓")
    print("  F 查询成交")
    print("  G 修改密码")
    print("  H 查询货币")
    print("  I 查询订单")
    print("  J 下单")
    print("  K 改单")
    print("  L 撤单")
    print("  M 查询交易所时间")
    print("  N 查询商品时间")
    print("  O 查询版本")
    print("  P 查询策略")
    print("  Q 查询策略细节")
    print("  R 查询问题")
    print("  S 校验密码")
    print("  T 安全验证")
    print("  U 设置验证问题答案")
    print("  V 查询持仓合计")
    print("  W 查询商品")
    print("  ? 帮助")
    print("  ......")
    print("  * 返回上一级")
    print("--------------------------")
    print("请输入命令:")


def login_check(api, help_text):
    """检查API是否创建并登录"""
    if api and api.login_status:
        print(help_text)
        return True
    else:
        print("请先输入命令 'A' 连接并登陆")
        return False


def test_future():
    """测试期货接口"""
    show_future_help()

    heartbeat = 180
    userid = "AF20248889"
    password = "888888"
    address = "222.73.119.230:7003"

    currency = "USD"
    exchange = "CME"
    symbol = "CL2501"
    volume = 1
    price = 65.00
    modified_price = 66.00
    strategy_commodity_no = "CL-BZ"

    api = None

    while True:
        cmd = input().strip().upper()

        if cmd == "*":
            print("返回上一级....")
            break

        elif cmd == "?":
            show_future_help()

        elif cmd == "A":
            print("连接并登录...")

            api = MyFutureApi(userid, password)
            api.createFutureApi(True, "future_log.txt", "Y")
            api.registerNameServer("tcp://" + address)
            api.setHeartBeatTimeout(heartbeat)
            api.init()

        elif cmd == "B":
            if login_check(api, "查询合约"):
                api.query_contract(exchange)

        elif cmd == "C":
            if login_check(api, "查询交易所"):
                api.query_exchange()

        elif cmd == "D":
            if login_check(api, "查询资金"):
                api.query_account()

        elif cmd == "E":
            if login_check(api, "查询持仓"):
                api.query_position()

        elif cmd == "F":
            if login_check(api, "查询成交"):
                api.query_trade()

        elif cmd == "G":
            if login_check(api, "修改密码"):
                api.change_password()

        elif cmd == "H":
            if login_check(api, "查询货币"):
                api.query_currency()

        elif cmd == "I":
            if login_check(api, "查询订单"):
                api.query_order()

        elif cmd == "J":
            if login_check(api, "下单"):
                api.send_order(
                    symbol=symbol,
                    exchange=exchange,
                    side=DERIVATIVE_BID,
                    price=price,
                    volume=volume,
                    currency=currency
                )

        elif cmd == "K":
            if login_check(api, "改单"):
                api.modify_order(
                    local_id=str(api.local_no),
                    modified_price=modified_price,
                    modified_volume=volume,
                    symbol=symbol,
                    exchange=exchange,
                    side=DERIVATIVE_BID,
                    price=price,
                    volume=volume,
                    currency=currency,
                )

        elif cmd == "L":
            if login_check(api, "撤单"):
                api.cancel_order(
                    local_id=str(api.local_no),
                    currency=currency
                )

        elif cmd == "M":
            if login_check(api, "查询交易所时间"):
                api.query_exchange_time()

        elif cmd == "N":
            if login_check(api, "查询商品时间"):
                api.query_commodity_time(exchange)

        elif cmd == "O":
            if login_check(api, "查询版本"):
                api.query_version()

        elif cmd == "P":
            if login_check(api, "查询策略"):
                api.query_strategy(exchange)

        elif cmd == "Q":
            if login_check(api, "查询策略细节"):
                api.query_strategy_detail(strategy_commodity_no)

        elif cmd == "R":
            if login_check(api, "查询问题"):
                api.query_question()

        elif cmd == "S":
            if login_check(api, "校验密码"):
                api.verify_code()

        elif cmd == "T":
            if login_check(api, "安全验证"):
                api.safe_verify()

        elif cmd == "U":
            if login_check(api, "设置验证问题答案"):
                api.set_verify_qa()

        elif cmd == "V":
            if login_check(api, "查询持仓合计"):
                api.query_position_total()

        elif cmd == "W":
            if login_check(api, "查询商品"):
                api.query_commodity()

        else:
            print("不能识别的命令!")

    if api:
        api.exit()


def show_root_help():
    print("\n※※※※※※※  直达接口测试程序  ※※※※※※※")
    print("\n  F 测试期货功能....")
    print("  X 退出测试程序")
    print("  ? 帮助")
    print("------------------------------------------")
    print("请输入命令:")


def main():
    show_root_help()

    while True:
        cmd = input().strip().upper()
        if cmd == "X":
            break
        elif cmd == "*":
            show_root_help()
        elif cmd == "?":
            show_root_help()
        elif cmd == "F":
            test_future()
            show_root_help()
        else:
            print("不能识别的命令!")

    print("安全退出程序.")


if __name__ == "__main__":
    main()
