Administrator
2025-12-09 249ddecd3afeb12537edfef4d7a127ffe32f7b9f
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
package com.xcong.excoin.modules.okxNewPrice.okxpi.verify.impl;
 
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcong.excoin.modules.okxNewPrice.utils.FebsException;
import com.xcong.excoin.modules.okxNewPrice.utils.FebsResponse;
import com.xcong.excoin.modules.okxNewPrice.okxpi.DataUtil;
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.DefaultUrls;
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.verify.IVerifyAccountService;
import com.xcong.excoin.modules.okxNewPrice.okxpi.verify.dto.*;
import com.xcong.excoin.modules.okxNewPrice.okxpi.verify.enums.PublicStatusEnum;
import com.xcong.excoin.modules.okxNewPrice.okxpi.verify.vo.ApiAccountHoldVo;
import com.xcong.excoin.modules.okxNewPrice.okxpi.verify.vo.ApiPositionsInfoVo;
import com.xcong.excoin.modules.okxNewPrice.okxpi.verify.vo.ProductMessVo;
import com.xcong.excoin.modules.okxNewPrice.okxpi.verify.vo.SinglemarketVo;
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.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
 
@Slf4j
@Service("oKXVerifyAccount")
@RequiredArgsConstructor
public class OKXVerifyAccountServiceImpl implements IVerifyAccountService {
 
    private final IApiMessageService apiMessageService;
    @Value("${spring.OKEX.baseurl}")
    private String baseurl;
 
    @Override
    public OKXAccount initAccount(QuantApiMessage quantApiMessage) {
        return new OKXAccount(
                quantApiMessage.getAccountType().equalsIgnoreCase("true") ? DefaultUrls.USDM_PROD_URL : DefaultUrls.USDM_UAT_URL,
                quantApiMessage.getASecretkey(),
                quantApiMessage.getBSecretkey(),
                quantApiMessage.getPassPhrass(),
                !quantApiMessage.getAccountType().equalsIgnoreCase("true"));
 
    }
 
    @Override
    public OKXAccount initAccountV2(String apiKey, String secretKey, String passPhrass, boolean accountType) {
        return new OKXAccount(
                accountType ? DefaultUrls.USDM_PROD_URL : DefaultUrls.USDM_UAT_URL,
                apiKey,
                secretKey,
                passPhrass,
                !accountType);
    }
 
    @SneakyThrows
    @Override
    public FebsResponse verifyAccount(ApiMessageDto apiMessageDto) {
        if(validateAccount(apiMessageDto)){
            return new FebsResponse().success();
        }
        return new FebsResponse().fail();
    }
 
    @Override
    public FebsResponse getProductMess(ApiValidApiMessageDto apiValidApiMessageDto) {
        Long id = apiValidApiMessageDto.getId();
 
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(ZhangHuEnum.JIAOYISUO.getValue());
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("参数错误");
        }
 
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
        LinkedHashMap<String, Object> balanceParameters = new LinkedHashMap<>();
        balanceParameters.put("instType", "SWAP");
        if(StringUtils.isNotBlank(apiValidApiMessageDto.getCoinName())){
            balanceParameters.put("instId", apiValidApiMessageDto.getCoinName()+"-USD-SWAP");
            balanceParameters.put("instFamily", apiValidApiMessageDto.getCoinName()+"-USD");
        }
 
        String productStr = okxAccount.requestHandler.sendSignedRequest(okxAccount.baseUrl, OKXContants.INSTRUMENTS, balanceParameters, HttpMethod.GET, okxAccount.isSimluate());
        log.info("productStr:{}", productStr);
        JSONObject balanceJson = JSON.parseObject(productStr);
        JSONObject data = balanceJson.getJSONArray("data").getJSONObject(0);
 
        ProductMessVo productMessVo = new ProductMessVo();
        productMessVo.setLotSz(data.getString("lotSz"));
        productMessVo.setMinSz(data.getString("minSz"));
        productMessVo.setTickSz(data.getString("tickSz"));
        productMessVo.setCtVal(data.getString("ctVal"));
 
