1
zyy
2026-04-03 4fefff17528a878d345ff3311c297a66a671b8d6
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
package com.yami.trading.huobi.tradingview.service;
 
import com.yami.trading.huobi.tradingview.api.TickerSubscription;
import com.yami.trading.huobi.tradingview.api.TradingViewAPI;
import com.yami.trading.huobi.tradingview.api.UpdateListener;
import com.yami.trading.huobi.tradingview.api.model.CandleData;
import com.yami.trading.huobi.tradingview.api.model.Kline;
import com.yami.trading.huobi.tradingview.api.model.TickerData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
 
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
 
/**
 * @Author: TG:哪吒出海
 * @Date: 2025-05-28-0:43
 * @Description:
 */
@Slf4j
@Service
public class TradingViewService {
 
    // 分别为行情和K线创建独立的API实例
    private final TradingViewAPI marketApi;
    private final TradingViewAPI klineApi;
    // 分别为行情和K线创建独立的线程池
    private final ExecutorService marketExecutor;
    private final ExecutorService klineExecutor;
 
    private final ExecutorService startExecutor;
 
    private static final String MARKET_DATA_KEY_PREFIX = "market:data:";
    private static final String KLINE_DATA_KEY_PREFIX = "kline:data:";
 
    // 存储所有活跃的订阅
    private final ConcurrentMap<String, List<TickerSubscription>> activeSubscriptions = new ConcurrentHashMap<>();
 
    public TradingViewService() {
        this.marketApi = new TradingViewAPI();
        this.klineApi = new TradingViewAPI();
 
        this.marketExecutor = Executors.newCachedThreadPool(r -> {
            Thread t = new Thread(r, "market-thread-pool");
            t.setDaemon(true);
            return t;
        });
        this.klineExecutor = Executors.newCachedThreadPool(r -> {
            Thread t = new Thread(r, "kline-thread-pool");
            t.setDaemon(true);
            return t;
        });
 
        this.startExecutor = Executors.newCachedThreadPool(r -> {
            Thread t = new Thread(r, "start-thread-pool");
            t.setDaemon(true);
            return t;
        });
 
        startExecutor.execute(this::initializeAPIs);
    }
 
    /**
     * 连接tw wss
     */
    private void initializeAPIs() {
        try {
            // 初始化行情API
            marketApi.setup().get();
            log.info("行情API初始化成功");
 
            // 初始化K线API
            klineApi.setup().get();
            log.info("K线API初始化成功");
        } catch (Exception e) {
            log.error("API初始化失败", e);
            throw new RuntimeException("API初始化失败", e);
        }
    }
 
