Administrator
3 hours ago 0d9c31cc7be76229cf71e141444598992758ebf6
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
package com.xcong.excoin.modules.gateApi;
 
import io.gate.gateapi.ApiClient;
import io.gate.gateapi.ApiException;
import io.gate.gateapi.GateApiException;
import io.gate.gateapi.api.AccountApi;
import io.gate.gateapi.api.FuturesApi;
import io.gate.gateapi.models.*;
import lombok.extern.slf4j.Slf4j;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
/**
 * Gate 网格交易服务 — 策略核心。
 *
 * <h3>策略</h3>
 * 多空双开基底 → 生成价格网格队列 → K线触达网格线 → 开仓+设止盈 → 队列动态转移。
 * 每根 K 线更新 {@code unrealizedPnl}(浮动盈亏),平仓后累加到 {@code cumulativePnl}(已实现盈亏)。
 *
 * <h3>未实现盈亏公式(正向合约)</h3>
 * <pre>
 *   多仓: 持仓量 × 合约乘数 × (计价价格 − 开仓均价)
 *   空仓: 持仓量 × 合约乘数 × (开仓均价 − 计价价格)
 * </pre>
 * 计价价格支持切换:{@link GateConfig.PnLPriceMode#LAST_PRICE 最新成交价} 或
 * {@link GateConfig.PnLPriceMode#MARK_PRICE 标记价格}(通过 {@link #setMarkPrice(BigDecimal)} 注入)。
 * 入场价和持仓量由 {@link #onPositionUpdate(String, Position.ModeEnum, BigDecimal, BigDecimal)} 实时更新。
 *
 * <h3>状态机</h3>
 * <pre>
 *   WAITING_KLINE → (首K线) → 异步双开基底
 *
 *   仓位推送(dual_long/dual_short) → 基底成交 → 记录入场价 → 双基底都成交 → 生成队列 → ACTIVE
 *
 *   ACTIVE:
 *     ├─ 每根K线 → 更新 unrealizedPnl + processShortGrid + processLongGrid
 *     │    ├─ 当前价 &lt; 空仓队列元素 → 匹配 → 开空 + 以多仓队列首元素为种子生成新元素加入多仓队列
 *     │    └─ 当前价 &gt; 多仓队列元素 → 匹配 → 开多 + 以空仓队列首元素为种子生成新元素加入空仓队列
 *     ├─ 仓位推送(非基底) → 设止盈条件单 entry × (1±gridRate),使用 plan-close-*-position
 *     ├─ 保证金≥初始本金 marginRatioLimit → 跳过开仓,队列照常更新
 *     ├─ 额外反向开仓:触发价夹在多/空持仓均价之间且多持仓均价&gt;空持仓均价时,额外反向开仓一次
 *     └─ cumulativePnl ≥ overallTp 或 ≤ -maxLoss → STOPPED
 * </pre>
 *
 * <h3>队列转移规则</h3>
 * 触发后不再简单复制 matched 元素到对方队列,而是以对方队列首元素为种子,生成新元素:
 * <ul>
 *   <li>空仓队列触发 → 多仓队列新增:以多仓队列首元素(最小价)为基准,生成递减元素</li>
 *   <li>多仓队列触发 → 空仓队列新增:以空仓队列首元素(最高价)为基准,生成递增元素</li>
 * </ul>
 *
 * <h3>贴近持仓均价过滤</h3>
 * 转移生成新元素时,若新元素与对应方向持仓均价的差距小于 gridRate,则跳过该元素,
 * 避免在持仓成本附近生成无效网格线。
 *
 * <h3>额外反向开仓条件</h3>
 * 当触发价在空仓均价和回撤后的多仓均价之间(即多&gt;空且价格夹在中间),额外反向开仓一次:
 * <ul>
 *   <li>空仓队列触发 → 额外开多:需满足 shortEntryPrice &lt; currentPrice &lt; longEntryPrice × (1 − gridRate)</li>
 *   <li>多仓队列触发 → 额外开空:需满足 shortEntryPrice × (1 + gridRate) &lt; currentPrice &lt; longEntryPrice</li>
 * </ul>
 *
 * <h3>止盈条件单</h3>
 * 使用 Gate API 的 plan-close-long-position / plan-close-short-position(仓位计划止盈止损),
 * 支持指定张数部分平仓。每次网格触发开仓 quantity 张,只为该批张数创建独立条件单,互不覆盖。
 *
 * @author Administrator
 */
@Slf4j
public class GateGridTradeService {
 
    public enum StrategyState {
        WAITING_KLINE, OPENING, ACTIVE, STOPPED
    }
 
