kaq-quant-common 0.2.8__py3-none-any.whl → 0.2.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,342 +1,342 @@
1
- import json
2
- import threading
3
- import time
4
- from typing import Callable
5
-
6
- from kaq_quant_common.api.rest.instruction.models.order import (
7
- OrderInfo,
8
- OrderSide,
9
- OrderStatus,
10
- PositionStatus,
11
- )
12
- from kaq_quant_common.api.rest.instruction.models.position import PositionSide
13
- from kaq_quant_common.utils import logger_utils, uuid_utils
14
-
15
-
16
- class OrderHelper:
17
- def __init__(self, ins_server):
18
- # 必须放在这里 延迟引入,否则会有循环引用问题
19
- from kaq_quant_common.api.rest.instruction.instruction_server_base import (
20
- InstructionServerBase,
21
- )
22
-
23
- self._server: InstructionServerBase = ins_server
24
- self._logger = logger_utils.get_logger(self)
25
-
26
- self._mysql_table_name_order = "kaq_futures_instruction_order"
27
- self._mysql_table_name_position = "kaq_futures_instruction_position"
28
- # 当前持仓
29
- self._redis_key_position = "kaq_futures_instruction_position"
30
- # 持仓历史
31
- self._redis_key_position_history = "kaq_futures_instruction_position_history"
32
-
33
- def _write_position_open_to_redis(
34
- self,
35
- position_id: str,
36
- exchange: str,
37
- symbol: str,
38
- position_side,
39
- coin_quantity: float,
40
- usdt_quantity: float,
41
- open_ins_id: str,
42
- open_price: float,
43
- open_fee: float,
44
- open_fee_rate: float,
45
- open_time: int,
46
- ):
47
- redis = self._server._redis
48
- if redis is None:
49
- return
50
- data = {
51
- "id": position_id,
52
- "exchange": exchange,
53
- "symbol": symbol,
54
- "position_side": position_side.value,
55
- "coin_quantity": coin_quantity,
56
- "usdt_quantity": usdt_quantity,
57
- "open_ins_id": open_ins_id,
58
- "open_price": open_price,
59
- "open_fee": open_fee,
60
- "open_fee_rate": open_fee_rate,
61
- "open_time": open_time,
62
- "close_ins_id": None,
63
- "close_price": 0,
64
- "close_time": 0,
65
- "status": PositionStatus.OPEN.value,
66
- }
67
- redis.client.hset(self._redis_key_position, position_id, json.dumps(data))
68
-
69
- def _write_position_close_to_redis(
70
- self,
71
- position_id: str,
72
- exchange: str,
73
- symbol: str,
74
- position_side,
75
- coin_quantity: float,
76
- usdt_quantity: float,
77
- open_ins_id: str,
78
- open_price: float,
79
- open_fee: float,
80
- open_fee_rate: float,
81
- open_time: int,
82
- close_ins_id: str,
83
- close_price: float,
84
- close_fee: float,
85
- close_fee_rate: float,
86
- close_time: int,
87
- ):
88
- redis = self._server._redis
89
- if redis is None:
90
- return
91
-
92
- # 先从 redis 读取现有的 position 数据,获取 funding_rate_records 字段
93
- funding_rate_records = None
94
- try:
95
- existing_position_json = redis.client.hget(self._redis_key_position, position_id)
96
- if existing_position_json:
97
- existing_position = json.loads(existing_position_json)
98
- if existing_position and "funding_rate_records" in existing_position:
99
- funding_rate_records = existing_position.get("funding_rate_records")
100
- except Exception as e:
101
- # 读取失败不影响后续流程,记录日志
102
- self._logger.warning(f"Failed to get funding_rate_records for position {position_id}: {e}")
103
-
104
- data = {
105
- "id": position_id,
106
- "exchange": exchange,
107
- "symbol": symbol,
108
- "position_side": position_side.value,
109
- "coin_quantity": coin_quantity,
110
- "usdt_quantity": usdt_quantity,
111
- "open_ins_id": open_ins_id,
112
- "open_price": open_price,
113
- "open_fee": open_fee,
114
- "open_fee_rate": open_fee_rate,
115
- "open_time": open_time,
116
- "close_ins_id": close_ins_id,
117
- "close_price": close_price,
118
- "close_fee": close_fee,
119
- "close_fee_rate": close_fee_rate,
120
- "close_time": close_time,
121
- "status": PositionStatus.CLOSE.value,
122
- }
123
-
124
- # 如果存在 funding_rate_records,添加到 data 中
125
- if funding_rate_records is not None:
126
- data["funding_rate_records"] = funding_rate_records
127
-
128
- redis.client.hdel(self._redis_key_position, position_id)
129
- redis.client.rpush(self._redis_key_position_history, json.dumps(data))
130
-
131
- def process_order(self, order: OrderInfo, get_order_result: Callable):
132
- # 获取交易所
133
- exchange = self._server._exchange
134
-
135
- # 记录时间,统计成交耗时
136
- start_time = time.time()
137
-
138
- #
139
- if not self._do_process_order(exchange, order, get_order_result, True, start_time):
140
- # 马上执行,没有成功,开启线程执行
141
- thread = threading.Thread(
142
- target=self._do_process_order,
143
- args=(exchange, order, get_order_result, False, start_time),
144
- )
145
- thread.name = f"process_order_{order.instruction_id}_{exchange}_{order.symbol}_{order.order_id}"
146
- thread.daemon = True
147
- thread.start()
148
-
149
- def _do_process_order(
150
- self,
151
- exchange: str,
152
- order: OrderInfo,
153
- get_order_result: Callable,
154
- first=True,
155
- start_time: float = 0,
156
- ):
157
- # 获取mysql
158
- mysql = self._server._mysql
159
-
160
- #
161
- ins_id = order.instruction_id
162
- order_id = order.order_id
163
- symbol = order.symbol
164
- side = order.side
165
- position_side = order.position_side
166
-
167
- is_open = True
168
- side_str = "开仓"
169
- if position_side == PositionSide.LONG:
170
- # 多单是正向理解的
171
- if side == OrderSide.SELL:
172
- side_str = "平仓"
173
- is_open = False
174
- else:
175
- side_str = "开仓"
176
- is_open = True
177
- else:
178
- # 空单是反向理解的
179
- if side == OrderSide.SELL:
180
- side_str = "开仓"
181
- is_open = True
182
- else:
183
- side_str = "平仓"
184
- is_open = False
185
-
186
- if first:
187
- self._logger.info(f"{ins_id}_{exchange}_{symbol} step 1. {side_str}挂单成功 {order_id}")
188
-
189
- # 步骤1.挂单成功 插入到订单记录
190
- # 获取当前时间-ms
191
- current_time = int(time.time() * 1000)
192
-
193
- if mysql is not None:
194
- status = OrderStatus.CREATE
195
- sql = f"""
196
- INSERT INTO {self._mysql_table_name_order} (ins_id, exchange, symbol, side, position_side, orig_price, orig_coin_quantity, order_id, status, create_time, last_update_time)
197
- VALUES ( '{ins_id}', '{exchange}', '{symbol}', '{side.value}', '{order.position_side.value}', {order.target_price}, {order.quantity}, '{order_id}', '{status.value}', {current_time}, {current_time} );
198
- """
199
- execute_ret = mysql.execute_sql(sql, True)
200
-
201
- # 步骤2.查询订单状态 直到订单成交后
202
- # 统计查询次数
203
- query_counter = 0
204
- while True:
205
- query_counter += 1
206
- # 获取订单结果
207
- order_info = None
208
- try:
209
- order_info = get_order_result()
210
- except Exception as e:
211
- self._logger.error(f"{ins_id}_{exchange}_{symbol} step 2. {side_str}订单 查询状态失败 {e}")
212
-
213
- if order_info is not None:
214
- break
215
- # 只查询一次
216
- if first:
217
- return False
218
- # 等待
219
- time.sleep(1)
220
-
221
- if not first:
222
- # 需要加上第一查询
223
- query_counter += 1
224
-
225
- # 记录时间,统计成交耗时
226
- end_time = time.time()
227
- cost_time = end_time - start_time
228
- self._logger.info(
229
- f"{ins_id}_{exchange}_{symbol} step 2. {side_str}订单 {order_id} 成交 耗时 {int(cost_time * 1000)}ms, 查询次数 {query_counter}"
230
- )
231
-
232
- # 步骤3.把最终持仓写进去
233
- # 平均成交价格 转float
234
- avg_price = float(order_info["avg_price"])
235
- # 最终成交数量 转float
236
- executed_qty = float(order_info["executed_qty"])
237
- # 计算出usdt数量
238
- executed_usdt = avg_price * executed_qty
239
- # 手续费,不一定有
240
- fee = float(order_info["fee"]) if "fee" in order_info else 0.0
241
- # 费率
242
- fee_rate = fee / executed_usdt
243
-
244
- current_time = int(time.time() * 1000)
245
-
246
- if mysql is None:
247
- self._logger.warning(f"{ins_id}_{exchange}_{symbol} 仅操作,没有入库,请设置 mysql!!")
248
- return
249
-
250
- status = OrderStatus.FINISH
251
- # 更新写入最终信息
252
- sql = f"""
253
- UPDATE {self._mysql_table_name_order}
254
- SET price = {avg_price}, coin_quantity = {executed_qty}, usdt_quantity = {executed_usdt}, fee = {fee}, fee_rate = {fee_rate}, status = '{status.value}', last_update_time = {current_time}
255
- WHERE ins_id = '{ins_id}' AND exchange = '{exchange}' AND symbol = '{symbol}';
256
- """
257
- execute_ret = mysql.execute_sql(sql, True)
258
-
259
- self._logger.info(
260
- f"{ins_id}_{exchange}_{symbol} step 2. 订单成交 {order_id}, {side_str}价格 {avg_price}, {side_str}数量 {executed_qty}, {side_str}usdt {executed_usdt}"
261
- )
262
- if is_open:
263
- # 同时插入持仓表
264
- position_id = uuid_utils.generate_uuid()
265
- sql = f"""
266
- INSERT INTO {self._mysql_table_name_position} (id, exchange, symbol, position_side, coin_quantity, usdt_quantity, open_ins_id, open_price, open_fee, open_fee_rate, open_time, status)
267
- VALUES ( '{position_id}', '{exchange}', '{symbol}', '{position_side.value}', '{executed_qty}', '{executed_usdt}', '{ins_id}', '{avg_price}', '{fee}', '{fee_rate}', {current_time}, '{PositionStatus.OPEN.value}' );
268
- """
269
- execute_ret = mysql.execute_sql(sql, True)
270
-
271
- self._logger.info(f"{ins_id}_{exchange}_{symbol} step 3. 创建持仓记录 {position_id}")
272
- try:
273
- self._write_position_open_to_redis(
274
- position_id,
275
- exchange,
276
- symbol,
277
- position_side,
278
- executed_qty,
279
- executed_usdt,
280
- ins_id,
281
- avg_price,
282
- fee,
283
- fee_rate,
284
- current_time,
285
- )
286
- except:
287
- pass
288
- else:
289
- # 需要找到对应的持仓记录
290
- sql = f"""
291
- SELECT * FROM {self._mysql_table_name_position}
292
- WHERE exchange = '{exchange}' AND symbol = '{symbol}' AND position_side = '{position_side.value}' AND status = '{PositionStatus.OPEN.value}'
293
- ORDER BY open_time ASC;
294
- """
295
-
296
- # 如果有指定仓位id,就用指定的
297
- if hasattr(order, "position_id") and order.position_id:
298
- sql = f"""
299
- SELECT * FROM {self._mysql_table_name_position}
300
- WHERE id = '{order.position_id}' AND status = '{PositionStatus.OPEN.value}'
301
- """
302
- self._logger.info(f"{ins_id}_{exchange}_{symbol} get position by id {order.position_id}")
303
-
304
- execute_ret = mysql.execute_sql(sql)
305
- try:
306
- row = execute_ret.fetchone()
307
- position_id = row.id
308
- if position_id is not None:
309
- # 更新持仓信息
310
- sql = f"""
311
- UPDATE {self._mysql_table_name_position}
312
- SET close_ins_id = '{ins_id}', close_price = {avg_price}, close_fee = '{fee}', close_fee_rate = '{fee_rate}', close_time = {current_time}, status = '{PositionStatus.CLOSE.value}'
313
- WHERE id = '{position_id}';
314
- """
315
- execute_ret = mysql.execute_sql(sql, True)
316
-
317
- self._logger.info(f"{ins_id}_{exchange}_{symbol} step 3. 更新持仓记录 {position_id}")
318
- try:
319
- self._write_position_close_to_redis(
320
- position_id,
321
- exchange,
322
- symbol,
323
- position_side,
324
- float(row.coin_quantity),
325
- float(row.usdt_quantity),
326
- row.open_ins_id,
327
- float(row.open_price),
328
- float(row.open_fee),
329
- float(row.open_fee_rate),
330
- int(row.open_time),
331
- ins_id,
332
- avg_price,
333
- fee,
334
- fee_rate,
335
- current_time,
336
- )
337
- except:
338
- pass
339
- except:
340
- pass
341
-
342
- return True
1
+ import json
2
+ import threading
3
+ import time
4
+ from typing import Callable
5
+
6
+ from kaq_quant_common.api.rest.instruction.models.order import (
7
+ OrderInfo,
8
+ OrderSide,
9
+ OrderStatus,
10
+ PositionStatus,
11
+ )
12
+ from kaq_quant_common.api.rest.instruction.models.position import PositionSide
13
+ from kaq_quant_common.utils import logger_utils, uuid_utils
14
+
15
+
16
+ class OrderHelper:
17
+ def __init__(self, ins_server):
18
+ # 必须放在这里 延迟引入,否则会有循环引用问题
19
+ from kaq_quant_common.api.rest.instruction.instruction_server_base import (
20
+ InstructionServerBase,
21
+ )
22
+
23
+ self._server: InstructionServerBase = ins_server
24
+ self._logger = logger_utils.get_logger(self)
25
+
26
+ self._mysql_table_name_order = "kaq_futures_instruction_order"
27
+ self._mysql_table_name_position = "kaq_futures_instruction_position"
28
+ # 当前持仓
29
+ self._redis_key_position = "kaq_futures_instruction_position"
30
+ # 持仓历史
31
+ self._redis_key_position_history = "kaq_futures_instruction_position_history"
32
+
33
+ def _write_position_open_to_redis(
34
+ self,
35
+ position_id: str,
36
+ exchange: str,
37
+ symbol: str,
38
+ position_side,
39
+ coin_quantity: float,
40
+ usdt_quantity: float,
41
+ open_ins_id: str,
42
+ open_price: float,
43
+ open_fee: float,
44
+ open_fee_rate: float,
45
+ open_time: int,
46
+ ):
47
+ redis = self._server._redis
48
+ if redis is None:
49
+ return
50
+ data = {
51
+ "id": position_id,
52
+ "exchange": exchange,
53
+ "symbol": symbol,
54
+ "position_side": position_side.value,
55
+ "coin_quantity": coin_quantity,
56
+ "usdt_quantity": usdt_quantity,
57
+ "open_ins_id": open_ins_id,
58
+ "open_price": open_price,
59
+ "open_fee": open_fee,
60
+ "open_fee_rate": open_fee_rate,
61
+ "open_time": open_time,
62
+ "close_ins_id": None,
63
+ "close_price": 0,
64
+ "close_time": 0,
65
+ "status": PositionStatus.OPEN.value,
66
+ }
67
+ redis.client.hset(self._redis_key_position, position_id, json.dumps(data))
68
+
69
+ def _write_position_close_to_redis(
70
+ self,
71
+ position_id: str,
72
+ exchange: str,
73
+ symbol: str,
74
+ position_side,
75
+ coin_quantity: float,
76
+ usdt_quantity: float,
77
+ open_ins_id: str,
78
+ open_price: float,
79
+ open_fee: float,
80
+ open_fee_rate: float,
81
+ open_time: int,
82
+ close_ins_id: str,
83
+ close_price: float,
84
+ close_fee: float,
85
+ close_fee_rate: float,
86
+ close_time: int,
87
+ ):
88
+ redis = self._server._redis
89
+ if redis is None:
90
+ return
91
+
92
+ # 先从 redis 读取现有的 position 数据,获取 funding_rate_records 字段
93
+ funding_rate_records = None
94
+ try:
95
+ existing_position_json = redis.client.hget(self._redis_key_position, position_id)
96
+ if existing_position_json:
97
+ existing_position = json.loads(existing_position_json)
98
+ if existing_position and "funding_rate_records" in existing_position:
99
+ funding_rate_records = existing_position.get("funding_rate_records")
100
+ except Exception as e:
101
+ # 读取失败不影响后续流程,记录日志
102
+ self._logger.warning(f"Failed to get funding_rate_records for position {position_id}: {e}")
103
+
104
+ data = {
105
+ "id": position_id,
106
+ "exchange": exchange,
107
+ "symbol": symbol,
108
+ "position_side": position_side.value,
109
+ "coin_quantity": coin_quantity,
110
+ "usdt_quantity": usdt_quantity,
111
+ "open_ins_id": open_ins_id,
112
+ "open_price": open_price,
113
+ "open_fee": open_fee,
114
+ "open_fee_rate": open_fee_rate,
115
+ "open_time": open_time,
116
+ "close_ins_id": close_ins_id,
117
+ "close_price": close_price,
118
+ "close_fee": close_fee,
119
+ "close_fee_rate": close_fee_rate,
120
+ "close_time": close_time,
121
+ "status": PositionStatus.CLOSE.value,
122
+ }
123
+
124
+ # 如果存在 funding_rate_records,添加到 data 中
125
+ if funding_rate_records is not None:
126
+ data["funding_rate_records"] = funding_rate_records
127
+
128
+ redis.client.hdel(self._redis_key_position, position_id)
129
+ redis.client.rpush(self._redis_key_position_history, json.dumps(data))
130
+
131
+ def process_order(self, order: OrderInfo, get_order_result: Callable):
132
+ # 获取交易所
133
+ exchange = self._server._exchange
134
+
135
+ # 记录时间,统计成交耗时
136
+ start_time = time.time()
137
+
138
+ #
139
+ if not self._do_process_order(exchange, order, get_order_result, True, start_time):
140
+ # 马上执行,没有成功,开启线程执行
141
+ thread = threading.Thread(
142
+ target=self._do_process_order,
143
+ args=(exchange, order, get_order_result, False, start_time),
144
+ )
145
+ thread.name = f"process_order_{order.instruction_id}_{exchange}_{order.symbol}_{order.order_id}"
146
+ thread.daemon = True
147
+ thread.start()
148
+
149
+ def _do_process_order(
150
+ self,
151
+ exchange: str,
152
+ order: OrderInfo,
153
+ get_order_result: Callable,
154
+ first=True,
155
+ start_time: float = 0,
156
+ ):
157
+ # 获取mysql
158
+ mysql = self._server._mysql
159
+
160
+ #
161
+ ins_id = order.instruction_id
162
+ order_id = order.order_id
163
+ symbol = order.symbol
164
+ side = order.side
165
+ position_side = order.position_side
166
+
167
+ is_open = True
168
+ side_str = "开仓"
169
+ if position_side == PositionSide.LONG:
170
+ # 多单是正向理解的
171
+ if side == OrderSide.SELL:
172
+ side_str = "平仓"
173
+ is_open = False
174
+ else:
175
+ side_str = "开仓"
176
+ is_open = True
177
+ else:
178
+ # 空单是反向理解的
179
+ if side == OrderSide.SELL:
180
+ side_str = "开仓"
181
+ is_open = True
182
+ else:
183
+ side_str = "平仓"
184
+ is_open = False
185
+
186
+ if first:
187
+ self._logger.info(f"{ins_id}_{exchange}_{symbol} step 1. {side_str}挂单成功 {order_id}")
188
+
189
+ # 步骤1.挂单成功 插入到订单记录
190
+ # 获取当前时间-ms
191
+ current_time = int(time.time() * 1000)
192
+
193
+ if mysql is not None:
194
+ status = OrderStatus.CREATE
195
+ sql = f"""
196
+ INSERT INTO {self._mysql_table_name_order} (ins_id, exchange, symbol, side, position_side, orig_price, orig_coin_quantity, order_id, status, create_time, last_update_time)
197
+ VALUES ( '{ins_id}', '{exchange}', '{symbol}', '{side.value}', '{order.position_side.value}', {order.target_price}, {order.quantity}, '{order_id}', '{status.value}', {current_time}, {current_time} );
198
+ """
199
+ execute_ret = mysql.execute_sql(sql, True)
200
+
201
+ # 步骤2.查询订单状态 直到订单成交后
202
+ # 统计查询次数
203
+ query_counter = 0
204
+ while True:
205
+ query_counter += 1
206
+ # 获取订单结果
207
+ order_info = None
208
+ try:
209
+ order_info = get_order_result()
210
+ except Exception as e:
211
+ self._logger.error(f"{ins_id}_{exchange}_{symbol} step 2. {side_str}订单 查询状态失败 {e}")
212
+
213
+ if order_info is not None:
214
+ break
215
+ # 只查询一次
216
+ if first:
217
+ return False
218
+ # 等待
219
+ time.sleep(1)
220
+
221
+ if not first:
222
+ # 需要加上第一查询
223
+ query_counter += 1
224
+
225
+ # 记录时间,统计成交耗时
226
+ end_time = time.time()
227
+ cost_time = end_time - start_time
228
+ self._logger.info(
229
+ f"{ins_id}_{exchange}_{symbol} step 2. {side_str}订单 {order_id} 成交 耗时 {int(cost_time * 1000)}ms, 查询次数 {query_counter}"
230
+ )
231
+
232
+ # 步骤3.把最终持仓写进去
233
+ # 平均成交价格 转float
234
+ avg_price = float(order_info["avg_price"])
235
+ # 最终成交数量 转float
236
+ executed_qty = float(order_info["executed_qty"])
237
+ # 计算出usdt数量
238
+ executed_usdt = avg_price * executed_qty
239
+ # 手续费,不一定有
240
+ fee = float(order_info["fee"]) if "fee" in order_info else 0.0
241
+ # 费率
242
+ fee_rate = fee / executed_usdt
243
+
244
+ current_time = int(time.time() * 1000)
245
+
246
+ if mysql is None:
247
+ self._logger.warning(f"{ins_id}_{exchange}_{symbol} 仅操作,没有入库,请设置 mysql!!")
248
+ return
249
+
250
+ status = OrderStatus.FINISH
251
+ # 更新写入最终信息
252
+ sql = f"""
253
+ UPDATE {self._mysql_table_name_order}
254
+ SET price = {avg_price}, coin_quantity = {executed_qty}, usdt_quantity = {executed_usdt}, fee = {fee}, fee_rate = {fee_rate}, status = '{status.value}', last_update_time = {current_time}
255
+ WHERE ins_id = '{ins_id}' AND exchange = '{exchange}' AND symbol = '{symbol}';
256
+ """
257
+ execute_ret = mysql.execute_sql(sql, True)
258
+
259
+ self._logger.info(
260
+ f"{ins_id}_{exchange}_{symbol} step 2. 订单成交 {order_id}, {side_str}价格 {avg_price}, {side_str}数量 {executed_qty}, {side_str}usdt {executed_usdt}"
261
+ )
262
+ if is_open:
263
+ # 同时插入持仓表
264
+ position_id = uuid_utils.generate_uuid()
265
+ sql = f"""
266
+ INSERT INTO {self._mysql_table_name_position} (id, exchange, symbol, position_side, coin_quantity, usdt_quantity, open_ins_id, open_price, open_fee, open_fee_rate, open_time, status)
267
+ VALUES ( '{position_id}', '{exchange}', '{symbol}', '{position_side.value}', '{executed_qty}', '{executed_usdt}', '{ins_id}', '{avg_price}', '{fee}', '{fee_rate}', {current_time}, '{PositionStatus.OPEN.value}' );
268
+ """
269
+ execute_ret = mysql.execute_sql(sql, True)
270
+
271
+ self._logger.info(f"{ins_id}_{exchange}_{symbol} step 3. 创建持仓记录 {position_id}")
272
+ try:
273
+ self._write_position_open_to_redis(
274
+ position_id,
275
+ exchange,
276
+ symbol,
277
+ position_side,
278
+ executed_qty,
279
+ executed_usdt,
280
+ ins_id,
281
+ avg_price,
282
+ fee,
283
+ fee_rate,
284
+ current_time,
285
+ )
286
+ except:
287
+ pass
288
+ else:
289
+ # 需要找到对应的持仓记录
290
+ sql = f"""
291
+ SELECT * FROM {self._mysql_table_name_position}
292
+ WHERE exchange = '{exchange}' AND symbol = '{symbol}' AND position_side = '{position_side.value}' AND status = '{PositionStatus.OPEN.value}'
293
+ ORDER BY open_time ASC;
294
+ """
295
+
296
+ # 如果有指定仓位id,就用指定的
297
+ if hasattr(order, "position_id") and order.position_id:
298
+ sql = f"""
299
+ SELECT * FROM {self._mysql_table_name_position}
300
+ WHERE id = '{order.position_id}' AND status = '{PositionStatus.OPEN.value}'
301
+ """
302
+ self._logger.info(f"{ins_id}_{exchange}_{symbol} get position by id {order.position_id}")
303
+
304
+ execute_ret = mysql.execute_sql(sql)
305
+ try:
306
+ row = execute_ret.fetchone()
307
+ position_id = row.id
308
+ if position_id is not None:
309
+ # 更新持仓信息
310
+ sql = f"""
311
+ UPDATE {self._mysql_table_name_position}
312
+ SET close_ins_id = '{ins_id}', close_price = {avg_price}, close_fee = '{fee}', close_fee_rate = '{fee_rate}', close_time = {current_time}, status = '{PositionStatus.CLOSE.value}'
313
+ WHERE id = '{position_id}';
314
+ """
315
+ execute_ret = mysql.execute_sql(sql, True)
316
+
317
+ self._logger.info(f"{ins_id}_{exchange}_{symbol} step 3. 更新持仓记录 {position_id}")
318
+ try:
319
+ self._write_position_close_to_redis(
320
+ position_id,
321
+ exchange,
322
+ symbol,
323
+ position_side,
324
+ float(row.coin_quantity),
325
+ float(row.usdt_quantity),
326
+ row.open_ins_id,
327
+ float(row.open_price),
328
+ float(row.open_fee),
329
+ float(row.open_fee_rate),
330
+ int(row.open_time),
331
+ ins_id,
332
+ avg_price,
333
+ fee,
334
+ fee_rate,
335
+ current_time,
336
+ )
337
+ except:
338
+ pass
339
+ except:
340
+ pass
341
+
342
+ return True