    public void subscribeSymbol(String symbols) {
        CompletableFuture.runAsync(() -> {
            try {
                // 取消已存在的订阅
                cancelSubscriptions(symbols);
 
                // 创建通用的更新监听器
                UpdateListener commonListener = data -> {
                    try {
 
                        System.out.println("收到更新:");
                        System.out.println("  交易对: " + data.getProName());
                        System.out.println("  最新价格: " + data.getLastPrice());
                        System.out.println("  24h涨跌: " + data.getChange());
                        System.out.println("  24h涨跌幅: " + data.getChangePercent() + "%");
                        System.out.println("  成交量: " + data.getVolume());
                        Date lastUpdated = data.getLastUpdated();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String formattedDate = sdf.format(lastUpdated);
                        System.out.println("  更新时间: " + formattedDate);
 
                        String redisKey = MARKET_DATA_KEY_PREFIX + data.getProName();
                        //redisTemplate.opsForValue().set(redisKey, data);
                        log.debug("更新行情数据到Redis: {} - 价格: {}", redisKey, data.getLastPrice());
                    } catch (Exception e) {
                        log.error("保存行情数据到Redis失败", e);
                    }
                };
 
                // 订阅所有交易对
                TickerSubscription tickers = marketApi.getTickers(symbols).get();
                List<TickerSubscription> newSubscriptions = new ArrayList<>();
 
                // 为每个交易对添加监听器
                tickers.addUpdateListener(commonListener);
                newSubscriptions.add(tickers);
                log.info("已添加监听器: {}", tickers.getSimpleOrProName());
 
                // 保存新的订阅
                activeSubscriptions.put(symbols, newSubscriptions);
 
            } catch (Exception e) {
                log.error("订阅symbols失败: " + symbols, e);
                throw new RuntimeException("订阅失败", e);
            }
        }, marketExecutor);
    }
 
 
    /**
     * 参数回调
     * @param symbols
     * @param callback
     */
    public void subscribeSymbol(String symbols, Consumer<TickerData> callback) {
        CompletableFuture.runAsync(() -> {
            try {
                // 取消已存在的订阅
                cancelSubscriptions(symbols);
 
                // 创建通用的更新监听器
                UpdateListener commonListener = data -> {
                    try {
 
                        //if(data.getShortName().equals("AUDJPY")){
                        //    System.out.println("收到更新:");
                        //    System.out.println("  名称: " + data.getShortName());
                        //    System.out.println("  交易对: " + data.getProName());
                        //    System.out.println("  最新价格: " + data.getLastPrice());
                        //    System.out.println("  开盘: " + data.getOpen());
                        //    System.out.println("  最高: " + data.getHigh());
                        //    System.out.println("  最低: " + data.getLow());
                        //    System.out.println("  昨日收盘: " + data.getPrevClose());
                        //    System.out.println("  24h涨跌: " + data.getChange());
                        //    System.out.println("  24h涨跌幅: " + data.getChangePercent() + "%");
                        //    System.out.println("  成交量: " + data.getVolume());
                        //    Date lastUpdated = data.getLastUpdated();
                        //    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        //    String formattedDate = sdf.format(lastUpdated);
                        //    System.out.println("  更新时间: " + formattedDate);
                        //}
 
                        // 直接回调行情数据
                        if (callback != null) {
                            callback.accept(data);
                        }
                        //String redisKey = MARKET_DATA_KEY_PREFIX + data.getProName();
                        //redisTemplate.opsForValue().set(redisKey, data);
                        //log.debug("更新行情数据到Redis: {} - 价格: {}", redisKey, data.getLastPrice());
                    } catch (Exception e) {
                        log.error("保存行情数据到Redis失败", e);
                    }
                };
 
                // 订阅所有交易对
                TickerSubscription tickers = marketApi.getTickers(symbols).get();
                List<TickerSubscription> newSubscriptions = new ArrayList<>();
 
                // 为每个交易对添加监听器
                tickers.addUpdateListener(commonListener);
                newSubscriptions.add(tickers);
                log.info("已添加监听器: {}", tickers.getSimpleOrProName());
 
                // 保存新的订阅
                activeSubscriptions.put(symbols, newSubscriptions);
 
            } catch (Exception e) {
                log.error("订阅symbols失败: " + symbols, e);
                throw new RuntimeException("订阅失败", e);
            }
        }, marketExecutor);
    }
 
    private void cancelSubscriptions(String symbols) {
        List<TickerSubscription> existingSubscriptions = activeSubscriptions.remove(symbols);
        if (existingSubscriptions != null) {
            for (TickerSubscription subscription : existingSubscriptions) {
                try {
                    //移除所有监听器
                    List<UpdateListener> updateListeners = subscription.getUpdateListeners();
                    for (UpdateListener updateListener : updateListeners) {
                        if(null != updateListener){
                            subscription.removeUpdateListener(updateListener);
                        }
                    }
                } catch (Exception e) {
                    log.error("取消订阅失败: " + subscription.getSimpleOrProName(), e);
                }
            }
            log.info("已取消现有订阅: {}", symbols);
        }
    }
 
    public TickerData getMarketData(String symbol) {
        String redisKey = MARKET_DATA_KEY_PREFIX + symbol;
        //TickerData data = (TickerData) redisTemplate.opsForValue().get(redisKey);
        //if (data == null) {
        //    log.warn("未找到symbol的市场数据: {}", symbol);
        //}
        //return data;
        return null;
    }
 
    public CompletableFuture<Map<String, List<Kline>>> getKlineData(String symbols, String interval) {
        CompletableFuture<Map<String, List<Kline>>> future = new CompletableFuture<>();
        try {
            // 将symbols按逗号分割成单个交易对
            String[] symbolArray = symbols.split(",");
            Map<String, CompletableFuture<List<Kline>>> futures = new HashMap<>();
 
            // 为每个交易对创建一个Future
            for (String symbol : symbolArray) {
                String trimmedSymbol = symbol.trim();
                futures.put(trimmedSymbol, getKlineDataForSingleSymbol(trimmedSymbol, interval));
            }
 
            // 等待所有Future完成
            CompletableFuture.allOf(futures.values().toArray(new CompletableFuture[0]))
                    .thenAccept(v -> {
                        try {
                            // 将每个交易对的K线数据放入Map
                            Map<String, List<Kline>> result = new HashMap<>();
                            for (Map.Entry<String, CompletableFuture<List<Kline>>> entry : futures.entrySet()) {
                                result.put(entry.getKey(), entry.getValue().get());
                            }
                            future.complete(result);
                        } catch (Exception e) {
                            future.completeExceptionally(e);
                            log.error("合并K线数据失败", e);
                        }
                    });
        } catch (Exception e) {
            future.completeExceptionally(e);
            log.error("获取K线数据失败: " + symbols, e);
        }
        return future;
    }
 
