can't exit event handler

Viewed 49

I am making a bot for binance using java. for this I found a library for binance websocket binance4j. I managed to open a websocket, but I don't know how to terminate it under certain conditions.

library documentation https://binance4j.github.io/binance4j/binance4j-documentation/docs/websocket

my code

public class Timer {
     private static String symbol = "btcusdt".toUpperCase();
     
     public Timer(CandlestickInterval interval) {
              WebsocketCandlestickClient client = new WebsocketCandlestickClient(symbol, interval);

              client.open();
    
              client.onMessage(cb -> {
        
                   if (cb.getIsBarFinal()) {
                   //when the candle closes
                   //close the connection and transfer execution to the main function
                   
                   }

              });

      }

}
1 Answers

According to documentation you already referenced you can call:

//Before closing, the `onClosing` handler will be called, then `onClosed` once the connection is closed.
client.close();

Also you should set handler first, only then open the connection:

client.onMessage(cb -> ...
client.open();
Related