-
Notifications
You must be signed in to change notification settings - Fork 0
/
exchange.cpp
66 lines (53 loc) · 2.11 KB
/
exchange.cpp
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
#include "exchange.h"
#include "orderbook.h"
#include <mutex>
#include <stdexcept>
#include <string>
#define LOCK_EXCHANGE() std::lock_guard<std::mutex> lock(mu)
#define UNLOCK_EXCHANGE() lock.
static ExchangeListener dummy;
Exchange::Exchange(ExchangeListener& listener) : listener(listener) {}
Exchange::Exchange() : listener(dummy) {}
const Order Exchange::getOrder(long exchangeId) {
OrderBook* book;
Order* order = allOrders.get(exchangeId);
if(!order) throw std::runtime_error("invalid exchange order id "+std::to_string(exchangeId));
book = books.get(order->instrument);
if(!book) throw std::runtime_error("missing book for order id"+std::to_string(exchangeId));
auto bookGuard = book->lock();
return book->getOrder(order);
}
const Book Exchange::book(const std::string& instrument) {
OrderBook* book;
book = books.getOrCreate(instrument,*this);
auto bookGuard = book->lock();
return book->book();
}
int Exchange::cancel(long exchangeId) {
OrderBook* book;
Order* order = allOrders.get(exchangeId);
if(!order) throw std::runtime_error("invalid exchange order id "+std::to_string(exchangeId));
book = books.get(order->instrument);
if(!book) throw std::runtime_error("missing book for order id"+std::to_string(exchangeId));
auto bookGuard = book->lock();
return book->cancelOrder(order);
}
long Exchange::insertOrder(std::string instrument,F price,int quantity,Side side,std::string orderId) {
OrderBook *book = books.getOrCreate(instrument,*this);
auto bookGuard = book->lock();
long id = nextID();
Order *order = new (book->allocateOrder()) Order(orderId,book->instrument,price,quantity,side,id);
allOrders.add(order);
book->insertOrder(order);
return id;
}
long Exchange::buy(std::string instrument,F price,int quantity,std::string orderId) {
return insertOrder(instrument,price,quantity,BUY,orderId);
}
long Exchange::sell(std::string instrument,F price,int quantity,std::string orderId) {
return insertOrder(instrument,price,quantity,SELL,orderId);
}
long Exchange::nextID() {
static std::atomic<long> id = 0;
return ++id;
}