新版仿ok交易所-后端
1
zj
2025-06-18 2ee9dbc37cbe186e98e5ca458033ba517b981d0d
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
package com.yami.trading.service.etf;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Tuple;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.yami.trading.bean.data.domain.Depth;
import com.yami.trading.bean.data.domain.DepthEntry;
import com.yami.trading.bean.data.domain.Kline;
import com.yami.trading.bean.data.domain.Realtime;
import com.yami.trading.bean.etf.domain.EtfMinuteKLine;
import com.yami.trading.bean.item.domain.Item;
import com.yami.trading.common.constants.RedisKeys;
import com.yami.trading.common.exception.YamiShopBindException;
import com.yami.trading.service.data.DataService;
import com.yami.trading.service.item.ItemService;
import com.yami.trading.service.purchasing.ProjectBreedService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
 
/**
 * ETF行情服务
 */
@Service
@Slf4j
@Getter
public class MarketService {
 
    public static final String IXIC = ".IXIC";
    @Autowired
    ItemService itemService;
 
    @Autowired
    KlineConfigService klineConfigService;
 
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private DataService dataService;
    @Autowired
    private EtfMinuteKLineService etfMinuteKLineService;
    // 加速行情
    public Map<String, Double> accelerate = new HashMap<>();
 
    public Map<String, Double> getAccelerate() {
        return accelerate;
    }
 
    private Map<String, LinkedHashMap<Long, Kline>> cacheKline = new ConcurrentHashMap<String, LinkedHashMap<Long, Kline>>();
 
    public Realtime queryRealtime(String symbol) {
 
        Kline kline = querySecKline(symbol);
 
        if (kline == null) {
            //    log.error("current sec market kline not found");
            Realtime realtime = new Realtime();
            realtime.setSymbol(symbol);
            realtime.setName(symbol);
 
            realtime.setTs(0L);
            realtime.setOpen(BigDecimal.ZERO);
            realtime.setClose(BigDecimal.ZERO);
            realtime.setHigh(BigDecimal.ZERO);
            realtime.setLow(BigDecimal.ZERO);
            return realtime;
        }
 
 
        Random random = new Random();
 
 
        Realtime realtime = new Realtime();
        int decimal = itemService.getDecimal(symbol);
        realtime.setSymbol(symbol);
        realtime.setName(symbol);
 
        realtime.setTs(kline.getTs() / 1000);
        realtime.setOpen(kline.getOpen().setScale(decimal, RoundingMode.HALF_UP));
        realtime.setClose(kline.getClose().setScale(decimal, RoundingMode.HALF_UP));
        realtime.setHigh(kline.getHigh().setScale(decimal, RoundingMode.HALF_UP));
        realtime.setLow(kline.getLow().setScale(decimal, RoundingMode.HALF_UP));
//        realtime.setMarketCapital(realtimeJson.getLong("marketCapital"));
//        realtime.setFloatMarketCapital(realtimeJson.getLong("floatMarketCapital"));
//        realtime.setPeForecast(realtimeJson.getBigDecimal("peForecast"));
//        realtime.setVolumeRatio(realtimeJson.getBigDecimal("volumeRatio"));
//        realtime.setTurnoverRate(realtimeJson.getBigDecimal("turnoverRate"));\
 
 
        BigDecimal lastAmount = (BigDecimal) Optional.ofNullable(redisTemplate.opsForHash().get(RedisKeys.SYMBOL_AMOUNT_VOLUME + symbol, "amount")).orElse(BigDecimal.ZERO);
        BigDecimal amount = Optional.of(kline.getAmount()).orElse(BigDecimal.ZERO);
 
        realtime.setAmount(lastAmount.add(amount).setScale(decimal, RoundingMode.HALF_UP));
        BigDecimal lastVolume = (BigDecimal) Optional.ofNullable(redisTemplate.opsForHash().get(RedisKeys.SYMBOL_AMOUNT_VOLUME + symbol, "volume")).orElse(BigDecimal.ZERO);
        BigDecimal volume = Optional.of(kline.getVolume()).orElse(BigDecimal.ZERO);
 
        realtime.setVolume(lastVolume.add(volume).setScale(decimal, RoundingMode.HALF_UP));
        realtime.setAsk(BigDecimal.valueOf(KlineConfigService.randomBigDecimal(realtime.getLow(), realtime.getClose(), random)));
        realtime.setBid(BigDecimal.valueOf(KlineConfigService.randomBigDecimal(realtime.getHigh(), realtime.getClose(), random)));
 
        redisTemplate.opsForHash().put(RedisKeys.SYMBOL_AMOUNT_VOLUME + symbol, "amount", realtime.getAmount());
        redisTemplate.opsForHash().put(RedisKeys.SYMBOL_AMOUNT_VOLUME + symbol, "volume", realtime.getVolume());
        return realtime;
    }
 
