1
zj
2024-08-12 440f0f0b37a10c82e54f402be8d4d99c7406b4d4
websocketSerivce/src/main/java/org/example/server/impl/CurrencySerivceImpl.java
@@ -1,5 +1,6 @@
package org.example.server.impl;
import org.apache.commons.lang3.StringUtils;
import org.example.websocket.server.WsServer;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
@@ -9,7 +10,6 @@
import com.google.gson.GsonBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.dao.CurrencyMapper;
import org.example.pojo.Currency;
import org.example.pojo.Market;
@@ -19,7 +19,6 @@
import org.example.pojo.bo.MarketBo;
import org.example.server.CurrencySerivce;
import org.example.util.RedisUtil;
import org.example.websocket.server.WsServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.error.Mark;
@@ -59,10 +58,10 @@
    private WsServer wsServer;
    private void extracted() {
        ExecutorService executor = Executors.newFixedThreadPool(4); // 适当增加线程数以匹配处理的交易所数量
        ExecutorService executor = Executors.newFixedThreadPool(20); // 适当增加线程数以匹配处理的交易所数量
        // 异步处理每个交易所的数据
        CompletableFuture<Void> mexcFuture = CompletableFuture.runAsync(() -> processMexc(), executor);
        CompletableFuture<Void> mexcFuture = CompletableFuture.runAsync(() -> processMarketData(RedisUtil.keys("mexc"), mexcList, "mexc"), executor);
        CompletableFuture<Void> gateFuture = CompletableFuture.runAsync(() -> processMarketData(RedisUtil.keys("gate"), gateList, "gate"), executor);
        CompletableFuture<Void> bitgetFuture = CompletableFuture.runAsync(() -> processMarketData(RedisUtil.keys("bitget"), bitgetList, "bitget"), executor);
        CompletableFuture<Void> kucoinFuture = CompletableFuture.runAsync(() -> processMarketData(RedisUtil.keys("kucoin"), kucoinList, "kucoin"), executor);
@@ -95,7 +94,7 @@
            if (bidsObj instanceof List && !((List<?>) bidsObj).isEmpty()) {
                List<?> bidsList = (List<?>) bidsObj;
                Map<?, ?> bidsMap = (Map<?, ?>) bidsList.get(bidsList.size() - 1);
                Map<?, ?> bidsMap = (Map<?, ?>) bidsList.get(0);
                BidsBo bidsBo = new BidsBo();
                bidsBo.setP(new BigDecimal(bidsMap.get("p").toString()));
                bidsBo.setV(new BigDecimal(bidsMap.get("v").toString()));
@@ -109,36 +108,46 @@
    }
    private void processMarketData(Set<String> set, List<MarketBo> list, String exchangeName) {
        for (String key : set) {
            String v = RedisUtil.get(key);
            Map<String, Object> redisValueMap = gson.fromJson(v, new TypeToken<Map<String, Object>>() {}.getType());
            Object asksObj = redisValueMap.get("asks");
            Object bidsObj = redisValueMap.get("bids");
        ArrayList<String> kyes = new ArrayList<>(set);
        List<String> mget = RedisUtil.mget(kyes);
        Map<String, String> resultMap = new HashMap<>();
        for (int i = 0; i < kyes.size(); i++) {
            resultMap.put(kyes.get(i), mget.get(i));
        }
        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
            String v = entry.getValue();
            String key = entry.getKey();
            MarketBo marketBo = new MarketBo();
            if (asksObj instanceof List && !((List<?>) asksObj).isEmpty()) {
                List<?> asksList = (List<?>) asksObj;
                String[][] dataArray = gson.fromJson(gson.toJson(asksList), String[][].class);
                String[] asksData = dataArray[0];
                AsksBo asksBo = new AsksBo();
                asksBo.setP(new BigDecimal(asksData[0]));
                asksBo.setV(new BigDecimal(asksData[1]));
                marketBo.setAsks(asksBo);
            Map<String, Map<String,String>> redisValueMap = gson.fromJson(v, new TypeToken<Map<String, Map<String,String>>>() {}.getType());
            Map<String,String> asksObj = redisValueMap.get("asks");
            Map<String,String> bidsObj = redisValueMap.get("bids");
            try {
                if(StringUtils.isNotEmpty(asksObj.get("p")) && StringUtils.isNotEmpty(asksObj.get("v")) &&
                        StringUtils.isNotEmpty(bidsObj.get("p")) && StringUtils.isNotEmpty(bidsObj.get("v"))) {
                    AsksBo asksBo = new AsksBo();
                    asksBo.setP(new BigDecimal(asksObj.get("p").toString()));
                    asksBo.setV(new BigDecimal(asksObj.get("v").toString()));
                    marketBo.setAsks(asksBo);
                    BidsBo bidsBo = new BidsBo();
                    bidsBo.setP(new BigDecimal(bidsObj.get("p").toString()));
                    bidsBo.setV(new BigDecimal(bidsObj.get("v").toString()));
                    marketBo.setBids(bidsBo);
                    marketBo.setKey(key.replaceAll(exchangeName, ""));
                    marketBo.setExchange(exchangeName);
                    list.add(marketBo);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            if (bidsObj instanceof List && !((List<?>) bidsObj).isEmpty()) {
                List<?> bidsList = (List<?>) bidsObj;
                String[][] dataArray = gson.fromJson(gson.toJson(bidsList), String[][].class);
                String[] bidsData = dataArray[bidsList.size() - 1];
                BidsBo bidsBo = new BidsBo();
                bidsBo.setP(new BigDecimal(bidsData[0]));
                bidsBo.setV(new BigDecimal(bidsData[1]));
                marketBo.setBids(bidsBo);
            }
            marketBo.setKey(key.replaceAll(exchangeName, ""));
            marketBo.setExchange(exchangeName);
            list.add(marketBo);
        }
    }
@@ -188,9 +197,14 @@
                if (markets1.getBids() == null) continue;
                for (int j = 0; j < exchanges.length; j++) {
                    if (i == j) continue;
                    MarketBo markets2 = exchangeMap.get(exchanges[j]);
                    if(markets1.getExchange().equals(markets2.getExchange())){
                        continue;
                    }
                    if (markets2.getAsks() == null) continue;
                    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
@@ -218,25 +232,37 @@
        allFutures.join();
        executor.shutdown(); // 关闭线程池
        mexcList.clear();
        gateList.clear();
        bitgetList.clear();
        kucoinList.clear();
        pushWs(marketDataOuts); // 推送结果
    }
    private static void assembleMarketDataOut(String coinName, MarketBo markets1, MarketBo markets2, BigDecimal profitPercentage, BigDecimal buyPrice, BigDecimal sellPrice, List<MarketDataOut> marketDataOuts, String formattedDateTime) {
        MarketDataOut marketDataOut = new MarketDataOut();
        marketDataOut.setBaseAsset(coinName.replaceAll("USDT","").toLowerCase()); // 设置基础资产
        marketDataOut.setBuyingPlatform(markets1.getExchange()); // 设置买入平台
        marketDataOut.setSellPlatform(markets2.getExchange()); // 设置卖出平台
        marketDataOut.setSpread(profitPercentage.toString()); // 设置利润百分比
        marketDataOut.setBuyPrice(buyPrice.toString()); // 设置买入价格
        marketDataOut.setSellPrice(sellPrice.toString()); // 设置卖出价格
        marketDataOut.setBuyNumber(markets1.getBids().getV().toString()); // 设置买入数量
        marketDataOut.setSellNumber(markets2.getAsks().getV().toString()); // 设置卖出数量
        marketDataOut.setBuyTotalPrice(markets1.getBids().getP().multiply(markets1.getBids().getV()).toString()); // 设置买入总价
        marketDataOut.setSellTotalPrice(markets2.getAsks().getP().multiply(markets2.getAsks().getV()).toString()); // 设置卖出总价
        marketDataOut.setBaseAsset(coinName.replaceAll("USDT","").toLowerCase().toUpperCase()); // 设置基础资产
        marketDataOut.setBuyingPlatform(capitalizeFirstLetter(markets1.getExchange())); // 设置买入平台,首字母大写
        marketDataOut.setSellPlatform(capitalizeFirstLetter(markets2.getExchange())); // 设置卖出平台,首字母大写
        marketDataOut.setSpread(profitPercentage.setScale(4, RoundingMode.DOWN).toPlainString()); // 设置利润百分比
        marketDataOut.setBuyPrice(buyPrice.toPlainString()); // 设置买入价格
        marketDataOut.setSellPrice(sellPrice.toPlainString()); // 设置卖出价格
        marketDataOut.setBuyNumber(markets1.getBids().getV().setScale(4, RoundingMode.HALF_UP).toPlainString()); // 设置买入数量
        marketDataOut.setSellNumber(markets2.getAsks().getV().setScale(4, RoundingMode.HALF_UP).toPlainString()); // 设置卖出数量
        marketDataOut.setBuyTotalPrice((markets1.getBids().getP().multiply(markets1.getBids().getV())).setScale(0, RoundingMode.HALF_UP).toPlainString()); // 设置买入总价
        marketDataOut.setSellTotalPrice((markets2.getAsks().getP().multiply(markets2.getAsks().getV())).setScale(0,RoundingMode.HALF_UP).toPlainString()); // 设置卖出总价
        marketDataOut.setServceTime(formattedDateTime); // 设置服务时间
        marketDataOut.setBuyAndSell(marketDataOut.getBaseAsset()+marketDataOut.getBuyingPlatform()+marketDataOut.getSellPlatform());
        marketDataOuts.add(marketDataOut); // 添加到输出列表
    }
    public static String capitalizeFirstLetter(String word) {
        if (word == null || word.isEmpty()) {
            return word;
        }
        return Character.toUpperCase(word.charAt(0)) + word.substring(1);
    }
    private void pushWs(List<MarketDataOut> marketDataOuts) {
//        String key = "MARKET_Date";
@@ -255,7 +281,7 @@
    public void quotationCalculation(){
        extracted();
        findProfitablePairs(mexcList, gateList, bitgetList, kucoinList);
        findProfitablePairs(mexcList, gateList, bitgetList, kucoinList); // 请确保这些变量有定义和赋值
    }
    public void scheduler(){