Administrator
2025-12-29 c9e423b3d739ccf49508f724bc11ce2f28807cc0
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
package com.xcong.excoin.modules.okxNewPrice.okxpi.order.impl;
 
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.Dto.TradeOrderDto;
import com.xcong.excoin.modules.okxNewPrice.okxpi.order.ITradeOrderService;
import com.xcong.excoin.modules.okxNewPrice.okxpi.order.vo.QuantExchangeReturnVo;
import com.xcong.excoin.modules.okxNewPrice.okxpi.trade.TradeRequestBuy;
import com.xcong.excoin.modules.okxNewPrice.okxpi.trade.TradeRequestSell;
import com.xcong.excoin.modules.okxNewPrice.jiaoyi.IMQService;
import lombok.SneakyThrows;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
 
@Service("oKXTradeOrderServiceImpl")
public class OKXTradeOrderServiceImpl implements ITradeOrderService {
    @Value("${spring.OKEX.baseurl}")
    private String baseurl;
 
    @Resource
    private IMQService imqService;
 
    @SneakyThrows
    @Override
    public FebsResponse QuantExchangeReturnVo(TradeOrderDto tradeOrderDto, QuantApiMessage quantApiMessage) {
        try {
            // 构建订单的JSON对象
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("instId", "BTC-USDT");
            jsonBody.put("tdMode", "cash");
            jsonBody.put("side", "buy");
            jsonBody.put("ordType", "limit");
            jsonBody.put("sz", "0.01");
            jsonBody.put("px", "30000");
 
            // 发起下单请求
            String result = postRequest("/api/v5/trade/order", jsonBody.toString(),quantApiMessage);
            System.out.println("Result: " + result);
 
            //解析返回数据
            JSONObject jsonResponse = new JSONObject(result);
            if (jsonResponse.has("code") && "0".equals(jsonResponse.getString("code"))) {
                // 订单提交成功
                JSONObject jSONObject = jsonResponse.getJSONObject("data");
                String clOrdId = jSONObject.getString("clOrdId");
                String ordId = jSONObject.getString("ordId");
                QuantExchangeReturnVo quantExchangeReturnVo = new QuantExchangeReturnVo();
                quantExchangeReturnVo.setCode("0");
                quantExchangeReturnVo.setOrdId(ordId);
                quantExchangeReturnVo.setClOrdId(clOrdId);
                return new FebsResponse().success().data(quantExchangeReturnVo);
            } else {
                String code =  jsonResponse.getString("code");
                String msg =  jsonResponse.getString("msg");
                QuantExchangeReturnVo quantExchangeReturnVo = new QuantExchangeReturnVo();
                quantExchangeReturnVo.setCode(code);
                quantExchangeReturnVo.setMessage(msg);
                return new FebsResponse().fail().data(quantExchangeReturnVo);
            }
 
        } catch (Exception e) {
            return new FebsResponse().fail().message("下单失败");
        }
    }
 
    @Override
    public void operationBuyMsg(TradeRequestBuy returnVo) {
 
        imqService.operationBuyMsg(returnVo);
    }
 
    @Override
    public void operationSellMsg(TradeRequestSell returnVo) {
 
        imqService.operationSellMsg(returnVo);
    }
 
    private String postRequest(String endpoint, String body, QuantApiMessage quantApiMessage) throws Exception {
        URL url = new URL(baseurl + endpoint);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("OK-ACCESS-KEY", quantApiMessage.getASecretkey());
        connection.setRequestProperty("OK-ACCESS-SIGN", generateSignature(body,quantApiMessage));
        connection.setRequestProperty("OK-ACCESS-TIMESTAMP", getTimestamp());
        connection.setRequestProperty("OK-ACCESS-PASSPHRASE", quantApiMessage.getPassPhrass());
 
        try (OutputStream os = connection.getOutputStream()) {
            os.write(body.getBytes());
            os.flush();
        }
 
        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP Error code : " + connection.getResponseCode());
        }
 
        BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
        StringBuilder output = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            output.append(line);
        }
        connection.disconnect();
        return output.toString();
    }
 
    private static String generateSignature(String body, QuantApiMessage quantApiMessage) throws Exception {
        String preHash = getTimestamp() + "POST" + "/api/v5/order" + body;
        SecretKeySpec secretKey = new SecretKeySpec(quantApiMessage.getBSecretkey().getBytes(), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKey);
        return Base64.getEncoder().encodeToString(mac.doFinal(preHash.getBytes()));
    }
 
    private static String getTimestamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }
}