        return new FebsResponse().success().data(productMessVo);
    }
 
    @Override
    public FebsResponse getCurrenPrice(OperateCurrencyDto operateCurrencyDto) {
 
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(ZhangHuEnum.JIAOYISUO.getValue());
        if(null == quantApiMessage){
            return new FebsResponse().fail().message("请先配置交易所");
        }
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
 
        LinkedHashMap<String, Object> balanceParameters = new LinkedHashMap<>();
        if(StringUtils.isNotBlank(operateCurrencyDto.getCoinSymbol())){
            balanceParameters.put("instId", operateCurrencyDto.getCoinSymbol()+"-SWAP");
        }
        String ticker = okxAccount.requestHandler.sendSignedRequest(okxAccount.baseUrl, OKXContants.TICKER, balanceParameters, HttpMethod.GET, okxAccount.isSimluate());
 
        log.info("ticker================:{}", ticker);
 
        JSONObject jsonObject = JSON.parseObject(ticker);
        JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0);
 
        SinglemarketVo singlemarketVo = new SinglemarketVo();
        singlemarketVo.setInstId(data.getString("instId"));
        singlemarketVo.setLast(data.getString("last"));
        singlemarketVo.setInstType(data.getString("instType"));
 
        return new FebsResponse().success().data(singlemarketVo);
    }
 
    @Override
    public FebsResponse getlever(OperateCurrencyLeverDto operateCurrencyLeverDto) {
 
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(ZhangHuEnum.JIAOYISUO.getValue());
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("参数错误");
        }
 
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
        LinkedHashMap<String, Object> balanceParameters = new LinkedHashMap<>();
        balanceParameters.put("instId", operateCurrencyLeverDto.getInstId());
        balanceParameters.put("mgnMode", "cross");
        String leverStr = okxAccount.requestHandler.sendSignedRequest(okxAccount.baseUrl, OKXContants.LEVERAGE, balanceParameters, HttpMethod.GET, okxAccount.isSimluate());
        log.info("leverStr:{}", leverStr);
        JSONObject leverStrJson = JSON.parseObject(leverStr);
 
        Set<String> leverage = new HashSet<>();
 
        JSONArray details = leverStrJson.getJSONArray("data");
        int size = details.size();
        for (int i = 0; i < size; i++) {
            leverage.add(details.getJSONObject(i).getString("lever"));
        }
 
 
        log.info("leverage:{}", leverage);
 
        return new FebsResponse().success().data(leverage);
    }
 
    @Override
    public FebsResponse setLever(OperateCurrencyLeverDto operateCurrencyLeverDto) {
 
        log.info("OKX_SET_LEVEL");
        log.info("operateCurrencyLeverDto:{}", operateCurrencyLeverDto);
 
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(ZhangHuEnum.JIAOYISUO.getValue());
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("参数错误");
        }
 
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
        LinkedHashMap<String, Object> balanceParameters = new LinkedHashMap<>();
        balanceParameters.put("instId", operateCurrencyLeverDto.getInstId()+"-SWAP");
        balanceParameters.put("mgnMode", "cross");
        balanceParameters.put("lever", operateCurrencyLeverDto.getLever());
        String setleverStr = okxAccount.requestHandler.sendSignedRequest(okxAccount.baseUrl, OKXContants.SETLEVERAGE, balanceParameters, HttpMethod.POST, okxAccount.isSimluate());
        log.info("setleverStr:{}", setleverStr);
        JSONObject leverStrJson = JSON.parseObject(setleverStr);
 
        String code = leverStrJson.getString("code");
        if("0".equals(code)||"59000".equals(code)){
            if("59000".equals(code)){
                return new FebsResponse().success().message("59000");
            }
            return new FebsResponse().success().message("设置杠杆成功");
        } else {
            return new FebsResponse().fail().message("设置杠杆失败");
        }
 
    }
 
    /**
     * 测试API链接
     *
     * @param quantApiMessage 包含API链接信息的DTO对象
     * @return 返回一个FebsResponse对象,包含验证结果和消息
     */
    @Override
    public FebsResponse testApiLink(QuantApiMessage quantApiMessage) {
        log.info("apiMessageDto:{}",quantApiMessage);
        try{
            // 初始化账户对象
            OKXAccount okxAccount = this.initAccount(quantApiMessage);
 
            // 创建用于存储余额查询参数的容器
            LinkedHashMap<String, Object> balanceParameters = new LinkedHashMap<>();
            log.info("okxAccount:{}",okxAccount);
 
            // 发送签名请求以获取账户余额
            String balance = okxAccount.requestHandler.sendSignedRequest(okxAccount.baseUrl, OKXContants.BALANCE, balanceParameters, HttpMethod.GET, okxAccount.isSimluate());
            log.info("balance:{}",balance);
 
            // 解析余额响应JSON
            JSONObject balanceJson = JSON.parseObject(balance);
 
            // 检查余额响应代码,如果为0则表示成功
            if("0".equals(balanceJson.getString("code").toString())){
                // 更新QuantApiMessage状态为成功
                HashMap<String, Integer> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("state", PublicStatusEnum.API_MESSAGE_STATUS_SUCCESS);
                return new FebsResponse().success().data(objectObjectHashMap).message("账号验证成功");
            }
 
            // 返回验证失败的消息
            return new FebsResponse().fail().message("账号验证失败");
        } catch (Exception e){
            // 异常情况下返回验证失败的消息
            return new FebsResponse().fail().message("账号验证失败");
        }
    }
 
    /**
     * 获取账户余额的方法
     *
     * @param apiAccountBalanceDto 包含账户余额查询信息的数据传输对象
     * @throws FebsException 当API消息信息未设置时抛出异常
     */
    @Override
    public void getAccountBalance(ApiAccountBalanceDto apiAccountBalanceDto) {
        // 提取API消息ID、账户类型和币种名称
        String coinName = apiAccountBalanceDto.getCoinName();
 
        // 根据ID查询API消息信息
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(ZhangHuEnum.JIAOYISUO.getValue());
        // 检查API消息信息是否存在
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("API_MESSAGE信息未设置");
        }
 
        // 初始化账户对象
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
 
        // 构建查询余额的参数
        LinkedHashMap<String, Object> balanceParameters = new LinkedHashMap<>();
        balanceParameters.put("ccy", coinName);
        // 发送签名请求获取余额信息
        String balance = okxAccount.requestHandler.sendSignedRequest(
                okxAccount.baseUrl,
                OKXContants.BALANCE,
                balanceParameters,
                HttpMethod.GET,
                okxAccount.isSimluate());
        // 记录余额信息日志
        log.info("ACCOUNT_BALANCE:{}", balance);
        JSONObject balanceJson = JSON.parseObject(balance);
        JSONObject data = balanceJson.getJSONArray("data").getJSONObject(0);
        JSONArray details = data.getJSONArray("details");
        for (int i = 0; i < details.size(); i++) {
            JSONObject jsonObject = details.getJSONObject(i);
            // 总权益
            String bal = jsonObject.getString("eq");
//            String upl = jsonObject.getString("upl");
        }
    }
 
    @Override
    public ApiAccountHoldVo getAccountBalanceInfo(ApiAccountBalanceInfoDto apiAccountBalanceInfoDto) {
        ApiAccountHoldVo apiAccountHoldVo = new ApiAccountHoldVo();
 
        // 提取API消息ID、账户类型和币种名称
        Long apiMessageId = apiAccountBalanceInfoDto.getId();
        String coinName = apiAccountBalanceInfoDto.getCoinName();
 
        // 根据ID查询API消息信息
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(
                ZhangHuEnum.JIAOYISUO.getValue()
        );
        // 检查API消息信息是否存在
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("API_MESSAGE信息未设置");
        }
 
        // 初始化账户对象
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
 
        // 构建查询余额的参数
        LinkedHashMap<String, Object> balanceParameters = new LinkedHashMap<>();
        balanceParameters.put("ccy", coinName);
        // 发送签名请求获取余额信息
        String balance = okxAccount.requestHandler.sendSignedRequest(
                okxAccount.baseUrl,
                OKXContants.BALANCE,
                balanceParameters,
                HttpMethod.GET,
                okxAccount.isSimluate());
        // 记录余额信息日志
        log.info("ACCOUNT_BALANCE:{}", balance);
        JSONObject balanceJson = JSON.parseObject(balance);
        JSONObject data = balanceJson.getJSONArray("data").getJSONObject(0);
        JSONArray details = data.getJSONArray("details");
        for (int i = 0; i < details.size(); i++) {
            JSONObject jsonObject = details.getJSONObject(i);
            log.info("OKX-HOLD:",jsonObject);
            // 总权益
            String bal = jsonObject.getString("eq");//币种总权益
            String cashBal = jsonObject.getString("cashBal");//币种余额
            String availEq = jsonObject.getString("availEq");//可用保证金
            String availBal = jsonObject.getString("availBal");//可用余额
            String frozenBal = jsonObject.getString("frozenBal");//币种占用金额
            String imr = jsonObject.getString("imr");//币种维度全仓占用保证金,适用于现货和合约模式且有全仓仓位时
            String mgnRatio = jsonObject.getString("mgnRatio");//币种全仓保证金率,衡量账户内某项资产风险的指标
            String mmr = jsonObject.getString("mmr");//币种维度全仓维持保证金
            String upl = jsonObject.getString("upl");//未实现盈亏
            apiAccountHoldVo.setTotalBalance(new BigDecimal(bal));
            apiAccountHoldVo.setTotalPercent(new BigDecimal(upl));
            apiAccountHoldVo.setAvailableBalance(new BigDecimal(availBal));
//            apiAccountHoldVo.setHoldBalance(new BigDecimal(mmr));
            apiAccountHoldVo.setHoldBalance(new BigDecimal(mmr));
            apiAccountHoldVo.setUseBalance(new BigDecimal(mmr));
            apiAccountHoldVo.setCashBal(new BigDecimal(cashBal));
            apiAccountHoldVo.setFrozenBal(new BigDecimal(frozenBal));
            apiAccountHoldVo.setAvailEq(new BigDecimal(availEq));
            apiAccountHoldVo.setMgnRatio(mgnRatio);
        }
        return apiAccountHoldVo;
    }
 
    @Override
    public ApiPositionsInfoVo getAccountPositionsInfo(ApiPositionsInfoDto apiPositionsInfoDto) {
 
        log.info("getAccountPositionsInfo:{}",apiPositionsInfoDto);
        ApiPositionsInfoVo apiPositionsInfoVo = new ApiPositionsInfoVo();
        // 提取API消息ID、账户类型和币种名称
        Long apiMessageId = apiPositionsInfoDto.getId();
        String coinName = apiPositionsInfoDto.getCoinName();
 
        // 根据ID查询API消息信息
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(
                ZhangHuEnum.JIAOYISUO.getValue()
        );
        // 检查API消息信息是否存在
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("API_MESSAGE信息未设置");
        }
 
        // 初始化账户对象
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
 
        // 构建查询余额的参数
        LinkedHashMap<String, Object> positionsParameters = new LinkedHashMap<>();
        positionsParameters.put("instType", "SWAP");
        positionsParameters.put("instId", coinName+"-USDT-SWAP");
        try{
            // 发送签名请求获取余额信息
            String positions = okxAccount.requestHandler.sendSignedRequest(
                    okxAccount.baseUrl,
                    OKXContants.POSITIONS,
                    positionsParameters,
                    HttpMethod.GET,
                    okxAccount.isSimluate());
            // 记录余额信息日志
            log.info("POSITIONS:{}", positions);
            JSONObject balanceJson = JSON.parseObject(positions);
            String code = balanceJson.getString("code");
            if(!"0".equals(code)){
                return null;
            }
            JSONObject data = balanceJson.getJSONArray("data").getJSONObject(0);
            String avgPx = data.getString("avgPx");
            String upl = data.getString("upl");
            String markPx = data.getString("markPx");
            String bePx = data.getString("bePx");
            String pos = data.getString("pos");
            apiPositionsInfoVo.setUpl(new BigDecimal(ObjectUtil.isNotEmpty(upl)? DataUtil.getDecimalDigits8(upl):"0"));
            apiPositionsInfoVo.setAvgPx(new BigDecimal(ObjectUtil.isNotEmpty(avgPx)?DataUtil.getDecimalDigits8(avgPx):"0"));
            apiPositionsInfoVo.setMarkPx(new BigDecimal(ObjectUtil.isNotEmpty(markPx)?DataUtil.getDecimalDigits8(markPx):"0"));
            apiPositionsInfoVo.setBePx(new BigDecimal(ObjectUtil.isNotEmpty(bePx)?DataUtil.getDecimalDigits8(bePx):"0"));
            apiPositionsInfoVo.setPos(new BigDecimal(ObjectUtil.isNotEmpty(pos)?DataUtil.getDecimalDigits8(pos):"0"));
            apiPositionsInfoVo.setCoinName(coinName);
            return apiPositionsInfoVo;
        }catch (Exception e){
            return null;
        }
 
    }
 
    @Override
    public FebsResponse getTradeData(ApiValidApiMessageDto apiValidApiMessageDto) {
 
        log.info("getTradeData:{}", apiValidApiMessageDto);
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(
                ZhangHuEnum.JIAOYISUO.getValue()
        );
        // 检查API消息信息是否存在
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("API_MESSAGE信息未设置");
        }
 
        // 初始化账户对象
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
 
        // 构建查询余额的参数
        LinkedHashMap<String, Object> positionsParameters = new LinkedHashMap<>();
        try{
            // 发送签名请求获取余额信息
            String tradedata = okxAccount.requestHandler.sendSignedRequest(
                    okxAccount.baseUrl,
                    OKXContants.TRADEDATA,
                    positionsParameters,
                    HttpMethod.GET,
                    okxAccount.isSimluate());
            // 记录余额信息日志
            log.info("tradedata:{}", tradedata);
            JSONObject balanceJson = JSON.parseObject(tradedata);
            String code = balanceJson.getString("code");
            if(!"0".equals(code)){
                return null;
            }
            JSONObject dataObject = balanceJson.getJSONObject("data");
            JSONArray contractArray = dataObject.getJSONArray("contract");
            List<String> contractList = new ArrayList<>();
            if (contractArray != null) {
                for (int i = 0; i < contractArray.size(); i++) {
                    contractList.add(contractArray.getString(i));
                }
            }
            return new FebsResponse().data(contractList);
        }catch (Exception e){
            return null;
        }
    }
 
    @Override
    public FebsResponse getBuySellSituation(ApiValidApiMessageDto apiValidApiMessageDto) {
        log.info("getBuySellSituation:{}", apiValidApiMessageDto);
 
        String coinName = apiValidApiMessageDto.getCoinName();//        String coinName = "BTC";
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(
                ZhangHuEnum.JIAOYISUO.getValue()
        );
        // 检查API消息信息是否存在
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("API_MESSAGE信息未设置");
        }
 
        // 初始化账户对象
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
 
        // 构建查询余额的参数
        LinkedHashMap<String, Object> positionsParameters = new LinkedHashMap<>();
        positionsParameters.put("period", "4H");
        positionsParameters.put("instId", coinName+"-USDT-SWAP");
        positionsParameters.put("limit", "1");
        try{
            // 发送签名请求获取余额信息
            String buySellSituation = okxAccount.requestHandler.sendSignedRequest(
                    okxAccount.baseUrl,
                    OKXContants.BUYSELLSITUATION,
                    positionsParameters,
                    HttpMethod.GET,
                    okxAccount.isSimluate());
            // 记录余额信息日志
            log.info("buySellSituation:{}", buySellSituation);
            JSONObject balanceJson = JSON.parseObject(buySellSituation);
            String code = balanceJson.getString("code");
            if(!"0".equals(code)){
                return null;
            }
            JSONArray dataArray = balanceJson.getJSONArray("data");
            TradeBigdataDto tradeBigdataDto = new TradeBigdataDto();
            if (dataArray != null) {
                JSONArray innerArray = dataArray.getJSONArray(0);
                String sellVol = innerArray.getString(1);
                String buyVol = innerArray.getString(2);
                String ts = innerArray.getString(0);
                tradeBigdataDto.setBuyVol(buyVol);
                tradeBigdataDto.setSellVol(sellVol);
                tradeBigdataDto.setTs(ts);
            }
            return new FebsResponse().data(tradeBigdataDto);
        }catch (Exception e){
            return null;
        }
    }
 
    @Override
    public FebsResponse getPositionRatio(ApiValidApiMessageDto apiValidApiMessageDto) {
        log.info("getPositionRatio:{}", apiValidApiMessageDto);
 
        String coinName = apiValidApiMessageDto.getCoinName();//        String coinName = "BTC";
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(
                ZhangHuEnum.JIAOYISUO.getValue()
        );
        // 检查API消息信息是否存在
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("API_MESSAGE信息未设置");
        }
 
        // 初始化账户对象
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
 
        // 构建查询余额的参数
        LinkedHashMap<String, Object> positionsParameters = new LinkedHashMap<>();
        positionsParameters.put("period", "4H");
        positionsParameters.put("instId", coinName+"-USDT-SWAP");
        positionsParameters.put("limit", "1");
        try{
            // 发送签名请求获取余额信息
            String positionRatio = okxAccount.requestHandler.sendSignedRequest(
                    okxAccount.baseUrl,
                    OKXContants.POSITIONRATIO,
                    positionsParameters,
                    HttpMethod.GET,
                    okxAccount.isSimluate());
            // 记录余额信息日志
            log.info("positionRatio:{}", positionRatio);
            JSONObject balanceJson = JSON.parseObject(positionRatio);
            String code = balanceJson.getString("code");
            if(!"0".equals(code)){
                return null;
            }
            JSONArray dataArray = balanceJson.getJSONArray("data");
            TradeBigdataDto tradeBigdataDto = new TradeBigdataDto();
            if (dataArray != null) {
                JSONArray innerArray = dataArray.getJSONArray(0);
                String longShortAcctRatio = innerArray.getString(1);
                String ts = innerArray.getString(0);
                tradeBigdataDto.setLongShortAcctRatio(longShortAcctRatio);
                tradeBigdataDto.setTs(ts);
            }
            return new FebsResponse().data(tradeBigdataDto);
        }catch (Exception e){
            return null;
        }
    }
 
    @Override
    public FebsResponse getPositionTradingvolume(ApiValidApiMessageDto apiValidApiMessageDto) {
        log.info("getPositionTradingvolume:{}", apiValidApiMessageDto);
 
        String coinName = apiValidApiMessageDto.getCoinName();//        String coinName = "BTC";
        QuantApiMessage quantApiMessage = apiMessageService.getApiMessage(
                ZhangHuEnum.JIAOYISUO.getValue()
        );
        // 检查API消息信息是否存在
        if(ObjectUtil.isEmpty(quantApiMessage)){
            throw new FebsException("API_MESSAGE信息未设置");
        }
 
        // 初始化账户对象
        OKXAccount okxAccount = this.initAccount(quantApiMessage);
 
        // 构建查询余额的参数
        LinkedHashMap<String, Object> positionsParameters = new LinkedHashMap<>();
        positionsParameters.put("period", "1D");
        positionsParameters.put("ccy", coinName);
        positionsParameters.put("limit", "1");
        try{
            // 发送签名请求获取余额信息
            String positionTradingvolume = okxAccount.requestHandler.sendSignedRequest(
                    okxAccount.baseUrl,
                    OKXContants.POSITIONVOLUME,
                    positionsParameters,
                    HttpMethod.GET,
                    okxAccount.isSimluate());
            // 记录余额信息日志
            log.info("positionTradingvolume:{}", positionTradingvolume);
            JSONObject balanceJson = JSON.parseObject(positionTradingvolume);
            String code = balanceJson.getString("code");
            if(!"0".equals(code)){
                return null;
            }
            JSONArray dataArray = balanceJson.getJSONArray("data");
            TradeBigdataDto tradeBigdataDto = new TradeBigdataDto();
            if (dataArray != null) {
                JSONArray innerArray = dataArray.getJSONArray(0);
                String oi = innerArray.getString(1);
                String vol = innerArray.getString(2);
                String ts = innerArray.getString(0);
                tradeBigdataDto.setOi(oi);
                tradeBigdataDto.setVol(vol);
                tradeBigdataDto.setTs(ts);
            }
            return new FebsResponse().data(tradeBigdataDto);
        }catch (Exception e){
            return null;
        }
    }
 
    //此方法用于验证账号
    private  boolean validateAccount(ApiMessageDto apiMessageDto) throws Exception {
        boolean flag = false;
//        try {
            //设置请求
            URL url = new URL(baseurl+"/api/v5/account/balance");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 
            //设置请求方法
            connection.setRequestMethod("GET");
 
            //设置必需的头信息
            long now = System.currentTimeMillis() / 1000;
            String timestamp = String.valueOf(now);
            String preHash = timestamp + "GET" + "/api/v5/account/balance"; //URL路径
            String signature = generateSignature(preHash, apiMessageDto.getBSecretkey());
 
            connection.setRequestProperty("OK-ACCESS-KEY", apiMessageDto.getASecretkey());
            connection.setRequestProperty("OK-ACCESS-SIGN", signature);
            connection.setRequestProperty("OK-ACCESS-TIMESTAMP", timestamp);
            connection.setRequestProperty("OK-ACCESS-PASSPHRASE", apiMessageDto.getPassPhrass());
 
            connection.setRequestProperty("Content-Type", "application/json");
 
            //执行请求
            int responseCode = connection.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
 
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
 
            //打印响应
            if(responseCode == 200){
                flag = true;
            } else {
                flag = false;
            }
//        } catch (Exception e) {
//            //在此打印异常信息
//            log.error("Exception: " + e.getMessage());
//            flag = false;
//        }
        return flag;
    }
 
    //此方法用于生成签名
    private static String generateSignature(String preHash, String secretKey) throws Exception{
        javax.crypto.Mac sha256_HMAC = javax.crypto.Mac.getInstance("HmacSHA256");
        javax.crypto.spec.SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(preHash.getBytes()));
    }
 
    public static void main(String[] args) throws Exception {
        String buySellSituation = "{\"code\":\"0\",\"data\":[[\"1718164800000\",\"52000.2999999999975\",\"60671.0000000000019\"]],\"msg\":\"\"}";
        log.info("buySellSituation:{}", buySellSituation);
        JSONObject balanceJson = JSON.parseObject(buySellSituation);
        JSONArray dataArray = balanceJson.getJSONArray("data");
        TradeBigdataDto tradeBigdataDto = new TradeBigdataDto();
        if (dataArray != null) {
            JSONArray innerArray = dataArray.getJSONArray(0);
            String sellVol = innerArray.getString(1);
            String buyVol = innerArray.getString(2);
            String ts = innerArray.getString(0);
            tradeBigdataDto.setBuyVol(buyVol);
            tradeBigdataDto.setSellVol(sellVol);
            tradeBigdataDto.setTs(ts);
        }
        System.out.println(tradeBigdataDto.toString());
    }
}