Jelajahi Sumber

update:watchlist赛道分类显示优化v1

lvzhiqiang 1 tahun lalu
induk
melakukan
22150153eb

+ 2 - 2
src/main/java/top/lvzhiqiang/entity/CoinWatchlist.java

@@ -89,9 +89,9 @@ public class CoinWatchlist implements Serializable {
     private Integer issuingDays;
 
     /**
-     * 采集URL
+     * coingeckoId
      */
-    private String collectUrl;
+    private String coingeckoId;
 
     /**
      * 排序

+ 112 - 70
src/main/java/top/lvzhiqiang/service/impl/CoinServiceImpl.java

@@ -24,6 +24,7 @@ import top.lvzhiqiang.config.InitRunner;
 import top.lvzhiqiang.config.WorkWeixinProperties;
 import top.lvzhiqiang.entity.*;
 import top.lvzhiqiang.exception.BusinessException;
+import top.lvzhiqiang.mapper.CoinApiConfigMapper;
 import top.lvzhiqiang.mapper.CoinMapper;
 import top.lvzhiqiang.service.CoinService;
 import top.lvzhiqiang.util.*;
@@ -101,6 +102,9 @@ public class CoinServiceImpl implements CoinService {
 
     private static final WxCpServiceImpl wxCpService4News;
 
+    @Resource
+    private CoinApiConfigMapper coinApiConfigMapper;
+
     static {
         // API KEY作为一个字符串。
         basicHeaderMap.put("ACCESS-KEY", "bg_433d37306df0e8901c6d107c6d9e9111");
@@ -790,20 +794,81 @@ public class CoinServiceImpl implements CoinService {
             params.put("sort", "desc");
             List<CoinWatchlist> watchlistList = coinMapper.findWatchlistList(params);
 
-            Map<Long, CoinWatchlist> watchlistMap4CmC = new HashMap<>();
-            for (CoinWatchlist coinWatchlist : watchlistList) {
-                try {
-                    Thread.sleep(5000L);
-                } catch (InterruptedException e) {
-                    throw new RuntimeException(e);
+            Map<String, CoinWatchlist> coinWatchlistMap4CoingeckoId = watchlistList.stream().collect(Collectors.toMap(CoinWatchlist::getCoingeckoId, coinWatchlist -> coinWatchlist));
+            parseWatchlistMap4Coingecko(coinWatchlistMap4CoingeckoId);
+
+            Map<Long, CoinWatchlist> coinWatchlistMap4CmcId = coinWatchlistMap4CoingeckoId.values().stream().collect(Collectors.toMap(CoinWatchlist::getCmcId, coinWatchlist -> coinWatchlist));
+            parseWatchlistMap4CmC(coinWatchlistMap4CmcId);
+        }, 0, 1, TimeUnit.HOURS);
+
+        // Upbit交易所监控报警
+        scheduler.scheduleWithFixedDelay(() -> {
+            try {
+                Map<String, String> paramMap = new HashMap<>();
+                paramMap.put("page", "1");
+                paramMap.put("per_page", "20");
+                paramMap.put("thread_name", "general");
+                Connection.Response response = JsoupUtil.requestBody("https://api-manager.upbit.com/api/v1/notices", JsoupUtil.HTTP_GET, InitRunner.proxy, null, paramMap);
+                JSONObject result = JSONObject.parseObject(response.body());
+                JSONArray noticeList = result.getJSONObject("data").getJSONArray("list");
+
+                for (int i = 0; i < noticeList.size(); i++) {
+                    if (i == 5) {
+                        break;
+                    }
+
+                    JSONObject notice = noticeList.getJSONObject(i);
+                    String idOri = notice.getString("id");
+                    String id = "Upbit" + idOri;
+                    String title = notice.getString("title");
+                    if (title.contains("New digital asset on KRW Market") && !orderMap.containsKey(id)) {
+                        orderMap.put(id, "1");
+
+                        String createTime = notice.getString("created_at");
+                        String updateTime = notice.getString("updated_at");
+                        String viewCount = notice.getString("view_count");
+
+                        JSONObject params = new JSONObject();
+                        params.put("title", "Upbit监控报警");
+                        params.put("btnTxt", "通知详情");
+                        params.put("logUrl", "https://sg-api-manager.upbit.com/api/v1/notices/" + idOri);
+                        // 文本卡片
+                        String contentStr = "<div class=\"highlight\">标题:" + title + "</div>" +
+                                "<div>发布时间:" + createTime + "</div>" +
+                                "<div>更新时间:" + updateTime + "</div>" +
+                                "<div class=\"gray\">查看次数:" + viewCount + "</div>";
+
+                        SpringUtils.getBean(CoinServiceImpl.class).monitorAlarm4APP_TEXT_CARD(contentStr, params, null);
+                    }
                 }
+            } catch (Exception e) {
+            }
+        }, 0, 3, TimeUnit.SECONDS);
 
-                watchlistMap4CmC.put(coinWatchlist.getCmcId(), coinWatchlist);
-                try {
-                    Connection.Response response = JsoupUtil.requestBody(coinWatchlist.getCollectUrl(), JsoupUtil.HTTP_GET, InitRunner.proxy, new HashMap<>(), new HashMap<>());
-                    JSONObject jsonObject = JSONObject.parseObject(response.body());
+        return null;
+    }
+
+    public void parseWatchlistMap4Coingecko(Map<String, CoinWatchlist> watchlistMap4Coingecko) {
+        String coingeckoCoinsMarketsUrl = InitRunner.dicCodeMap.get("coingecko_coins_markets_url").getCodeValue();
+        Map<String, String> headerMap = new HashMap<>();
+        headerMap.put("Accept", "application/json");
+        headerMap.put("Accept-Encoding", "deflate,gzip");
+
+        Map<String, String> paramMap = new LinkedHashMap<>();
+        paramMap.put("ids", StringUtils.join(watchlistMap4Coingecko.keySet(), ","));
+        paramMap.put("vs_currency", "usd");
+        AtomicInteger i = new AtomicInteger();
+        try {
+            Connection.Response response = JsoupUtil.requestBody(coingeckoCoinsMarketsUrl, JsoupUtil.HTTP_GET, InitRunner.proxy, headerMap, paramMap);
+            JSONArray result = JSONArray.parseArray(response.body());
+
+            for (int j = 0; j < result.size(); j++) {
+                JSONObject marketData = result.getJSONObject(j);
+                String id = marketData.getString("id");
+
+                if (watchlistMap4Coingecko.containsKey(id)) {
+                    CoinWatchlist coinWatchlist = watchlistMap4Coingecko.get(id);
 
-                    JSONObject marketData = jsonObject.getJSONObject("market_data");
                     // 总市值排名
                     if (marketData.containsKey("market_cap_rank") && null != marketData.get("market_cap_rank")) {
                         Integer totalMarketRanking = marketData.getInteger("market_cap_rank");
@@ -812,37 +877,37 @@ public class CoinServiceImpl implements CoinService {
 
                     // 总市值
                     if (marketData.containsKey("market_cap") && null != marketData.get("market_cap")) {
-                        BigDecimal totalMarketValue = marketData.getJSONObject("market_cap").getBigDecimal("usd");
+                        BigDecimal totalMarketValue = marketData.getBigDecimal("market_cap").setScale(2, RoundingMode.HALF_UP);
                         coinWatchlist.setTotalMarketValue(totalMarketValue);
                     }
 
                     // 市场价格
                     if (marketData.containsKey("current_price") && null != marketData.get("current_price")) {
-                        String markPrice = marketData.getJSONObject("current_price").getString("usd");
+                        String markPrice = marketData.getBigDecimal("current_price").toPlainString();
                         coinWatchlist.setMarkPrice(markPrice);
                     }
 
                     // 历史最高价格
                     if (marketData.containsKey("ath") && null != marketData.get("ath")) {
-                        String highestHistoricalPrice = marketData.getJSONObject("ath").getString("usd");
+                        String highestHistoricalPrice = marketData.getBigDecimal("ath").toPlainString();
                         coinWatchlist.setHighestHistoricalPrice(highestHistoricalPrice);
                     }
 
                     // 历史最高日期
                     if (marketData.containsKey("ath_date") && null != marketData.get("ath_date")) {
-                        LocalDate highestHistoricalDate = LocalDate.parse(marketData.getJSONObject("ath_date").getString("usd"), DateUtils.utcTimeFormatter);
+                        LocalDate highestHistoricalDate = LocalDate.parse(marketData.getString("ath_date"), DateUtils.utcTimeFormatter);
                         coinWatchlist.setHighestHistoricalDate(highestHistoricalDate);
                     }
 
                     // 历史最低价格
                     if (marketData.containsKey("atl") && null != marketData.get("atl")) {
-                        String lowestHistoricalPrice = marketData.getJSONObject("atl").getString("usd");
+                        String lowestHistoricalPrice = marketData.getBigDecimal("atl").toPlainString();
                         coinWatchlist.setLowestHistoricalPrice(lowestHistoricalPrice);
                     }
 
                     // 历史最低日期
                     if (marketData.containsKey("atl_date") && null != marketData.get("atl_date")) {
-                        LocalDate lowestHistoricalDate = LocalDate.parse(marketData.getJSONObject("atl_date").getString("usd"), DateUtils.utcTimeFormatter);
+                        LocalDate lowestHistoricalDate = LocalDate.parse(marketData.getString("atl_date"), DateUtils.utcTimeFormatter);
                         coinWatchlist.setLowestHistoricalDate(lowestHistoricalDate);
                     }
 
@@ -860,61 +925,11 @@ public class CoinServiceImpl implements CoinService {
                     }
 
                     coinMapper.updateCoinWatchlist(coinWatchlist);
-                } catch (Exception ex) {
-                    log.error("jsoup CoinWatchlist error,coinWatchlist={}", coinWatchlist, ex);
                 }
             }
-
-            if (watchlistMap4CmC.size() > 0) {
-                parseWatchlistMap4CmC(watchlistMap4CmC);
-            }
-        }, 0, 1, TimeUnit.HOURS);
-
-        // Upbit交易所监控报警
-        scheduler.scheduleWithFixedDelay(() -> {
-            try {
-                Map<String, String> paramMap = new HashMap<>();
-                paramMap.put("page", "1");
-                paramMap.put("per_page", "20");
-                paramMap.put("thread_name", "general");
-                Connection.Response response = JsoupUtil.requestBody("https://api-manager.upbit.com/api/v1/notices", JsoupUtil.HTTP_GET, InitRunner.proxy, null, paramMap);
-                JSONObject result = JSONObject.parseObject(response.body());
-                JSONArray noticeList = result.getJSONObject("data").getJSONArray("list");
-
-                for (int i = 0; i < noticeList.size(); i++) {
-                    if (i == 5) {
-                        break;
-                    }
-
-                    JSONObject notice = noticeList.getJSONObject(i);
-                    String idOri = notice.getString("id");
-                    String id = "Upbit" + idOri;
-                    String title = notice.getString("title");
-                    if (title.contains("New digital asset on KRW Market") && !orderMap.containsKey(id)) {
-                        orderMap.put(id, "1");
-
-                        String createTime = notice.getString("created_at");
-                        String updateTime = notice.getString("updated_at");
-                        String viewCount = notice.getString("view_count");
-
-                        JSONObject params = new JSONObject();
-                        params.put("title", "Upbit监控报警");
-                        params.put("btnTxt", "通知详情");
-                        params.put("logUrl", "https://sg-api-manager.upbit.com/api/v1/notices/" + idOri);
-                        // 文本卡片
-                        String contentStr = "<div class=\"highlight\">标题:" + title + "</div>" +
-                                "<div>发布时间:" + createTime + "</div>" +
-                                "<div>更新时间:" + updateTime + "</div>" +
-                                "<div class=\"gray\">查看次数:" + viewCount + "</div>";
-
-                        SpringUtils.getBean(CoinServiceImpl.class).monitorAlarm4APP_TEXT_CARD(contentStr, params, null);
-                    }
-                }
-            } catch (Exception e) {
-            }
-        }, 0, 3, TimeUnit.SECONDS);
-
-        return null;
+        } catch (Exception e) {
+            log.error("parseWatchlistMap4Coingecko error,size={},i={}", watchlistMap4Coingecko.size(), i.get(), e);
+        }
     }
 
     public void parseWatchlistMap4CmC(Map<Long, CoinWatchlist> watchlistMap4CmC) {
@@ -1311,6 +1326,25 @@ public class CoinServiceImpl implements CoinService {
 
     private void renderMainSearch4Watchlist(List<CoinWatchlist> watchlistList) {
         BigDecimal bigDecimal10000 = new BigDecimal("10000");
+
+        List<String> trackCategoryList = coinApiConfigMapper.findTrackCategoryList();
+        Map<String, String> trackCategoryMap = new HashMap<>();
+        List<String> colorList = new ArrayList<>();
+        colorList.add("background-color: rgba(253, 236, 200, 1);");
+        colorList.add("background-color: rgba(219, 237, 219, 1);");
+        colorList.add("background-color: rgba(250, 222, 201, 1);");
+        colorList.add("background-color: rgba(245, 224, 233, 1);");
+        colorList.add("background-color: rgba(211, 229, 239, 1);");
+        colorList.add("background-color: rgba(238, 224, 218, 1);");
+        colorList.add("background-color: rgba(255, 226, 221, 1);");
+        int j = 0;
+        for (int i = 0; i < trackCategoryList.size(); i++) {
+            if (j > colorList.size() - 1) {
+                j = 0;
+            }
+            trackCategoryMap.put(trackCategoryList.get(i), colorList.get(j));
+            j++;
+        }
         for (CoinWatchlist coinWatchlist : watchlistList) {
             if (null != coinWatchlist.getTotalMarketValue()) {
                 BigDecimal divide = coinWatchlist.getTotalMarketValue().divide(bigDecimal10000, 8, RoundingMode.HALF_UP);
@@ -1321,6 +1355,14 @@ public class CoinServiceImpl implements CoinService {
                     coinWatchlist.setTotalMarketValueStr(divide + "亿");
                 }
             }
+
+            // 赛道分类
+            String[] trackCategoryArr = coinWatchlist.getTrackCategory().split(",");
+            StringBuffer sb = new StringBuffer();
+            for (String trackCategory : trackCategoryArr) {
+                sb.append("<span class=\"selected-value\" style=\" " + trackCategoryMap.get(trackCategory) + " \" >" + trackCategory + " </span>");
+            }
+            coinWatchlist.setTrackCategory(sb.toString());
         }
     }
 

+ 11 - 0
src/main/resources/static/coin.html

@@ -69,6 +69,17 @@
         left: 50%;
         transform: translate(-50%, -25%);
     }
+
+    .selected-value {
+        display: inline-block;
+        padding: 0 0.5em;
+        background: rgba(206, 205, 202, 0.5);
+        border-radius: 3px;
+        margin-right: 0.3em;
+        margin-top: 0.1em;
+        margin-bottom: 0.1em;
+        white-space: nowrap;
+    }
 </style>
 <script type="text/javascript">
     function show() {

+ 2 - 2
src/main/resources/static/js/my-coin.js

@@ -10,7 +10,7 @@ $(function () {
 });
 
 
-var dragJob=false;
+/*var dragJob=false;
 $(document).on("mousedown", '.watchlistpreview-top', function (e) {
     dragJob = true;
 });
@@ -34,7 +34,7 @@ document.onmousemove = function (e) {
 };
 $(document).mouseup(function (e) {
     dragJob = false;
-});
+});*/
 
 /**
  * 初始化其他操作

+ 7 - 81
src/test/java/top/lvzhiqiang/TestCoin.java

@@ -1,8 +1,8 @@
 package top.lvzhiqiang;
 
+import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import lombok.extern.slf4j.Slf4j;
-import org.jsoup.Connection;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.springframework.boot.test.context.SpringBootTest;
@@ -11,17 +11,9 @@ import top.lvzhiqiang.entity.CoinWatchlist;
 import top.lvzhiqiang.mapper.CoinMapper;
 import top.lvzhiqiang.service.CoinService;
 import top.lvzhiqiang.util.DateUtils;
-import top.lvzhiqiang.util.JsoupUtil;
-import top.lvzhiqiang.util.StringUtils;
 
 import javax.annotation.Resource;
-import java.math.BigDecimal;
-import java.math.RoundingMode;
-import java.net.InetSocketAddress;
-import java.net.Proxy;
-import java.time.LocalDate;
 import java.time.LocalDateTime;
-import java.time.temporal.ChronoUnit;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -77,79 +69,13 @@ public class TestCoin {
         params.put("sortField", "create_time");
         params.put("sort", "desc");
         List<CoinWatchlist> watchlistList = coinMapper.findWatchlistList(params);
+    }
 
-        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 1080));
-        for (CoinWatchlist coinWatchlist : watchlistList) {
-            try {
-                Thread.sleep(5000L);
-            } catch (InterruptedException e) {
-                throw new RuntimeException(e);
-            }
-
-            try {
-                Connection.Response response = JsoupUtil.requestBody(coinWatchlist.getCollectUrl(), JsoupUtil.HTTP_GET, proxy, new HashMap<>(), new HashMap<>());
-                JSONObject jsonObject = JSONObject.parseObject(response.body());
-
-                JSONObject marketData = jsonObject.getJSONObject("market_data");
-                // 总市值排名
-                if (marketData.containsKey("market_cap_rank") && null != marketData.get("market_cap_rank")) {
-                    Integer totalMarketRanking = marketData.getInteger("market_cap_rank");
-                    coinWatchlist.setTotalMarketRanking(totalMarketRanking);
-                }
-
-                // 总市值
-                if (marketData.containsKey("market_cap") && null != marketData.get("market_cap")) {
-                    BigDecimal totalMarketValue = marketData.getJSONObject("market_cap").getBigDecimal("usd");
-                    coinWatchlist.setTotalMarketValue(totalMarketValue);
-                }
-
-                // 市场价格
-                if (marketData.containsKey("current_price") && null != marketData.get("current_price")) {
-                    String markPrice = marketData.getJSONObject("current_price").getString("usd");
-                    coinWatchlist.setMarkPrice(markPrice);
-                }
-
-                // 历史最高价格
-                if (marketData.containsKey("ath") && null != marketData.get("ath")) {
-                    String highestHistoricalPrice = marketData.getJSONObject("ath").getString("usd");
-                    coinWatchlist.setHighestHistoricalPrice(highestHistoricalPrice);
-                }
-
-                // 历史最高日期
-                if (marketData.containsKey("ath_date") && null != marketData.get("ath_date")) {
-                    LocalDate highestHistoricalDate = LocalDate.parse(marketData.getJSONObject("ath_date").getString("usd"), DateUtils.utcTimeFormatter);
-                    coinWatchlist.setHighestHistoricalDate(highestHistoricalDate);
-                }
-
-                // 历史最低价格
-                if (marketData.containsKey("atl") && null != marketData.get("atl")) {
-                    String lowestHistoricalPrice = marketData.getJSONObject("atl").getString("usd");
-                    coinWatchlist.setLowestHistoricalPrice(lowestHistoricalPrice);
-                }
-
-                // 历史最低日期
-                if (marketData.containsKey("atl_date") && null != marketData.get("atl_date")) {
-                    LocalDate lowestHistoricalDate = LocalDate.parse(marketData.getJSONObject("atl_date").getString("usd"), DateUtils.utcTimeFormatter);
-                    coinWatchlist.setLowestHistoricalDate(lowestHistoricalDate);
-                }
-
-                // 涨幅倍数
-                if (StringUtils.isNotEmpty(coinWatchlist.getHighestHistoricalPrice()) && StringUtils.isNotEmpty(coinWatchlist.getLowestHistoricalPrice())) {
-                    BigDecimal increaseMultiple = new BigDecimal(coinWatchlist.getHighestHistoricalPrice()).divide(new BigDecimal(coinWatchlist.getLowestHistoricalPrice()), 0, RoundingMode.HALF_UP);
-                    coinWatchlist.setIncreaseMultiple(increaseMultiple.intValue());
-                }
-
-                // 发行日期
-                // 发行天数
-                if (coinWatchlist.getIssuingDate() != null) {
-                    long totalDays = ChronoUnit.DAYS.between(coinWatchlist.getIssuingDate(), LocalDate.now());
-                    coinWatchlist.setIssuingDays((int) totalDays);
-                }
+    public static void main(String[] args) {
+        String s = "[{\"id\":\"dogecoin\",\"symbol\":\"doge\",\"name\":\"Dogecoin\",\"image\":\"https://assets.coingecko.com/coins/images/5/large/dogecoin.png?1696501409\",\"current_price\":0.091631,\"market_cap\":13047603006,\"market_cap_rank\":11,\"fully_diluted_valuation\":13047543490,\"total_volume\":460955017,\"high_24h\":0.094371,\"low_24h\":0.090707,\"price_change_24h\":-0.002739353491127444,\"price_change_percentage_24h\":-2.90276,\"market_cap_change_24h\":-405382366.76885605,\"market_cap_change_percentage_24h\":-3.01333,\"circulating_supply\":142498276383.705,\"total_supply\":142497626383.705,\"max_supply\":null,\"ath\":0.731578,\"ath_change_percentage\":-87.46751,\"ath_date\":\"2021-05-08T05:08:23.458Z\",\"atl\":8.69e-05,\"atl_change_percentage\":105401.73855,\"atl_date\":\"2015-05-06T00:00:00.000Z\",\"roi\":null,\"last_updated\":\"2024-01-03T08:51:38.584Z\"}]";
+        JSONArray marketData = JSONArray.parseArray(s);
+        String lowestHistoricalPrice = marketData.getJSONObject(0).getBigDecimal("atl").toEngineeringString();
 
-                coinMapper.updateCoinWatchlist(coinWatchlist);
-            } catch (Exception ex) {
-                ex.printStackTrace();
-            }
-        }
+        System.out.println(lowestHistoricalPrice);
     }
 }