Skip to content

Commit 792b9e4

Browse files
committed
Add additional caching examples.
* How to cache account balances from the user data stream; * How to cache candlestick information from the klines data streams; * How to cache aggregated trades from the aggTrades data stream.
1 parent 415a801 commit 792b9e4

5 files changed

Lines changed: 178 additions & 3 deletions

File tree

src/main/java/com/binance/api/client/domain/account/AssetBalance.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package com.binance.api.client.domain.account;
22

3-
import com.binance.api.client.domain.account.Account;
43
import org.apache.commons.lang3.builder.ToStringBuilder;
54
import org.apache.commons.lang3.builder.ToStringStyle;
65

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package com.binance.api.examples;
2+
3+
import com.binance.api.client.BinanceApiClientFactory;
4+
import com.binance.api.client.BinanceApiRestClient;
5+
import com.binance.api.client.BinanceApiWebSocketClient;
6+
import com.binance.api.client.domain.account.Account;
7+
import com.binance.api.client.domain.account.AssetBalance;
8+
9+
import java.util.Map;
10+
import java.util.TreeMap;
11+
12+
import static com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType.ACCOUNT_UPDATE;
13+
14+
/**
15+
* Illustrates how to use the user data event stream to create a local cache for the balance of an account.
16+
*/
17+
public class AccountBalanceCacheExample {
18+
19+
private final BinanceApiClientFactory clientFactory;
20+
21+
/**
22+
* Key is the symbol, and the value is the balance of that symbol on the account.
23+
*/
24+
private Map<String, AssetBalance> accountBalanceCache;
25+
26+
/**
27+
* Listen key used to interact with the user data streaming API.
28+
*/
29+
private final String listenKey;
30+
31+
public AccountBalanceCacheExample(String apiKey, String secret) {
32+
this.clientFactory = BinanceApiClientFactory.newInstance(apiKey, secret);
33+
this.listenKey = initializeAssetBalanceCacheAndStreamSession();
34+
startAccountBalanceEventStreaming(listenKey);
35+
}
36+
37+
/**
38+
* Initializes the asset balance cache by using the REST API and starts a new user data streaming session.
39+
*
40+
* @return a listenKey that can be used with the user data streaming API.
41+
*/
42+
private String initializeAssetBalanceCacheAndStreamSession() {
43+
BinanceApiRestClient client = clientFactory.newRestClient();
44+
Account account = client.getAccount();
45+
46+
this.accountBalanceCache = new TreeMap<>();
47+
for (AssetBalance assetBalance : account.getBalances()) {
48+
accountBalanceCache.put(assetBalance.getAsset(), assetBalance);
49+
}
50+
51+
return client.startUserDataStream();
52+
}
53+
54+
/**
55+
* Begins streaming of agg trades events.
56+
*/
57+
private void startAccountBalanceEventStreaming(String listenKey) {
58+
BinanceApiWebSocketClient client = clientFactory.newWebSocketClient();
59+
60+
client.onUserDataUpdateEvent(listenKey, response -> {
61+
if (response.getEventType() == ACCOUNT_UPDATE) {
62+
// Override cached asset balances
63+
for (AssetBalance assetBalance : response.getAccountUpdateEvent().getBalances()) {
64+
accountBalanceCache.put(assetBalance.getAsset(), assetBalance);
65+
}
66+
System.out.println(accountBalanceCache);
67+
}
68+
});
69+
}
70+
71+
/**
72+
* @return an account balance cache, containing the balance for every asset in this account.
73+
*/
74+
public Map<String, AssetBalance> getAccountBalanceCache() {
75+
return accountBalanceCache;
76+
}
77+
78+
public static void main(String[] args) {
79+
new AccountBalanceCacheExample("YOUR_API_KEY", "YOUR_SECRET");
80+
}
81+
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package com.binance.api.examples;
2+
3+
import com.binance.api.client.BinanceApiClientFactory;
4+
import com.binance.api.client.BinanceApiRestClient;
5+
import com.binance.api.client.BinanceApiWebSocketClient;
6+
import com.binance.api.client.domain.market.AggTrade;
7+
import com.binance.api.client.domain.market.Candlestick;
8+
import com.binance.api.client.domain.market.CandlestickInterval;
9+
10+
import java.util.HashMap;
11+
import java.util.List;
12+
import java.util.Map;
13+
14+
/**
15+
* Illustrates how to use the aggTrades event stream to create a local cache of trades for a symbol.
16+
*/
17+
public class AggTradesCacheExample {
18+
19+
/**
20+
* Key is the aggregate trade id, and the value contains the aggregated trade data, which is
21+
* automatically updated whenever a new agg data stream event arrives.
22+
*/
23+
private Map<Long, AggTrade> aggTradesCache;
24+
25+
public AggTradesCacheExample(String symbol) {
26+
initializeAggTradesCache(symbol);
27+
startAggTradesEventStreaming(symbol);
28+
}
29+
30+
/**
31+
* Initializes the aggTrades cache by using the REST API.
32+
*/
33+
private void initializeAggTradesCache(String symbol) {
34+
BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance();
35+
BinanceApiRestClient client = factory.newRestClient();
36+
List<AggTrade> aggTrades = client.getAggTrades(symbol.toUpperCase());
37+
38+
this.aggTradesCache = new HashMap<>();
39+
for (AggTrade aggTrade : aggTrades) {
40+
aggTradesCache.put(aggTrade.getAggregatedTradeId(), aggTrade);
41+
}
42+
}
43+
44+
/**
45+
* Begins streaming of agg trades events.
46+
*/
47+
private void startAggTradesEventStreaming(String symbol) {
48+
BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance();
49+
BinanceApiWebSocketClient client = factory.newWebSocketClient();
50+
51+
client.onAggTradeEvent(symbol.toLowerCase(), response -> {
52+
Long aggregatedTradeId = response.getAggregatedTradeId();
53+
AggTrade updateAggTrade = aggTradesCache.get(aggregatedTradeId);
54+
if (updateAggTrade == null) {
55+
// new agg trade
56+
updateAggTrade = new AggTrade();
57+
}
58+
updateAggTrade.setAggregatedTradeId(aggregatedTradeId);
59+
updateAggTrade.setPrice(response.getPrice());
60+
updateAggTrade.setQuantity(response.getQuantity());
61+
updateAggTrade.setFirstBreakdownTradeId(response.getFirstBreakdownTradeId());
62+
updateAggTrade.setLastBreakdownTradeId(response.getLastBreakdownTradeId());
63+
updateAggTrade.setBuyerMaker(response.isBuyerMaker());
64+
65+
// Store the updated agg trade in the cache
66+
aggTradesCache.put(aggregatedTradeId, updateAggTrade);
67+
System.out.println(updateAggTrade);
68+
});
69+
}
70+
71+
/**
72+
* @return an aggTrades cache, containing the aggregated trade id as the key,
73+
* and the agg trade data as the value.
74+
*/
75+
public Map<Long, AggTrade> getAggTradesCache() {
76+
return aggTradesCache;
77+
}
78+
79+
public static void main(String[] args) {
80+
new AggTradesCacheExample("ETHBTC");
81+
}
82+
}

src/test/java/com/binance/api/examples/CandlesticksCacheExample.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,14 @@ private void startCandlestickEventStreaming(String symbol, CandlestickInterval i
7272
});
7373
}
7474

