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 io.gate.gateapi.models.Position;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;
/**
* 仓位频道处理器。
*
*
数据用途
* 监控仓位数量(size)。当 size 从有变为 0 时,表示该方向被止盈条件单平仓,
* 触发补仓(reopenLongPosition / reopenShortPosition)。
*
* 推送字段
* contract, mode(dual_long / dual_short), size(正=持有,0=无仓位), entry_price
*
* 注意
* 双向持仓模式下空头 size 为负数,使用 {@code size.abs()} 判断是否有仓位。
* 累计盈亏不由本频道计算,而是由 {@link PositionClosesChannelHandler} 独立处理。
*
* @author Administrator
*/
@Slf4j
public class PositionsChannelHandler extends AbstractPrivateChannelHandler {
private static final String CHANNEL_NAME = "futures.positions";
public PositionsChannelHandler(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 pos = resultArray.getJSONObject(i);
if (!getContract().equals(pos.getString("contract"))) {
continue;
}
String modeStr = pos.getString("mode");
Position.ModeEnum mode = Position.ModeEnum.fromValue(modeStr);
BigDecimal size = new BigDecimal(pos.getString("size"));
BigDecimal entryPrice = new BigDecimal(pos.getString("entry_price"));
log.info("[{}] 持仓更新, 模式:{}, 数量:{}, 入场价:{}", CHANNEL_NAME, modeStr, size, entryPrice);
if (getGridTradeService() != null) {
getGridTradeService().onPositionUpdate(getContract(), mode, size, entryPrice);
}
}
} catch (Exception e) { log.error("[{}] 处理数据失败", CHANNEL_NAME, e); }
return true;
}
}