Administrator
2025-12-17 2e3a140443cd65de5f8c17f50338a87d877d9035
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
package com.xcong.excoin.modules.okxNewPrice.okxpi.query.impl;
 
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.xcong.excoin.modules.okxNewPrice.utils.FebsException;
import com.xcong.excoin.modules.okxNewPrice.utils.FebsResponse;
import com.xcong.excoin.modules.okxNewPrice.okxpi.config.Dto.QuantApiMessage;
import com.xcong.excoin.modules.okxNewPrice.okxpi.config.OKXAccount;
import com.xcong.excoin.modules.okxNewPrice.okxpi.config.enums.HttpMethod;
import com.xcong.excoin.modules.okxNewPrice.okxpi.config.utils.OKXContants;
import com.xcong.excoin.modules.okxNewPrice.okxpi.config.vo.BalanceVo;
import com.xcong.excoin.modules.okxNewPrice.okxpi.query.IQueryOrderService;
import com.xcong.excoin.modules.okxNewPrice.okxpi.query.dto.QuantOperateRecode;
import com.xcong.excoin.modules.okxNewPrice.okxpi.query.vo.QuantCheckOrderVo;
import com.xcong.excoin.modules.okxNewPrice.okxpi.query.vo.QuantOperateRecodeVo;
import com.xcong.excoin.modules.okxNewPrice.okxpi.verify.VerifyAccountFactory;
import com.xcong.excoin.modules.okxNewPrice.zhanghu.IApiMessageService;
import com.xcong.excoin.modules.okxNewPrice.zhanghu.ZhangHuEnum;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
 
@Service("oKXQueryOrderServiceImpl")
@RequiredArgsConstructor
@Slf4j
public class OKXQueryOrderServiceImpl implements IQueryOrderService {
    @Value("spring.OKEX.baseurl")
    private String baseurl;
 
    private final IApiMessageService apiMessageService;
 
    private final VerifyAccountFactory verifyAccountFactory;
 