    /**
     * 止盈条件单 order_type:仓位计划止盈止损 — 平多仓(支持部分平仓,size&lt;0)。
     * 注意:不能用 close-long-position(仅支持全平且双仓需 auto_size),
     * 必须用 plan-close-long-position 以支持指定张数部分平仓。
     */
    private static final String ORDER_TYPE_CLOSE_LONG = "plan-close-long-position";
    /**
     * 止盈条件单 order_type:仓位计划止盈止损 — 平空仓(支持部分平仓,size&gt;0)。
     * 注意:不能用 close-short-position(仅支持全平且双仓需 auto_size),
     * 必须用 plan-close-short-position 以支持指定张数部分平仓。
     */
    private static final String ORDER_TYPE_CLOSE_SHORT = "plan-close-short-position";
 
    private final GateConfig config;
    private final GateTradeExecutor executor;
    private final FuturesApi futuresApi;
    private static final String SETTLE = "usdt";
 
    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> longTakeProfitQueue = Collections.synchronizedList(new ArrayList<>());
    /** 空仓止盈队列,降序排列(大→小),仓位推送时消费 */
    private final List<BigDecimal> shortTakeProfitQueue = Collections.synchronizedList(new ArrayList<>());
 
    /** 当前多仓限价单 ID,用于取消旧单 */
    private volatile String currentLongOrderId;
    /** 当前空仓限价单 ID,用于取消旧单 */
    private volatile String currentShortOrderId;
 
    /** 基底空头入场价 */
    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 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 Long userId;
    private volatile BigDecimal initialPrincipal = BigDecimal.ZERO;
 
    public GateGridTradeService(GateConfig config) {
        this.config = config;
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(config.getRestBasePath());
        apiClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
        this.futuresApi = new FuturesApi(apiClient);
        this.executor = new GateTradeExecutor(apiClient, config.getContract());
    }
 
    // ---- 初始化 ----
 
