ybf

ybf


1.6coinbase汇率抓取代码参考

<p>/**</p> <ul> <li>coinbase(api.coinbase.com)网汇率抓取实现类</li> <li> </li> <li>@author</li> <li> <p>@date 2021-12-02 */ @Service @Slf4j public class CoinbaseExchangePrice implements CoinPriceFetchService {</p> <p>private String BASE_URL = &quot;<a href="https://api.coinbase.com/v2/exchange-rates">https://api.coinbase.com/v2/exchange-rates</a>&quot;;</p> <p>private static final String USDT_CNY = &quot;USDT&quot;;</p> <p>private static final String ETH_CNY = &quot;ETH&quot;; private static final String appName = &quot;coinBase&quot;;</p> <p>private static String BUY = &quot;buy&quot;; private static String SELL = &quot;sell&quot;;</p> <p>@Autowired private FetchExchangeRateService fetchExchangeRateService;</p> <p>@Autowired private CoinDisposeExchangePrice coinDisposeExchangePrice;</p> <p>private final BaseExchangeRateServiceImpl baseExchangeRateService; @Autowired private Environment environment;</p> <p>@Autowired public CoinbaseExchangePrice(BaseExchangeRateServiceImpl baseExchangeRateService ) { this.baseExchangeRateService = baseExchangeRateService; }</p> <p>@Override public void fetchPriceJsonAndSave() { getAndSavePriceInfo(BUY, AssetType.USDT.getSymbol(), AssetType.USD.getSymbol()); getAndSavePriceInfo(SELL, AssetType.USDT.getSymbol(), AssetType.USD.getSymbol()); }</p> <p>private void getAndSavePriceInfo(String sellOrBuy, String assetType,String currency) { String scheme = &quot;https&quot;; String host = &quot;api.coinbase.com&quot;; String path =&quot;v2/prices/USDT-USD/&quot;+sellOrBuy; Map&lt;String, String&gt; headers = new HashMap<>(1); Map&lt;String, String&gt; params = new HashMap<>(2); HttpGetRequestBean requestBean = new HttpGetRequestBean(); requestBean.setHeaders(headers); requestBean.setHost(host); requestBean.setParams(params); requestBean.setPath(path); requestBean.setScheme(scheme); String responseString; long start = System.currentTimeMillis(); //本段代码为测试汇率波动使用,生产不执行------BEGIN int testSleepTime = environment.getProperty(&quot;exchange.rate.test.sleep.time&quot;, Integer.class, 0); if (testSleepTime&gt;0) { try { TimeUnit.SECONDS.sleep(testSleepTime); } catch (InterruptedException e) { e.printStackTrace(); } log.warn(&quot;延迟测试时间,{}&quot;,testSleepTime); } //本段代码为测试汇率波动使用,生产不执行------END try { responseString = HttpUtil.getResponse(requestBean); /<em>log.info(&quot;获取coinBase网{}币价信息:\n{}&quot;, assetType, responseString);</em>/ } catch (Exception e) { log.error(&quot;获取coinBase网{}币价信息失败:{}&quot;, assetType, e.getMessage()); responseString = e.getMessage(); } long duration = System.currentTimeMillis() - start;</p> <pre><code>/*已改: 注意条件中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.COINBASE_USDT_USD_FIRST_BUY_PRICE, RateTradingEnum.USD_USDT, BUY_DIRECTION, duration); //根据中国银行汇率进行USD兑换 coinDisposeExchangePrice.fetchPriceJsonAndSave(AssetType.USD.getSymbol(), RateSourceEnum.COINBASE.getMsg()); return; } } 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.COINBASE_USDT_USD_FIRST_SELL_PRICE,RateTradingEnum.USD_USDT, SELL_DIRECTION, duration); //根据中国银行汇率进行USD兑换 coinDisposeExchangePrice.fetchPriceJsonAndSave(AssetType.USD.getSymbol(), RateSourceEnum.COINBASE.getMsg()); return; } }</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 { JSONObject json = new JSONObject(responseString); JSONObject data = json.getJSONObject(&quot;data&quot;); price = new BigDecimal(data.getString(&quot;amount&quot;)); try { log.info(&quot;coinBase网抓取到的{}价格为:{}&quot;, assetType, price); } catch (Exception e) { return; } } catch (Exception e) { log.error(&quot;coinBase网数据格式异常{}&quot;, e.getMessage()); } }</p> <pre><code>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.COINBASE); baseExchangeRateHistoryDTO.setPriceTrading(rateTradingEnum); baseExchangeRateService.mergeBaseExchangeRate(baseExchangeRateHistoryDTO, true); } catch (Exception e) { log.error("coinBase网汇率更新失败:{}", e.getMessage()); }</code></pre> <p>}</p> <p>public void fetchPriceAndSave(String fetchId) { List<FetchExchangeRatePO> exchangeRates = Lists.newArrayList(); exchangeRates.addAll(this.sendRequest(USDT_CNY, fetchId)); exchangeRates.addAll(this.sendRequest(ETH_CNY, fetchId)); if (!exchangeRates.isEmpty()) { log.warn(&quot;【coinbase】查询汇率成功,开始批量入库:{}&quot;, JSON.toJSONString(exchangeRates)); //批量保存汇率结果集 fetchExchangeRateService.saveBatch(exchangeRates); } }</p> <p>private final List<FetchExchangeRatePO> sendRequest(String symbol, String fetchId) { List<FetchExchangeRatePO> list = Lists.newArrayList(); long start = System.currentTimeMillis(); //本段代码为测试汇率波动使用,生产不执行------BEGIN int testSleepTime = environment.getProperty(&quot;exchange.rate.test.sleep.time&quot;, Integer.class, 0); if (testSleepTime&gt;0) { try { TimeUnit.SECONDS.sleep(testSleepTime); } catch (InterruptedException e) { e.printStackTrace(); } log.warn(&quot;延迟测试时间,{}&quot;,testSleepTime); } //本段代码为测试汇率波动使用,生产不执行------END try { String scheme = &quot;https&quot;; String host = &quot;api.coinbase.com&quot;; String path = &quot;v2/exchange-rates&quot;; Map&lt;String, String&gt; headers = new HashMap<>(1); Map&lt;String, String&gt; params = new HashMap<>(2); params.put(&quot;currency&quot;, symbol); HttpGetRequestBean requestBean = new HttpGetRequestBean(); requestBean.setHeaders(headers); requestBean.setHost(host); requestBean.setParams(params); requestBean.setPath(path); requestBean.setScheme(scheme); final String resp = HttpUtil.getResponse(requestBean); log.info(&quot;【coinbase】{} 汇率抓取,请求地址:{} 返回结果:{}&quot;, symbol, BASE_URL, resp);</p> <pre><code> if (StringUtils.isNotBlank(resp)) { long delayTime = System.currentTimeMillis() - start; JSONObject json = new JSONObject(resp); JSONObject data = json.getJSONObject("data"); JSONObject rates = data.getJSONObject("rates"); Double usdt_cnyRate = null; Double usdt_usdRate = null; if (rates.has("CNY")) { usdt_cnyRate = Double.valueOf(rates.get("CNY").toString()); AssetType assetType = symbol.equals(USDT_CNY) ? AssetType.USDT : AssetType.ETH; list.add(newInstance(assetType, new BigDecimal(usdt_cnyRate.doubleValue()), fetchId, AssetType.CNY.getCode(), TradeDirectionEnum.STANDARD.getCode(), assetType.getSymbol() + "-CNY标准价", delayTime)); } if (rates.has("USD")) { usdt_usdRate = Double.valueOf(rates.get("USD").toString()); AssetType assetType = symbol.equals(USDT_CNY) ? AssetType.USDT : AssetType.ETH; list.add(newInstance(assetType, new BigDecimal(usdt_usdRate.doubleValue()), fetchId, AssetType.USD.getCode(), TradeDirectionEnum.STANDARD.getCode(), assetType.getSymbol() + "-USD标准价", delayTime)); } } } catch (Throwable e) { log.error("COINBASE汇率获取异常,{}", e); } return list;</code></pre> <p>}</p> <p>private final static FetchExchangeRatePO newInstance(AssetType assetType, BigDecimal price, String fetchId, Integer priceUnit, Integer tradeType, String apiInfo, Long delayTime) { FetchExchangeRatePO fetchExchangeRatePO = new FetchExchangeRatePO(); fetchExchangeRatePO.setPrice(price); fetchExchangeRatePO.setTradeType(tradeType); fetchExchangeRatePO.setPriceUnit(priceUnit); fetchExchangeRatePO.setCoinType(assetType.getCode()); fetchExchangeRatePO.setFetchBatches(fetchId); fetchExchangeRatePO.setDelayTime(delayTime); //TODO 增加数据来源枚举类 fetchExchangeRatePO.setApiName(appName); fetchExchangeRatePO.setApiInfo(apiInfo); fetchExchangeRatePO.setStatus(1); return fetchExchangeRatePO; }</p> </li> </ul> <p>}</p>

页面列表

ITEM_HTML