-
Notifications
You must be signed in to change notification settings - Fork 0
/
MatchingEngine.java
273 lines (225 loc) · 8.9 KB
/
MatchingEngine.java
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package com.zapata.reactivestockmarket.domain.engine;
import com.zapata.reactivestockmarket.cqrs.UpdateEvent;
import com.zapata.reactivestockmarket.domain.engine.events.OrderCanceledEvent;
import com.zapata.reactivestockmarket.domain.engine.events.OrderMatchedEvent;
import com.zapata.reactivestockmarket.domain.engine.events.OrderPlacedEvent;
import com.zapata.reactivestockmarket.domain.query.OrderType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong;
/**
* Single threaded matching engine - any thread synchronization should be done externally.
* <p>
* Uses Max-Heap and Min-Heap {@link TreeSet}
* <p>
* Time complexity for critical operations are as.
* - Add – O(log N)
* - Cancel – O(1)
* <p>
* Asynchronous - no immediate return values, all events are publishes to local event bus {@link
* MatchingEngine#engineEventSink}
*/
public class MatchingEngine {
private final Logger logger = LoggerFactory.getLogger(MatchingEngine.class);
private final TreeSet<Order> bids;
private final TreeSet<Order> asks;
private final Map<Long, Order> orders;
private final AtomicLong term;
Sinks.Many<UpdateEvent> engineEventSink = Sinks.many().multicast().onBackpressureBuffer();
Flux<UpdateEvent> engineEventFlux = engineEventSink.asFlux()
.doOnNext(n -> logger.info(n.toString()))
.publish()
.autoConnect();
public MatchingEngine() {
this.bids = new TreeSet<>(MatchingEngine::compareBids);
this.asks = new TreeSet<>(MatchingEngine::compareAsks);
this.orders = new HashMap<>();
this.term = new AtomicLong(0);
}
private static int compareBids(Order a, Order b) {
int result = b.getPrice().compareTo(a.getPrice());
if (result != 0) {
return result;
}
return Long.compare(a.getTerm(), b.getTerm());
}
private static int compareAsks(Order a, Order b) {
int result = a.getPrice().compareTo(b.getPrice());
if (result != 0) {
return result;
}
return Long.compare(a.getTerm(), b.getTerm());
}
/**
* All engine execution events are published to this bus
*
* @return local engine event bus - hot stream
*/
public Flux<UpdateEvent> engineEvents() {
return engineEventFlux;
}
/**
* Places order into matching engine
*
* @param orderId - order identifier
* @param aggregateId - asset name / aggregate identifier
* @param entryTimestamp - time when the system registered order
* @param type - direction - can be either "BUY" or "SELL"
* @param price - a price for limit order
* @param amount - amount of asset to fill by order
*/
public void placeOrder(long orderId, String aggregateId, Instant entryTimestamp, OrderType type, BigDecimal price,
BigDecimal amount) {
if (orders.containsKey(orderId)) {
return;
}
if (type == OrderType.BUY) {
buy(orderId, aggregateId, entryTimestamp, price, amount);
} else {
sell(orderId, aggregateId, entryTimestamp, price, amount);
}
}
private void buy(long incomingId, String aggregateId, Instant entryTimestamp, BigDecimal incomingPrice,
BigDecimal incomingAmount) {
while (!asks.isEmpty()) {
Order resting = asks.first();
BigDecimal restingPrice = resting.getPrice();
if (restingPrice.compareTo(incomingPrice) > 0) {
break;
}
long restingId = resting.getId();
BigDecimal restingAmount = resting.getRemainingAmount();
if (restingAmount.compareTo(incomingAmount) > 0) {
resting.reduce(incomingAmount);
engineEventSink.tryEmitNext(new OrderMatchedEvent(restingId,
aggregateId,
entryTimestamp,
incomingId,
OrderType.BUY,
incomingPrice,
restingPrice,
incomingAmount,
restingAmount,
resting.getRemainingAmount()));
return;
}
asks.remove(resting);
orders.remove(restingId);
engineEventSink.tryEmitNext(new OrderMatchedEvent(restingId,
aggregateId,
entryTimestamp,
incomingId,
OrderType.BUY,
incomingPrice,
restingPrice,
incomingAmount,
restingAmount,
BigDecimal.ZERO));
incomingAmount = incomingAmount.subtract(restingAmount);
if (incomingAmount.compareTo(BigDecimal.ZERO) == 0) {
return;
}
}
add(incomingId, aggregateId, entryTimestamp, OrderType.BUY, incomingPrice, incomingAmount, bids);
}
private void sell(long incomingId, String aggregateId, Instant entryTimestamp, BigDecimal incomingPrice,
BigDecimal incomingAmount) {
while (!bids.isEmpty()) {
Order resting = bids.first();
BigDecimal restingPrice = resting.getPrice();
if (restingPrice.compareTo(incomingPrice) < 0) {
break;
}
long restingId = resting.getId();
BigDecimal restingAmount = resting.getRemainingAmount();
if (restingAmount.compareTo(incomingAmount) > 0) {
resting.reduce(incomingAmount);
engineEventSink.tryEmitNext(new OrderMatchedEvent(restingId,
aggregateId,
entryTimestamp,
incomingId,
OrderType.SELL,
incomingPrice,
restingPrice,
incomingAmount,
restingAmount,
resting.getRemainingAmount()));
return;
}
bids.remove(resting);
orders.remove(restingId);
engineEventSink.tryEmitNext(new OrderMatchedEvent(restingId,
aggregateId,
entryTimestamp,
incomingId,
OrderType.SELL,
incomingPrice,
restingPrice,
incomingAmount,
restingAmount,
BigDecimal.ZERO));
incomingAmount = incomingAmount.subtract(restingAmount);
if (incomingAmount.compareTo(BigDecimal.ZERO) == 0) {
return;
}
}
add(incomingId, aggregateId, entryTimestamp, OrderType.SELL, incomingPrice, incomingAmount, asks);
}
private void add(long orderId, String aggregateId, Instant entryTimestamp, OrderType type, BigDecimal price,
BigDecimal amount, TreeSet<Order> queue) {
Order order = new Order(orderId, type, price, amount, term.incrementAndGet());
queue.add(order);
orders.put(orderId, order);
engineEventSink.tryEmitNext(new OrderPlacedEvent(orderId,
aggregateId,
entryTimestamp,
type,
price,
amount));
}
/**
* Cancels full amount of order.
*
* @param orderId - order identifier
* @param aggregateId - asset name / aggregate identifier
*/
public void cancelAll(long orderId, String aggregateId) {
cancel(orderId, aggregateId, BigDecimal.ZERO);
}
/**
* Partially cancels order and sets new amount to be filled
*
* @param orderId - order identifier
* @param aggregateId - asset name / aggregate identifier
* @param newAmount - new amount to replace previous amount
*/
public void cancel(long orderId, String aggregateId, BigDecimal newAmount) {
Order order = orders.get(orderId);
if (order == null) {
return;
}
BigDecimal remainingAmount = order.getRemainingAmount();
if (newAmount.compareTo(remainingAmount) >= 0) {
return;
}
if (newAmount.compareTo(BigDecimal.ZERO) > 0) {
order.resize(newAmount);
} else {
TreeSet<Order> queue = order.type() == OrderType.BUY ? bids : asks;
queue.remove(order);
orders.remove(orderId);
}
engineEventSink.tryEmitNext(new OrderCanceledEvent(orderId,
aggregateId,
order.type(),
remainingAmount.subtract(newAmount),
newAmount));
}
}