-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathorderbook.go
269 lines (210 loc) · 6.6 KB
/
orderbook.go
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
package main
import (
"fmt"
"math"
"math/rand"
"sync"
)
type Orderbook struct {
BaseQueue *OrderQueue
BaseSymbol string
QuoteQueue *OrderQueue
QuoteSymbol string
Dirty bool
mu *sync.RWMutex
}
type MatchDiscovery struct {
Match *Match
QuoteOrder *Order
BaseOrder *Order
}
func NewOrderbook(symbol1, symbol2 string) *Orderbook {
baseSymbol, quoteSymbol := GetBaseQuote(symbol1, symbol2)
baseQueue := NewOrderQueue(BASE)
quoteQueue := NewOrderQueue(QUOTE)
dirty := false
mu := &sync.RWMutex{}
return &Orderbook{baseQueue, baseSymbol, quoteQueue, quoteSymbol, dirty, mu}
}
func (ob *Orderbook) Add(order *Order, sellSymbol string) {
ob.mu.Lock()
defer ob.mu.Unlock()
ob.Dirty = true
if sellSymbol == ob.BaseSymbol {
ob.QuoteQueue.Enq(order)
} else if sellSymbol == ob.QuoteSymbol {
ob.BaseQueue.Enq(order)
}
//Log("%s %v", GetBookName(ob.BaseSymbol, ob.QuoteSymbol), ob.QuoteQueue)
//Log("%s %v", GetBookName(ob.BaseSymbol, ob.QuoteSymbol), ob.BaseQueue)
}
func (ob *Orderbook) Cancel(order *Order, sellSymbol string) {
ob.mu.Lock()
defer ob.mu.Unlock()
if sellSymbol == ob.BaseSymbol {
ob.QuoteQueue.Remove(order.ID)
} else if sellSymbol == ob.QuoteSymbol {
ob.BaseQueue.Remove(order.ID)
}
//Log("%s %v", GetBookName(ob.BaseSymbol, ob.QuoteSymbol), ob.QuoteQueue)
//Log("%s %v", GetBookName(ob.BaseSymbol, ob.QuoteSymbol), ob.BaseQueue)
}
func (ob *Orderbook) ApplyMatch(match *Match) {
ob.mu.Lock()
defer ob.mu.Unlock()
ob.Dirty = true
ob.applyMatchUnlocked(match)
}
func (ob *Orderbook) applyMatchUnlocked(match *Match) {
buyOrder, ok := ob.QuoteQueue.GetOrder(match.BuyOrderID)
if !ok {
Log("Buy Order %v does not exist for match %v", match.BuyOrderID, match)
panic("error")
}
sellOrder, ok := ob.BaseQueue.GetOrder(match.SellOrderID)
if !ok {
Log("Sell Order %v does not exist for match %v", match.SellOrderID, match)
panic("error")
}
buyOrder.AmountToBuy -= match.TransferAmt
buyOrder.AmountToSell -= match.BuyerLoss
ob.QuoteQueue.FixPrice(buyOrder.ID)
if buyOrder.AmountToBuy == 0 {
Log("Removing buy order %v", buyOrder.ID)
ob.QuoteQueue.Remove(buyOrder.ID)
}
sellOrder.AmountToSell -= match.TransferAmt
sellOrder.AmountToBuy -= match.SellerGain
ob.BaseQueue.FixPrice(sellOrder.ID)
if sellOrder.AmountToBuy == 0 {
Log("Removing sell order %v", sellOrder.ID)
ob.BaseQueue.Remove(sellOrder.ID)
}
Log("Result of applying match buy order %v sell order %v", buyOrder, sellOrder)
//Log("%s %v", GetBookName(ob.BaseSymbol, ob.QuoteSymbol), ob.QuoteQueue)
//Log("%s %v", GetBookName(ob.BaseSymbol, ob.QuoteSymbol), ob.BaseQueue)
}
func (ob *Orderbook) UnapplyMatch(match *Match, order1 *Order, order2 *Order) {
ob.mu.Lock()
defer ob.mu.Unlock()
ob.Dirty = true
ob.unapplyMatchUnlocked(match, order1, order2)
}
func (ob *Orderbook) unapplyMatchUnlocked(match *Match, order1 *Order, order2 *Order) {
var backupBuy, backupSell *Order
if order1.BuySymbol == ob.QuoteSymbol {
backupBuy = order1
backupSell = order2
} else {
backupBuy = order2
backupSell = order1
}
buyOrder, buyExists := ob.QuoteQueue.GetOrder(match.BuyOrderID)
sellOrder, sellExists := ob.BaseQueue.GetOrder(match.SellOrderID)
if !buyExists {
buyOrder = backupBuy
ob.QuoteQueue.Enq(buyOrder)
}
if !sellExists {
sellOrder = backupSell
ob.BaseQueue.Enq(sellOrder)
}
buyOrder.AmountToBuy += match.TransferAmt
buyOrder.AmountToSell += match.BuyerLoss
sellOrder.AmountToBuy += match.SellerGain
sellOrder.AmountToSell += match.TransferAmt
ob.QuoteQueue.FixPrice(buyOrder.ID)
ob.BaseQueue.FixPrice(sellOrder.ID)
//Log("%s %v", GetBookName(ob.BaseSymbol, ob.QuoteSymbol), ob.QuoteQueue)
//Log("%s %v", GetBookName(ob.BaseSymbol, ob.QuoteSymbol), ob.BaseQueue)
}
func (ob *Orderbook) FindMatch() (found bool, match *Match) {
ob.mu.RLock()
defer ob.mu.RUnlock()
Log("Checking for matches on %s/%s", ob.QuoteSymbol, ob.BaseSymbol)
found, match, _, _ = ob.findMatchUnlocked()
return
}
func (ob *Orderbook) findMatchUnlocked() (found bool, match *Match, quoteOrder *Order, baseOrder *Order) {
buyOrder, buyPrice, buyErr := ob.QuoteQueue.Peek()
sellOrder, sellPrice, sellErr := ob.BaseQueue.Peek()
if buyErr != nil {
Log("No buy orders on %s/%s", ob.QuoteSymbol, ob.BaseSymbol)
return
}
if sellErr != nil {
Log("No sell orders on %s/%s", ob.QuoteSymbol, ob.BaseSymbol)
return
}
Log("%f bid (%v), %f ask (%v)", buyPrice, buyOrder.ID, sellPrice, sellOrder.ID)
if buyPrice < sellPrice {
return
}
var transferAmt, buyerBaseLoss, sellerBaseGain uint64
if buyOrder.AmountToBuy > sellOrder.AmountToSell {
transferAmt = sellOrder.AmountToSell
sellerBaseGain = sellOrder.AmountToBuy
buyerBaseLoss = uint64(math.Floor(buyPrice * float64(transferAmt)))
} else { // buyOrder.AmountToBuy <= sellOrder.AmountToSell
transferAmt = buyOrder.AmountToBuy
buyerBaseLoss = buyOrder.AmountToSell
sellerBaseGain = uint64(math.Ceil(sellPrice * float64(transferAmt)))
}
if sellerBaseGain > buyerBaseLoss {
return
}
found = true
id := rand.Uint64()
match = &Match{id, ob.QuoteSymbol, sellOrder.ID, sellerBaseGain, ob.BaseSymbol, buyOrder.ID, buyerBaseLoss, uint64(transferAmt)}
quoteOrder = buyOrder
baseOrder = sellOrder
return
}
func (ob *Orderbook) FindAllMatches() []*Match {
ob.mu.Lock()
defer ob.mu.Unlock()
discoveries := make([]*MatchDiscovery, 0)
matches := make([]*Match, 0)
for {
found, match, quoteOrder, baseOrder := ob.findMatchUnlocked()
if found {
discovery := &MatchDiscovery{match, quoteOrder, baseOrder}
discoveries = append(discoveries, discovery)
matches = append(matches, match)
ob.applyMatchUnlocked(match)
} else {
break
}
}
for i := len(discoveries) - 1; i >= 0; i-- {
discovery := discoveries[i]
ob.unapplyMatchUnlocked(discovery.Match, discovery.QuoteOrder, discovery.BaseOrder)
}
Log("Found %v matches on %s", len(matches), GetBookName(ob.BaseSymbol, ob.QuoteSymbol))
return matches
}
func (ob *Orderbook) Serial() string {
ob.mu.Lock()
defer ob.mu.Unlock()
_, bid, bidErr := ob.QuoteQueue.Peek()
_, ask, askErr := ob.BaseQueue.Peek()
marketPrice := (bid + ask) / 2
if bidErr != nil {
marketPrice = ask
} else if askErr != nil {
marketPrice = bid
}
return fmt.Sprintf("%v\n%v\n%v\n%v\n%v", marketPrice, ob.QuoteSymbol, ob.BaseSymbol, ob.QuoteQueue.Serial(), ob.BaseQueue.Serial())
}
func GetBaseQuote(symbol1, symbol2 string) (base, quote string) {
if symbol1 > symbol2 {
return symbol1, symbol2
}
return symbol2, symbol1
}
func GetBookName(symbol1, symbol2 string) string {
if symbol1 < symbol2 {
return fmt.Sprintf("%v/%v", symbol1, symbol2)
}
return fmt.Sprintf("%v/%v", symbol2, symbol1)
}