Administrator
2023-08-15 a4473df83dc143f5a1f4f6ac73f01a3fcdbf6e05
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""
华鑫交易
"""
import json
import time
 
import constant
from db.redis_manager_delegate import RedisManager, RedisUtils
from log_module.log import logger_juejin_trade, hx_logger_trade_debug
from trade.huaxin import huaxin_trade_api
from utils import tool, huaxin_util
from l2 import huaxin
 
__context_dict = {}
 
 
# 交易订单号管理
class TradeOrderIdManager:
    __db = 2
    __redisManager = RedisManager(2)
    __instance = None
    __huaxin_order_id_cache = {}
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(TradeOrderIdManager, cls).__new__(cls, *args, **kwargs)
            cls.__load_datas()
        return cls.__instance
 
    @classmethod
    def __get_redis(cls):
        return cls.__redisManager.getRedis()
 
    @classmethod
    def __load_datas(cls):
        __redis = cls.__get_redis()
        try:
            keys = RedisUtils.keys(__redis, "huaxin_order_id-*")
            for k in keys:
                code = k.split("-")[-1]
                vals = RedisUtils.smembers(__redis, k)
                tool.CodeDataCacheUtil.set_cache(cls.__huaxin_order_id_cache, code, vals)
        finally:
            RedisUtils.realse(__redis)
 
    # 添加订单ID
    def add_order_id(self, code, account_id, order_id):
        val = json.dumps((account_id, order_id))
        if code not in self.__huaxin_order_id_cache:
            self.__huaxin_order_id_cache[code] = set()
        self.__huaxin_order_id_cache[code].add(val)
        RedisUtils.sadd_async(self.__db, f"huaxin_order_id-{code}", val)
        RedisUtils.expire_async(self.__db, f"huaxin_order_id-{code}", tool.get_expire())
 
    # 删除订单ID
    def remove_order_id(self, code, account_id, order_id):
        val = json.dumps((account_id, order_id))
        if code in self.__huaxin_order_id_cache:
            self.__huaxin_order_id_cache[code].discard(val)
        RedisUtils.srem_async(self.__get_redis(), f"huaxin_order_id-{code}", val)
 
    # 查询所有的订单号
 
    def list_order_ids(self, code):
        return RedisUtils.smembers(self.__get_redis(), f"huaxin_order_id-{code}")
 
    def list_order_ids_cache(self, code):
        if code in self.__huaxin_order_id_cache:
            return self.__huaxin_order_id_cache[code]
        return set()
 
 
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, last_data_index):
    price = round(float(price), 2)
    if code.find("00") != 0 and code.find("60") != 0:
        raise Exception("只支持00开头与60开头的代码下单")
    start_time = time.time()
    # 保存下单信息
    huaxin.huaxin_delegate_postion_manager.place_order(code, price, count, last_data_index)
    if not constant.TRADE_ENABLE:
        return
    result = None
    try:
        result = huaxin_trade_api.order(1, code, count, price)
        print("华鑫下单耗时", time.time() - start_time)
        hx_logger_trade_debug.info(f"{code}:下单耗时{round(time.time() - start_time, 3)}s")
    except Exception as e:
        if str(e).find("超时") >= 0:
            # 此处出现超时,需要通过读取委托列表来设置订单信息
            hx_logger_trade_debug.error(f"{code}:下单结果反馈出错-{str(e)}")
        else:
            raise e
 
    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.get('statusMsg')}")
                raise Exception(result.get('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_cache(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