    private Kline querySecKline(String symbol) {
        if (cacheKline.size() == 0 || CollectionUtil.isEmpty(cacheKline.get(symbol))) {
            List<Kline> secKlines = klineConfigService.querySecKlineBySymbol(symbol);
 
            secKlines.sort(Comparator.comparing(Kline::getTs));
 
            // secKlines 变成key为时间,value为kline的map
            LinkedHashMap collect = secKlines.stream().collect(Collectors.toMap(k -> k.getTs() / 1000, kline -> kline, (k1, k2) -> k1, LinkedHashMap::new));
 
            if (collect.size() != 0) {
                cacheKline.put(symbol, collect);
                // 一天的秒级k线是23400,取当天最后一秒的数据保存到redis中
                redisTemplate.opsForValue().set(RedisKeys.SYMBOL_DEPTH + symbol, secKlines.size() == 23400 ? secKlines.get(23399) : secKlines.get(secKlines.size() - 1));
            } else {
                // 如果没有数据,跟随纳斯达克大盘
                Kline kline = (Kline) redisTemplate.opsForValue().get(RedisKeys.SYMBOL_DEPTH + symbol);
                if (kline == null) {
                    QueryWrapper<EtfMinuteKLine> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("symbol", symbol);
                    queryWrapper.lt("ts", System.currentTimeMillis());
                    queryWrapper.orderByDesc("ts");
                    queryWrapper.last("limit 1");
                    List<EtfMinuteKLine> list = etfMinuteKLineService.list(queryWrapper);
                    if (CollectionUtil.isNotEmpty(list)) {
                        kline = BeanUtil.copyProperties(list.get(0), Kline.class);
                        kline.setPeriod(Kline.PERIOD_1MIN);
                        kline.setTs(System.currentTimeMillis());
                    } else {
                        return null;
                    }
                }
                Kline retKline = null;
                try {
                    retKline = (Kline) kline.clone();
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                    return retKline;
                }
                retKline.setTs(System.currentTimeMillis());
                List<Realtime> realtimes = dataService.realtime(IXIC);
                if (CollectionUtils.isNotEmpty(realtimes)) {
                    Realtime realtime = realtimes.get(0);
                    BigDecimal ratio = realtime.getClose().divide(realtime.getOpen(), 10, RoundingMode.HALF_UP);
                    BigDecimal close = ratio.multiply(kline.getClose()).setScale(2, RoundingMode.HALF_UP);
                    BigDecimal low = ratio.multiply(kline.getLow()).setScale(2, RoundingMode.HALF_UP);
                    BigDecimal high = ratio.multiply(kline.getHigh()).setScale(2, RoundingMode.HALF_UP);
                    retKline.setClose(close);
                    retKline.setLow(low);
                    retKline.setHigh(high);
                    return retKline;
                }
 
 
            }
 
        }
 
        // 获取到
        long currentSec = System.currentTimeMillis() / 1000;
 
        if (cacheKline.get(symbol) == null) {
            return null;
        }
        Kline kline = cacheKline.get(symbol).get(currentSec);
        return kline;
    }
 
 
    public void clear() {
        cacheKline.clear();
    }
 
 
    public List<Kline> build5min(String symbol) {
 
        // 获取所有的1s的kline
        List<Kline> klines = klineConfigService.querySecKlineBySymbolAllData(symbol);
 
        return convertTo5MinKLine(klines);
    }
 
