Administrator
4 days ago 981a87bd0b06a17064f7b0d2435e96045cc03987
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
package com.xcong.excoin.modules.okxApi;
 
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcong.excoin.utils.dingtalk.DingTalkUtils;
import lombok.extern.slf4j.Slf4j;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
 
/**
 * OKX 网格交易策略引擎 — 多空对冲网格。
 *
 * <h3>策略原理</h3>
 * 以空仓基底入场价(shortBaseEntryPrice)为价格基准,向上/向下各生成一个价格网格队列。
 * 价格触发网格层级时挂条件单,成交后自动挂止盈单。每笔止盈盈利 = step - minTick。
 *
 * <h3>与 GateGridTradeService 的关系</h3>
 * 策略逻辑完全一致,仅 API 层(REST/WS/签名)替换为 OKX 实现。
 * GridElement 和 TraderParam 从 gateApi 包复用(交易所无关的数据模型)。
 *
 * <h3>完整生命周期</h3>
 * <pre>
 *   init() → startGrid() → WAITING_KLINE
 *     ↓
 *   onKline(首根K线) → OPENING → 异步市价双开基底(开多+开空)
 *     ↓
 *   onPositionUpdate() → 基底成交 → baseLongOpened && baseShortOpened
 *     ↓
 *   tryGenerateQueues()
 *     ├── generateShortQueue()   ← 空仓价格队列(降序,从 shortBaseEntryPrice-step 向下)
 *     ├── generateLongQueue()    ← 多仓价格队列(升序,从 shortBaseEntryPrice+step 向上)
 *     ├── updateGridElements()   ← 构建 GridElement 列表 + TraderParam + 全局索引
 *     ├── 挂基座止盈单(ID=0 的 long/short takeProfit)
 *     └── 挂初始条件单(up=-1 多单, down=1 空单)
 *     ↓
 *   state = ACTIVE
 *     ↓
 *   onKline() → processLongGrid() + processShortGrid()
 *     ├── 匹配队列元素 → 队列补偿 → 保证金检查
 *     ├── 首元素方向:挂条件开仓单 → 订单ID + GridElement状态同步
 *     └── 反向守卫:在 downGrid 位置挂对向单
 *     ↓
 *   onAutoOrder() ← orders-algo WS 推送
 *     ├── 匹配止盈单ID → 清空止盈状态(已成交)
 *     └── 匹配挂单ID → 挂止盈条件单 → 止盈ID + GridElement状态同步
 * </pre>
 *
 * @author Administrator
 */
@Slf4j
public class OkxGridTradeService {
 
    public enum StrategyState {
        WAITING_KLINE, OPENING, ACTIVE, STOPPED
    }
 
    /** 止盈条件单 order_type:平多仓 */
    private static final String ORDER_TYPE_CLOSE_LONG = "plan-close-long-position";
    /** 止盈条件单 order_type:平空仓 */
    private static final String ORDER_TYPE_CLOSE_SHORT = "plan-close-short-position";
 
    private final OkxConfig config;
    private final OkxTradeExecutor executor;
 
    private volatile StrategyState state = StrategyState.WAITING_KLINE;
 
    /** 空仓价格队列,降序排列(大→小),容量 gridQueueSize */
    private final List<BigDecimal> shortPriceQueue = Collections.synchronizedList(new ArrayList<>());
    /** 多仓价格队列,升序排列(小→大),容量 gridQueueSize */
    private final List<BigDecimal> longPriceQueue = Collections.synchronizedList(new ArrayList<>());
    private final List<BigDecimal> totalLongPriceQueue = Collections.synchronizedList(new ArrayList<>());
    private final List<BigDecimal> totalShortPriceQueue = Collections.synchronizedList(new ArrayList<>());
 
    /** 当前多仓条件单映射 */
    private final Map<String, BigDecimal> currentLongOrderIds = Collections.synchronizedMap(new LinkedHashMap<>());
    /** 当前空仓条件单映射 */
    private final Map<String, BigDecimal> currentShortOrderIds = Collections.synchronizedMap(new LinkedHashMap<>());
 
    /** 基底空头入场价 */
    private BigDecimal shortBaseEntryPrice;
    /** 基底多头入场价 */
    private BigDecimal longBaseEntryPrice;
    /** 基底多头是否已开 */
    private volatile boolean baseLongOpened = false;
    /** 基底空头是否已开 */
    private volatile boolean baseShortOpened = false;
 
    /** 空头是否活跃 */
    private volatile boolean shortActive = false;
    /** 多头是否活跃 */
    private volatile boolean longActive = false;
 
    /** 多头累计止损张数 */
    private volatile int accumulatedLongLossCount = 0;
    /** 空头累计止损张数 */
    private volatile int accumulatedShortLossCount = 0;
 
    private volatile BigDecimal lastKlinePrice;
    private volatile BigDecimal markPrice = BigDecimal.ZERO;
    private volatile BigDecimal cumulativePnl = BigDecimal.ZERO;
    private volatile BigDecimal unrealizedPnl = BigDecimal.ZERO;
    private volatile BigDecimal longEntryPrice = BigDecimal.ZERO;
    private volatile BigDecimal shortEntryPrice = BigDecimal.ZERO;
    private volatile BigDecimal longPositionSize = BigDecimal.ZERO;
    private volatile BigDecimal shortPositionSize = BigDecimal.ZERO;
    private volatile BigDecimal initialPrincipal = BigDecimal.ZERO;
    private volatile OkxKlineWebSocketClient wsClient;
 
    public OkxGridTradeService(OkxConfig config) {
        this.config = config;
        this.executor = new OkxTradeExecutor(config);
    }
 
    // ---- 仓位模式(替代 Gate 的 Position.ModeEnum)----
 
    /** OKX 持仓方向枚举 */
    public enum OkxPosMode { LONG, SHORT }
 
    /** 持仓查询结果 */
    static class OkxPositionInfo {
        String size;
        String entryPrice;
    }
 
    // ---- 初始化 ----
 
