Administrator
4 days ago e998a5d44dd7fede8691b752219217d9da1973bb
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
package com.xcong.excoin.modules.gateApi.wsHandler.handler;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcong.excoin.modules.gateApi.GateGridTradeService;
import com.xcong.excoin.modules.gateApi.wsHandler.AbstractPrivateChannelHandler;
import lombok.extern.slf4j.Slf4j;
 
import java.math.BigDecimal;
 
/**
 * 平仓频道处理器。
 *
 * <h3>数据用途</h3>
 * 每笔平仓发生时推送 pnl(盈亏金额),累加到 {@code cumulativePnl} 用于判断策略停止条件:
 * cumulativePnl ≥ overallTp(达到止盈目标)或 ≤ -maxLoss(超过亏损上限)。
 * 止盈由 Gate 服务端条件单自动触发,平仓后仓位变为 0,盈亏通过本频道推送。
 *
 * <h3>推送字段</h3>
 * contract, side(long / short), pnl(该次平仓的盈亏,如 "+0.2" 或 "-0.1")
 *
 * <h3>注意</h3>
 * 平仓盈亏来自服务器端,不受本地计算误差影响。这是策略停止的唯一盈亏判断来源。
 *
 * @author Administrator
 */
@Slf4j
public class PositionClosesChannelHandler extends AbstractPrivateChannelHandler {
 
    private static final String CHANNEL_NAME = "futures.position_closes";
 
    public PositionClosesChannelHandler(String apiKey, String apiSecret,
                                         String contract,
                                         GateGridTradeService gridTradeService) {
        super(CHANNEL_NAME, apiKey, apiSecret, contract, gridTradeService);
    }
 
    @Override
    public boolean handleMessage(JSONObject response) {
        if (!CHANNEL_NAME.equals(response.getString("channel"))) {
            return false;
        }
        try {
            JSONArray resultArray = response.getJSONArray("result");
            if (resultArray == null || resultArray.isEmpty()) {
                return true;
            }
            for (int i = 0; i < resultArray.size(); i++) {
                JSONObject item = resultArray.getJSONObject(i);
                if (!getContract().equals(item.getString("contract"))) {
                    continue;
                }
                BigDecimal pnl = new BigDecimal(item.getString("pnl"));
                String side = item.getString("side");
                log.info("[{}] 平仓更新, 方向:{}, 盈亏:{}", CHANNEL_NAME, side, pnl);
                if (getGridTradeService() != null) {
                    getGridTradeService().onPositionClose(getContract(), side, pnl);
                }
            }
        } catch (Exception e) { log.error("[{}] 处理数据失败", CHANNEL_NAME, e); }
        return true;
    }
}