    public static List<Kline> convertTo5MinKLine(List<Kline> sKLineList) {
 
        List<Kline> fiveMinKLineList = new ArrayList<>();
 
        int currentIndex = 0;
        int dataSize = sKLineList.size();
 
        while (currentIndex < dataSize) {
            Kline currentKLine = sKLineList.get(currentIndex);
            long currentTimestamp = currentKLine.getTs();
            BigDecimal open = currentKLine.getOpen();
            BigDecimal high = currentKLine.getHigh();
            BigDecimal low = currentKLine.getLow();
            BigDecimal close = currentKLine.getClose();
            BigDecimal volume = currentKLine.getVolume();
            BigDecimal amount = currentKLine.getAmount();
 
            long nextTimestamp = currentTimestamp + (5 * 60 * 1000); // 5 minutes in milliseconds
 
            // Find the index of the next KLine that satisfies the 5-minute condition
            int nextIndex = currentIndex + 1;
            while (nextIndex < dataSize && sKLineList.get(nextIndex).getTs() < nextTimestamp) {
                Kline nextKLine = sKLineList.get(nextIndex);
                high = high.max(nextKLine.getHigh());
                low = low.min(nextKLine.getLow());
                volume = volume.add(nextKLine.getVolume());
                amount = amount.add(nextKLine.getAmount());
                close = nextKLine.getClose();
                nextIndex++;
            }
 
            // Create the 5-minute KLine and add it to the list
            Kline fiveMinKLine = new Kline();
            fiveMinKLine.setSymbol(currentKLine.getSymbol());
            fiveMinKLine.setTs(currentTimestamp);
            fiveMinKLine.setOpen(open);
            fiveMinKLine.setHigh(high);
            fiveMinKLine.setLow(low);
            fiveMinKLine.setClose(close);
            fiveMinKLine.setVolume(volume);
            fiveMinKLine.setAmount(amount);
            fiveMinKLineList.add(fiveMinKLine);
 
            currentIndex = nextIndex;
        }
 
        return fiveMinKLineList;
 
    }
 
 
    public Depth queryDepth(String symbol) {
        Depth depth = new Depth();
        depth.setSymbol(symbol);
        depth.setTs(System.currentTimeMillis());
 
 
        Kline kline = querySecKline(symbol);
 
 
        Item item = itemService.findBySymbol(symbol);
 
        if (kline == null || kline.getVolume().doubleValue() == 0) {
            kline = (Kline) redisTemplate.opsForValue().get(RedisKeys.SYMBOL_DEPTH + symbol);
        }
        if (kline == null){
            return depth;
        }
 
        List<BigDecimal> volumeSplit = KlineConfigService.splitData(kline.getVolume().doubleValue(), 10, 10);
 
        DepthEntry buy;
        DepthEntry sell;
 
 
        // 拿到这一秒的挂单数量,怎么分到5档位上
        Random random = new Random();
 
        for (int i = 0; i < 5; i++) {
 
            double enlarge = 1;
 
            if (accelerate.get(symbol) != null) {
                enlarge = accelerate.get(symbol);
            }
 
            buy = new DepthEntry();
            // 买
            BigDecimal.valueOf(KlineConfigService.randomBigDecimal(kline.getLow(), kline.getClose(), random)).setScale(item.getDecimals(), RoundingMode.HALF_UP).doubleValue();
            buy.setPrice(BigDecimal.valueOf(KlineConfigService.randomBigDecimal(kline.getLow(), kline.getClose(), random)).setScale(item.getDecimals(), RoundingMode.HALF_UP).doubleValue());
            buy.setAmount(enlarge * volumeSplit.get(i).setScale(item.getDecimals(), RoundingMode.HALF_UP).doubleValue());
 
            // 卖
            sell = new DepthEntry();
            sell.setPrice(BigDecimal.valueOf(KlineConfigService.randomBigDecimal(kline.getHigh(), kline.getClose(), random)).setScale(item.getDecimals(), RoundingMode.HALF_UP).doubleValue());
 
            sell.setAmount(enlarge * volumeSplit.get(i + 5).setScale(item.getDecimals(), RoundingMode.HALF_UP).doubleValue());
 
 
            depth.getAsks().add(sell);
            depth.getBids().add(buy);
        }
 
        depth.getBids().sort(Comparator.comparing(DepthEntry::getPrice).reversed());
        depth.getAsks().sort(Comparator.comparing(DepthEntry::getPrice));
        return depth;
    }
 
 
}