Skip to content

Commit ed507bf

Browse files
authored
Merge pull request #12 from cryptomkt/feat/readme-websocket-connection
feat: websocket connection secction on readme
2 parents b88717e + f5d6bdf commit ed507bf

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

README.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,12 +151,47 @@ On an authenticated client, onConnect is called after authentication, which happ
151151
// ws client lifetime
152152
CryptomarketWSSpotTradingClient wsClient;
153153
wsClient = new CryptomarketWSSpotTradingClientImpl(KeyLoader.getApiKey(), KeyLoader.getApiSecret());
154-
wsClient.onConnect(() -> System.out.println("connecting"));
154+
wsClient.onConnect(() -> System.out.println("client is connected!"));
155155
wsClient.onClose(reason -> System.out.println("closing: "+ reason));
156156
wsClient.onFailure(t -> t.printStackTrace());
157157
wsClient.connect();
158158
```
159159

160+
### Websocket Connection
161+
The websockets take some time (around one second) to connect, and authenticated sockets take a little more time to authenticate, so we must wait to the client to call onConnect first.
162+
163+
A way of doing this is using a future task
164+
```java
165+
var wsClient = new CryptomarketWSSpotTradingClientImpl(KeyLoader.getApiKey(), KeyLoader.getApiSecret());
166+
var ft = new FutureTask<Object>(() -> {}, new Object());
167+
wsClient.onConnect(ft);
168+
wsClient.connect();
169+
ft.get();
170+
// here we are connected and authenticated already
171+
wsClient.getSpotTradingBalances((balances, err) -> {...});
172+
```
173+
We can also run our logic inside the onConnect hook
174+
175+
```java
176+
var wsClient = new CryptomarketWSSpotTradingClientImpl(KeyLoader.getApiKey(), KeyLoader.getApiSecret());
177+
var ft = new FutureTask<Object>(() -> {}, new Object());
178+
wsClient.onConnect(()-> {
179+
// here we are connected and authenticated already
180+
wsClient.getSpotTradingBalances((balances, err) -> {...});
181+
});
182+
wsClient.connect();
183+
```
184+
Or we can sleep some time to wait connection
185+
186+
```java
187+
var wsClient = new CryptomarketWSSpotTradingClientImpl(KeyLoader.getApiKey(), KeyLoader.getApiSecret());
188+
var ft = new FutureTask<Object>(() -> {}, new Object());
189+
wsClient.connect();
190+
TimeUnit.Seconds.sleep(3);
191+
// here we are connected and authenticated already
192+
wsClient.getSpotTradingBalances((balances, err) -> {...});
193+
```
194+
160195
### MarketDataClient
161196

162197
Example of use of the market data client

0 commit comments

Comments
 (0)