    /**
     * 初始化策略环境:获取账户信息 → 切双向持仓 → 清旧条件单 → 平仓 → 设杠杆。
     */
    public void init() {
        try {
            JSONObject account = executorGet("/api/v5/account/balance");
            JSONArray dataArr = account.getJSONArray("data");
            if (dataArr != null && !dataArr.isEmpty()) {
                JSONArray details = dataArr.getJSONObject(0).getJSONArray("details");
                if (details != null) {
                    for (int i = 0; i < details.size(); i++) {
                        JSONObject currency = details.getJSONObject(i);
                        if ("USDT".equals(currency.getString("ccy"))) {
                            this.initialPrincipal = currency.getBigDecimal("eq");
                            log.info("[OKX] 初始本金(USDT余额): {}", initialPrincipal);
                            break;
                        }
                    }
                }
            }
 
            // 设置双向持仓模式
            JSONObject posModeBody = new JSONObject();
            posModeBody.put("posMode", config.getPositionMode());
            executorPost("/api/v5/account/set-position-mode", posModeBody.toJSONString());
            log.info("[OKX] 持仓模式已设为: {}", config.getPositionMode());
 
            // 设置杠杆
            JSONObject levBody = new JSONObject();
            levBody.put("instId", config.getContract());
            levBody.put("lever", config.getLeverage());
            levBody.put("mgnMode", config.getMarginMode());
            executorPost("/api/v5/account/set-leverage", levBody.toJSONString());
            log.info("[OKX] 杠杆已设为: {}x {}", config.getLeverage(), config.getMarginMode());
 
            executor.cancelAllPriceTriggeredOrders();
            log.info("[OKX] 旧条件单已清除");
            closeExistingPositions();
 
            log.info("[OKX] 初始化完成");
        } catch (Exception e) {
            log.error("[OKX] 初始化失败", e);
        }
    }
 
    /**
     * 平掉当前合约的所有已有仓位。
     */
    private void closeExistingPositions() {
        try {
            JSONObject resp = executorGet("/api/v5/account/positions?instType=SWAP");
            JSONArray data = resp.getJSONArray("data");
            if (data == null || data.isEmpty()) {
                log.info("[OKX] 无已有仓位");
                return;
            }
            for (int i = 0; i < data.size(); i++) {
                JSONObject pos = data.getJSONObject(i);
                String instId = pos.getString("instId");
                if (instId == null || !instId.equals(config.getContract())) {
                    continue;
                }
                String posVal = pos.getString("pos");
                if (posVal == null || "0".equals(posVal)) {
                    continue;
                }
                String posSide = pos.getString("posSide");
                String side = "long".equals(posSide) ? "sell" : "buy";
 
                JSONObject body = new JSONObject();
                body.put("instId", config.getContract());
                body.put("tdMode", "cross");
                body.put("side", side);
                body.put("posSide", posSide);
                body.put("ordType", "market");
                body.put("sz", posVal);
                executorPost("/api/v5/trade/order", body.toJSONString());
                log.info("[OKX] 平已有仓位, posSide:{}, sz:{}", posSide, posVal);
            }
        } catch (Exception e) {
            log.warn("[OKX] 平仓位异常", e);
        }
    }
 
    // ---- 启动/停止 ----
 
    public void startGrid() {
        if (state != StrategyState.WAITING_KLINE && state != StrategyState.STOPPED) {
            log.warn("[OKX] 策略已在运行中, state:{}", state);
            return;
        }
        state = StrategyState.WAITING_KLINE;
        cumulativePnl = BigDecimal.ZERO;
        unrealizedPnl = BigDecimal.ZERO;
        markPrice = BigDecimal.ZERO;
        longEntryPrice = BigDecimal.ZERO;
        shortEntryPrice = BigDecimal.ZERO;
        longPositionSize = BigDecimal.ZERO;
        shortPositionSize = BigDecimal.ZERO;
        baseLongOpened = false;
        baseShortOpened = false;
        longActive = false;
        shortActive = false;
        accumulatedLongLossCount = 0;
        accumulatedShortLossCount = 0;
        shortPriceQueue.clear();
        longPriceQueue.clear();
        totalShortPriceQueue.clear();
        totalLongPriceQueue.clear();
        currentLongOrderIds.clear();
        currentShortOrderIds.clear();
        refreshInitialPrincipal();
        log.info("[OKX] 网格策略已启动, 当前本金: {} USDT", initialPrincipal);
    }
 
