获取Java可关闭响应正文的值

时间:2019-12-06 15:05:41

标签: java spring-boot trading binance closeablehttpresponse

我从Binance获取返回响应的数据列表,如何访问响应正文的值?

private Closeable candleStick(){
        BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient();
        return client.onCandlestickEvent("btcusdt", CandlestickInterval.FIVE_MINUTES, new BinanceApiCallback<com.binance.api.client.domain.event.CandlestickEvent>() {
            @Override
            public void onResponse(com.binance.api.client.domain.event.CandlestickEvent response) {
                System.out.println(response);
            }
        });
    }

响应的值类似response.getHigh(), response.getLow()等。如何用另一种方法访问这些值。它

private String show() throws IOException {
        Double high = candleStick().getHigh() //didn't work as the method returns a closeable object.
    }

1 个答案:

答案 0 :(得分:1)

这是一个基于回调的API,因此您应该在应用中更新一些数据结构以添加/显示新值,而不是System.out.println(...)。

一个简单的例子:

public class CandleStickDataSource {

  private final BinanceApiWebSocketClient client;
  private final Closeable socket;

  private final List<Double> highs = new ArrayList<>();
  private final List<Double> lows = new ArrayList<>();

  private Double lastHigh;    
  private Double lastLow;

  public CandleStickDataSource(String ticker, CandlestickInterval interval) {
    this.client = BinanceApiClientFactory.newInstance().newWebSocketClient();
    this.socket = client.onCandlestickEvent(ticker, interval, new BinanceApiCallback<CandlestickEvent>() {
            @Override
            public void onResponse(CandlestickEvent response) {
                lastHigh = Double.valueOf(response.getHigh());
                lastLow = Double.valueOf(response.getLow()); 
                highs.add(lastHigh);
                lows.add(lastLow);
            }
        });  //  don't forget to call close() on this somewhere when you're done with this class
  }

  public List<Double> getHighs() { return highs; }
  public List<Double> getLows() { return lows; }
  public Double getLastHigh() { return lastHigh; }
  public Double getLastLow() { return lastLow; }

}

因此在您应用程序中要访问数据的其他地方:

CandleStickDataSource data = new CandleStickDataSource("btcusdt", CandlestickInterval.FIVE_MINUTES); // Create this first. This is now reusable for any ticker and any interval

,然后每当要查看数据时

data.getHighs(); // history
data.getLows();
data.getLastHigh(); // or getLastLow() for latest values