    private static String hmacSha256(String data, String key) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        mac.init(secretKeySpec);
        return Base64.getEncoder().encodeToString(mac.doFinal(data.getBytes()));
    }
 
    @SneakyThrows
    @Override
    public FebsResponse QueryOrder(QuantApiMessage quantApiMessage, String instId, String clOrdId) {
        String url = baseurl + "/api/v5/trade/order?instId=" + instId + "&clOrdId=" + clOrdId; // 构建请求URL
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("OK-ACCESS-KEY", quantApiMessage.getASecretkey());
            connection.setRequestProperty("OK-ACCESS-SIGN", hmacSha256(quantApiMessage.getBSecretkey(), clOrdId)); // 根据需要生成签名
            connection.setRequestProperty("OK-ACCESS-TIMESTAMP", String.valueOf(System.currentTimeMillis() / 1000));
            connection.setRequestProperty("OK-ACCESS-PASSPHRASE", "your_passphrase"); // 替换为您的Passphrase
 
            int responseCode = connection.getResponseCode();
 
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
 
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
 
                JSONObject jsonResponse = new JSONObject(response.toString());
                QuantCheckOrderVo quantCheckOrderVo = new QuantCheckOrderVo();
                if (jsonResponse.has("clOrdId") && StringUtils.isNotBlank(jsonResponse.getString("clOrdId"))) {
                    quantCheckOrderVo.setTradeNumber(jsonResponse.getString("clOrdId"));
                }
                if (jsonResponse.has("ordId") && StringUtils.isNotBlank(jsonResponse.getString("ordId"))) {
                    quantCheckOrderVo.setOrdId(jsonResponse.getString("ordId"));
                }
                if (jsonResponse.has("pnl") && StringUtils.isNotBlank(jsonResponse.getString("pnl"))) {
                    quantCheckOrderVo.setProfit(new BigDecimal(jsonResponse.getString("pnl")));
                }
                if (jsonResponse.has("sz") && StringUtils.isNotBlank(jsonResponse.getString("sz"))) {
                    quantCheckOrderVo.setPageNum(new Integer(jsonResponse.getString("sz")));
                }
                if (jsonResponse.has("fillPx") && StringUtils.isNotBlank(jsonResponse.getString("fillPx"))) {
                    quantCheckOrderVo.setPrice(new BigDecimal(jsonResponse.getString("fillPx")));
                    BigDecimal total = new BigDecimal(new Integer(jsonResponse.getString("sz"))).multiply(new BigDecimal(jsonResponse.getString("fillPx")));
                    quantCheckOrderVo.setAmount(total);
                }
                return new FebsResponse().success().data(quantCheckOrderVo);
            } else {
                return new FebsResponse().fail().message("交易所订单查询异常");
            }
        } catch (Exception e) {
            return new FebsResponse().fail().message("订单查询异常");
        }
    }
 
    @Override
    public FebsResponse checkOrder(QuantOperateRecode operateRecode) {
        log.info("查询OKX订单信息:{}",operateRecode);
 
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(ZhangHuEnum.JIAOYISUO.getValue());
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("参数错误");
        }
 
        OKXAccount okxAccount = (OKXAccount) verifyAccountFactory.getAccountMap().get(quantApiMessage.getExchange())
                .initAccount(quantApiMessage);
        ArrayList<BalanceVo> balanceVos = new ArrayList<>();
 
        LinkedHashMap<String, Object> orderParameters = new LinkedHashMap<>();
        orderParameters.put("clOrdId", operateRecode.getTradeNumber());
        //将字符串BTC-USDTU-空 截取为 BTC-USDT
        String coinPair = operateRecode.getCoinPair().substring(0, operateRecode.getCoinPair().indexOf("-USDT")+5);
        orderParameters.put("instId", coinPair+"-SWAP");
        String orderStr = okxAccount.requestHandler.sendSignedRequest(okxAccount.baseUrl, OKXContants.ORDER, orderParameters, HttpMethod.GET, okxAccount.isSimluate());
        log.info("查询OKX订单返回信息:{}",orderStr);
        QuantOperateRecodeVo quantOperateRecodeVo = new QuantOperateRecodeVo();
        com.alibaba.fastjson.JSONObject orderStrJson = JSON.parseObject(orderStr);
        String code = orderStrJson.getString("code");
        if("0".equals(code)){
            com.alibaba.fastjson.JSONObject data = orderStrJson.getJSONArray("data").getJSONObject(0);
            quantOperateRecodeVo.setQuantity(ObjectUtil.isEmpty(data.getString("accFillSz"))?new BigDecimal("0"): new BigDecimal(data.getString("accFillSz")));
            quantOperateRecodeVo.setPrice(ObjectUtil.isEmpty(data.getString("avgPx"))?new BigDecimal("0"): new BigDecimal(data.getString("avgPx")));
            quantOperateRecodeVo.setProfit(ObjectUtil.isEmpty(data.getString("pnl"))?new BigDecimal("0"): new BigDecimal(data.getString("pnl")));
            quantOperateRecodeVo.setFee(ObjectUtil.isEmpty(data.getString("fee"))?new BigDecimal("0"): new BigDecimal(data.getString("fee")));
            quantOperateRecodeVo.setExchangeNumber(data.getString("ordId"));
            quantOperateRecodeVo.setCoinLevel(ObjectUtil.isEmpty(data.getString("lever"))?new BigDecimal("0"): new BigDecimal(data.getString("lever")));
            quantOperateRecodeVo.setOrdType(data.getString("ordType"));
            quantOperateRecodeVo.setExChangeState(data.getString("state"));
        } else if("51603".equals(code)){
                quantOperateRecodeVo.setQuantity(new BigDecimal("0"));
                quantOperateRecodeVo.setPrice(new BigDecimal("0"));
                quantOperateRecodeVo.setProfit(new BigDecimal("0"));
                quantOperateRecodeVo.setCoinLevel(new BigDecimal("0"));
                quantOperateRecodeVo.setExchangeNumber("");
                quantOperateRecodeVo.setOrdType("");
                quantOperateRecodeVo.setExChangeState("canceled");
        } else {
            return null;
        }
 
        return new FebsResponse().success().data(quantOperateRecodeVo);
    }
}