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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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()); } }