-
Notifications
You must be signed in to change notification settings - Fork 3
/
match.go
256 lines (223 loc) · 6.79 KB
/
match.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
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type PriceDirection int
const (
PriceStaying PriceDirection = iota + 1
PriceIncreasing
PriceDecreasing
)
type MatchEngine struct {
BuyOrderSource OrderSource
SellOrderSource OrderSource
TickPrecision int // price tick precision
}
func NewMatchEngine(buys, sells OrderSource, prec int) *MatchEngine {
return &MatchEngine{
BuyOrderSource: buys,
SellOrderSource: sells,
TickPrecision: prec,
}
}
func NewMatchEngineFromOrderBook(ob *OrderBook) *MatchEngine {
return NewMatchEngine(ob.OrderSource(SwapDirectionBuy), ob.OrderSource(SwapDirectionSell), ob.TickPrecision)
}
func (engine *MatchEngine) Matchable() bool {
highestBuyPrice, found := engine.BuyOrderSource.HighestTick()
if !found {
return false
}
return engine.SellOrderSource.AmountLTE(highestBuyPrice).IsPositive()
}
func (engine *MatchEngine) EstimatedPriceDirection(midPrice sdk.Dec) PriceDirection {
buyAmount := engine.BuyOrderSource.AmountGTE(midPrice)
sellAmount := engine.SellOrderSource.AmountLTE(midPrice)
switch {
case buyAmount.GT(sellAmount):
return PriceIncreasing
case sellAmount.GT(buyAmount):
return PriceDecreasing
default:
return PriceStaying
}
}
func (engine *MatchEngine) InitialMatchPrice() (price sdk.Dec, dir PriceDirection) {
highestBuyPrice, found := engine.BuyOrderSource.HighestTick()
if !found {
panic("there is no buy orders")
}
lowestSellPrice, found := engine.SellOrderSource.LowestTick()
if !found {
panic("there is no sell orders")
}
midPrice := highestBuyPrice.Add(lowestSellPrice).QuoInt64(2)
midPriceTick := PriceToTick(midPrice, engine.TickPrecision)
dir = engine.EstimatedPriceDirection(midPrice)
switch dir {
case PriceStaying:
price = RoundPrice(midPrice, engine.TickPrecision)
case PriceIncreasing:
price = midPriceTick
case PriceDecreasing:
if !midPrice.Equal(midPriceTick) {
price = UpTick(midPriceTick, engine.TickPrecision)
} else {
price = midPriceTick
}
}
return
}
func (engine *MatchEngine) FindMatchPrice() sdk.Dec {
matchPrice, dir := engine.InitialMatchPrice()
if dir == PriceStaying { // TODO: is this correct?
return matchPrice
}
tickSource := MergeOrderSources(engine.BuyOrderSource, engine.SellOrderSource) // temporary order source just for ticks
buysCache := map[int]sdk.Int{}
buyAmountGTE := func(i int) sdk.Int {
ba, ok := buysCache[i]
if !ok {
ba = engine.BuyOrderSource.AmountGTE(TickFromIndex(i, engine.TickPrecision))
buysCache[i] = ba
}
return ba
}
sellsCache := map[int]sdk.Int{}
sellAmountLTE := func(i int) sdk.Int {
sa, ok := sellsCache[i]
if !ok {
sa = engine.SellOrderSource.AmountLTE(TickFromIndex(i, engine.TickPrecision))
sellsCache[i] = sa
}
return sa
}
for {
i := TickToIndex(matchPrice, engine.TickPrecision)
if buyAmountGTE(i+1).LTE(sellAmountLTE(i)) && buyAmountGTE(i).GTE(sellAmountLTE(i-1)) {
return matchPrice
}
var nextPrice sdk.Dec
var found bool
switch dir {
case PriceIncreasing:
if buyAmountGTE(i + 1).IsZero() {
return matchPrice
}
nextPrice, found = tickSource.UpTick(matchPrice)
case PriceDecreasing:
if sellAmountLTE(i - 1).IsZero() {
return matchPrice
}
nextPrice, found = tickSource.DownTick(matchPrice)
}
if !found {
return matchPrice
}
matchPrice = nextPrice
}
}
// TODO: no need to return the order book
func (engine *MatchEngine) Match() (orderBook *OrderBook, matchPrice sdk.Dec, quoteCoinDustAmt sdk.Int, matched bool) {
if !engine.Matchable() {
return
}
matchPrice = engine.FindMatchPrice()
buyPrice, _ := engine.BuyOrderSource.HighestTick()
sellPrice, _ := engine.SellOrderSource.LowestTick()
var buyOrders, sellOrders Orders
orderBook = NewOrderBook(engine.TickPrecision)
for buyPrice.GTE(matchPrice) {
orders := engine.BuyOrderSource.Orders(buyPrice)
orderBook.AddOrders(orders...)
buyOrders = append(buyOrders, orders...)
var found bool
buyPrice, found = engine.BuyOrderSource.DownTickWithOrders(buyPrice)
if !found {
break
}
}
for sellPrice.LTE(matchPrice) {
orders := engine.SellOrderSource.Orders(sellPrice)
orderBook.AddOrders(orders...)
sellOrders = append(sellOrders, orders...)
var found bool
sellPrice, found = engine.SellOrderSource.UpTickWithOrders(sellPrice)
if !found {
break
}
}
quoteCoinDustAmt, matched = MatchOrders(buyOrders, sellOrders, matchPrice)
return
}
func FindLastMatchableOrders(orders1, orders2 Orders, matchPrice sdk.Dec) (idx1, idx2 int, partialMatchAmt1, partialMatchAmt2 sdk.Int, found bool) {
sides := []*struct {
orders Orders
totalAmt sdk.Int
i int
partialMatchAmt sdk.Int
}{
{orders1, orders1.OpenAmount(), len(orders1) - 1, sdk.Int{}},
{orders2, orders2.OpenAmount(), len(orders2) - 1, sdk.Int{}},
}
for {
ok := true
for _, side := range sides {
i := side.i
order := side.orders[i]
matchAmt := sdk.MinInt(sides[0].totalAmt, sides[1].totalAmt)
side.partialMatchAmt = matchAmt.Sub(side.totalAmt.Sub(order.GetOpenAmount()))
if side.totalAmt.Sub(order.GetOpenAmount()).GT(matchAmt) ||
matchPrice.MulInt(side.partialMatchAmt).TruncateInt().IsZero() {
if i == 0 {
return
}
side.totalAmt = side.totalAmt.Sub(order.GetOpenAmount())
side.i--
ok = false
}
}
if ok {
return sides[0].i, sides[1].i, sides[0].partialMatchAmt, sides[1].partialMatchAmt, true
}
}
}
func MatchOrders(buyOrders, sellOrders Orders, matchPrice sdk.Dec) (quoteCoinDustAmt sdk.Int, matched bool) {
buyOrders.Sort(DescendingPrice)
sellOrders.Sort(AscendingPrice)
bi, si, pmb, pms, found := FindLastMatchableOrders(buyOrders, sellOrders, matchPrice)
if !found {
return
}
quoteCoinDustAmt = sdk.ZeroInt()
for i := 0; i <= bi; i++ {
buyOrder := buyOrders[i]
var receivedBaseCoinAmt sdk.Int
if i < bi {
receivedBaseCoinAmt = buyOrder.GetOpenAmount()
} else {
receivedBaseCoinAmt = pmb
}
paidQuoteCoinAmt := matchPrice.MulInt(receivedBaseCoinAmt).Ceil().TruncateInt()
buyOrder.SetOpenAmount(buyOrder.GetOpenAmount().Sub(receivedBaseCoinAmt))
buyOrder.SetRemainingOfferCoinAmount(buyOrder.GetRemainingOfferCoinAmount().Sub(paidQuoteCoinAmt))
buyOrder.SetReceivedAmount(receivedBaseCoinAmt)
quoteCoinDustAmt = quoteCoinDustAmt.Add(paidQuoteCoinAmt)
}
for i := 0; i <= si; i++ {
sellOrder := sellOrders[i]
var paidBaseCoinAmt sdk.Int
if i < si {
paidBaseCoinAmt = sellOrder.GetOpenAmount()
} else {
paidBaseCoinAmt = pms
}
receivedQuoteCoinAmt := matchPrice.MulInt(paidBaseCoinAmt).TruncateInt()
sellOrder.SetOpenAmount(sellOrder.GetOpenAmount().Sub(paidBaseCoinAmt))
sellOrder.SetRemainingOfferCoinAmount(sellOrder.GetRemainingOfferCoinAmount().Sub(paidBaseCoinAmt))
sellOrder.SetReceivedAmount(receivedQuoteCoinAmt)
quoteCoinDustAmt = quoteCoinDustAmt.Sub(receivedQuoteCoinAmt)
}
matched = true
return
}