1
zyy
2026-03-16 7ff42a6a92785f26a2b973323443e2eed1e460c2
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
package com.yami.trading.huobi.tradingview.api;
 
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Splitter;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
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 java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
 
public class TradingViewAPI {
    private final Map<String, Set<TickerSubscription>> subscriptionMap = new HashMap<>();
    private final Map<String, Set<Consumer<CandleData>>> candleSubscriptions = new HashMap<>();
    private final TradingViewWebSocket ws = new TradingViewWebSocket();
 
    //价格缓存,避免更新实时价格的时候,错位
    private static final Cache<String, TickerData> cache = CacheBuilder.newBuilder()
            .maximumSize(20000)  // 设置最大缓存大小为100条
            .build();
 
    public CompletableFuture<Void> setup() {
        ws.setDataHandler(event -> {
            if (!"ok".equals(event.status)) {
                return;
            }
 
            // 处理实时报价数据
            if (event.data.has("lp")) {
                Set<TickerSubscription> subs = subscriptionMap.get(event.simpleOrProName);
                if (subs != null) {
                    subs.removeIf(s -> {
                        if (s.isCanBeDestroyed()) {
                            s.setDestroyed(true);
                            if (subs.isEmpty()) {
                                ws.unregisterSymbol(s.getSimpleOrProName());
                                subscriptionMap.remove(s.getSimpleOrProName());
                            }
                            return true;
                        }
                        s.updateData(convertToTickerData(event.simpleOrProName,event.data));
                        return false;
                    });
                }
            }
 
            // 处理K线数据
            if (event.simpleOrProName.contains("cs_")) {
                JsonNode candleNode = event.data;
 
                for (Map.Entry<String, Set<Consumer<CandleData>>> entry : candleSubscriptions.entrySet()) {
                    String symbol = entry.getKey();
                    Set<Consumer<CandleData>> listeners = entry.getValue();
 
                    // 遍历每个监听器并触发
                    for (Consumer<CandleData> listener : listeners) {
                        CandleData candle = convertToCandleData(symbol, candleNode);
                        listener.accept(candle);
                    }
 
                }
            }
        });
        return ws.connect();
    }
 
    public void cleanup() {
        ws.disconnect();
    }
 
    public CompletableFuture<TickerSubscription> getTicker(String simpleOrProName) {
        Set<TickerSubscription> tickers = subscriptionMap.get(simpleOrProName);
        if (tickers != null && !tickers.isEmpty()) {
            return CompletableFuture.completedFuture(tickers.iterator().next());
        }
 
        TickerSubscription ticker = new TickerSubscription(this, simpleOrProName);
        return ticker.fetch().thenApply(v -> ticker);
    }
 
    /**
     * 支持多产品订阅
     * @return
     */
    public CompletableFuture<TickerSubscription> getTickers(String simpleOrProName) {
        Set<TickerSubscription> tickers = subscriptionMap.get(simpleOrProName);
        if (tickers != null && !tickers.isEmpty()) {
            return CompletableFuture.completedFuture(tickers.iterator().next());
        }
 
        TickerSubscription ticker = new TickerSubscription(this, simpleOrProName);
        return ticker.fetch().thenApply(v -> ticker);
    }
 
    public CompletableFuture<Void> ensureRegistered(TickerSubscription ticker) {
        Set<TickerSubscription> tickers = subscriptionMap.get(ticker.getSimpleOrProName());
        if (tickers != null && tickers.contains(ticker)) {
            return CompletableFuture.completedFuture(null);
        }
 
        CompletableFuture<Void> future = new CompletableFuture<>();
 
        final UpdateListener onUpdate = new UpdateListener() {
            @Override
            public void onUpdate(TickerData data) {
                if (data.getProName() == null) {
                    return;
                }
                ticker.removeUpdateListener(this);
                future.complete(null);
            }
        };
 
        ticker.addUpdateListener(onUpdate);
 
        if (tickers == null) {
            tickers = new HashSet<>();
            //设置多产品订阅回调
            List<String> symbols = Splitter.on(",").trimResults().splitToList(ticker.getSimpleOrProName());
            for (String symbol : symbols) {
                subscriptionMap.put(symbol, tickers);
            }
        }
 
        tickers.add(ticker);
 
        //数字货币用
        //ws.registerSymbol(ticker.getSimpleOrProName())
        //        .orTimeout(3000, TimeUnit.MILLISECONDS)
        //        .exceptionally(ex -> {
        //            ticker.removeUpdateListener(onUpdate);
        //            future.completeExceptionally(new RuntimeException("Registration timed out"));
        //            return null;
        //        });
 
        //最新接口
        //ws.registerSymbolV2(ticker.getSimpleOrProName())
        //        .orTimeout(3000, TimeUnit.MILLISECONDS)
        //        .exceptionally(ex -> {
        //            ticker.removeUpdateListener(onUpdate);
        //            future.completeExceptionally(new RuntimeException("Registration timed out"));
        //            return null;
        //        });
 
        //jdk8
        try {
            CompletableFuture.supplyAsync(() -> {
                        try {
                            return ws.registerSymbolV2(ticker.getSimpleOrProName());
                        } catch (Exception e) {
                            throw new CompletionException(e);
                        }
                    }).get(3000, TimeUnit.MILLISECONDS)
                    .exceptionally(ex -> {
                        ticker.removeUpdateListener(onUpdate);
                        future.completeExceptionally(new RuntimeException("Registration timed out"));
                        return null;
                    });
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        }
 
        return future;
    }
 