    /**
     * 初始化策略环境。
     *
     * <h3>执行顺序</h3>
     * <ol>
     *   <li>获取用户 ID(用于私有频道订阅 payload)</li>
     *   <li>获取账户信息 → 记录初始本金</li>
     *   <li>如需要,切换为双向持仓模式</li>
     *   <li>如需要,调整持仓模式(single/dual)</li>
     *   <li>清除旧的止盈止损条件单</li>
     *   <li>平掉所有已有仓位</li>
     *   <li>设置杠杆倍数</li>
     * </ol>
     */
    public void init() {
        try {
            ApiClient detailClient = new ApiClient();
            detailClient.setBasePath(config.getRestBasePath());
            detailClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
            AccountDetail detail = new AccountApi(detailClient).getAccountDetail();
            this.userId = detail.getUserId();
            log.info("[Gate] 用户ID: {}", userId);
 
            FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE);
            this.initialPrincipal = new BigDecimal(account.getTotal());
            log.info("[Gate] 初始本金: {} USDT", initialPrincipal);
 
            futuresApi.cancelPriceTriggeredOrderList(SETTLE, config.getContract());
            log.info("[Gate] 旧条件单已清除");
            closeExistingPositions();
 
            //设置持仓模式为双向持仓
            Boolean inDualMode = account.getInDualMode();
            if (!inDualMode) {
                try {
                    futuresApi.setDualModeCall(SETTLE,true,null).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
            try {
                futuresApi.updateDualModePositionLeverageCall(
                        SETTLE, config.getContract(), config.getLeverage(),
                        null, null).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
 
            if (!config.getMarginMode().equals(account.getMarginMode())) {
 
                UpdateDualCompPositionCrossModeRequest updateDualCompPositionCrossModeRequest = new UpdateDualCompPositionCrossModeRequest();
                updateDualCompPositionCrossModeRequest.setMode(config.getMarginMode());
                updateDualCompPositionCrossModeRequest.setContract(config.getContract());
                try {
                    futuresApi.updateDualCompPositionCrossModeCall(SETTLE, updateDualCompPositionCrossModeRequest, null).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            log.info("[Gate] 持仓模式: {} 余额: {}", config.getPositionMode(), account.getAvailable());
            log.info("[Gate] 杠杆: {}x {}", config.getLeverage(), config.getMarginMode());
        } catch (GateApiException e) {
            log.error("[Gate] 初始化失败, label:{}, msg:{}", e.getErrorLabel(), e.getMessage());
        } catch (ApiException e) {
            log.error("[Gate] 初始化失败, code:{}", e.getCode());
        }
    }
 
    /**
     * 平掉当前合约的所有已有仓位。
     *
     * <h3>平仓策略</h3>
     * <ul>
     *   <li>单向持仓:size=相反数,reduceOnly=true,市价 IOC 平仓</li>
     *   <li>双向持仓:size=0,close=false,autoSize=LONG/SHORT,reduceOnly=true,市价 IOC 全平</li>
     * </ul>
     *
     * <h3>注意事项</h3>
     * 双向持仓模式下必须使用 autoSize 参数,不能直接传负数 size,
     * 否则 Gate API 会拒绝(双向模式下空头 size 为负是正常的持仓方向)。
     */
    private void closeExistingPositions() {
        try {
            List<Position> positions = futuresApi.listPositions(SETTLE).execute();
            if (positions == null || positions.isEmpty()) { log.info("[Gate] 无已有仓位"); return; }
            for (Position pos : positions) {
                if (!config.getContract().equals(pos.getContract())) {
                    continue;
                }
                String sizeStr = pos.getSize();
                long size = Long.parseLong(sizeStr);
                if (size == 0) {
                    continue;
                }
                String closeSize = size > 0 ? String.valueOf(-size) : String.valueOf(Math.abs(size));
                Position.ModeEnum mode = pos.getMode();
                FuturesOrder closeOrder = new FuturesOrder();
                closeOrder.setContract(config.getContract());
                closeOrder.setPrice("0");
                closeOrder.setTif(FuturesOrder.TifEnum.IOC);
                closeOrder.setReduceOnly(true);
                if (mode != null && mode.getValue() != null && mode.getValue().contains("dual")) {
                    closeOrder.setSize("0");
                    closeOrder.setClose(false);
                    closeOrder.setAutoSize(size > 0 ? FuturesOrder.AutoSizeEnum.LONG : FuturesOrder.AutoSizeEnum.SHORT);
                } else {
                    closeOrder.setSize(closeSize);
                }
                closeOrder.setText("t-grid-init-close");
                futuresApi.createFuturesOrder(SETTLE, closeOrder, null);
                log.info("[Gate] 平已有仓位, 方向:{}, size:{}, mode:{}", size > 0 ? "多" : "空", sizeStr, mode);
            }
        } catch (GateApiException e) {
            log.warn("[Gate] 平仓位失败, label:{}, msg:{}", e.getErrorLabel(), e.getMessage());
        } catch (Exception e) {
            log.warn("[Gate] 平仓位异常", e);
        }
    }
 
    // ---- 启动/停止 ----
 
    /**
     * 启动网格策略。重置所有状态变量和队列,进入 WAITING_KLINE 等待首根 K 线。
     * 仅当当前状态为 WAITING_KLINE 或 STOPPED 时才允许启动。
     */
    public void startGrid() {
        if (state != StrategyState.WAITING_KLINE && state != StrategyState.STOPPED) {
            log.warn("[Gate] 策略已在运行中, 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;
        shortPriceQueue.clear();
        longPriceQueue.clear();
        longTakeProfitQueue.clear();
        shortTakeProfitQueue.clear();
        currentLongOrderId = null;
        currentShortOrderId = null;
        log.info("[Gate] 网格策略已启动");
    }
 
    /**
     * 停止网格策略。取消所有条件单 → 关闭交易线程池。
     * 状态设为 STOPPED,K 线回调将直接返回不再处理。
     */
    public void stopGrid() {
        state = StrategyState.STOPPED;
        executor.cancelAllPriceTriggeredOrders();
        executor.shutdown();
        log.info("[Gate] 策略已停止, 累计盈亏: {}", cumulativePnl);
    }
 
    // ---- K线回调 ----
 
    /**
     * K 线回调入口。由 {@link CandlestickChannelHandler} 在收到 WebSocket K 线推送时调用。
     *
     * <h3>处理流程</h3>
     * <ol>
     *   <li>更新 lastKlinePrice → 计算 unrealizedPnl(浮动盈亏)</li>
     *   <li>STOPPED → 直接返回(仅保留盈亏更新)</li>
     *   <li>WAITING_KLINE → 切换为 OPENING → 异步提交基底双开(开多+开空)</li>
     *   <li>OPENING → 等待仓位推送回调生成队列,此处返回</li>
     *   <li>ACTIVE → 执行 processShortGrid + processLongGrid</li>
     * </ol>
     *
     * <h3>注意</h3>
     * 基底双开下单提交到 GateTradeExecutor 的独立线程池中异步执行,
     * 成交状态由 onPositionUpdate 回调驱动,不阻塞 WS 回调线程。
     *
     * @param closePrice K 线收盘价(即当前最新成交价)
     */
    public void onKline(BigDecimal closePrice) {
        lastKlinePrice = closePrice;
        updateUnrealizedPnl();
        if (state == StrategyState.STOPPED) {
            return;
        }
 
        if (state == StrategyState.WAITING_KLINE) {
            state = StrategyState.OPENING;
            log.info("[Gate] 首根K线到达,开基底仓位...");
            executor.openLong(config.getQuantity(), () -> {
                log.info("[Gate] 基底多单已提交");
            }, null);
            executor.openShort(negate(config.getQuantity()), () -> {
                log.info("[Gate] 基底空单已提交");
            }, null);
            return;
        }
 
        if (state != StrategyState.ACTIVE) {
            return;
        }
        if (!longPriceQueue.isEmpty() && closePrice.compareTo(longPriceQueue.get(0)) > 0) {
            processLongGrid(closePrice);
        } else if (!shortPriceQueue.isEmpty() && closePrice.compareTo(shortPriceQueue.get(0)) < 0) {
            processShortGrid(closePrice);
        }
    }
 
    // ---- 仓位推送回调 ----
 
    /**
     * 仓位推送回调。由 {@link PositionsChannelHandler} 在收到 WebSocket 仓位更新时调用。
     *
     * <h3>处理逻辑</h3>
     * <ul>
     *   <li><b>有仓位 (size ≠ 0)</b>:
     *     <ul>
     *       <li>首次开仓(基底):标记 baseOpened=true,记录基底入场价,双基底都成交后生成网格队列</li>
     *       <li>仓位净增加(size > 之前记录值):说明网格触发了新开仓 → 取对应方向队列首元素为止盈价,设止盈条件单</li>
     *       <li>仓位减少或不变(止盈平仓后):仅更新 positionSize,不重复设止盈</li>
     *     </ul>
     *   </li>
     *   <li><b>无仓位 (size = 0)</b>:清空活跃标记和持仓量</li>
     * </ul>
     *
     * @param contract   合约名称
     * @param mode       持仓模式(DUAL_LONG / DUAL_SHORT)
     * @param size       持仓张数(多头为正、空头为负)
     * @param entryPrice 当前持仓加权均价(交易所计算)
     */
    public void onPositionUpdate(String contract, Position.ModeEnum mode, BigDecimal size,
                                  BigDecimal entryPrice) {
        if (state == StrategyState.STOPPED || state == StrategyState.WAITING_KLINE) {
            return;
        }
 
        boolean hasPosition = size.abs().compareTo(BigDecimal.ZERO) > 0;
 
        if (Position.ModeEnum.DUAL_LONG == mode) {
            if (hasPosition) {
                longActive = true;
                longEntryPrice = entryPrice;
                if (!baseLongOpened) {
                    longPositionSize = size;
                    longBaseEntryPrice = entryPrice;
                    baseLongOpened = true;
                    log.info("[Gate] 基底多成交价: {}", longBaseEntryPrice);
                    tryGenerateQueues();
                } else if (size.compareTo(longPositionSize) > 0) {
                    BigDecimal unitQty = new BigDecimal(config.getQuantity());
                    long prevUnits = longPositionSize.divide(unitQty, 0, RoundingMode.DOWN).longValue();
                    longPositionSize = size;
                    long nowUnits = size.divide(unitQty, 0, RoundingMode.DOWN).longValue();
                    long newUnits = nowUnits - prevUnits;
                    for (int i = 0; i < newUnits; i++) {
                        BigDecimal tpPrice;
                        if (!longTakeProfitQueue.isEmpty()) {
                            tpPrice = longTakeProfitQueue.remove(0);
                        } else {
                            tpPrice = longEntryPrice.add(config.getStep()).setScale(1, RoundingMode.HALF_UP);
                            log.warn("[Gate] 多止盈队列为空, 兜底止盈价:{}", tpPrice);
                        }
                        executor.placeTakeProfit(tpPrice,
                                FuturesPriceTrigger.RuleEnum.NUMBER_1, ORDER_TYPE_CLOSE_LONG, negate(config.getQuantity()));
                        log.info("[Gate] 多单止盈已设, tp:{}, size:{}", tpPrice, negate(config.getQuantity()));
                    }
                } else {
                    longPositionSize = size;
                }
            } else {
                longActive = false;
                longPositionSize = BigDecimal.ZERO;
            }
        } else if (Position.ModeEnum.DUAL_SHORT == mode) {
            if (hasPosition) {
                shortActive = true;
                shortEntryPrice = entryPrice;
                if (!baseShortOpened) {
                    shortPositionSize = size.abs();
                    shortBaseEntryPrice = entryPrice;
                    baseShortOpened = true;
                    log.info("[Gate] 基底空成交价: {}", shortBaseEntryPrice);
                    tryGenerateQueues();
                } else if (size.abs().compareTo(shortPositionSize) > 0) {
                    BigDecimal unitQty = new BigDecimal(config.getQuantity());
                    long prevUnits = shortPositionSize.divide(unitQty, 0, RoundingMode.DOWN).longValue();
                    BigDecimal nowAbsSize = size.abs();
                    shortPositionSize = nowAbsSize;
                    long nowUnits = nowAbsSize.divide(unitQty, 0, RoundingMode.DOWN).longValue();
                    long newUnits = nowUnits - prevUnits;
                    for (int i = 0; i < newUnits; i++) {
                        BigDecimal tpPrice;
                        if (!shortTakeProfitQueue.isEmpty()) {
                            tpPrice = shortTakeProfitQueue.remove(0);
                        } else {
                            tpPrice = shortEntryPrice.subtract(config.getStep()).setScale(1, RoundingMode.HALF_UP);
                            log.warn("[Gate] 空止盈队列为空, 兜底止盈价:{}", tpPrice);
                        }
                        executor.placeTakeProfit(tpPrice,
                                FuturesPriceTrigger.RuleEnum.NUMBER_2, ORDER_TYPE_CLOSE_SHORT, config.getQuantity());
                        log.info("[Gate] 空单止盈已设, tp:{}, size:{}", tpPrice, config.getQuantity());
                    }
                } else {
                    shortPositionSize = size.abs();
                }
            } else {
                shortActive = false;
                shortPositionSize = BigDecimal.ZERO;
            }
        }
    }
 
    // ---- 平仓推送回调 ----
 
    /**
     * 平仓推送回调。由 {@link PositionClosesChannelHandler} 在收到平仓推送时调用。
     *
     * <h3>累加规则</h3>
     * cumulativePnl += pnl。止盈平仓时 pnl > 0,止损平仓时 pnl < 0。
     * 累加后检查停止条件:≥ overallTp 或 ≤ -maxLoss。
     *
     * @param contract 合约名称
     * @param side     平仓方向("long" / "short")
     * @param pnl      本次平仓的盈亏金额
     */
    public void onPositionClose(String contract, String side, BigDecimal pnl) {
        if (state == StrategyState.STOPPED) {
            return;
        }
        cumulativePnl = cumulativePnl.add(pnl);
        log.info("[Gate] 盈亏累加:{}, 方向:{}, 累计:{}", pnl, side, cumulativePnl);
 
        if (cumulativePnl.compareTo(config.getOverallTp()) >= 0) {
            log.info("[Gate] 已达止盈目标 {}→已停止", cumulativePnl);
            state = StrategyState.STOPPED;
        } else if (cumulativePnl.compareTo(config.getMaxLoss().negate()) <= 0) {
            log.info("[Gate] 已达亏损上限 {}→已停止", cumulativePnl);
            state = StrategyState.STOPPED;
        }
    }
 
    // ---- 网格队列处理 ----
 
    /**
     * 尝试生成网格队列。双基底(多+空)都成交后才触发:
     * 生成空仓队列 + 多仓队列 → 状态切换为 ACTIVE。
     */
    private void tryGenerateQueues() {
        if (baseLongOpened && baseShortOpened) {
            generateShortQueue();
            generateLongQueue();
 
            BigDecimal step = config.getStep();
            BigDecimal longTp = longPriceQueue.get(0).add(step).setScale(1, RoundingMode.HALF_UP);
            BigDecimal shortTp = shortPriceQueue.get(0).subtract(step).setScale(1, RoundingMode.HALF_UP);
            longTakeProfitQueue.add(longTp);
            shortTakeProfitQueue.add(shortTp);
            log.info("[Gate] 多止盈队列:{}", longTakeProfitQueue);
            log.info("[Gate] 空止盈队列:{}", shortTakeProfitQueue);
 
            executor.placeConditionalEntryOrder(longPriceQueue.get(0),
                    FuturesPriceTrigger.RuleEnum.NUMBER_1, config.getQuantity(),
                    orderId -> { currentLongOrderId = orderId; log.info("[Gate] 初始条件多单已挂, id:{}, trigger:{}", orderId, longPriceQueue.get(0)); },
                    null);
            executor.placeConditionalEntryOrder(shortPriceQueue.get(0),
                    FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(config.getQuantity()),
                    orderId -> { currentShortOrderId = orderId; log.info("[Gate] 初始条件空单已挂, id:{}, trigger:{}", orderId, shortPriceQueue.get(0)); },
                    null);
 
            state = StrategyState.ACTIVE;
            log.info("[Gate] 网格队列已生成, 空队首:{} → 尾:{}, 多队首:{} → 尾:{}, step:{}, 已激活",
                    shortPriceQueue.get(0), shortPriceQueue.get(shortPriceQueue.size() - 1),
                    longPriceQueue.get(0), longPriceQueue.get(longPriceQueue.size() - 1),
                    step);
        }
    }
 
    /**
     * 生成空仓价格队列。
     * 以 shortBaseEntryPrice × gridRate 作为绝对步长 step,存到 config。
     * 第1个元素 = shortBaseEntryPrice − step,后续依次递减 step,共 gridQueueSize 个。
     * 队列降序排列(大→小),方便 processShortGrid 中从头遍历。
     */
    private void generateShortQueue() {
        shortPriceQueue.clear();
        BigDecimal step = shortBaseEntryPrice.multiply(config.getGridRate()).setScale(1, RoundingMode.HALF_UP);
        config.setStep(step);
        BigDecimal elem = shortBaseEntryPrice.subtract(step).setScale(1, RoundingMode.HALF_UP);
        for (int i = 0; i < config.getGridQueueSize(); i++) {
            shortPriceQueue.add(elem);
            elem = elem.subtract(step).setScale(1, RoundingMode.HALF_UP);
        }
        shortPriceQueue.sort((a, b) -> b.compareTo(a));
        log.info("[Gate] 空队列:{}", shortPriceQueue);
    }
 
    /**
     * 生成多仓价格队列。
     * 以 shortBaseEntryPrice + step 为首元素,后续依次递增 step,共 gridQueueSize 个。
     * 队列升序排列(小→大),方便 processLongGrid 中从头遍历。
     */
    private void generateLongQueue() {
        longPriceQueue.clear();
        BigDecimal step = config.getStep();
        BigDecimal elem = shortBaseEntryPrice.add(step).setScale(1, RoundingMode.HALF_UP);
        for (int i = 0; i < config.getGridQueueSize(); i++) {
            longPriceQueue.add(elem);
            elem = elem.add(step).setScale(1, RoundingMode.HALF_UP);
        }
        longPriceQueue.sort(BigDecimal::compareTo);
        log.info("[Gate] 多队列:{}", longPriceQueue);
    }
 
    /**
     * 空仓网格处理(价格跌破空仓队列中的高价)。
     *
     * <h3>匹配规则</h3>
     * 遍历空仓队列(降序),收集所有大于当前价的元素为 matched。
     * 队列为降序排列,一旦遇 price ≤ currentPrice 即停止遍历。
     *
     * <h3>执行流程</h3>
     * <ol>
     *   <li>匹配队列元素 → 为空则直接返回</li>
     *   <li>空仓队列:移除 matched 元素,尾部补充新元素(尾价 − step 循环递减)</li>
     *   <li>多仓队列:以多仓队列首元素(最小价)为种子,递减 step 生成 matched.size() 个元素加入</li>
     *   <li>保证金检查 → 安全则开空一次</li>
     *   <li>额外反向开多:若多仓均价 > 空仓均价 且 当前价夹在中间且远离多仓均价</li>
     * </ol>
     *
     * <h3>多仓队列转移过滤</h3>
     * 新增元素若与多仓持仓均价差距小于 gridRate,则跳过该元素(避免在持仓成本附近生成无效网格线)。
     */
    private void processShortGrid(BigDecimal currentPrice) {
        List<BigDecimal> matched = new ArrayList<>();
        synchronized (shortPriceQueue) {
            for (BigDecimal p : shortPriceQueue) {
                if (p.compareTo(currentPrice) > 0) {
                    matched.add(p);
                } else {
                    break;
                }
            }
        }
        log.info("[Gate] 原空队列:{}", shortPriceQueue);
        if (matched.isEmpty()) {
            log.info("[Gate] 空仓队列未触发, 当前价:{}", currentPrice);
            return;
        }
        log.info("[Gate] 空仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice);
 
        synchronized (shortPriceQueue) {
            shortPriceQueue.removeAll(matched);
            BigDecimal min = shortPriceQueue.isEmpty() ? matched.get(matched.size() - 1) : shortPriceQueue.get(shortPriceQueue.size() - 1);
            BigDecimal gridStep = config.getStep();
            for (int i = 0; i < matched.size(); i++) {
                min = min.subtract(gridStep).setScale(1, RoundingMode.HALF_UP);
                shortPriceQueue.add(min);
                log.info("[Gate] 空队列增加:{}", min);
            }
            shortPriceQueue.sort((a, b) -> b.compareTo(a));
            log.info("[Gate] 现空队列:{}", shortPriceQueue);
        }
 
        synchronized (longPriceQueue) {
            BigDecimal first = longPriceQueue.isEmpty() ? matched.get(matched.size() - 1) : longPriceQueue.get(0);
            BigDecimal gridStep = config.getStep();
            for (int i = 1; i <= matched.size(); i++) {
                BigDecimal elem = first.subtract(gridStep.multiply(BigDecimal.valueOf(i))).setScale(1, RoundingMode.HALF_UP);
                longPriceQueue.add(elem);
                log.info("[Gate] 多队列增加:{}", elem);
            }
            longPriceQueue.sort(BigDecimal::compareTo);
            while (longPriceQueue.size() > config.getGridQueueSize()) {
                longPriceQueue.remove(longPriceQueue.size() - 1);
            }
            log.info("[Gate] 现多队列:{}", longPriceQueue);
        }
 
        BigDecimal newShortFirst = shortPriceQueue.get(0);
        BigDecimal newLongFirst = longPriceQueue.get(0);
        BigDecimal step = config.getStep();
        BigDecimal stpElem = newShortFirst.subtract(step).setScale(1, RoundingMode.HALF_UP);
        shortTakeProfitQueue.add(stpElem);
        shortTakeProfitQueue.sort((a, b) -> b.compareTo(a));
        log.info("[Gate] 空止盈队列增加:{}, 现止盈队列:{}", stpElem, shortTakeProfitQueue);
 
        if (!isMarginSafe()) {
            log.warn("[Gate] 保证金超限,跳过挂条件单");
        } else {
            String oldLongId = currentLongOrderId;
            executor.cancelConditionalOrder(oldLongId);
            executor.placeConditionalEntryOrder(newShortFirst,
                    FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(config.getQuantity()),
                    orderId -> { currentShortOrderId = orderId; log.info("[Gate] 新条件空单, id:{}, trigger:{}", orderId, newShortFirst); },
                    null);
            executor.placeConditionalEntryOrder(newLongFirst,
                    FuturesPriceTrigger.RuleEnum.NUMBER_1, config.getQuantity(),
                    orderId -> { currentLongOrderId = orderId; log.info("[Gate] 新条件多单, id:{}, trigger:{}", orderId, newLongFirst); },
                    null);
        }
 
        if (isMarginSafe()
                && shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
                && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
                && longEntryPrice.compareTo(shortEntryPrice) > 0
                && currentPrice.compareTo(shortEntryPrice) > 0
                && currentPrice.compareTo(longEntryPrice) < 0) {
            executor.openLong(config.getQuantity(), null, null);
            log.info("[Gate] 额外反向开多, 当前价:{} 在[{},{}]之间", currentPrice, shortEntryPrice, longEntryPrice);
        }
    }
 
    /**
     * 多仓网格处理(价格涨破多仓队列中的低价)。
     *
     * <h3>匹配规则</h3>
     * 遍历多仓队列(升序),收集所有小于当前价的元素为 matched。
     * 队列为升序排列,一旦遇 price ≥ currentPrice 即停止遍历。
     *
     * <h3>执行流程</h3>
     * <ol>
     *   <li>匹配队列元素 → 为空则直接返回</li>
     *   <li>多仓队列:移除 matched 元素,尾部补充新元素(尾价 + step 循环递增)</li>
     *   <li>空仓队列:以空仓队列首元素(最高价)为种子,递增 step 生成 matched.size() 个元素加入</li>
     *   <li>保证金检查 → 安全则开多一次</li>
     *   <li>额外反向开空:若多仓均价 > 空仓均价 且 当前价夹在中间且远离空仓均价</li>
     * </ol>
     *
     * <h3>空仓队列转移过滤</h3>
     * 新增元素若与空仓持仓均价差距小于 gridRate,则跳过该元素(避免在持仓成本附近生成无效网格线)。
     */
    private void processLongGrid(BigDecimal currentPrice) {
        List<BigDecimal> matched = new ArrayList<>();
        synchronized (longPriceQueue) {
            for (BigDecimal p : longPriceQueue) {
                if (p.compareTo(currentPrice) < 0) {
                    matched.add(p);
                } else {
                    break;
                }
            }
        }
        log.info("[Gate] 原多队列:{}", longPriceQueue);
        if (matched.isEmpty()) {
            log.info("[Gate] 多仓队列未触发, 当前价:{}", currentPrice);
            return;
        }
 
        log.info("[Gate] 多仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice);
 
        synchronized (longPriceQueue) {
            longPriceQueue.removeAll(matched);
            BigDecimal max = longPriceQueue.isEmpty() ? matched.get(matched.size() - 1) : longPriceQueue.get(longPriceQueue.size() - 1);
            BigDecimal gridStep = config.getStep();
            for (int i = 0; i < matched.size(); i++) {
                max = max.add(gridStep).setScale(1, RoundingMode.HALF_UP);
                longPriceQueue.add(max);
                log.info("[Gate] 多队列增加:{}", max);
            }
            longPriceQueue.sort(BigDecimal::compareTo);
            log.info("[Gate] 现多队列:{}", longPriceQueue);
        }
 
        synchronized (shortPriceQueue) {
            BigDecimal first = shortPriceQueue.isEmpty() ? matched.get(0) : shortPriceQueue.get(0);
            BigDecimal gridStep = config.getStep();
            for (int i = 1; i <= matched.size(); i++) {
                BigDecimal elem = first.add(gridStep.multiply(BigDecimal.valueOf(i))).setScale(1, RoundingMode.HALF_UP);
                shortPriceQueue.add(elem);
                log.info("[Gate] 空队列增加:{}", elem);
            }
            shortPriceQueue.sort((a, b) -> b.compareTo(a));
            while (shortPriceQueue.size() > config.getGridQueueSize()) {
                shortPriceQueue.remove(shortPriceQueue.size() - 1);
            }
            log.info("[Gate] 现空队列:{}", shortPriceQueue);
        }
 
        BigDecimal newLongFirst = longPriceQueue.get(0);
        BigDecimal newShortFirst = shortPriceQueue.get(0);
        BigDecimal step = config.getStep();
        BigDecimal ltpElem = newLongFirst.add(step).setScale(1, RoundingMode.HALF_UP);
        longTakeProfitQueue.add(ltpElem);
        longTakeProfitQueue.sort(BigDecimal::compareTo);
        log.info("[Gate] 多止盈队列增加:{}, 现止盈队列:{}", ltpElem, longTakeProfitQueue);
 
        if (!isMarginSafe()) {
            log.warn("[Gate] 保证金超限,跳过挂条件单");
        } else {
            String oldShortId = currentShortOrderId;
            executor.cancelConditionalOrder(oldShortId);
            executor.placeConditionalEntryOrder(newLongFirst,
                    FuturesPriceTrigger.RuleEnum.NUMBER_1, config.getQuantity(),
                    orderId -> { currentLongOrderId = orderId; log.info("[Gate] 新条件多单, id:{}, trigger:{}", orderId, newLongFirst); },
                    null);
            executor.placeConditionalEntryOrder(newShortFirst,
                    FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(config.getQuantity()),
                    orderId -> { currentShortOrderId = orderId; log.info("[Gate] 新条件空单, id:{}, trigger:{}", orderId, newShortFirst); },
                    null);
        }
 
        if (isMarginSafe()
                && shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
                && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
                && longEntryPrice.compareTo(shortEntryPrice) > 0
                && currentPrice.compareTo(shortEntryPrice) > 0
                && currentPrice.compareTo(longEntryPrice) < 0) {
            executor.openShort(negate(config.getQuantity()), null, null);
            log.info("[Gate] 额外反向开空, 当前价:{} 在[{},{}]之间", currentPrice, shortEntryPrice, longEntryPrice);
        }
    }
 
    // ---- 保证金安全阀 ----
 
    /**
     * 保证金安全阀检查。
     *
     * <p>实时查询当前保证金占用额(positionInitialMargin),计算其占初始本金的比例。
     * 比例 ≥ marginRatioLimit(默认 20%)时拒绝开仓,但仍照常更新队列。
     *
     * <p>查询失败时默认放行(返回 true),避免因 REST API 异常导致策略完全停滞。
     *
     * @return true=安全可开仓 / false=保证金超限跳过开仓
     */
    private boolean isMarginSafe() {
        try {
            FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE);
            BigDecimal margin = new BigDecimal(account.getPositionInitialMargin());
            BigDecimal ratio = margin.divide(initialPrincipal, 4, RoundingMode.HALF_UP);
            log.debug("[Gate] 保证金比例: {}/{}={}", margin, initialPrincipal, ratio);
            return ratio.compareTo(config.getMarginRatioLimit()) < 0;
        } catch (Exception e) {
            log.warn("[Gate] 查保证金失败,默认放行", e);
            return true;
        }
    }
 
    // ---- 工具 ----
 
    /**
     * 取反字符串数字。如 "1" → "-1","-2" → "2"。
     * 用于开空单时将正数张数转为负数。
     */
    private String negate(String qty) {
        return qty.startsWith("-") ? qty.substring(1) : "-" + qty;
    }
 
    /**
     * 根据持仓和当前价格计算未实现盈亏。
     *
     * <h3>正向合约公式</h3>
     * <pre>
     *   多仓: 持仓量 × 合约乘数 × (计价价格 − 开仓均价)
     *   空仓: 持仓量 × 合约乘数 × (开仓均价 − 计价价格)
     * </pre>
     * 计价价格由 {@link GateConfig.PnLPriceMode} 决定:LAST_PRICE 用最新成交价,MARK_PRICE 用标记价格。
     */
    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("[Gate] 未实现盈亏: {}", unrealizedPnl);
    }
 
    /**
     * 根据配置的 PnLPriceMode 返回计价价格。
     * MARK_PRICE 模式优先使用标记价格(外部注入),未注入时回退到最新成交价。
     *
     * @return 计价价格,可能为 null
     */
    private BigDecimal resolvePnlPrice() {
        if (config.getUnrealizedPnlPriceMode() == GateConfig.PnLPriceMode.MARK_PRICE
                && markPrice.compareTo(BigDecimal.ZERO) > 0) {
            return markPrice;
        }
        return lastKlinePrice;
    }
 
    /** @return 最新 K 线价格(每次 onKline 更新) */
    public BigDecimal getLastKlinePrice() { return lastKlinePrice; }
    /** 设置标记价格(外部注入,MARK_PRICE 模式时用于盈亏计算) */
    public void setMarkPrice(BigDecimal markPrice) { this.markPrice = markPrice; }
    /** @return 策略是否处于活跃状态(非 STOPPED 且非 WAITING_KLINE) */
    public boolean isStrategyActive() { return state != StrategyState.STOPPED && state != StrategyState.WAITING_KLINE; }
    /** @return 累计已实现盈亏(平仓推送驱动累加) */
    public BigDecimal getCumulativePnl() { return cumulativePnl; }
    /** @return 当前未实现盈亏(每根 K 线实时计算) */
    public BigDecimal getUnrealizedPnl() { return unrealizedPnl; }
    /** @return Gate 用户 ID(用于私有频道订阅 payload) */
    public Long getUserId() { return userId; }
    /** @return 当前策略状态 */
    public StrategyState getState() { return state; }
}