    private CompletableFuture<List<Kline>> getKlineDataForSingleSymbol(String symbol, String interval) {
        CompletableFuture<List<Kline>> future = new CompletableFuture<>();
        try {
            String redisKey = String.format("%s:%s:%s", KLINE_DATA_KEY_PREFIX, symbol, interval);
 
            // 先从Redis获取数据
            //List<Kline> cachedData = (List<Kline>) redisTemplate.opsForValue().get(redisKey);
            //if (cachedData != null) {
            //    log.debug("从Redis获取K线数据: {}", redisKey);
            //    future.complete(cachedData);
            //    return future;
            //}
 
            // 转换interval字符串为CandleData.Interval枚举
            CandleData.Interval candleInterval = parseInterval(interval);
 
            // 订阅K线数据
            klineApi.subscribeCandles(symbol, candleInterval, candleData -> {
                try {
                    List<Kline> klines = candleData.getKlines();
                    if (klines != null && !klines.isEmpty()) {
                        // 将数据保存到Redis(设置5分钟过期)
                        //redisTemplate.opsForValue().set(redisKey, klines, 5, TimeUnit.MINUTES);
                        log.debug("更新K线数据到Redis: {}", redisKey);
 
                        // 完成Future并清理资源
                        future.complete(klines);
                        //这里不再调用cleanup(),而是创建新的连接实例\
                        klineApi.cleanup();
                        klineApi.setup().get();
                    }
                } catch (Exception e) {
                    future.completeExceptionally(e);
                    log.error("处理K线数据失败: " + symbol, e);
                }
            });
 
        } catch (Exception e) {
            future.completeExceptionally(e);
            log.error("订阅K线数据失败: " + symbol, e);
        }
        return future;
    }
 
    private CandleData.Interval parseInterval(String interval) {
        // 根据传入的interval字符串返回对应的枚举值
        switch (interval.toUpperCase()) {
            case "1D":
                return CandleData.Interval.DAY_1;
            case "5D":
                return CandleData.Interval.DAY_5;
            case "1W":
                return CandleData.Interval.WEEK_1;
            case "1M":
                return CandleData.Interval.MONTH_1;
            case "6M":
                return CandleData.Interval.MONTH_6;
            case "YTD":
                return CandleData.Interval.YEAR_THIS;
            case "12M":
                return CandleData.Interval.YEAR_1;
            case "60M":
                return CandleData.Interval.YEAR_5;
            default:
                return CandleData.Interval.ALL;
        }
    }
 
    //@PreDestroy
    public void cleanup() {
        try {
            // 清理所有活跃的订阅
            activeSubscriptions.forEach((symbols, subscriptions) -> {
                for (TickerSubscription subscription : subscriptions) {
                    try {
                        //移除所有监听器
                        List<UpdateListener> updateListeners = subscription.getUpdateListeners();
                        for (UpdateListener updateListener : updateListeners) {
                            subscription.removeUpdateListener(updateListener);
                        }
                    } catch (Exception e) {
                        log.error("清理订阅失败: " + subscription.getSimpleOrProName(), e);
                    }
                }
            });
            activeSubscriptions.clear();
 
            // 关闭行情线程池
            marketExecutor.shutdown();
            if (!marketExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                marketExecutor.shutdownNow();
            }
 
            // 关闭K线线程池
            klineExecutor.shutdown();
            if (!klineExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                klineExecutor.shutdownNow();
            }
 
            // 清理API资源
            marketApi.cleanup();
            klineApi.cleanup();
            log.info("TradingView服务清理完成");
        } catch (Exception e) {
            log.error("清理资源失败", e);
            marketExecutor.shutdownNow();
            klineExecutor.shutdownNow();
        }
    }
}