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 = "<a href="https://api.coinbase.com/v2/exchange-rates">https://api.coinbase.com/v2/exchange-rates</a>";</p>
<p>private static final String USDT_CNY = "USDT";</p>
<p>private static final String ETH_CNY = "ETH";
private static final String appName = "coinBase";</p>
<p>private static String BUY = "buy";
private static String SELL = "sell";</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 = "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);
/<em>log.info("获取coinBase网{}币价信息:\n{}", assetType, responseString);</em>/
} catch (Exception e) {
log.error("获取coinBase网{}币价信息失败:{}", assetType, e.getMessage());
responseString = e.getMessage();
}
long duration = System.currentTimeMillis() - start;</p>
<pre><code>/*已改: 注意条件中sell和buy,与方法参数中的方向是相反的*/
if (BUY.equals(sellOrBuy) && AssetType.USDT.getSymbol().equals(assetType)) {
//USDT->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) && AssetType.USDT.getSymbol().equals(assetType)) {
//USDT->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("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());
}
}</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("【coinbase】查询汇率成功,开始批量入库:{}", 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("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);</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>