    private void refreshInitialPrincipal() {
        try {
            JSONObject account = executorGet("/api/v5/account/balance");
            JSONArray dataArr = account.getJSONArray("data");
            if (dataArr != null && !dataArr.isEmpty()) {
                JSONArray details = dataArr.getJSONObject(0).getJSONArray("details");
                if (details != null) {
                    for (int i = 0; i < details.size(); i++) {
                        JSONObject currency = details.getJSONObject(i);
                        if ("USDT".equals(currency.getString("ccy"))) {
                            this.initialPrincipal = currency.getBigDecimal("eq");
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.warn("[OKX] 获取初始化本金失败,使用旧值: {}", initialPrincipal);
        }
    }
 
    public void stopGrid() {
        state = StrategyState.STOPPED;
        executor.cancelAllPriceTriggeredOrders();
        closeExistingPositions();
        executor.shutdown();
        log.info("[OKX] 策略已停止, 累计盈亏: {}", cumulativePnl);
    }
 
    // ---- K线回调 ----
 
    public void onKline(BigDecimal closePrice) {
        lastKlinePrice = closePrice;
 
        if (state == StrategyState.WAITING_KLINE) {
            if (wsClient == null || !wsClient.areAllSubscribed()) {
                return;
            }
            state = StrategyState.OPENING;
            String size = config.getBaseQuantity();
            log.info("[OKX] 首根K线到达,开基底仓位 多空各{}张...", size);
            executor.openLong(size, (orderId) -> {
                TraderParam baseLongTp = TraderParam.builder()
                        .entryOrderId(orderId)
                        .build();
                config.setBaseLongTraderParam(baseLongTp);
                baseLongOpened = true;
            }, null);
            executor.openShort(size, (orderId) -> {
                TraderParam baseShortTp = TraderParam.builder()
                        .entryOrderId(orderId)
                        .build();
                config.setBaseShortTraderParam(baseShortTp);
                baseShortOpened = true;
            }, null);
            return;
        }
 
 
 
        if (state == StrategyState.ACTIVE &&
                !longActive &&
                longPositionSize.compareTo(BigDecimal.ZERO) == 0) {
            processShortGrid(closePrice);
        }
 
        if (state == StrategyState.ACTIVE &&
                !shortActive &&
                shortPositionSize.compareTo(BigDecimal.ZERO) == 0) {
            processLongGrid(closePrice);
        }
    }
 
    // ---- 仓位推送回调 ----
 
    /**
     * 仓位推送回调。由 PositionsOkxChannelHandler 调用。
     * direction 使用 TraderParam.Direction:LONG 表示多头,SHORT 表示空头。
     */
    public void onPositionUpdate(String contract, TraderParam.Direction direction, BigDecimal size,
                                  BigDecimal entryPrice) {
        if (state == StrategyState.STOPPED || state == StrategyState.WAITING_KLINE) {
            return;
        }
 
        boolean hasPosition = size.abs().compareTo(BigDecimal.ZERO) > 0;
        boolean isLong = (direction == TraderParam.Direction.LONG);
 
        if (state == StrategyState.OPENING) {
            // 基底成交通知仅记录价格/数量,flag 在 REST 回调中设置
            if (isLong && hasPosition) {
                longActive = true;
                longPositionSize = size;
                longEntryPrice = entryPrice;
                longBaseEntryPrice = entryPrice;
                log.info("[OKX] 基底多成交价: {}", longBaseEntryPrice);
                tryGenerateQueues();
            } else if (!isLong && hasPosition) {
                shortActive = true;
                shortPositionSize = size.abs();
                shortEntryPrice = entryPrice;
                shortBaseEntryPrice = entryPrice;
                log.info("[OKX] 基底空成交价: {}", shortBaseEntryPrice);
                tryGenerateQueues();
            }
        }
 
        if (state == StrategyState.ACTIVE) {
            if (isLong) {
                if (hasPosition) {
                    longActive = true;
                    longPositionSize = size;
                    longEntryPrice = entryPrice;
                } else {
                    log.info("[OKX-0]多仓归零: {}", shortBaseEntryPrice);
                    longActive = false;
                    longPositionSize = BigDecimal.ZERO;
                    longEntryPrice = BigDecimal.ZERO;
                }
            } else {
                if (hasPosition) {
                    shortActive = true;
                    shortPositionSize = size.abs();
                    shortEntryPrice = entryPrice;
                } else {
                    log.info("[OKX-0]空仓归零: {}", shortBaseEntryPrice);
                    shortActive = false;
                    shortPositionSize = BigDecimal.ZERO;
                    shortEntryPrice = BigDecimal.ZERO;
                }
            }
        }
 
        if (state == StrategyState.ACTIVE && !shortActive && !longActive) {
            executor.cancelAllPriceTriggeredOrders();
            closeExistingPositions();
            state = StrategyState.STOPPED;
            executor.submitTask(() -> {
                try { Thread.sleep(3000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
                startGrid();
            });
            log.info("[OKX] 重置策略");
        }
    }
 
    // ---- 平仓推送回调 ----
 
    /**
     * 平仓盈亏累加(OKX 目前没有独立的 position_closes 频道,
     * 盈亏信息可从 orders 频道或 REST API 获取,这里保留接口以备将来使用)。
     */
    public void onPositionClose(String contract, String side, BigDecimal pnl) {
        if (state == StrategyState.STOPPED) {
            return;
        }
        cumulativePnl = cumulativePnl.add(pnl);
        updateUnrealizedPnl();
        BigDecimal totalPnl = cumulativePnl.add(unrealizedPnl);
        log.info("[OKX] 已实现:{}, 未实现:{}, 合计:{}",
                cumulativePnl, unrealizedPnl, totalPnl);
        if (totalPnl.compareTo(config.getMaxLoss().negate()) <= 0) {
            String logMessage = StrUtil.format("[OKX] 已达亏损风险值(合计{}), 已实现:{}, 未实现:{}",
                    totalPnl, cumulativePnl, unrealizedPnl);
            log.info(logMessage);
            DingTalkUtils.getDefault().sendActionCard("风险提醒", logMessage, config.getApiKey(), "");
        }
    }
 
    // ---- 自动订单(条件单)状态变更回调 ----
 
    /**
     * 自动订单状态变更回调。由 OrdersOkxChannelHandler 调用。
     */
    public void onAutoOrder(String orderId, String status, String orderType, String tradeId) {
        if (state == StrategyState.STOPPED) {
            return;
        }
        log.info("[OKX] 条件单状态变更, id:{}, status:{}, order_type:{}",
                orderId, status,  orderType);
        if (!"finished".equals(status)) {
            return;
        }
 
        // 多仓止盈触发
        GridElement longTpElem = GridElement.findByLongTakeProfitOrderId(orderId);
        if (longTpElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) {
            longTakeProfitTraderIdParam(longTpElem, null, false);
            log.info("[OKX] 多仓止盈触发 gridId:{}, orderId:{}", longTpElem.getId(), orderId);
            cancelFarthestLongStopLoss();
            checkLastTakeProfitAndRestart();
            return;
        }
        // 空仓止盈触发
        GridElement shortTpElem = GridElement.findByShortTakeProfitOrderId(orderId);
        if (shortTpElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) {
            shortTakeProfitTraderIdParam(shortTpElem, null, false);
            log.info("[OKX] 空仓止盈触发 gridId:{}, orderId:{}", shortTpElem.getId(), orderId);
            cancelFarthestShortStopLoss();
            checkLastTakeProfitAndRestart();
            return;
        }
 
        // 多仓止损触发
        GridElement longStopLossElem = GridElement.findByLongStopLossOrderId(orderId);
        if (longStopLossElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) {
            handleLongStopLossTriggered(longStopLossElem);
            return;
        }
        // 空仓止损触发
        GridElement shortStopLossElem = GridElement.findByShortStopLossOrderId(orderId);
        if (shortStopLossElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) {
            handleShortStopLossTriggered(shortStopLossElem);
            return;
        }
 
        // 空仓挂单成交
        GridElement shortGridElement = GridElement.findByShortOrderId(orderId);
        if (shortGridElement != null) {
            if (shortGridElement.isHasShortOrder() && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) {
                int filledQty = Integer.parseInt(shortGridElement.getShortTraderParam().getQuantity());
                shortEntryTraderIdParam(shortGridElement, null, false);
                cancelAllShortTakeProfitsAndStopLosses();
                int posSize = queryPositionSize(OkxPosMode.SHORT);
                extendShortStopLoss(posSize, shortGridElement.getId());
                accumulatedShortLossCount = 0;
                log.info("[OKX] 空单成交 gridId:{}, 成交{}张, 当前持仓:{}张",
                        shortGridElement.getId(), filledQty, posSize);
 
                BigDecimal shortBaseQty = new BigDecimal(config.getBaseQuantity());
                BigDecimal shortGridQty = new BigDecimal(config.getQuantity());
                if (BigDecimal.valueOf(posSize).compareTo(shortBaseQty) > 0) {
                    BigDecimal shortExcess = BigDecimal.valueOf(posSize).subtract(shortBaseQty);
                    int shortExcessCount = shortExcess.divide(shortGridQty, 0, RoundingMode.DOWN).intValue();
                    for (int i = 0; i < shortExcessCount; i++) {
                        int tpGridId = shortGridElement.getId() - 2 * (i + 1);
                        GridElement tpElem = GridElement.findById(tpGridId);
                        if (tpElem == null || tpElem.getShortTakeProfitOrderId() != null) {
                            continue;
                        }
                        BigDecimal tpPrice = tpElem.getGridPrice();
                        int finalTpGridId = tpGridId;
                        executor.placeTakeProfit(
                                tpPrice,
                                "close_short",
                                config.getQuantity(),
                                profitId -> {
                                    shortTakeProfitTraderIdParam(tpElem, profitId, true);
                                    log.info("[OKX] 空仓止盈挂单, gridId:{}, 触发价:{}, takeProfitId:{}",
                                            finalTpGridId, tpPrice, profitId);
                                }
                        );
                    }
                }
            }
        }
        // 多仓挂单成交
        GridElement longGridElement = GridElement.findByLongOrderId(orderId);
        if (longGridElement != null) {
            if (longGridElement.isHasLongOrder() && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) {
                int filledQty = Integer.parseInt(longGridElement.getLongTraderParam().getQuantity());
                longEntryTraderIdParam(longGridElement, null, false);
                cancelAllLongTakeProfitsAndStopLosses();
                int posSize = queryPositionSize(OkxPosMode.LONG);
                extendLongStopLoss(posSize, longGridElement.getId());
                accumulatedLongLossCount = 0;
                log.info("[OKX] 多单成交 gridId:{}, 成交{}张, 当前持仓:{}张",
                        longGridElement.getId(), filledQty, posSize);
 
                BigDecimal longBaseQty = new BigDecimal(config.getBaseQuantity());
                BigDecimal longGridQty = new BigDecimal(config.getQuantity());
                if (BigDecimal.valueOf(posSize).compareTo(longBaseQty) > 0) {
                    BigDecimal longExcess = BigDecimal.valueOf(posSize).subtract(longBaseQty);
                    int longExcessCount = longExcess.divide(longGridQty, 0, RoundingMode.DOWN).intValue();
                    for (int i = 0; i < longExcessCount; i++) {
                        int tpGridId = longGridElement.getId() + 2 * (i + 1);
                        GridElement tpElem = GridElement.findById(tpGridId);
                        if (tpElem == null || tpElem.getLongTakeProfitOrderId() != null) {
                            continue;
                        }
                        BigDecimal tpPrice = tpElem.getGridPrice();
                        int finalTpGridId = tpGridId;
                        executor.placeTakeProfit(
                                tpPrice,
                                "close_long",
                                config.getQuantity(),
                                profitId -> {
                                    longTakeProfitTraderIdParam(tpElem, profitId, true);
                                    log.info("[OKX] 多仓止盈挂单, gridId:{}, 触发价:{}, takeProfitId:{}",
                                            finalTpGridId, tpPrice, profitId);
                                }
                        );
                    }
                }
            }
        }
    }
 
    // ========== REST 查询辅助 ==========
 
    private int queryPositionSize(OkxPosMode mode) {
        OkxPositionInfo p = queryPosition(mode);
        if (p != null) {
            return new BigDecimal(p.size).abs().intValue();
        }
        return 0;
    }
 
    private BigDecimal queryEntryPrice(OkxPosMode mode) {
        OkxPositionInfo p = queryPosition(mode);
        if (p != null && p.entryPrice != null) {
            return new BigDecimal(p.entryPrice);
        }
        return BigDecimal.ZERO;
    }
 
    private OkxPositionInfo queryPosition(OkxPosMode mode) {
        try {
            JSONObject resp = executorGet("/api/v5/account/positions?instType=SWAP");
            JSONArray data = resp.getJSONArray("data");
            if (data != null) {
                for (int i = 0; i < data.size(); i++) {
                    JSONObject p = data.getJSONObject(i);
                    if (config.getContract().equals(p.getString("instId"))
                            && mode.name().toLowerCase().equals(p.getString("posSide"))) {
                        OkxPositionInfo info = new OkxPositionInfo();
                        info.size = p.getString("pos");
                        info.entryPrice = p.getString("avgPx");
                        return info;
                    }
                }
            }
        } catch (Exception e) {
            log.warn("[OKX] 查询{}持仓失败", mode, e);
        }
        return null;
    }
 
    // ---- REST 快捷方法 ----
 
    private JSONObject executorGet(String path) throws Exception {
        return executor.okGet(path);
    }
 
    private JSONObject executorPost(String path, String body) throws Exception {
        return executor.okPost(path, body);
    }
 
    // ---- 网格队列处理 ----
 
    private void tryGenerateQueues() {
        // OPENING 状态下若 WS 仓位已确认但 REST 回调尚未完成,等标记价格推送时重试队列生成
        if (state == StrategyState.OPENING && baseLongOpened && baseShortOpened) {
            // 确保 openLong/openShort 的 REST 回调已完成(WS 推送可能比回调更快到达)
            if (config.getBaseLongTraderParam() == null || config.getBaseShortTraderParam() == null) {
                log.warn("[OKX] 基底REST回调尚未完成, 延后队列生成");
                return;
            }
 
            generateShortQueue();
            generateLongQueue();
            updateGridElements();
 
            GridElement baseGridElement = GridElement.findById(0);
            TraderParam baseLongTraderParam = config.getBaseLongTraderParam();
            baseGridElement.setLongOrderId(baseLongTraderParam.getEntryOrderId());
            baseGridElement.setHasLongOrder(true);
            TraderParam baseShortTraderParam = config.getBaseShortTraderParam();
            baseGridElement.setShortOrderId(baseShortTraderParam.getEntryOrderId());
            baseGridElement.setHasShortOrder(true);
 
            // 挂初始止损
            int stopCount = Integer.parseInt(config.getBaseQuantity()) / Integer.parseInt(config.getQuantity()) + 1;
            for (int id = 2; id <= stopCount; id++) {
                GridElement elem = GridElement.findById(id);
                if (elem == null) {
                    continue;
                }
                BigDecimal triggerPrice = elem.getGridPrice();
                int finalId = id;
                executor.placeStopLoss(triggerPrice, "close_short", config.getQuantity(),
                        profitId -> {
                            elem.setShortStopLossOrderId(profitId);
                            GridElement.refreshIndices();
                            log.info("[OKX] 空仓止损已挂, gridId:{}, 触发价:{}, slId:{}", finalId, triggerPrice, profitId);
                        });
            }
            for (int id = -2; id >= -stopCount; id--) {
                GridElement elem = GridElement.findById(id);
                if (elem == null) {
                    continue;
                }
                BigDecimal triggerPrice = elem.getGridPrice();
                int finalId = id;
                executor.placeStopLoss(triggerPrice, "close_long", config.getQuantity(),
                        profitId -> {
                            elem.setLongStopLossOrderId(profitId);
                            GridElement.refreshIndices();
                            log.info("[OKX] 多仓止损已挂, gridId:{}, 触发价:{}, slId:{}", finalId, triggerPrice, profitId);
                        });
            }
            log.info("[OKX] 止损单已全部挂完, 空仓止损: 2~{}, 多仓止损: -2~-{}", stopCount, stopCount);
 
            state = StrategyState.ACTIVE;
        }
    }
 
    // ---- TraderParam 更新辅助方法 ----
 
    private void longTakeProfitTraderIdParam(GridElement e, String profitId, boolean flag) {
        TraderParam tp = e.getLongTraderParam();
        tp.setTakeProfitOrderId(profitId);
        tp.setTakeProfitPlaced(flag);
        e.setLongTakeProfitOrderId(profitId);
        GridElement.refreshIndices();
    }
 
    private void shortTakeProfitTraderIdParam(GridElement e, String profitId, boolean flag) {
        TraderParam tp = e.getShortTraderParam();
        tp.setTakeProfitOrderId(profitId);
        tp.setTakeProfitPlaced(flag);
        e.setShortTakeProfitOrderId(profitId);
        GridElement.refreshIndices();
    }
 
    private void longEntryTraderIdParam(GridElement e, String entryId, boolean flag) {
        TraderParam tp = e.getLongTraderParam();
        tp.setEntryOrderId(entryId);
        tp.setEntryOrderPlaced(flag);
        e.setHasLongOrder(flag);
        e.setLongOrderId(entryId);
        GridElement.refreshIndices();
    }
 
    private void shortEntryTraderIdParam(GridElement e, String entryId, boolean flag) {
        TraderParam tp = e.getShortTraderParam();
        tp.setEntryOrderId(entryId);
        tp.setEntryOrderPlaced(flag);
        e.setHasShortOrder(flag);
        e.setShortOrderId(entryId);
        GridElement.refreshIndices();
    }
 
    // ---- 队列生成 ----
 
    private void generateShortQueue() {
        shortPriceQueue.clear();
        totalShortPriceQueue.clear();
        totalLongPriceQueue.clear();
        int prec = config.getPriceScale();
        BigDecimal step = shortBaseEntryPrice.multiply(config.getGridRate()).setScale(prec, RoundingMode.HALF_UP);
        config.setStep(step);
        BigDecimal elem = shortBaseEntryPrice.subtract(step).setScale(prec, RoundingMode.HALF_UP);
        for (int i = 0; i < config.getGridQueueSize(); i++) {
            shortPriceQueue.add(elem);
            totalLongPriceQueue.add(elem);
            totalShortPriceQueue.add(elem);
            elem = elem.subtract(step).setScale(prec, RoundingMode.HALF_UP);
            if (elem.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
        }
        shortPriceQueue.sort((a, b) -> b.compareTo(a));
        log.info("[OKX] 空队列:{}", shortPriceQueue);
    }
 
    private void generateLongQueue() {
        longPriceQueue.clear();
        int prec = config.getPriceScale();
        BigDecimal step = config.getStep();
        BigDecimal elem = shortBaseEntryPrice.add(step).setScale(prec, RoundingMode.HALF_UP);
        for (int i = 0; i < config.getGridQueueSize(); i++) {
            longPriceQueue.add(elem);
            totalLongPriceQueue.add(elem);
            totalShortPriceQueue.add(elem);
            elem = elem.add(step).setScale(prec, RoundingMode.HALF_UP);
        }
        longPriceQueue.sort(BigDecimal::compareTo);
        log.info("[OKX] 多队列:{}", longPriceQueue);
        totalShortPriceQueue.sort((a, b) -> b.compareTo(a));
        totalLongPriceQueue.sort(BigDecimal::compareTo);
    }
 
    private void updateGridElements() {
        List<GridElement> elements = new ArrayList<>();
        int shortSize = shortPriceQueue.size();
        int longSize = longPriceQueue.size();
        int prec = config.getPriceScale();
        BigDecimal step = config.getStep();
        String qty = config.getQuantity();
 
        // 空仓队列:id 从 -1 自减
        for (int i = 0; i < shortSize; i++) {
            int id = -(i + 1);
            Integer upId = (i == 0) ? 0 : id + 1;
            Integer downId = (i == shortSize - 1) ? null : id - 1;
            BigDecimal price = shortPriceQueue.get(i);
            elements.add(GridElement.builder()
                    .id(id).gridPrice(price).upId(upId).downId(downId)
                    .longTraderParam(TraderParam.builder().direction(TraderParam.Direction.LONG)
                            .entryPrice(price).takeProfitPrice(price.add(step).setScale(prec, RoundingMode.HALF_UP))
                            .quantity(qty).build())
                    .shortTraderParam(TraderParam.builder().direction(TraderParam.Direction.SHORT)
                            .entryPrice(price).takeProfitPrice(price.subtract(step).setScale(prec, RoundingMode.HALF_UP))
                            .quantity(qty).build())
                    .build());
        }
 
        // 位置 0
        {
            BigDecimal price = shortBaseEntryPrice;
            elements.add(GridElement.builder()
                    .id(0).gridPrice(price)
                    .upId(longSize > 0 ? 1 : null).downId(shortSize > 0 ? -1 : null)
                    .longTraderParam(TraderParam.builder().direction(TraderParam.Direction.LONG)
                            .entryPrice(price).takeProfitPrice(price.add(step).setScale(prec, RoundingMode.HALF_UP))
                            .quantity(qty).build())
                    .shortTraderParam(TraderParam.builder().direction(TraderParam.Direction.SHORT)
                            .entryPrice(price).takeProfitPrice(price.subtract(step).setScale(prec, RoundingMode.HALF_UP))
                            .quantity(qty).build())
                    .build());
        }
 
        // 多仓队列:id 从 1 自增
        for (int i = 0; i < longSize; i++) {
            int id = i + 1;
            Integer downId = (i == 0) ? 0 : id - 1;
            Integer upId = (i == longSize - 1) ? null : id + 1;
            BigDecimal price = longPriceQueue.get(i);
            elements.add(GridElement.builder()
                    .id(id).gridPrice(price).upId(upId).downId(downId)
                    .longTraderParam(TraderParam.builder().direction(TraderParam.Direction.LONG)
                            .entryPrice(price).takeProfitPrice(price.add(step).setScale(prec, RoundingMode.HALF_UP))
                            .quantity(qty).build())
                    .shortTraderParam(TraderParam.builder().direction(TraderParam.Direction.SHORT)
                            .entryPrice(price).takeProfitPrice(price.subtract(step).setScale(prec, RoundingMode.HALF_UP))
                            .quantity(qty).build())
                    .build());
        }
 
        config.setGridElements(elements);
        log.info("[OKX] 网格元素列表已构建, 共{}个元素 (空仓:{} 位置:0 多仓:{})", elements.size(), shortSize, longSize);
    }
 
    // ---- processShortGrid / processLongGrid ----
 
    private void processShortGrid(BigDecimal currentPrice) {
        BigDecimal matched = BigDecimal.ZERO;
        synchronized (totalLongPriceQueue) {
            for (BigDecimal p : totalLongPriceQueue) {
                if (p.compareTo(currentPrice) >= 0) { matched = p; break; }
            }
            if (BigDecimal.ZERO.compareTo(matched) == 0) {
                return;
            }
            GridElement matchedUpGridElement = GridElement.findByPrice(matched);
            if (matchedUpGridElement != null && !matchedUpGridElement.isHasLongOrder()) {
                Integer upId = matchedUpGridElement.getUpId();
                GridElement newEntryGrid = GridElement.findById(upId);
                if (newEntryGrid != null) {
                    GridElement cancelGridElement = GridElement.findById(newEntryGrid.getUpId());
                    String quantity = cancelGridElement != null
                            ? cancelGridElement.getLongTraderParam().getQuantity()
                            : config.getBaseQuantity();
                    if (cancelGridElement != null && cancelGridElement.isHasLongOrder()) {
                        String longOrderId = cancelGridElement.getLongOrderId();
                        executor.cancelConditionalOrder(longOrderId, oid -> {
                            longEntryTraderIdParam(cancelGridElement, null, false);
                            log.info("[OKX] 多仓仓位归零, 取消gridId:{}的多单,{}", cancelGridElement.getId(), longOrderId);
                        });
                    }
                    if (!newEntryGrid.isHasLongOrder()) {
                        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
                        String size = quantity;
                        log.info("[OKX] 多仓仓位归零 gridId:{}, 挂{}基础张多单", newEntryGrid.getId(), size);
                        newEntryGrid.getLongTraderParam().setQuantity(size);
                        placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice, size);
                    }
                }
            }
        }
    }
 
    private void processLongGrid(BigDecimal currentPrice) {
        BigDecimal matched = BigDecimal.ZERO;
        synchronized (totalShortPriceQueue) {
            for (BigDecimal p : totalShortPriceQueue) {
                if (p.compareTo(currentPrice) <= 0) { matched = p; break; }
            }
            if (BigDecimal.ZERO.compareTo(matched) == 0) {
                return;
            }
            GridElement matchedUpGridElement = GridElement.findByPrice(matched);
            if (matchedUpGridElement != null && !matchedUpGridElement.isHasShortOrder()) {
                Integer downId = matchedUpGridElement.getDownId();
                GridElement newEntryGrid = GridElement.findById(downId);
                if (newEntryGrid != null) {
                    GridElement cancelGridElement = GridElement.findById(newEntryGrid.getDownId());
                    String quantity = cancelGridElement != null
                            ? cancelGridElement.getShortTraderParam().getQuantity()
                            : config.getBaseQuantity();
                    if (cancelGridElement != null && cancelGridElement.isHasShortOrder()) {
                        String shortOrderId = cancelGridElement.getShortOrderId();
                        executor.cancelConditionalOrder(shortOrderId, oid -> {
                            shortEntryTraderIdParam(cancelGridElement, null, false);
                            log.info("[OKX] 空仓仓位归零, 取消gridId:{}的空单{}", cancelGridElement.getId(), shortOrderId);
                        });
                    }
                    if (!newEntryGrid.isHasShortOrder()) {
                        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
                        String size = quantity;
                        log.info("[OKX] 空仓仓位归零 gridId:{}, 挂{}基础张空单", newEntryGrid.getId(), size);
                        newEntryGrid.getShortTraderParam().setQuantity(size);
                        placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice, negate(size));
                    }
                }
            }
        }
    }
 
    // ---- 止损处理 ----
 
    private void handleLongStopLossTriggered(GridElement gridElement) {
        gridElement.setLongStopLossOrderId(null);
        int gridId = gridElement.getId();
        log.info("[OKX] 多仓止损触发 gridId:{}, 开始追单", gridId);
        int newEntryGridId = gridId + 1;
        GridElement newEntryGrid = GridElement.findById(newEntryGridId);
        if (newEntryGrid == null) {
            log.warn("[OKX] 多仓止损触发 but gridId:{} 不存在", newEntryGridId);
            GridElement.refreshIndices();
            return;
        }
        if (!newEntryGrid.isHasLongOrder()) {
            BigDecimal triggerPrice = newEntryGrid.getGridPrice();
            accumulatedLongLossCount += Integer.parseInt(config.getQuantity());
            String size = String.valueOf(accumulatedLongLossCount + Integer.parseInt(config.getQuantity()));
            log.info("[OKX] 多仓止损触发 gridId:{}, 在gridId:{}挂{}基础张多单", gridId, newEntryGridId, size);
            newEntryGrid.getLongTraderParam().setQuantity(size);
            placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice, size);
        } else {
            log.warn("[OKX] 多仓止损触发 gridId:{}, 目标gridId:{}已有挂单,跳过", gridId, newEntryGridId);
        }
        int cancelGridId = gridId + 2;
        GridElement cancelGrid = GridElement.findById(cancelGridId);
        if (cancelGrid != null && cancelGrid.isHasLongOrder()) {
            executor.cancelConditionalOrder(cancelGrid.getLongOrderId(), oid -> {
                longEntryTraderIdParam(cancelGrid, null, false);
                log.info("[OKX] 多仓止损触发, 取消gridId:{}的多单", cancelGridId);
            });
        }
        GridElement farthestLongTp = null;
        for (GridElement e : config.getGridElements()) {
            if (e.getLongTakeProfitOrderId() != null) {
                if (farthestLongTp == null || e.getGridPrice().compareTo(farthestLongTp.getGridPrice()) > 0) {
                    farthestLongTp = e;
                }
            }
        }
        if (farthestLongTp != null) {
            String tpOrderId = farthestLongTp.getLongTakeProfitOrderId();
            GridElement finalFarthest = farthestLongTp;
            executor.cancelConditionalOrder(tpOrderId, oid -> {
                longTakeProfitTraderIdParam(finalFarthest, null, false);
                log.info("[OKX] 多仓止损触发, 取消最远止盈 gridId:{}, orderId:{}", finalFarthest.getId(), tpOrderId);
            });
        }
    }
 
    private void handleShortStopLossTriggered(GridElement gridElement) {
        gridElement.setShortStopLossOrderId(null);
        int gridId = gridElement.getId();
        log.info("[OKX] 空仓止损触发 gridId:{}, 开始追单", gridId);
        int newEntryGridId = gridId - 1;
        GridElement newEntryGrid = GridElement.findById(newEntryGridId);
        if (newEntryGrid == null) {
            log.warn("[OKX] 空仓止损触发 but gridId:{} 不存在", newEntryGridId);
            GridElement.refreshIndices();
            return;
        }
        if (!newEntryGrid.isHasShortOrder()) {
            BigDecimal triggerPrice = newEntryGrid.getGridPrice();
            accumulatedShortLossCount += Integer.parseInt(config.getQuantity());
            String size = String.valueOf(accumulatedShortLossCount + Integer.parseInt(config.getQuantity()));
            log.info("[OKX] 空仓止损触发 gridId:{}, 在gridId:{}挂{}基础张空单", gridId, newEntryGridId, size);
            newEntryGrid.getShortTraderParam().setQuantity(size);
            placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice, negate(size));
        } else {
            log.warn("[OKX] 空仓止损触发 gridId:{}, 目标gridId:{}已有挂单,跳过", gridId, newEntryGridId);
        }
        int cancelGridId = gridId - 2;
        GridElement cancelGrid = GridElement.findById(cancelGridId);
        if (cancelGrid != null && cancelGrid.isHasShortOrder()) {
            executor.cancelConditionalOrder(cancelGrid.getShortOrderId(), oid -> {
                shortEntryTraderIdParam(cancelGrid, null, false);
                log.info("[OKX] 空仓止损触发, 取消gridId:{}的空单", cancelGridId);
            });
        }
        GridElement farthestShortTp = null;
        for (GridElement e : config.getGridElements()) {
            if (e.getShortTakeProfitOrderId() != null) {
                if (farthestShortTp == null || e.getGridPrice().compareTo(farthestShortTp.getGridPrice()) < 0) {
                    farthestShortTp = e;
                }
            }
        }
        if (farthestShortTp != null) {
            String tpOrderId = farthestShortTp.getShortTakeProfitOrderId();
            GridElement finalFarthest = farthestShortTp;
            executor.cancelConditionalOrder(tpOrderId, oid -> {
                shortTakeProfitTraderIdParam(finalFarthest, null, false);
                log.info("[OKX] 空仓止损触发, 取消最远止盈 gridId:{}, orderId:{}", finalFarthest.getId(), tpOrderId);
            });
        }
    }
 
    // ---- 止盈/止损取消辅助 ----
 
    private void checkLastTakeProfitAndRestart() {
        int span = config.getRestartGridSpan();
        if (span <= 0) {
            return;
        }
 
        if (GridElement.getLongTakeProfitCount() > 0 || GridElement.getShortTakeProfitCount() > 0) {
            log.info("[OKX] 尚有未触发止盈单, 暂不检查跨度重启 longTpCount:{}, shortTpCount:{}",
                    GridElement.getLongTakeProfitCount(), GridElement.getShortTakeProfitCount());
            return;
        }
 
        BigDecimal step = config.getStep();
        if (step == null || step.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        BigDecimal threshold = step.multiply(new BigDecimal(span));
        BigDecimal currentPrice = lastKlinePrice;
        if (currentPrice == null || currentPrice.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
 
        // 查交易所获取最新持仓均价
        OkxPositionInfo longPos = queryPosition(OkxPosMode.LONG);
        OkxPositionInfo shortPos = queryPosition(OkxPosMode.SHORT);
        boolean hasLong = longPos != null && Math.abs(Integer.parseInt(longPos.size)) > 0;
        boolean hasShort = shortPos != null && Math.abs(Integer.parseInt(shortPos.size)) > 0;
        BigDecimal longAvgPrice = (longPos != null && longPos.entryPrice != null)
                ? new BigDecimal(longPos.entryPrice) : BigDecimal.ZERO;
        BigDecimal shortAvgPrice = (shortPos != null && shortPos.entryPrice != null)
                ? new BigDecimal(shortPos.entryPrice) : BigDecimal.ZERO;
 
        boolean shouldRestart = false;
        String reason = "";
 
        if (hasLong && hasShort) {
            BigDecimal gap = shortAvgPrice.subtract(longAvgPrice);
            if (gap.compareTo(threshold) >= 0) {
                shouldRestart = true;
                reason = StrUtil.format("双边跨度 |多均价:{} − 空均价:{}| = {} >= {} (span:{}×step:{})",
                        longAvgPrice, shortAvgPrice, gap, threshold, span, step);
            }
        } else if (hasLong) {
            BigDecimal gap = currentPrice.subtract(longAvgPrice);
            if (gap.compareTo(threshold) >= 0) {
                shouldRestart = true;
                reason = StrUtil.format("多仓跨度 当前价:{} − 多均价:{} = {} > {} (span:{}×step:{})",
                        currentPrice, longAvgPrice, gap, threshold, span, step);
            }
        } else if (hasShort) {
            BigDecimal gap = shortAvgPrice.subtract(currentPrice);
            if (gap.compareTo(threshold) >= 0) {
                shouldRestart = true;
                reason = StrUtil.format("空仓跨度 空均价:{} − 当前价:{} = {} > {} (span:{}×step:{})",
                        shortAvgPrice, currentPrice, gap, threshold, span, step);
            }
        }
 
        if (shouldRestart) {
            log.info("[OKX] 跨度已达要求 → {},最后一个止盈触发策略重启", reason);
            executor.cancelAllPriceTriggeredOrders();
            closeExistingPositions();
            state = StrategyState.STOPPED;
            executor.submitTask(() -> {
                try { Thread.sleep(3000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); }
                startGrid();
            });
        }
    }
 
    private void cancelFarthestLongStopLoss() {
        GridElement farthest = null;
        for (GridElement e : config.getGridElements()) {
            if (e.getLongStopLossOrderId() != null) {
                if (farthest == null || e.getId() < farthest.getId()) {
                    farthest = e;
                }
            }
        }
        if (farthest != null) {
            String slId = farthest.getLongStopLossOrderId();
            farthest.setLongStopLossOrderId(null);
            GridElement.refreshIndices();
            GridElement finalFarthest = farthest;
            executor.cancelConditionalOrder(slId, oid ->
                    log.info("[OKX] 止盈触发, 取消最远多仓止损 gridId:{}, orderId:{}", finalFarthest.getId(), slId));
        }
    }
 
    private void cancelFarthestShortStopLoss() {
        GridElement farthest = null;
        for (GridElement e : config.getGridElements()) {
            if (e.getShortStopLossOrderId() != null) {
                if (farthest == null || e.getId() > farthest.getId()) {
                    farthest = e;
                }
            }
        }
        if (farthest != null) {
            String slId = farthest.getShortStopLossOrderId();
            farthest.setShortStopLossOrderId(null);
            GridElement.refreshIndices();
            GridElement finalFarthest = farthest;
            executor.cancelConditionalOrder(slId, oid ->
                    log.info("[OKX] 止盈触发, 取消最远空仓止损 gridId:{}, orderId:{}", finalFarthest.getId(), slId));
        }
    }
 
    private void cancelAllLongTakeProfitsAndStopLosses() {
        for (GridElement e : config.getGridElements()) {
            String tpId = e.getLongTakeProfitOrderId();
            if (tpId != null) { e.setLongTakeProfitOrderId(null); executor.cancelConditionalOrder(tpId, oid -> {}); }
            String slId = e.getLongStopLossOrderId();
            if (slId != null) { e.setLongStopLossOrderId(null); executor.cancelConditionalOrder(slId, oid -> {}); }
        }
        GridElement.refreshIndices();
        log.info("[OKX] 已提交取消所有多仓止盈+止损");
    }
 
    private void cancelAllShortTakeProfitsAndStopLosses() {
        for (GridElement e : config.getGridElements()) {
            String tpId = e.getShortTakeProfitOrderId();
            if (tpId != null) { e.setShortTakeProfitOrderId(null); executor.cancelConditionalOrder(tpId, oid -> {}); }
            String slId = e.getShortStopLossOrderId();
            if (slId != null) { e.setShortStopLossOrderId(null); executor.cancelConditionalOrder(slId, oid -> {}); }
        }
        GridElement.refreshIndices();
        log.info("[OKX] 已提交取消所有空仓止盈+止损");
    }
 
    // ---- 止损追单 ----
 
    private void extendLongStopLoss(int filledQty, int gridId) {
        int furthestSlId = 0;
        for (GridElement e : config.getGridElements()) {
            if (e.getLongStopLossOrderId() != null && e.getId() < furthestSlId) {
                furthestSlId = e.getId();
            }
        }
        int interval = 1;
        if (furthestSlId == 0) { furthestSlId = gridId; interval = 2; }
        int stopLossCount = filledQty / Integer.parseInt(config.getQuantity());
        log.info("[OKX] 多仓追挂止损, 当前最远止损gridId:{}, 成交{}张, 追加{}个止损单", furthestSlId, filledQty, stopLossCount);
        for (int i = 0; i < stopLossCount; i++) {
            int newSlId = furthestSlId - i - interval;
            GridElement elem = GridElement.findById(newSlId);
            if (elem == null) {
                continue;
            }
            BigDecimal triggerPrice = elem.getGridPrice();
            int finalSlId = newSlId;
            executor.placeStopLoss(triggerPrice, "close_long", config.getQuantity(),
                    profitId -> {
                        elem.setLongStopLossOrderId(profitId);
                        GridElement.refreshIndices();
                        log.info("[OKX] 多仓止损追加, gridId:{}, 触发价:{}, slId:{}", finalSlId, triggerPrice, profitId);
                    });
        }
    }
 
    private void extendShortStopLoss(int filledQty, int gridId) {
        int furthestSlId = 0;
        for (GridElement e : config.getGridElements()) {
            if (e.getShortStopLossOrderId() != null && e.getId() > furthestSlId) {
                furthestSlId = e.getId();
            }
        }
        int interval = 1;
        if (furthestSlId == 0) { furthestSlId = gridId; interval = 2; }
        int stopLossCount = filledQty / Integer.parseInt(config.getQuantity());
        log.info("[OKX] 空仓追挂止损, 当前最远止损gridId:{}, 成交{}张, 追加{}个止损单", furthestSlId, filledQty, stopLossCount);
        for (int i = 0; i < stopLossCount; i++) {
            int newSlId = furthestSlId + i + interval;
            GridElement elem = GridElement.findById(newSlId);
            if (elem == null) {
                continue;
            }
            BigDecimal triggerPrice = elem.getGridPrice();
            int finalSlId = newSlId;
            executor.placeStopLoss(triggerPrice, "close_short", config.getQuantity(),
                    profitId -> {
                        elem.setShortStopLossOrderId(profitId);
                        GridElement.refreshIndices();
                        log.info("[OKX] 空仓止损追加, gridId:{}, 触发价:{}, slId:{}", finalSlId, triggerPrice, profitId);
                    });
        }
    }
 
    // ---- 工具 ----
 
    private String negate(String qty) {
        return qty.startsWith("-") ? qty.substring(1) : "-" + qty;
    }
 
    private void placeEntryOrderWithPreFlag(GridElement gridElement, boolean isLong,
                                             BigDecimal triggerPrice, String size) {
        if (isLong) {
            gridElement.setHasLongOrder(true);
        } else {
            gridElement.setHasShortOrder(true);
        }
        executor.placeConditionalEntryOrder(triggerPrice, isLong, size,
                orderId -> {
                    if (isLong) {
                        longEntryTraderIdParam(gridElement, orderId, true);
                    } else {
                        shortEntryTraderIdParam(gridElement, orderId, true);
                    }
                },
                () -> {
                    if (isLong) {
                        gridElement.setHasLongOrder(false);
                        gridElement.setLongOrderId(null);
                    } else {
                        gridElement.setHasShortOrder(false);
                        gridElement.setShortOrderId(null);
                    }
                    GridElement.refreshIndices();
                    log.warn("[OKX] 条件单创建失败,回滚标志位 gridId:{}, isLong:{}", gridElement.getId(), isLong);
                });
    }
 
    private void updateUnrealizedPnl() {
        BigDecimal price = resolvePnlPrice();
        if (price == null || price.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        BigDecimal multiplier = config.getContractMultiplier();
        BigDecimal longPnl = BigDecimal.ZERO;
        BigDecimal shortPnl = BigDecimal.ZERO;
        if (longPositionSize.compareTo(BigDecimal.ZERO) > 0 && longEntryPrice.compareTo(BigDecimal.ZERO) > 0) {
            longPnl = longPositionSize.multiply(multiplier).multiply(price.subtract(longEntryPrice));
        }
        if (shortPositionSize.compareTo(BigDecimal.ZERO) > 0 && shortEntryPrice.compareTo(BigDecimal.ZERO) > 0) {
            shortPnl = shortPositionSize.multiply(multiplier).multiply(shortEntryPrice.subtract(price));
        }
        unrealizedPnl = longPnl.add(shortPnl);
        log.info("[OKX] 未实现盈亏: {}", unrealizedPnl);
    }
 
    private BigDecimal resolvePnlPrice() {
        if (config.getUnrealizedPnlPriceMode() == OkxConfig.PnLPriceMode.MARK_PRICE
                && markPrice.compareTo(BigDecimal.ZERO) > 0) {
            return markPrice;
        }
        return lastKlinePrice;
    }
 
    // ---- getters ----
 
    public BigDecimal getLastKlinePrice() { return lastKlinePrice; }
    public void setMarkPrice(BigDecimal markPrice) { this.markPrice = markPrice; }
    public boolean isStrategyActive() { return state != StrategyState.STOPPED && state != StrategyState.WAITING_KLINE; }
    public BigDecimal getCumulativePnl() { return cumulativePnl; }
    public BigDecimal getUnrealizedPnl() { return unrealizedPnl; }
    public StrategyState getState() { return state; }
    public void setWsClient(OkxKlineWebSocketClient wsClient) { this.wsClient = wsClient; }
}