1
zyy3
2025-11-05 0426160a1f283c1f810e3059f6037676da8cb110
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
package com.yami.trading.admin.task;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.yami.trading.admin.util.us.HttpClientRequest;
import com.yami.trading.admin.util.us.ReponseBase;
import com.yami.trading.bean.data.domain.Realtime;
import com.yami.trading.bean.item.domain.Item;
import com.yami.trading.bean.model.StockRealTimeBean;
import com.yami.trading.common.constants.RedisKeys;
import com.yami.trading.common.util.RedisUtil;
import com.yami.trading.huobi.data.DataCache;
import com.yami.trading.huobi.websocket.constant.enums.EStockType;
import com.yami.trading.service.item.ItemService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
 
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
 
 
@Component
public class StockTask {
    private static final Logger log = LoggerFactory.getLogger(StockTask.class);
 
    private final AtomicBoolean syncINStockData = new AtomicBoolean(false);
 
    private final Lock syncINStockDataLock = new ReentrantLock();
 
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
 
    @Autowired
    ItemService itemService;
 
    /**
     * 同步系统所需要的股票
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void syncINStockData() {
 
        if (syncINStockData.get()) { // 判断任务是否在处理中
            return;
        }
        if (syncINStockDataLock.tryLock()) {
            try {
                syncINStockData.set(true);
 
                // 1. 定义需要处理的所有股票类型(集中管理,新增类型只需添加到列表)
                List<EStockType> stockTypes = Arrays.asList(
                        EStockType.US
                );
 
                // 2. 批量创建所有异步任务
                List<CompletableFuture<Void>> futures = new ArrayList<>();
                for (EStockType type : stockTypes) {
                    // 添加loadAllStock任务
                    futures.add(CompletableFuture.runAsync(() -> loadAllStock(type), taskExecutor));
                }
 
                // 3. 等待所有任务完成(将List转换为数组传入allOf)
                CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            } catch (Exception e) {
                log.error("同步股票数据出错", e);
            } finally {
                syncINStockDataLock.unlock();
                syncINStockData.set(false);
            }
        }
    }
 
    /**
     * 加载所有股票数据
     */
    public void loadAllStock(EStockType eStockType) {
        log.info("同步股票 数据 {}", eStockType.getCode());
        List<StockRealTimeBean> list = new ArrayList<>();
        int totleStock = 1;
        int page = 0;
        try {
            while (totleStock > list.size()) {
                try {
                    String result = HttpClientRequest.doGet(eStockType.stockUrl + "list?country_id=" + eStockType.getContryId() + "&size=100000&page=" + page + "&key=" + eStockType.stockKey);
                    ReponseBase reponseBase = new Gson().fromJson(result, ReponseBase.class);
                    list.addAll(reponseBase.getData());
                    page++;
                    totleStock = reponseBase.getTotal();
                } catch (Exception e) {
                    e.printStackTrace();
                    break;
                }
            }
            if (list.isEmpty()) {
                return;
            }
            List<String> stockCodeList = list.stream().map(StockRealTimeBean::getId).collect(Collectors.toList());
            List<Item> stockList = itemService.list(new QueryWrapper<Item>()
                            .eq("type", Item.US_STOCKS).in("stock_code", stockCodeList));
 
            List<Item> indicesList = itemService.list(new QueryWrapper<Item>()
                    .eq("type", Item.indices));
 
            log.info("同步股票 已有数据 {} 获取数据 {}", stockList.size(), list.size());
            System.out.println(stockList);
            List<Item> updateStockList = new ArrayList<>();
            for (StockRealTimeBean o : list) {
                //System.out.println(o);
                Item item = stockList.stream()
                        .filter(x -> x.getSymbol().equals(o.getSymbol()) &&
                                x.getStockCode().equals(o.getId()))
                        .findFirst()
                        .orElse(null);
                if (item != null) {  //已有不添加
                    continue;
                }
                item = indicesList.stream()
                        .filter(x -> x.getSymbol().equals(o.getSymbol()))
                        .findFirst()
                        .orElse(null);
                if (item != null) {  //已有不添加
                    continue;
                }
 
                item = new Item();
                String name = StringUtils.trim(o.getName());
                item.setEnName(name);
                item.setName(name);
                item.setSymbolFullName(name);
                item.setSymbol(o.getSymbol());
                item.setSymbolData(o.getSymbol());
                item.setPips(BigDecimal.valueOf(0.01).doubleValue());
                item.setPipsAmount(BigDecimal.valueOf(0.02).doubleValue());
                item.setAdjustmentValue(BigDecimal.ZERO.doubleValue());
                item.setUnitAmount(BigDecimal.valueOf(1000).doubleValue());
                item.setUnitFee(BigDecimal.valueOf(30).doubleValue());
                item.setMarket("FOREVER");
                item.setDecimals(2);
                item.setMultiple(BigDecimal.ZERO.doubleValue());
                item.setBorrowingRate(BigDecimal.ZERO.doubleValue());
                item.setDelFlag(0);
                item.setType(Item.US_STOCKS);
                item.setCategory(Item.US_STOCKS);
                item.setSorted("100");
                item.setOpenCloseType(Item.US_STOCKS);
                item.setFake("0");
                item.setShowStatus("1");
                item.setTradeStatus("1");
                item.setQuoteCurrency("USDT");
                item.setCrawlStatus("default_active");
                item.setStockCode(o.getId());
 
                updateStockList.add(item);
 
 
                Realtime realtime = new Realtime();
                realtime.setUuid(o.getId());
                realtime.setSymbol(o.getSymbol());
                realtime.setName(o.getName());
                realtime.setClose(new BigDecimal(o.getLast().trim()).doubleValue());
                realtime.setLow(new BigDecimal(o.getLow().trim()).doubleValue());
                realtime.setHigh(new BigDecimal(o.getHigh().trim()).doubleValue());
                realtime.setOpen(new BigDecimal(o.getOpen().trim()).doubleValue());
                realtime.setPrevClose(new BigDecimal(o.getPrevClose().trim()).doubleValue());
                realtime.setTs(Long.valueOf(o.getTime() + "000"));
                realtime.setVolume(new BigDecimal(o.getVolume().trim()).doubleValue());
                realtime.setNetChange(new BigDecimal(o.getChg().trim()).doubleValue());
                realtime.setChangeRatio(new BigDecimal(o.getChgPct()).doubleValue());
                realtime.setType(o.getType());
                realtime.setBid(new BigDecimal(o.getBid()).doubleValue());
                realtime.setAsk(new BigDecimal(o.getAsk()).doubleValue());
 
                DataCache.putRealtime(realtime.getSymbol(), realtime);
            }
            if (!updateStockList.isEmpty()) {
                itemService.saveOrUpdateBatch(updateStockList);
            }
            log.info("同步股票 数据 成功 {}  总共同步数据 {}", eStockType.getCode(), updateStockList.size());
        } catch (
                Exception e) {
            log.error("同步出错", e);
        }
    }
 
    public static void main(String[] args) {
        StockTask task = new StockTask();
        task.loadAllStock(EStockType.US);
    }
}