Administrator
2023-07-11 18cd3598a6abf19dac1a02eb19c9db8edae8cc0c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
"""
华鑫交易
"""
import json
import time
 
import constant
from db.redis_manager import RedisManager
from log_module.log import logger_juejin_trade
from trade.huaxin import huaxin_trade_api
from utils import tool, huaxin_util
 
__context_dict = {}
 
 
# 交易订单号管理
class TradeOrderIdManager:
    __redisManager = RedisManager(2)
 
    @classmethod
    def __get_redis(cls):
        return cls.__redisManager.getRedis()
 
    # 添加订单ID
    @classmethod
    def add_order_id(cls, code, account_id, order_id):
        cls.__get_redis().sadd(f"huaxin_order_id-{code}", json.dumps((account_id, order_id)))
        cls.__get_redis().expire(f"huaxin_order_id-{code}", tool.get_expire())
 
    # 删除订单ID
    @classmethod
    def remove_order_id(cls, code, account_id, order_id):
        cls.__get_redis().srem(f"huaxin_order_id-{code}", json.dumps((account_id, order_id)))
 
    # 查询所有的订单号
    @classmethod
    def list_order_ids(cls, code):
        return cls.__get_redis().smembers(f"huaxin_order_id-{code}")
 
 
def init(context):
    __context_dict["init"] = context
    print("掘金交易初始化成功")
 
 
# 可用金额
def get_account_left_money():
    if "init" in __context_dict:
        dict_ = __context_dict["init"].account().cash
        return dict_["available"]
    return None
 
 
# 通过量下单,返回(代码,账号ID,订单号)
def order_volume(code, price, count):
    if not constant.TRADE_ENABLE:
        return
    if code.find("00") != 0 and code.find("60") != 0:
        raise Exception("只支持00开头与60开头的代码下单")
    code_str = code
    if code[0:2] == '00':
        code_str = f"SZSE.{code}"
    elif code[0:2] == '60':
        code_str = f"SHSE.{code}"
    start_time = time.time()
    result = huaxin_trade_api.order(1, code, count, price)
    print("华鑫下单耗时", time.time() - start_time)
    logger_juejin_trade.info(f"{code}:下单耗时{round(time.time() - start_time, 3)}s")
 
    if result:
        print("下单结果", result)
        if result['code'] == 0:
            result = result["data"]
            if result["orderStatus"] == huaxin_util.TORA_TSTP_OST_Rejected:
                logger_juejin_trade.info(f"{code}:下单失败:{result['statusMsg']}")
                raise Exception(result["statusMsg"])
            else:
                TradeOrderIdManager.add_order_id(code, result["accountID"], result["orderSysID"])
                logger_juejin_trade.info(f"{code}:下单成功 orderSysID:{result['orderSysID']}")
                return result["securityId"], result["accountID"], result["orderSysID"]
        else:
            raise Exception(result['msg'])
    else:
        raise Exception("下单失败,无返回")
 
 
def order_success(code, accountId, orderSysID):
    TradeOrderIdManager.add_order_id(code, accountId, orderSysID)
 
 
def cancel_order_success(code, accountId, orderSysID):
    TradeOrderIdManager.remove_order_id(code, accountId, orderSysID)
 
 
# 撤单
def cancel_order(code):
    orders_info = TradeOrderIdManager.list_order_ids(code)
    orders = []
    if orders_info:
        for order in orders_info:
            order_info = json.loads(order)
            orders.append({'orderSysID': order_info[1], 'accountId': order_info[0]})
    if orders:
        logger_juejin_trade.info(f"{code}:开始执行撤单")
        logger_juejin_trade.info(f"{code}:撤单成功,撤单数量:{len(orders)}")
        for order in orders:
            huaxin_trade_api.cancel_order(1, code, order["orderSysID"])
            TradeOrderIdManager.remove_order_id(code, order["accountId"], order["orderSysID"])
 
 
if __name__ == "__main__":
    pass