Search code examples
javaspring-boottradingbinancecloseablehttpresponse

Get values of a Java closable response body


I'm getting a list of data from Binance that returns a response, how do I access the values of the response body?

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

The response has values like response.getHigh(), response.getLow(), etc. How do I access these values in another method. It

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

Solution

  • It's a callback based API, so instead of your System.out.println(...) you should update some data structure in your app to add/show the new values.

    Just a simple example:

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

    So somewhere else in your app where you want to get access to the data:

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

    and then whenever you want to see the data

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