ybf

ybf


1.3币安汇率抓取代码参考

<p>/**</p> <ul> <li> <p>@author */ @Service @Slf4j public class BinanceExchangePrice implements CoinPriceFetchService {</p> <p>private static String BUY = &quot;BUY&quot;; private static String SELL = &quot;SELL&quot;;</p> <p>@Autowired private Environment environment; private int index = 0;</p> <p>private final BaseExchangeRateServiceImpl baseExchangeRateService; private final ExchangeRateCheckService exchangeRateService; private final DisposeRateDataService disposeRateDataService; private final ExchangeRateStatService exchangeRateStatService;</p> <p>@Autowired private CoinDisposeExchangePrice coinDisposeExchangePrice;</p> <p>private final static Map&lt;String, String&gt; HEADERS = buildHeader();</p> <p>@Autowired public BinanceExchangePrice(BaseExchangeRateServiceImpl baseExchangeRateService , ExchangeRateCheckService exchangeRateService,DisposeRateDataService disposeRateDataService,ExchangeRateStatService exchangeRateStatService ) { this.baseExchangeRateService = baseExchangeRateService; this.exchangeRateService = exchangeRateService; this.disposeRateDataService=disposeRateDataService; this.exchangeRateStatService=exchangeRateStatService; }</p> <p>@Override public void fetchPriceJsonAndSave() { /<em>注意,均为大写</em>/ getAndSavePriceInfo(BUY, AssetType.USDT.getSymbol(),AssetType.CNY.getSymbol()); getAndSavePriceInfo(SELL, AssetType.USDT.getSymbol(),AssetType.CNY.getSymbol());</p> <pre><code>getAndSavePriceInfo(BUY, AssetType.BTC.getSymbol(),AssetType.CNY.getSymbol()); getAndSavePriceInfo(SELL, AssetType.BTC.getSymbol(),AssetType.CNY.getSymbol()); /** * 新增USDT-&gt;USD汇率抓取 * @author mortal * @date 2021-12-12 */ getAndSavePriceInfo(BUY,AssetType.USDT.getSymbol(),AssetType.USD.getSymbol()); getAndSavePriceInfo(SELL,AssetType.USDT.getSymbol(),AssetType.USD.getSymbol());</code></pre> <p>}</p> <p>private void parseAndSave(String responseString, AssetType assetType,AssetType priceUnit, ApiInfoEnum apiInfoEnum, RateTradingEnum rateTradingEnum, Integer directionCode, long duration) { BigDecimal price = null; if (StringUtils.isNotBlank(responseString)) { try { JSONArray jsonArray = JSONObject.parseObject(responseString).getJSONArray(&quot;data&quot;); if(Objects.nonNull(jsonArray)&amp;&amp;jsonArray.size()&gt;0){ //获取前20条挂单数据 if(assetType.equals(AssetType.USDT)&amp;&amp;priceUnit.equals(AssetType.CNY)){ List<CommonExchageResp> exchanges = jsonArray.stream().map(js -&gt; { JSONObject adv = ((JSONObject) js).getJSONObject(&quot;adv&quot;); JSONObject advertiser = ((JSONObject) js).getJSONObject(&quot;advertiser&quot;);</p> <pre><code> CommonExchageResp commonExchageResp = new CommonExchageResp(); commonExchageResp.setPrice(new BigDecimal(adv.getString("price"))); commonExchageResp.setPendingOrderVolume(new BigDecimal(adv.getString("tradableQuantity"))); commonExchageResp.setDownLimit(new BigDecimal(adv.getString("minSingleTransAmount"))); commonExchageResp.setUpLimit(new BigDecimal(adv.getString("dynamicMaxSingleTransAmount"))); commonExchageResp.setTradingVolume(Integer.parseInt(advertiser.getString("monthOrderCount"))); commonExchageResp.setCloseRate(new BigDecimal(advertiser.getString("monthFinishRate"))); commonExchageResp.setPriceUnit(AssetType.CNY.getSymbol()); return commonExchageResp; }).limit(20).collect(Collectors.toList()); //获取有效汇率 CommonExchageResp filterExchangeRate = disposeRateDataService .disposeRateData(PatformKeyEnum.BN, TradeDirectionEnum.valueOf(directionCode), exchanges); log.info("【币安】汇率过滤,{},原始汇率条数:{},有效汇率:{}", apiInfoEnum.getDescription(),exchanges.size(), JSON.toJSONString(filterExchangeRate)); if(Objects.nonNull(filterExchangeRate)){ price=filterExchangeRate.getPrice(); } //保存第一条和第六条数据价格,以便运营进行分析 exchangeRateStatService.saveExchangeRateStat( directionCode.equals(TradeDirectionEnum.BUY_FROM_USER.getCode())?"buy":"sell", RateSourceEnum.BNB.getMsg(),exchanges,price); }else{ //取第一条价格即可 JSONObject jsonObject = jsonArray.getJSONObject(0); JSONObject advDetail = jsonObject.getJSONObject("adv"); price = new BigDecimal(advDetail.getString("price")); } } log.info("币安抓取到的{}价格为:{}", assetType, price); } catch (Exception e) { log.error("币安数据格式异常{}", e.getMessage(),e); } } try { BaseExchangeRateHistoryDTO baseExchangeRateHistoryDTO = new BaseExchangeRateHistoryDTO(); baseExchangeRateHistoryDTO.setPriceUnit(priceUnit); baseExchangeRateHistoryDTO.setCoinType(assetType); baseExchangeRateHistoryDTO.setDuration(duration); baseExchangeRateHistoryDTO.setResponse(responseString); baseExchangeRateHistoryDTO.setPrice(price); baseExchangeRateHistoryDTO.setApiInfo(apiInfoEnum); baseExchangeRateHistoryDTO.setDirection(directionCode); baseExchangeRateHistoryDTO.setApiSource(RateSourceEnum.BNB); baseExchangeRateHistoryDTO.setPriceTrading(rateTradingEnum); baseExchangeRateService.mergeBaseExchangeRate(baseExchangeRateHistoryDTO, true); } catch (Exception e) { log.error("币安汇率更新失败:{}", e.getMessage()); }</code></pre> <p>}</p> <p>private static Map&lt;String, Object&gt; buildParams(String sellOrBuy, String assetType,String currency) { Map&lt;String, Object&gt; params = new HashMap<>(7); params.put(&quot;page&quot;, 1); params.put(&quot;rows&quot;, 20); params.put(&quot;payTypes&quot;, Lists.newArrayList()); params.put(&quot;asset&quot;, assetType); params.put(&quot;tradeType&quot;, sellOrBuy); params.put(&quot;publisherType&quot;,&quot;merchant&quot;); params.put(&quot;fiat&quot;, currency); return params; }</p> <p>private static Map&lt;String, String&gt; buildHeader() { Map&lt;String, String&gt; headers = new HashMap<>(); headers.put(&quot;:method&quot;, &quot;POST&quot;); headers.put(&quot;Accept-Encoding&quot;, &quot;gzip&quot;); headers.put(&quot;Accept-Encoding&quot;, &quot;compress&quot;); headers.put(&quot;Accept-Encoding&quot;, &quot;deflate&quot;); headers.put(&quot;Accept-Encoding&quot;, &quot;br&quot;); headers.put(&quot;Accept-Encoding&quot;, &quot;identity&quot;); headers.put(&quot;Content-Encoding&quot;, &quot;gzip&quot;); headers.put(&quot;Content-Encoding&quot;, &quot;compress&quot;); headers.put(&quot;Content-Encoding&quot;, &quot;deflate&quot;); headers.put(&quot;Content-Encoding&quot;, &quot;br&quot;); headers.put(&quot;Content-Encoding&quot;, &quot;identity&quot;); headers.put(&quot;content-type&quot;, &quot;application/json&quot;); return headers; }</p> <p>private void getAndSavePriceInfo(String sellOrBuy, String assetType,String currency) { //旧地址 mortal 废弃 //String binanceUrlStr = environment.getProperty(&quot;binance.url&quot;, &quot;<a href="https://c2c.binance.com/gateway-api/v2/public/c2c/adv/search">https://c2c.binance.com/gateway-api/v2/public/c2c/adv/search</a>&quot;); String binanceUrlStr=environment.getProperty(&quot;binance.url&quot;, &quot;<a href="https://c2c.binance.com/bapi/c2c/v2/friendly/c2c/adv/search">https://c2c.binance.com/bapi/c2c/v2/friendly/c2c/adv/search</a>&quot;); List<String> binanceUrlList = new ArrayList<>(); Collections.addAll(binanceUrlList, binanceUrlStr.split(&quot;,&quot;)); Map&lt;String, Object&gt; params = buildParams(sellOrBuy, assetType,currency);</p> <pre><code>String responseString; long start = System.currentTimeMillis(); try { int size = binanceUrlList.size(); if (index &gt;= size) { index = 0; } String url = binanceUrlList.get(index++); responseString = HttpClientUtils.postUseProxy(url, JacksonUtils.toJson(params), HEADERS); log.info("【币安网】汇率抓取,{},响应结果:{}", assetType, responseString); } catch (Exception e) { log.warn("获取币安网{}币价信息失败:{}", assetType, e.getMessage()); responseString = e.getMessage(); } long duration = System.currentTimeMillis() - start; /* * https://c2c.binance.com/gateway-api/v2/public/c2c/adv/search *user buy数币时参数.返回的价格由低到高,6.52--7.18,取到的第一条数据为网站的卖出一价 * {"page":1,"rows":10,"payTypeList":[],"asset":"USDT","tradeType":"BUY","fiat":"CNY"} *user sell数币时参数.返回的价格由高到低,6.51---5.00,取到的第一条数据为网站的买入一价 * {"page":1,"rows":10,"payTypeList":[],"asset":"USDT","tradeType":"SELL","fiat":"CNY"} * * */ /*已改: 注意条件中sell和buy,与方法参数中的方向是相反的*/ if (BUY.equals(sellOrBuy) &amp;&amp; AssetType.USDT.getSymbol().equals(assetType)) { //USDT-&gt;USD汇率 if(AssetType.USD.getSymbol().equals(currency)){ parseAndSave(responseString, AssetType.USDT,AssetType.USD, ApiInfoEnum.BNB_USDT_USD_FIRST_BUY_PRICE,RateTradingEnum.USD_USDT, BUY_DIRECTION, duration); //根据中国银行汇率进行USD兑换 coinDisposeExchangePrice.fetchPriceJsonAndSave(AssetType.USD.getSymbol(), RateSourceEnum.BNB.getMsg()); return; } parseAndSave(responseString, AssetType.USDT,AssetType.CNY, ApiInfoEnum.BNB_OTC_USDT_FIRST_BUY_PRICE,RateTradingEnum.CNY_USDT, BUY_DIRECTION, duration); } else if (SELL.equals(sellOrBuy) &amp;&amp; AssetType.USDT.getSymbol().equals(assetType)) { //USDT-&gt;USD汇率 if(AssetType.USD.getSymbol().equals(currency)){ parseAndSave(responseString, AssetType.USDT,AssetType.USD, ApiInfoEnum.BNB_USDT_USD_FIRST_SELL_PRICE,RateTradingEnum.USD_USDT, SELL_DIRECTION, duration); //根据中国银行汇率进行USD兑换 coinDisposeExchangePrice.fetchPriceJsonAndSave(AssetType.USD.getSymbol(), RateSourceEnum.BNB.getMsg()); return; } parseAndSave(responseString, AssetType.USDT,AssetType.CNY, ApiInfoEnum.BNB_OTC_USDT_FIRST_SELL_PRICE,RateTradingEnum.CNY_USDT, SELL_DIRECTION, duration); } else if (BUY.equals(sellOrBuy) &amp;&amp; AssetType.BTC.getSymbol().equals(assetType)) { parseAndSave(responseString, AssetType.BTC,AssetType.CNY, ApiInfoEnum.BNB_OTC_BTC_FIRST_BUY_PRICE,RateTradingEnum.CNY_BTC, BUY_DIRECTION, duration); } else if (SELL.equals(sellOrBuy) &amp;&amp; AssetType.BTC.getSymbol().equals(assetType)) { parseAndSave(responseString, AssetType.BTC,AssetType.CNY, ApiInfoEnum.BNB_OTC_BTC_FIRST_SELL_PRICE,RateTradingEnum.CNY_BTC, SELL_DIRECTION, duration); }</code></pre> <p>}</p> <p>@SneakyThrows public static void main(String[] args) { Map&lt;String, Object&gt; params = new HashMap<>(); params.put(&quot;page&quot;, 1); params.put(&quot;rows&quot;, 20); params.put(&quot;payTypes&quot;, Lists.newArrayList()); params.put(&quot;asset&quot;, &quot;USDT&quot;); params.put(&quot;tradeType&quot;, &quot;BUY&quot;); params.put(&quot;publisherType&quot;,&quot;merchant&quot;); params.put(&quot;fiat&quot;, &quot;CNY&quot;); String url =&quot;<a href="https://c2c.binance.com/bapi/c2c/v2/friendly/c2c/adv/search">https://c2c.binance.com/bapi/c2c/v2/friendly/c2c/adv/search</a>&quot;; String responseString = HttpClientUtils.postUseProxy(url, JacksonUtils.toJson(params), HEADERS); System.out.println(responseString); JSONArray jsonArray = JSONObject.parseObject(responseString).getJSONArray(&quot;data&quot;); jsonArray.stream().map(js-&gt;{ JSONObject adv = ((JSONObject) js).getJSONObject(&quot;adv&quot;); JSONObject advertiser = ((JSONObject) js).getJSONObject(&quot;advertiser&quot;); System.out.println( &quot; 单价:&quot;+adv.getString(&quot;price&quot;) +&quot; 数量:&quot;+adv.get(&quot;tradableQuantity&quot;) +&quot; 限额:&quot;+adv.getString(&quot;minSingleTransAmount&quot;)+&quot;~&quot;+adv.getString(&quot;dynamicMaxSingleTransAmount&quot;) +&quot; 成交量:&quot;+advertiser.getString(&quot;monthOrderCount&quot;) +&quot; 成交率:&quot;+advertiser.getString(&quot;monthFinishRate&quot;) ); return null; }).collect(Collectors.toList()); //取第一条价格即可 JSONObject jsonObject = jsonArray.getJSONObject(0); JSONObject advDetail = jsonObject.getJSONObject(&quot;adv&quot;); BigDecimal price = new BigDecimal(advDetail.getString(&quot;price&quot;)); System.out.println(price); /*</p> <ul> <li><a href="https://c2c.binance.com/gateway-api/v2/public/c2c/adv/search">https://c2c.binance.com/gateway-api/v2/public/c2c/adv/search</a> *user buy数币时参数</li> <li>{&quot;page&quot;:1,&quot;rows&quot;:10,&quot;payTypeList&quot;:[],&quot;asset&quot;:&quot;USDT&quot;,&quot;tradeType&quot;:&quot;BUY&quot;,&quot;fiat&quot;:&quot;CNY&quot;} *user sell数币时参数</li> <li>{&quot;page&quot;:1,&quot;rows&quot;:10,&quot;payTypeList&quot;:[],&quot;asset&quot;:&quot;USDT&quot;,&quot;tradeType&quot;:&quot;SELL&quot;,&quot;fiat&quot;:&quot;CNY&quot;}</li> <li> <p>*/</p> <p>/<em> try { Map&lt;String, Object&gt; params = buildParams(&quot;BUY&quot;, &quot;USDT&quot;); String paramStr = JacksonUtils.toJson(params); String destUrl = &quot;<a href="https://www.binancezh.pro/gateway-api/v2/public/c2c/adv/search">https://www.binancezh.pro/gateway-api/v2/public/c2c/adv/search</a>&quot;; String result = HttpClientUtils.postUseProxy(destUrl, paramStr, HEADERS); log.info(result); } catch (Exception e) { log.error(e.getMessage(), e); }</em>/</p> <p>/<em> 求众数</em>/ int[] nums = {2, 2, 1, 1, 1, 1, 2, 2}; int max = majorityElement1(nums);</p> <p>log.info(String.valueOf(max)); }</p> </li> </ul> <p>public static int majorityElement(int[] nums) { if (nums.length == 1) return nums[0]; int sum = 1; Arrays.sort(nums); for (int i = 0; i &lt; nums.length - 1; i++) { if (nums[i] == nums[i + 1]) { sum++; if (sum &gt; nums.length / 2) { return nums[i]; } } else { sum = 1; } } return 0; }</p> <p>public static int majorityElement1(int[] nums) { if (nums.length == 1) return nums[0]; Map&lt;Integer, Integer&gt; map = new HashMap<>(); int result = 0; for (int i = 0; i &lt; nums.length; i++) { if (!map.containsKey(nums[i])) { map.put(nums[i], 1); } else { if (map.get(nums[i]) &gt; nums.length / 2) { result = nums[i]; break; } else { map.put(nums[i], map.get(nums[i]) + 1); } } } return result; } }</p> </li> </ul>

页面列表

ITEM_HTML