ybf

ybf


1.3币安汇率抓取代码参考

/**

  • @author */ @Service @Slf4j public class BinanceExchangePrice implements CoinPriceFetchService {

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

    @Autowired private Environment environment; private int index = 0;

    private final BaseExchangeRateServiceImpl baseExchangeRateService; private final ExchangeRateCheckService exchangeRateService; private final DisposeRateDataService disposeRateDataService; private final ExchangeRateStatService exchangeRateStatService;

    @Autowired private CoinDisposeExchangePrice coinDisposeExchangePrice;

    private final static Map<String, String> HEADERS = buildHeader();

    @Autowired public BinanceExchangePrice(BaseExchangeRateServiceImpl baseExchangeRateService , ExchangeRateCheckService exchangeRateService,DisposeRateDataService disposeRateDataService,ExchangeRateStatService exchangeRateStatService ) { this.baseExchangeRateService = baseExchangeRateService; this.exchangeRateService = exchangeRateService; this.disposeRateDataService=disposeRateDataService; this.exchangeRateStatService=exchangeRateStatService; }

    @Override public void fetchPriceJsonAndSave() { /注意,均为大写/ getAndSavePriceInfo(BUY, AssetType.USDT.getSymbol(),AssetType.CNY.getSymbol()); getAndSavePriceInfo(SELL, AssetType.USDT.getSymbol(),AssetType.CNY.getSymbol());

    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());

    }

    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("data"); if(Objects.nonNull(jsonArray)&&jsonArray.size()>0){ //获取前20条挂单数据 if(assetType.equals(AssetType.USDT)&&priceUnit.equals(AssetType.CNY)){ List<CommonExchageResp> exchanges = jsonArray.stream().map(js -> { JSONObject adv = ((JSONObject) js).getJSONObject("adv"); JSONObject advertiser = ((JSONObject) js).getJSONObject("advertiser");

                        CommonExchageResp commonExchageResp = new CommonExchageResp();
                        commonExchageResp.setPrice(new BigDecimal(adv.getString(&quot;price&quot;)));
                        commonExchageResp.setPendingOrderVolume(new BigDecimal(adv.getString(&quot;tradableQuantity&quot;)));
                        commonExchageResp.setDownLimit(new BigDecimal(adv.getString(&quot;minSingleTransAmount&quot;)));
                        commonExchageResp.setUpLimit(new BigDecimal(adv.getString(&quot;dynamicMaxSingleTransAmount&quot;)));
                        commonExchageResp.setTradingVolume(Integer.parseInt(advertiser.getString(&quot;monthOrderCount&quot;)));
                        commonExchageResp.setCloseRate(new BigDecimal(advertiser.getString(&quot;monthFinishRate&quot;)));
                        commonExchageResp.setPriceUnit(AssetType.CNY.getSymbol());
                        return commonExchageResp;
                    }).limit(20).collect(Collectors.toList());
                    //获取有效汇率
                    CommonExchageResp filterExchangeRate = disposeRateDataService
                            .disposeRateData(PatformKeyEnum.BN, TradeDirectionEnum.valueOf(directionCode), exchanges);
                    log.info(&quot;【币安】汇率过滤,{},原始汇率条数:{},有效汇率:{}&quot;,
                            apiInfoEnum.getDescription(),exchanges.size(), JSON.toJSONString(filterExchangeRate));
                    if(Objects.nonNull(filterExchangeRate)){
                        price=filterExchangeRate.getPrice();
                    }
                    //保存第一条和第六条数据价格,以便运营进行分析
                    exchangeRateStatService.saveExchangeRateStat(
                            directionCode.equals(TradeDirectionEnum.BUY_FROM_USER.getCode())?&quot;buy&quot;:&quot;sell&quot;,
                            RateSourceEnum.BNB.getMsg(),exchanges,price);
                }else{
                    //取第一条价格即可
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    JSONObject advDetail = jsonObject.getJSONObject(&quot;adv&quot;);
                    price = new BigDecimal(advDetail.getString(&quot;price&quot;));
                }
            }
            log.info(&quot;币安抓取到的{}价格为:{}&quot;, assetType, price);
        } catch (Exception e) {
            log.error(&quot;币安数据格式异常{}&quot;, 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(&quot;币安汇率更新失败:{}&quot;, e.getMessage());
    }

    }

    private static Map<String, Object> buildParams(String sellOrBuy, String assetType,String currency) { Map<String, Object> params = new HashMap<>(7); params.put("page", 1); params.put("rows", 20); params.put("payTypes", Lists.newArrayList()); params.put("asset", assetType); params.put("tradeType", sellOrBuy); params.put("publisherType","merchant"); params.put("fiat", currency); return params; }

    private static Map<String, String> buildHeader() { Map<String, String> headers = new HashMap<>(); headers.put(":method", "POST"); headers.put("Accept-Encoding", "gzip"); headers.put("Accept-Encoding", "compress"); headers.put("Accept-Encoding", "deflate"); headers.put("Accept-Encoding", "br"); headers.put("Accept-Encoding", "identity"); headers.put("Content-Encoding", "gzip"); headers.put("Content-Encoding", "compress"); headers.put("Content-Encoding", "deflate"); headers.put("Content-Encoding", "br"); headers.put("Content-Encoding", "identity"); headers.put("content-type", "application/json"); return headers; }

    private void getAndSavePriceInfo(String sellOrBuy, String assetType,String currency) { //旧地址 mortal 废弃 //String binanceUrlStr = environment.getProperty("binance.url", "https://c2c.binance.com/gateway-api/v2/public/c2c/adv/search";); String binanceUrlStr=environment.getProperty("binance.url", "https://c2c.binance.com/bapi/c2c/v2/friendly/c2c/adv/search";); List<String> binanceUrlList = new ArrayList<>(); Collections.addAll(binanceUrlList, binanceUrlStr.split(",")); Map<String, Object> params = buildParams(sellOrBuy, assetType,currency);

    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(&quot;【币安网】汇率抓取,{},响应结果:{}&quot;, assetType, responseString);
    } catch (Exception e) {
        log.warn(&quot;获取币安网{}币价信息失败:{}&quot;, 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,取到的第一条数据为网站的卖出一价
     * {&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数币时参数.返回的价格由高到低,6.51---5.00,取到的第一条数据为网站的买入一价
     * {&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;}
     *
     * */
    /*已改: 注意条件中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);
    }

    }

    @SneakyThrows public static void main(String[] args) { Map<String, Object> params = new HashMap<>(); params.put("page", 1); params.put("rows", 20); params.put("payTypes", Lists.newArrayList()); params.put("asset", "USDT"); params.put("tradeType", "BUY"); params.put("publisherType","merchant"); params.put("fiat", "CNY"); String url ="https://c2c.binance.com/bapi/c2c/v2/friendly/c2c/adv/search";; String responseString = HttpClientUtils.postUseProxy(url, JacksonUtils.toJson(params), HEADERS); System.out.println(responseString); JSONArray jsonArray = JSONObject.parseObject(responseString).getJSONArray("data"); jsonArray.stream().map(js->{ JSONObject adv = ((JSONObject) js).getJSONObject("adv"); JSONObject advertiser = ((JSONObject) js).getJSONObject("advertiser"); System.out.println( " 单价:"+adv.getString("price") +" 数量:"+adv.get("tradableQuantity") +" 限额:"+adv.getString("minSingleTransAmount")+"~"+adv.getString("dynamicMaxSingleTransAmount") +" 成交量:"+advertiser.getString("monthOrderCount") +" 成交率:"+advertiser.getString("monthFinishRate") ); return null; }).collect(Collectors.toList()); //取第一条价格即可 JSONObject jsonObject = jsonArray.getJSONObject(0); JSONObject advDetail = jsonObject.getJSONObject("adv"); BigDecimal price = new BigDecimal(advDetail.getString("price")); System.out.println(price); /*

    • https://c2c.binance.com/gateway-api/v2/public/c2c/adv/search *user buy数币时参数
    • {"page":1,"rows":10,"payTypeList":[],"asset":"USDT","tradeType":"BUY","fiat":"CNY"} *user sell数币时参数
    • {"page":1,"rows":10,"payTypeList":[],"asset":"USDT","tradeType":"SELL","fiat":"CNY"}
    • */

      / try { Map<String, Object> params = buildParams("BUY", "USDT"); String paramStr = JacksonUtils.toJson(params); String destUrl = "https://www.binancezh.pro/gateway-api/v2/public/c2c/adv/search";; String result = HttpClientUtils.postUseProxy(destUrl, paramStr, HEADERS); log.info(result); } catch (Exception e) { log.error(e.getMessage(), e); }/

      / 求众数/ int[] nums = {2, 2, 1, 1, 1, 1, 2, 2}; int max = majorityElement1(nums);

      log.info(String.valueOf(max)); }

    public static int majorityElement(int[] nums) { if (nums.length == 1) return nums[0]; int sum = 1; Arrays.sort(nums); for (int i = 0; i < nums.length - 1; i++) { if (nums[i] == nums[i + 1]) { sum++; if (sum > nums.length / 2) { return nums[i]; } } else { sum = 1; } } return 0; }

    public static int majorityElement1(int[] nums) { if (nums.length == 1) return nums[0]; Map<Integer, Integer> map = new HashMap<>(); int result = 0; for (int i = 0; i < nums.length; i++) { if (!map.containsKey(nums[i])) { map.put(nums[i], 1); } else { if (map.get(nums[i]) > nums.length / 2) { result = nums[i]; break; } else { map.put(nums[i], map.get(nums[i]) + 1); } } } return result; } }

页面列表

ITEM_HTML