    public CompletableFuture<Void> subscribeCandles(String symbol, CandleData.Interval interval,
                                                    Consumer<CandleData> listener) {
        String subscriptionKey = symbol + "_" + interval;
        Set<Consumer<CandleData>> listeners = candleSubscriptions.computeIfAbsent(subscriptionKey,
                k -> new HashSet<>());
        listeners.add(listener);
 
        return ws.subscribeCandles(symbol, interval);
    }
 
    public void unsubscribeCandles(String symbol, CandleData.Interval interval, Consumer<CandleData> listener) {
        String subscriptionKey = symbol + "_" + interval.getCode();
        Set<Consumer<CandleData>> listeners = candleSubscriptions.get(subscriptionKey);
        if (listeners != null) {
            listeners.remove(listener);
            if (listeners.isEmpty()) {
                candleSubscriptions.remove(subscriptionKey);
                ws.unsubscribeCandles(symbol, interval);
            }
        }
    }
 
    private TickerData convertToTickerData(String proName,JsonNode data) {
        TickerData tickerData = new TickerData();
        if(Objects.nonNull(proName)){
            tickerData.setProName(proName);
        }
        if (data.has("pro_name"))
            tickerData.setProName(data.get("pro_name").asText());
 
        if (data.has("short_name")) {
            tickerData.setShortName(data.get("short_name").asText());
        } else {
            //兼容 价格跟币种错位问题
            //FX_IDC:USDJPY
            String result = proName.substring(proName.indexOf(":") + 1);
            tickerData.setShortName(result);
        }
 
        if (data.has("exchange"))
            tickerData.setExchange(data.get("exchange").asText());
        else
            tickerData.setExchange(cache.getIfPresent(proName).getExchange());
 
        if (data.has("description"))
            tickerData.setDescription(data.get("description").asText());
        else
            tickerData.setDescription(cache.getIfPresent(proName).getDescription());
 
        if (data.has("type"))
            tickerData.setType(data.get("type").asText());
        else
            tickerData.setType(cache.getIfPresent(proName).getType());
 
        if (data.has("lp"))
            tickerData.setLastPrice(data.get("lp").asDouble());
        else
            tickerData.setLastPrice(cache.getIfPresent(proName).getLastPrice());
 
        if (data.has("ch"))
            tickerData.setChange(data.get("ch").asDouble());
        else
            tickerData.setChange(cache.getIfPresent(proName).getChange() == null ? 0 : cache.getIfPresent(proName).getChange());
 
        if (data.has("chp"))
            tickerData.setChangePercent(data.get("chp").asDouble());
        else
            tickerData.setChangePercent(cache.getIfPresent(proName).getChangePercent() == null ? 0 : cache.getIfPresent(proName).getChangePercent());
 
        if (data.has("volume"))
            tickerData.setVolume(data.get("volume").asLong());
        else
            tickerData.setVolume(cache.getIfPresent(proName).getVolume());
 
        // 新增字段
        if (data.has("open_price"))
            tickerData.setOpen(data.get("open_price").asDouble());
        else
            tickerData.setOpen(cache.getIfPresent(proName).getOpen());
 
        if (data.has("high_price"))
            tickerData.setHigh(data.get("high_price").asDouble());
        else
            tickerData.setHigh(cache.getIfPresent(proName).getHigh());
 
        if (data.has("low_price"))
            tickerData.setLow(data.get("low_price").asDouble());
        else
            tickerData.setLow(cache.getIfPresent(proName).getLow());
 
        if (data.has("prev_close_price"))
            tickerData.setPrevClose(data.get("prev_close_price").asDouble());
        else
            tickerData.setPrevClose(cache.getIfPresent(proName).getPrevClose());
 
        //首次数据写入缓存
        if(data.has("open_price") && data.has("high_price") && data.has("low_price") && data.has("prev_close_price")){
            cache.put(proName,tickerData);
        }
 
 
        return tickerData;
    }
 
    private CandleData convertToCandleData(String symbol, JsonNode rootNode) {
        CandleData candle = new CandleData();
        candle.setSymbol(symbol);
 
        List<Kline> kLineList = new ArrayList<>();
        // 解析JSON数组
        for (JsonNode node : rootNode) {
            long index = node.get("i").asLong();
            JsonNode valuesNode = node.get("v");
            long timestamp = valuesNode.get(0).asLong() * 1000;
            double open = valuesNode.get(1).asDouble();
            double high = valuesNode.get(2).asDouble();
            double low = valuesNode.get(3).asDouble();
            double close = valuesNode.get(4).asDouble();
            double volume = null != valuesNode.get(5) ? valuesNode.get(5).asDouble() : 0.00;  // 如果有成交量的话
 
            // 封装成K线数据对象
            Kline kLine = new Kline(index,timestamp, open, high, low, close, volume);
            kLineList.add(kLine);
        }
        candle.setKlines(kLineList);
        return candle;
    }
}