-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathChannelHandler.java
More file actions
222 lines (185 loc) · 7.52 KB
/
Copy pathChannelHandler.java
File metadata and controls
222 lines (185 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package bittrex;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
public class ChannelHandler {
private static final Logger LOG = LoggerFactory.getLogger(ChannelHandler.class);
private final CurrencyPair pair;
private WebsocketChannelState state = WebsocketChannelState.SYNCING;
// price -> amount
private final TreeMap<BigDecimal, BigDecimal> bids = new TreeMap<>((k1, k2) -> -k1.compareTo(k2));
private final TreeMap<BigDecimal, BigDecimal> asks = new TreeMap<>();
private final HubProxy proxy;
private final String marketName;
private OrderBook orderBook = null;
private long heartbeat;
private Date syncTimestamp;
private long nounce;
private final List<UpdateExchangeStateItem> queue = new ArrayList<>();
private final RingBuffer<Trade> tradeRing = new RingBuffer<Trade>(1000);
private final Set<Consumer<Trade>> tradeListener;
public ChannelHandler(String marketName, CurrencyPair pair, HubProxy proxy, Set<Consumer<Trade>> tradeListener) {
this.pair = pair;
this.proxy = proxy;
this.marketName = marketName;
this.tradeListener = tradeListener;
}
protected void fetchState() {
SignalRFuture<QueryExchangeState> state = proxy.invoke(QueryExchangeState.class, "QueryExchangeState", marketName);
try {
QueryExchangeState queryExchangeState = state.get(10, TimeUnit.SECONDS);
if (queryExchangeState == null) {
throw new RuntimeException("Exchange State in null, pair " + pair + ".");
}
processSnapShot(queryExchangeState);
getOrderBook();
} catch (Throwable e) {
LOG.warn("Could not fetch the snapshot " + e.getClass().getSimpleName(), e);
this.state = WebsocketChannelState.ERROR;
throw new BittrexException(false, "Could not fetch the snapshot. " + e.getClass().getSimpleName() + ": "+ e.getMessage(), true);
}
}
synchronized protected void processUpdate(UpdateExchangeStateItem o) {
orderBook = null;
if (state == WebsocketChannelState.SYNCING) {
queue.add(o);
} else {
processUpdate0(o);
}
heartbeat = System.currentTimeMillis();
}
private void processUpdate0(UpdateExchangeStateItem o) {
if (o.nounce <= nounce) {
return;
}
if (o.nounce - nounce == 1) {
nounce++;
} else {
LOG.warn("Missing data, going to resubscribe " + pair);
state = WebsocketChannelState.ERROR;
syncTimestamp = null;
orderBook = null;
return;
}
BiConsumer<OrderUpdate, TreeMap<BigDecimal, BigDecimal>> ordersProcessor = (u, col) -> {
switch (u.type) {
case ADD:
case UPDATE:
col.put(u.rate, u.quantity);
break;
case REMOVE:
col.remove(u.rate);
break;
default:
throw new RuntimeException("Unknown update type " + u.type); // should never happen
}
};
Stream.of(o.buys).forEach(u -> ordersProcessor.accept(u, bids));
Stream.of(o.sells).forEach(u -> ordersProcessor.accept(u, asks));
Stream.of(o.fills).forEach(u -> {
OrderType ordeType = u.orderType.equals("SELL") ? OrderType.ASK : OrderType.BID;
Trade t = new Trade(ordeType, u.quantity, pair, u.rate, u.timeStamp, null);
tradeRing.add(t);
informListener(t);
});
}
private void informListener(Trade trade) {
try {
tradeListener.parallelStream().forEach(c -> c.accept(trade));
} catch (Throwable t) {
LOG.warn("Error executing listeners.", t);
}
}
private synchronized void processSnapShot(QueryExchangeState v) {
nounce = v.nounce;
bids.clear();
asks.clear();
Stream.of(v.buys).forEach(o -> bids.put(o.rate, o.quantity));
Stream.of(v.sells).forEach(o -> asks.put(o.rate, o.quantity));
queue.forEach(this::processUpdate0);
queue.clear();
tradeRing.clear();
Stream.of(v.fills).forEach(f -> {
String id = Long.toString(f.id);
OrderType ordeType = f.orderType.equals("SELL") ? OrderType.ASK : OrderType.BID;
tradeRing.add(new Trade(ordeType, f.quantity, pair, f.price, f.timeStamp, id));
});
// inform trde listeners about the very last trade
Trade last = tradeRing.last();
if (last != null) {
informListener(last);
}
state = WebsocketChannelState.SYNCED;
heartbeat = System.currentTimeMillis();
syncTimestamp = new Date();
}
public OrderBook getOrderBook() {
checkState();
OrderBook old = orderBook;
if (old != null) {
return old;
}
synchronized (this) {
orderBook = new OrderBook(asks, bids);
checkConsistency(orderBook);
return orderBook;
}
}
private void checkConsistency(OrderBook orderBook) {
if (orderBook.bids.isEmpty()) {
throw new BittrexException(false, String.format("Order book inconsistent, pair: %s, bid site is empty.", pair), true);
}
if (orderBook.asks.isEmpty()) {
throw new BittrexException(false, String.format("Order book inconsistent, pair: %s, ask site is empty.", pair), true);
}
if (gt(orderBook.bids.firstKey(), orderBook.asks.firstKey())) {
throw new BittrexException(false, String.format("Order book inconsistent, pair: %s, first bid %s is higher than first ask %s.", pair, orderBook.bids.firstKey(), orderBook.asks.firstKey()), true);
}
}
public static boolean gt(BigDecimal a, BigDecimal b) { return a.compareTo(b) > 0; }
public List<Trade> getTrades() {
checkState();
synchronized (this) {
return tradeRing.list();
}
}
private void checkState() {
if (!state.synced()) {
throw new BittrexException(false, "Channel is not synced @ bittrex, pair: " + pair + ", state: " + state, state == WebsocketChannelState.ERROR);
} else if(System.currentTimeMillis() - heartbeat > TimeUnit.SECONDS.toMillis(60)) {
throw new BittrexException(false, "Channel has not received updates @ bittrex, pair: " + pair + ", state: " + state, true);
}
}
public String getId() {
return marketName;
}
public WebsocketChannelState getState() {
return state;
}
public CurrencyPair getPair() {
return pair;
}
public Date getSyncTimestamp() {
return syncTimestamp;
}
public int getTimeSinceLastUpdateSeconds() {
return heartbeat == 0 ? -1 : (int) ((System.currentTimeMillis() - heartbeat) / 1000);
}
public static enum WebsocketChannelState {
SYNCED, SYNCING, ERROR;
public boolean synced() {
return this == SYNCED;
}
}
}