ybf

ybf


1.6coinbase汇率抓取代码参考

/**

  • coinbase(api.coinbase.com)网汇率抓取实现类
  • @author
  • @date 2021-12-02 */ @Service @Slf4j public class CoinbaseExchangePrice implements CoinPriceFetchService {

    private String BASE_URL = "https://api.coinbase.com/v2/exchange-rates";;

    private static final String USDT_CNY = "USDT";

    private static final String ETH_CNY = "ETH"; private static final String appName = "coinBase";

    private static String BUY = "buy"; private static String SELL = "sell";

    @Autowired private FetchExchangeRateService fetchExchangeRateService;

    @Autowired private CoinDisposeExchangePrice coinDisposeExchangePrice;

    private final BaseExchangeRateServiceImpl baseExchangeRateService; @Autowired private Environment environment;

    @Autowired public CoinbaseExchangePrice(BaseExchangeRateServiceImpl baseExchangeRateService ) { this.baseExchangeRateService = baseExchangeRateService; }

    @Override public void fetchPriceJsonAndSave() { getAndSavePriceInfo(BUY, AssetType.USDT.getSymbol(), AssetType.USD.getSymbol()); getAndSavePriceInfo(SELL, AssetType.USDT.getSymbol(), AssetType.USD.getSymbol()); }

    private void getAndSavePriceInfo(String sellOrBuy, String assetType,String currency) { String scheme = "https"; String host = "api.coinbase.com"; String path ="v2/prices/USDT-USD/"+sellOrBuy; Map<String, String> headers = new HashMap<>(1); Map<String, String> 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("exchange.rate.test.sleep.time", Integer.class, 0); if (testSleepTime>0) { try { TimeUnit.SECONDS.sleep(testSleepTime); } catch (InterruptedException e) { e.printStackTrace(); } log.warn("延迟测试时间,{}",testSleepTime); } //本段代码为测试汇率波动使用,生产不执行------END try { responseString = HttpUtil.getResponse(requestBean); /log.info("获取coinBase网{}币价信息:\n{}", assetType, responseString);/ } catch (Exception e) { log.error("获取coinBase网{}币价信息失败:{}", assetType, e.getMessage()); responseString = e.getMessage(); } long duration = System.currentTimeMillis() - start;

    /*已改: 注意条件中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;
        }
    }

    }

    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("data"); price = new BigDecimal(data.getString("amount")); try { log.info("coinBase网抓取到的{}价格为:{}", assetType, price); } catch (Exception e) { return; } } catch (Exception e) { log.error("coinBase网数据格式异常{}", e.getMessage()); } }

    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(&quot;coinBase网汇率更新失败:{}&quot;, e.getMessage());
    }

    }

    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("【coinbase】查询汇率成功,开始批量入库:{}", JSON.toJSONString(exchangeRates)); //批量保存汇率结果集 fetchExchangeRateService.saveBatch(exchangeRates); } }

    private final List<FetchExchangeRatePO> sendRequest(String symbol, String fetchId) { List<FetchExchangeRatePO> list = Lists.newArrayList(); long start = System.currentTimeMillis(); //本段代码为测试汇率波动使用,生产不执行------BEGIN int testSleepTime = environment.getProperty("exchange.rate.test.sleep.time", Integer.class, 0); if (testSleepTime>0) { try { TimeUnit.SECONDS.sleep(testSleepTime); } catch (InterruptedException e) { e.printStackTrace(); } log.warn("延迟测试时间,{}",testSleepTime); } //本段代码为测试汇率波动使用,生产不执行------END try { String scheme = "https"; String host = "api.coinbase.com"; String path = "v2/exchange-rates"; Map<String, String> headers = new HashMap<>(1); Map<String, String> params = new HashMap<>(2); params.put("currency", 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("【coinbase】{} 汇率抓取,请求地址:{} 返回结果:{}", symbol, BASE_URL, resp);

        if (StringUtils.isNotBlank(resp)) {
            long delayTime = System.currentTimeMillis() - start;
            JSONObject json = new JSONObject(resp);
            JSONObject data = json.getJSONObject(&quot;data&quot;);
            JSONObject rates = data.getJSONObject(&quot;rates&quot;);
            Double usdt_cnyRate = null;
            Double usdt_usdRate = null;
            if (rates.has(&quot;CNY&quot;)) {
                usdt_cnyRate = Double.valueOf(rates.get(&quot;CNY&quot;).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() + &quot;-CNY标准价&quot;, delayTime));
            }
            if (rates.has(&quot;USD&quot;)) {
                usdt_usdRate = Double.valueOf(rates.get(&quot;USD&quot;).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() + &quot;-USD标准价&quot;, delayTime));
            }
        }
    } catch (Throwable e) {
        log.error(&quot;COINBASE汇率获取异常,{}&quot;, e);
    }
    return list;

    }

    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; }

}

页面列表

ITEM_HTML