1
zj
2024-07-26 738d92406da5313021bd9a092cadbc2a24d88034
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
package org.example.server.impl;
 
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
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;
import org.example.pojo.MarketDataOut;
import org.example.pojo.bo.AsksBo;
import org.example.pojo.bo.BidsBo;
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;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.ArrayList;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.io.ByteArrayOutputStream;
 
 
/**
 * @program: demo
 * @description:
 * @create: 2024-07-16 15:23
 **/
@Service
@Slf4j
public class CurrencySerivceImpl extends ServiceImpl<CurrencyMapper, Currency> implements CurrencySerivce {
 
    private static final Gson gson = new Gson();
    private ArrayList<String> keys;
 
    List<MarketBo> mexcList = new ArrayList<>();
    List<MarketBo> gateList = new ArrayList<>();
    List<MarketBo> bitgetList = new ArrayList<>();
    List<MarketBo> kucoinList = new ArrayList<>();
 
    private final Lock syncCurrencyLock = new ReentrantLock();
 
    @Autowired
    private WsServer wsServer;
 
    private void extracted() {
        ExecutorService executor = Executors.newFixedThreadPool(4); // 适当增加线程数以匹配处理的交易所数量
 
        // 异步处理每个交易所的数据
        CompletableFuture<Void> mexcFuture = CompletableFuture.runAsync(() -> processMexc(), 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);
 
        // 等待所有任务完成
        CompletableFuture.allOf(mexcFuture, gateFuture, bitgetFuture, kucoinFuture).join();
 
        executor.shutdown(); // 关闭线程池
    }
 