75+
/**
76+
* @return a klines/candlestick cache, containing the open/start time of the candlestick as the key,
77+
* and the candlestick data as the value.
78+
*/
79+
public Map<Long, Candlestick> getCandlesticksCache() {
80+
return candlesticksCache;
81+
}
82+
7583
public static void main(String[] args) {
7684
new CandlesticksCacheExample("ETHBTC", CandlestickInterval.ONE_MINUTE);
7785
}

src/test/java/com/binance/api/examples/DepthCacheExample.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,6 @@ private void startDepthEventStreaming(String symbol) {
7373
});
7474
}
7575

76-
77-
7876
/**
7977
* Updates an order book (bids or asks) with a delta received from the server.
8078
*
@@ -115,6 +113,13 @@ private Map.Entry<BigDecimal, BigDecimal> getBestBid() {
115113
return getBids().firstEntry();
116114
}
117115

116+
/**
117+
* @return a depth cache, containing two keys (ASKs and BIDs), and for each, an ordered list of book entries.
118+
*/
119+
public Map<String, NavigableMap<BigDecimal, BigDecimal>> getDepthCache() {
120+
return depthCache;
121+
}
122+
118123
/**
119124
* Prints the cached order book / depth of a symbol as well as the best ask and bid price in the book.
120125
*/

0 commit comments

Comments
 (0)