Skip to content

Commit 0eb1acb

Browse files
committed
add balance subscription
redo subscription logic
1 parent 84df3fd commit 0eb1acb

File tree

7 files changed

+177
-89
lines changed

7 files changed

+177
-89
lines changed

src/main/java/com/cryptomarket/sdk/websocket/ClientBase.java

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.cryptomarket.sdk.websocket;
22

33
import java.io.IOException;
4+
import java.util.HashMap;
45
import java.util.Map;
56

67
import com.cryptomarket.sdk.Adapter;
@@ -16,6 +17,7 @@ public class ClientBase implements Handler {
1617
OrderbookCache OBCache = new OrderbookCache();
1718
public Adapter adapter = new Adapter();
1819
private WebSocketConnection websocket;
20+
private Map<String,String> subscriptionKeys;
1921

2022
static class Payload {
2123
String method;
@@ -33,9 +35,14 @@ public Payload(String method, Map<String, Object> params) {
3335
protected ClientBase(String url) {
3436
Moshi moshi = new Moshi.Builder().build();
3537
payloadAdapter = moshi.adapter(Payload.class);
38+
this.subscriptionKeys = new HashMap<String, String>();
3639
websocket = new WebSocketConnection(this, url);
3740
}
3841

42+
protected Map<String, String> getSubscritpionKeys() {
43+
return this.subscriptionKeys;
44+
}
45+
3946
protected void sendSubscription(String method, Map<String, Object> params, Interceptor feedInterceptor,
4047
Interceptor resultInterceptor) {
4148
String key = buildKey(method, params);
@@ -67,7 +74,7 @@ public void handle(String json) throws CryptomarketSDKException {
6774
}
6875

6976
protected void handleNotification(WSJsonResponse response) {
70-
String key = "subscription";
77+
String key = buildKey(response.getMethod());
7178
Interceptor interceptor = interceptorCache.getSubscriptionInterceptor(key);
7279
if (interceptor != null) interceptor.makeCall(response);
7380
}
@@ -77,7 +84,14 @@ protected void handleResponse(WSJsonResponse response) {
7784
if (interceptor != null) interceptor.makeCall(response);
7885
}
7986

87+
88+
protected String buildKey(String method) {
89+
if (subscriptionKeys.containsKey(method)) return this.subscriptionKeys.get(method);
90+
return "subscription";
91+
}
92+
8093
protected String buildKey(String method, Map<String, Object> params) {
94+
if (subscriptionKeys.containsKey(method)) return this.subscriptionKeys.get(method);
8195
return "subscription";
8296
}
8397

src/main/java/com/cryptomarket/sdk/websocket/CryptomarketWSAccountClient.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,28 @@ public void loadTransactions(
137137
* @return The operation result. true if success
138138
*/
139139
public void unsubscribeToTransactions(@Nullable Callback<Boolean> callback);
140+
141+
142+
/**
143+
* Subscribe to a feed of balance events of the account
144+
*
145+
* https://api.exchange.cryptomkt.com/#subscribe-to-reports
146+
*
147+
* @param callback Optional. A Callback to call with the result data.
148+
*
149+
* @return balances of the account as feed for the callback
150+
*/
151+
public void subscribeToBalance(Callback<List<Balance>> callback, @Nullable Callback<Boolean> resultCallback);
152+
153+
154+
/**
155+
* unsubscribe to the balances feed.
156+
*
157+
* https://api.exchange.cryptomkt.com/#subscription-to-the-transactions
158+
*
159+
* @param callback Optional. A Callback to call with the result data.
160+
*
161+
* @return The operation result. true if success
162+
*/
163+
public void unsubscribeToBalance(@Nullable Callback<Boolean> callback);
140164
}

src/main/java/com/cryptomarket/sdk/websocket/CryptomarketWSAccountClientImpl.java

Lines changed: 67 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -20,35 +20,15 @@ public class CryptomarketWSAccountClientImpl extends AuthClient implements Crypt
2020

2121
public CryptomarketWSAccountClientImpl(String apiKey, String apiSecret) throws IOException {
2222
super("wss://api.exchange.cryptomkt.com/api/2/ws/account", apiKey, apiSecret);
23-
}
24-
25-
@Override
26-
public void subscribeToTransactions(Callback<Transaction> callback, Callback<Boolean> resultCallback) {
27-
Map<String, Object> params = new HashMap<>();
28-
Interceptor interceptor = new Interceptor() {
29-
@Override
30-
public void makeCall(WSJsonResponse response) {
31-
ErrorBody error = response.getError();
32-
if (error != null) {
33-
callback.reject(new CryptomarketAPIException(error));
34-
} else {
35-
Transaction transaction = adapter.objectFromValue(response.getParams(), Transaction.class);
36-
callback.resolve(transaction);
37-
}
38-
}
39-
};
40-
Interceptor resultInterceptor = (resultCallback == null) ? null
41-
: InterceptorFactory.newOfWSResponseObject(resultCallback, Boolean.class);
42-
sendSubscription("subscribeTransactions", params, interceptor, resultInterceptor);
43-
}
44-
45-
@Override
46-
public void unsubscribeToTransactions(Callback<Boolean> callback) {
47-
Interceptor interceptor =
48-
(callback == null) ?
49-
null :
50-
InterceptorFactory.newOfWSResponseObject(callback, Boolean.class);
51-
sendUnsubscription("unsubscribeTicker", null, interceptor);
23+
Map<String, String> subsKeys = this.getSubscritpionKeys();
24+
// transactions
25+
subsKeys.put("unsubscribeTransactions","transactions");
26+
subsKeys.put("subscribeTransactions","transactions");
27+
subsKeys.put("updateTransaction","transactions");
28+
//balance
29+
subsKeys.put("unsubscribeBalance","balance");
30+
subsKeys.put("subscribeBalance","balance");
31+
subsKeys.put("balance","balance");
5232
}
5333

5434
@Override
@@ -116,4 +96,62 @@ public void loadTransactions(String currency, Pagination pagination, Boolean sho
11696
callback);
11797

11898
}
99+
100+
@Override
101+
public void subscribeToTransactions(Callback<Transaction> callback, Callback<Boolean> resultCallback) {
102+
Map<String, Object> params = new HashMap<>();
103+
Interceptor interceptor = new Interceptor() {
104+
@Override
105+
public void makeCall(WSJsonResponse response) {
106+
ErrorBody error = response.getError();
107+
if (error != null) {
108+
callback.reject(new CryptomarketAPIException(error));
109+
} else {
110+
Transaction transaction = adapter.objectFromValue(response.getParams(), Transaction.class);
111+
callback.resolve(transaction);
112+
}
113+
}
114+
};
115+
Interceptor resultInterceptor = (resultCallback == null) ? null
116+
: InterceptorFactory.newOfWSResponseObject(resultCallback, Boolean.class);
117+
sendSubscription("subscribeTransactions", params, interceptor, resultInterceptor);
118+
}
119+
120+
@Override
121+
public void unsubscribeToTransactions(Callback<Boolean> callback) {
122+
Interceptor interceptor =
123+
(callback == null) ?
124+
null :
125+
InterceptorFactory.newOfWSResponseObject(callback, Boolean.class);
126+
sendUnsubscription("unsubscribeTicker", null, interceptor);
127+
}
128+
129+
@Override
130+
public void subscribeToBalance(Callback<List<Balance>> callback, Callback<Boolean> resultCallback) {
131+
Map<String, Object> params = new HashMap<>();
132+
Interceptor interceptor = new Interceptor() {
133+
@Override
134+
public void makeCall(WSJsonResponse response) {
135+
ErrorBody error = response.getError();
136+
if (error != null) {
137+
callback.reject(new CryptomarketAPIException(error));
138+
} else {
139+
List<Balance> balances = adapter.listFromValue(response.getParams(), Balance.class);
140+
callback.resolve(balances);
141+
}
142+
}
143+
};
144+
Interceptor resultInterceptor = (resultCallback == null) ? null
145+
: InterceptorFactory.newOfWSResponseObject(resultCallback, Boolean.class);
146+
sendSubscription("subscribeBalance", params, interceptor, resultInterceptor);
147+
}
148+
149+
@Override
150+
public void unsubscribeToBalance(Callback<Boolean> callback) {
151+
Interceptor interceptor =
152+
(callback == null) ?
153+
null :
154+
InterceptorFactory.newOfWSResponseObject(callback, Boolean.class);
155+
sendUnsubscription("unsubscribeBalance", null, interceptor);
156+
}
119157
}

src/main/java/com/cryptomarket/sdk/websocket/CryptomarketWSPublicClientImpl.java

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,26 @@ static class CandleListInData {
4343

4444
public CryptomarketWSPublicClientImpl() throws IOException {
4545
super("wss://api.exchange.cryptomkt.com/api/2/ws/public");
46+
Map<String, String> subsKeys = this.getSubscritpionKeys();
47+
// tickers
48+
subsKeys.put("subscribeTicker","tickers");
49+
subsKeys.put("unsubscribeTicker","tickers");
50+
subsKeys.put("ticker","tickers");
51+
//orderbooks
52+
subsKeys.put("subscribeOrderbook","orderbooks");
53+
subsKeys.put("unsubscribeOrderbook","orderbooks");
54+
subsKeys.put("snapshotOrderbook","orderbooks");
55+
subsKeys.put("updateOrderbook","orderbooks");
56+
// trades
57+
subsKeys.put("subscribeTrades","trades");
58+
subsKeys.put("unsubscribeTrades","trades");
59+
subsKeys.put("snapshotTrades","trades");
60+
subsKeys.put("updateTrades","trades");
61+
// candles
62+
subsKeys.put("subscribeCandles","candles");
63+
subsKeys.put("unsubscribeCandles","candles");
64+
subsKeys.put("snapshotCandles","candles");
65+
subsKeys.put("updateCandles","candles");
4666
}
4767

4868
@Override
@@ -56,7 +76,7 @@ protected void handleNotification(WSJsonResponse response) {
5676
}
5777
String key = buildKey(method, sp.symbol, sp.period);
5878
Interceptor interceptor = interceptorCache.getSubscriptionInterceptor(key);
59-
if (MethodMap.isOrderbookFeed(method)) {
79+
if (this.isOrderbookFeed(method)) {
6080
OBCache.update(method, key, response);
6181
if (OBCache.orderbookBroken(key)) {
6282
OBCache.waitOrderbook(key);
@@ -80,12 +100,16 @@ protected String buildKey(String method, Map<String, Object> params) {
80100
}
81101

82102
private String buildKey(String method, String symbol, String period) {
83-
String methodKey = MethodMap.getMethodKey(method);
84-
if (method.equals("report") || method.equals("activeOrders")) return methodKey + "::";
103+
String methodKey = this.getSubscritpionKeys().get(method);
85104
String key = methodKey + ":" + symbol + ":" + period;
86105
return key.toUpperCase();
87106
}
88107

108+
public boolean isOrderbookFeed(String method) {
109+
if (getSubscritpionKeys().get(method).equals("orderbooks")) return true;
110+
return false;
111+
}
112+
89113
@Override
90114
public void getCurrencies(Callback<List<Currency>> callback) {
91115
Map<String, Object> params = new HashMap<>();

src/main/java/com/cryptomarket/sdk/websocket/CryptomarketWSTradingClientImpl.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ public class CryptomarketWSTradingClientImpl extends AuthClient implements Crypt
2323

2424
public CryptomarketWSTradingClientImpl(String apiKey, String apiSecret) throws IOException {
2525
super("wss://api.exchange.cryptomkt.com/api/2/ws/trading", apiKey, apiSecret);
26+
Map<String, String> subsKeys = this.getSubscritpionKeys();
27+
// reports
28+
subsKeys.put("subscribeReports", "reports");
29+
subsKeys.put("unsubscribeReports","reports");
30+
subsKeys.put("activeOrders","reports");
31+
subsKeys.put("report","reports");
2632
}
2733

2834
@Override

src/main/java/com/cryptomarket/sdk/websocket/MethodMap.java

Lines changed: 0 additions & 56 deletions
This file was deleted.

src/test/java/com/cryptomarket/sdk/TestWSAccountClientSubs.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
import static org.junit.Assert.fail;
44

5+
import java.util.List;
56
import java.util.concurrent.TimeUnit;
67

78
import com.cryptomarket.sdk.models.Transaction;
9+
import com.cryptomarket.sdk.models.Balance;
810
import com.cryptomarket.sdk.websocket.CryptomarketWSAccountClient;
911
import com.cryptomarket.sdk.websocket.CryptomarketWSAccountClientImpl;
1012

@@ -70,4 +72,40 @@ public void resolve(Transaction result) {
7072
}
7173
try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {fail();}
7274
}
75+
76+
@Test
77+
public void testSubscribeToBalance() {
78+
79+
Callback<List<Balance>> callback = new Callback<List<Balance>>() {
80+
@Override
81+
public void resolve(List<Balance> result) {
82+
for (Balance balance : result) {
83+
Checker.checkBalance.accept(balance);
84+
}
85+
}
86+
};
87+
wsClient.subscribeToBalance(callback, resultCallback);
88+
89+
Callback<Transaction> callback2 = new Callback<Transaction>() {
90+
@Override
91+
public void resolve(Transaction result) {
92+
Checker.checkTransaction.accept(result);
93+
}
94+
};
95+
wsClient.subscribeToTransactions(callback2, resultCallback);
96+
97+
try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {fail();}
98+
try {
99+
restClient.transferMoneyFromAccountBalanceToTradingBalance("EOS", "0.1");
100+
} catch (Exception e) {
101+
e.printStackTrace();
102+
}
103+
try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {fail();}
104+
try {
105+
restClient.transferMoneyFromTradingBalanceToAccountBalance("EOS", "0.1");
106+
} catch (Exception e) {
107+
e.printStackTrace();
108+
}
109+
try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {fail();}
110+
}
73111
}

0 commit comments

Comments
 (0)