    private void processMexc() {
        Set<String> mexcSet = RedisUtil.keys("mexc");
 
        for (String key : mexcSet) {
            MarketBo marketBo = new MarketBo();
 
            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");
 
            if (asksObj instanceof List && !((List<?>) asksObj).isEmpty()) {
                List<?> asksList = (List<?>) asksObj;
                Map<?, ?> asksMap = (Map<?, ?>) asksList.get(0);
                AsksBo asksBo = new AsksBo();
                asksBo.setP(new BigDecimal(asksMap.get("p").toString()));
                asksBo.setV(new BigDecimal(asksMap.get("v").toString()));
                marketBo.setAsks(asksBo);
            }
 
            if (bidsObj instanceof List && !((List<?>) bidsObj).isEmpty()) {
                List<?> bidsList = (List<?>) bidsObj;
                Map<?, ?> bidsMap = (Map<?, ?>) bidsList.get(bidsList.size() - 1);
                BidsBo bidsBo = new BidsBo();
                bidsBo.setP(new BigDecimal(bidsMap.get("p").toString()));
                bidsBo.setV(new BigDecimal(bidsMap.get("v").toString()));
                marketBo.setBids(bidsBo);
            }
 
            marketBo.setKey(key.replaceAll("mexc", ""));
            marketBo.setExchange("mexc");
            mexcList.add(marketBo);
        }
    }
 
    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");
            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);
            }
 
            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);
        }
    }
 
    // 计算利润百分比
    private static BigDecimal calculateProfitPercentage(BigDecimal buyPrice, BigDecimal sellPrice) {
        BigDecimal profit = sellPrice.subtract(buyPrice);
        if (buyPrice.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO; // 防止除以零
        }
        BigDecimal profitPercentage = profit.divide(buyPrice, 12, RoundingMode.DOWN).multiply(new BigDecimal(100));
        return profitPercentage;
    }
 
    private void findProfitablePairs(List<MarketBo>... exchangeLists) {
        Map<String, Map<String, MarketBo>> marketMap = new HashMap<>();
        List<MarketDataOut> marketDataOuts = Collections.synchronizedList(new ArrayList<>()); // 使用线程安全的集合
 
        // 按币种名称和交易所分组市场数据
        for (List<MarketBo> exchangeList : exchangeLists) {
            for (MarketBo market : exchangeList) {
                String coinName = market.getKey();
                String exchangeName = market.getExchange();
                marketMap.computeIfAbsent(coinName, k -> new HashMap<>())
                        .put(exchangeName, market);
            }
        }
 
        // 过滤出至少在两个交易所都有的币种
        marketMap.values().removeIf(exchangeMap -> exchangeMap.size() == 1);
 
        // 并行计算利润百分比
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(8, marketMap.size())); // 根据需要调整线程池大小
 
        List<CompletableFuture<Void>> futures = new ArrayList<>();
 
        // 获取当前时间,用于后续所有 MarketDataOut 的时间戳
        LocalDateTime currentTime = LocalDateTime.now();
        String formattedDateTime = currentTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // 格式化时间字符串
 
        for (Map.Entry<String, Map<String, MarketBo>> entry : marketMap.entrySet()) {
            String coinName = entry.getKey();
            Map<String, MarketBo> exchangeMap = entry.getValue();
            String[] exchanges = exchangeMap.keySet().toArray(new String[0]);
 
            for (int i = 0; i < exchanges.length; i++) {
                MarketBo markets1 = exchangeMap.get(exchanges[i]);
                if (markets1.getBids() == null) continue;
 
                for (int j = 0; j < exchanges.length; j++) {
                    if (i == j) continue;
 
                    MarketBo markets2 = exchangeMap.get(exchanges[j]);
                    if (markets2.getAsks() == null) continue;
 
                    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                        try {
                            BigDecimal buyPrice = markets1.getBids().getP();
                            BigDecimal sellPrice = markets2.getAsks().getP();
                            BigDecimal profitPercentage = calculateProfitPercentage(buyPrice, sellPrice);
 
                            // 只有在利润百分比大于0时才组装市场数据
                            if (profitPercentage.compareTo(BigDecimal.ZERO) > 0) {
                                assembleMarketDataOut(coinName, markets1, markets2, profitPercentage, buyPrice, sellPrice, marketDataOuts, formattedDateTime);
                            }
                        } catch (Exception e) {
                            e.printStackTrace(); // 输出异常信息
                        }
                    }, executor);
 
                    futures.add(future); // 收集所有 Future
                }
            }
        }
 
        // 等待所有任务完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        allFutures.join();
 
        executor.shutdown(); // 关闭线程池
 
        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.setServceTime(formattedDateTime); // 设置服务时间
        marketDataOuts.add(marketDataOut); // 添加到输出列表
    }
 
    private void pushWs(List<MarketDataOut> marketDataOuts) {
//        String key = "MARKET_Date";
//        // 创建 Gson 对象
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        // 将列表转换为 JSON 字符串
        String json = gson.toJson(marketDataOuts);
//        RedisUtil.set(key,json);
        try {
            // 全体发送
            wsServer.sendMessageToAll(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public void quotationCalculation(){
        extracted();
        findProfitablePairs(mexcList, gateList, bitgetList, kucoinList);
    }
 
    public void scheduler(){
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 
        // 获取当前时间
        Calendar now = Calendar.getInstance();
        int currentHour = now.get(Calendar.HOUR_OF_DAY);
        int currentMinute = now.get(Calendar.MINUTE);
 
        // 计算距离下一个1点的小时数和分钟数
        int hourToSchedule = 1;
        int minuteToSchedule = 0;
        if (currentHour > hourToSchedule || (currentHour == hourToSchedule && currentMinute >= minuteToSchedule)) {
            now.add(Calendar.DAY_OF_MONTH, 1); // 如果当前时间已过1点,则将调度时间设为明天的1点
        }
        now.set(Calendar.HOUR_OF_DAY, hourToSchedule);
        now.set(Calendar.MINUTE, minuteToSchedule);
        now.set(Calendar.SECOND, 0);
        now.set(Calendar.MILLISECOND, 0);
 
        Date scheduledTime = now.getTime();
        long initialDelay = scheduledTime.getTime() - System.currentTimeMillis();
 
        // 调度任务
        scheduler.scheduleAtFixedRate(task, initialDelay, TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS);
    }
 
    Runnable task = new Runnable() {
        @Override
        public void run() {
 
            // 获取所有 Redis 键
            Set<String> setKeys = RedisUtil.keys("*");
            keys = new ArrayList<>(setKeys);
            log.info("---------------------更新交易对完成---------------------");
        }
    };
}