Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(OrderBook.ts) persist trades to DB #659

Merged
merged 7 commits into from
Nov 16, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/orderbook/OrderBook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ class OrderBook extends EventEmitter {
portion.localId = maker.localId;
result.internalMatches.push(maker);
this.emit('ownOrder.filled', portion);
await this.perssitTrade(portion.quantity, maker.id, taker.id);
onUpdate && onUpdate({ case: PlaceOrderEventCase.InternalMatch, payload: maker });
} else {
if (!this.swaps) {
Expand All @@ -314,6 +315,7 @@ class OrderBook extends EventEmitter {
await this.repository.addOrderIfNotExists(maker);
const swapResult = await this.swaps.executeSwap(maker, taker);
this.emit('peerOrder.filled', portion);
await this.perssitTrade(swapResult.quantity, maker.id, taker.id);
result.swapResults.push(swapResult);
onUpdate && onUpdate({ case: PlaceOrderEventCase.SwapResult, payload: swapResult });
} catch (err) {
Expand Down Expand Up @@ -361,6 +363,7 @@ class OrderBook extends EventEmitter {
try {
const swapResult = await this.swaps!.executeSwap(maker, taker);
this.emit('peerOrder.filled', maker);
await this.perssitTrade(swapResult.quantity, maker.id, taker.id);
return swapResult;
} catch (err) {
this.emit('peerOrder.invalidation', maker);
Expand All @@ -387,6 +390,14 @@ class OrderBook extends EventEmitter {
return true;
}

private perssitTrade = async (quantity: number, makerOrderId: string, takerOrderId: string) => {
ImmanuelSegol marked this conversation as resolved.
Show resolved Hide resolved
await this.repository.addTrade({
makerOrderId,
takerOrderId,
quantity,
});
}

/**
* Adds an incoming peer order to the local order book. It timestamps the order based on when it
* enters the order book and also records its initial quantity upon being received.
Expand Down
4 changes: 4 additions & 0 deletions lib/orderbook/OrderBookRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ class OrderbookRepository {
await this.models.Order.create(order as OrderAttributes);
}
}

public addTrade = async (trade: db.TradeFactory) => {
await this.models.Trade.create(trade);
}
}

export default OrderbookRepository;