-
Notifications
You must be signed in to change notification settings - Fork 179
/
fill.go
247 lines (202 loc) · 7.97 KB
/
fill.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
package periodicauction
import (
"fmt"
"strings"
sdk "github.com/okex/exchain/libs/cosmos-sdk/types"
orderkeeper "github.com/okex/exchain/x/order/keeper"
"github.com/okex/exchain/x/order/types"
token "github.com/okex/exchain/x/token/types"
)
func fillBuyOrders(ctx sdk.Context, keeper orderkeeper.Keeper, product string,
bestPrice, maxExecution sdk.Dec, buyExecuted *sdk.Dec,
blockRemainDeals int64, feeParams *types.Params) ([]types.Deal, int64) {
var buyDeals []types.Deal
book := keeper.GetDepthBookCopy(product)
// Fill buy orders, prices from high to low
index := 0
for index < len(book.Items) {
if !(book.Items[index].Price.GTE(bestPrice) && buyExecuted.LT(maxExecution)) {
break
}
// item.InitPrice >= bestPrice, fill buy orders
fillAmount := sdk.MinDec(book.Items[index].BuyQuantity, maxExecution.Sub(*buyExecuted))
if fillAmount.IsZero() { // no buyer at this price
index++
continue
}
// Fill buy orders at this price
key := types.FormatOrderIDsKey(product, book.Items[index].Price, types.BuyOrder)
filledBuyDeals, filledBuyAmount, filledDealsCnt := fillOrderByKey(ctx, keeper, key,
fillAmount, bestPrice, feeParams, blockRemainDeals)
blockRemainDeals -= filledDealsCnt
buyDeals = append(buyDeals, filledBuyDeals...)
*buyExecuted = buyExecuted.Add(filledBuyAmount)
book.Sub(index, filledBuyAmount, types.BuyOrder)
res := book.RemoveIfEmpty(index)
if !res {
index++
}
if blockRemainDeals <= 0 {
break
}
}
keeper.SetDepthBook(product, book)
return buyDeals, blockRemainDeals
}
func fillSellOrders(ctx sdk.Context, keeper orderkeeper.Keeper, product string,
bestPrice, maxExecution sdk.Dec, sellExecuted *sdk.Dec,
blockRemainDeals int64, feeParams *types.Params) ([]types.Deal, int64) {
var sellDeals []types.Deal
book := keeper.GetDepthBookCopy(product)
// Fill sell orders, prices from low to high
index := len(book.Items) - 1
for index >= 0 {
if !(book.Items[index].Price.LTE(bestPrice) && sellExecuted.LT(maxExecution)) {
break
}
// item.InitPrice <= bestPrice, fill sell orders
fillAmount := sdk.MinDec(book.Items[index].SellQuantity, maxExecution.Sub(*sellExecuted))
if fillAmount.IsZero() {
index--
continue
}
// Fill sell orders at this price
key := types.FormatOrderIDsKey(product, book.Items[index].Price, types.SellOrder)
filledSellDeals, filledSellAmount, filledDealsCnt := fillOrderByKey(ctx, keeper,
key, fillAmount, bestPrice, feeParams, blockRemainDeals)
blockRemainDeals -= filledDealsCnt
sellDeals = append(sellDeals, filledSellDeals...)
*sellExecuted = sellExecuted.Add(filledSellAmount)
book.Sub(index, filledSellAmount, types.SellOrder)
book.RemoveIfEmpty(index)
if blockRemainDeals <= 0 {
break
}
index--
}
keeper.SetDepthBook(product, book) // update depthbook on filled
return sellDeals, blockRemainDeals
}
// fillDepthBook will fill orders in depth book with bestPrice.
// It will update book and orderIDsMap, also update orders, charge fees, and transfer tokens,
// then return all deals.
func fillDepthBook(ctx sdk.Context,
keeper orderkeeper.Keeper,
product string,
bestPrice,
maxExecution sdk.Dec,
buyExecutedCnt,
sellExecutedCnt *sdk.Dec,
blockRemainDeals int64,
feeParams *types.Params) ([]types.Deal, int64) {
var deals []types.Deal
if maxExecution.IsZero() {
return deals, blockRemainDeals
}
buyDeals, blockRemainDeals := fillBuyOrders(ctx, keeper, product, bestPrice, maxExecution,
buyExecutedCnt, blockRemainDeals, feeParams)
deals = append(deals, buyDeals...)
if blockRemainDeals <= 0 {
return deals, blockRemainDeals
}
sellDeals, blockRemainDeals := fillSellOrders(ctx, keeper, product, bestPrice, maxExecution,
sellExecutedCnt, blockRemainDeals, feeParams)
deals = append(deals, sellDeals...)
return deals, blockRemainDeals
}
// Fill orders in orderIDsMap at specific key
func fillOrderByKey(ctx sdk.Context, keeper orderkeeper.Keeper, key string,
needFillAmount sdk.Dec, fillPrice sdk.Dec, feeParams *types.Params,
remainDeals int64) ([]types.Deal, sdk.Dec, int64) {
deals := []types.Deal{}
filledAmount := sdk.ZeroDec()
orderIDsMap := keeper.GetDiskCache().GetOrderIDsMapCopy()
filledDealsCnt := int64(0)
orderIDs, ok := orderIDsMap.Data[key]
// if key not found in orderIDsMap, return
if !ok {
return deals, filledAmount, filledDealsCnt
}
index := 0
for filledDealsCnt < remainDeals && filledAmount.LT(needFillAmount) {
order := keeper.GetOrder(ctx, orderIDs[index])
if order == nil {
ctx.Logger().Error("[Order] Not exist orderID: ", orderIDs[index])
}
if filledAmount.Add(order.RemainQuantity).LTE(needFillAmount) {
filledAmount = filledAmount.Add(order.RemainQuantity)
if deal := fillOrder(order, ctx, keeper, fillPrice, order.RemainQuantity, feeParams); deal != nil {
deals = append(deals, *deal)
}
filledDealsCnt++
index++
} else {
if deal := fillOrder(order, ctx, keeper, fillPrice, needFillAmount.Sub(filledAmount), feeParams); deal != nil {
deals = append(deals, *deal)
}
filledAmount = needFillAmount
break
}
}
unFilledOrderIDs := orderIDs[index:] // update orderIDs, remove filled orderIDs
// Note: orderIDs cannot be nil, we will use empty slice to remove Data on keeper
if len(unFilledOrderIDs) == 0 {
unFilledOrderIDs = []string{}
}
keeper.SetOrderIDs(key, unFilledOrderIDs) // update orderIDsMap on filled
return deals, filledAmount, filledDealsCnt
}
func balanceAccount(order *types.Order, ctx sdk.Context, keeper orderkeeper.Keeper,
fillPrice, fillQuantity sdk.Dec) {
symbols := strings.Split(order.Product, "_")
// transfer tokens
var outputCoins, inputCoins sdk.SysCoins
if order.Side == types.BuyOrder {
outputCoins = sdk.SysCoins{{Denom: symbols[1], Amount: fillPrice.Mul(fillQuantity)}}
inputCoins = sdk.SysCoins{{Denom: symbols[0], Amount: fillQuantity}}
} else {
outputCoins = sdk.SysCoins{{Denom: symbols[0], Amount: fillQuantity}}
inputCoins = sdk.SysCoins{{Denom: symbols[1], Amount: fillPrice.Mul(fillQuantity)}}
}
keeper.BalanceAccount(ctx, order.Sender, outputCoins, inputCoins)
}
func chargeFee(order *types.Order, ctx sdk.Context, keeper orderkeeper.Keeper, fillQuantity sdk.Dec,
feeParams *types.Params) (dealFee sdk.SysCoins, feeReceiver string) {
// charge fee
fee := orderkeeper.GetZeroFee()
if order.Status == types.OrderStatusFilled {
lockedFee := orderkeeper.GetOrderNewFee(order)
fee = orderkeeper.GetOrderCostFee(order, ctx)
receiveFee := lockedFee.Sub(fee)
keeper.UnlockCoins(ctx, order.Sender, lockedFee, token.LockCoinsTypeFee)
keeper.AddFeeDetail(ctx, order.Sender, receiveFee, types.FeeTypeOrderReceive)
order.RecordOrderReceiveFee(receiveFee)
err := keeper.AddCollectedFees(ctx, fee, order.Sender, types.FeeTypeOrderNew, false)
if err != nil {
ctx.Logger().Error(fmt.Sprintf("Send fee failed:%s\n", err.Error()))
}
}
dealFee = orderkeeper.GetDealFee(order, fillQuantity, ctx, keeper, feeParams)
feeReceiver, err := keeper.SendFeesToProductOwner(ctx, dealFee, order.Sender, types.FeeTypeOrderDeal, order.Product)
if err == nil {
order.RecordOrderDealFee(fee)
}
return
}
// Fill an order. Update order, charge fee and transfer tokens. Return a deal.
// If an order is fully filled but still lock some coins, unlock it.
func fillOrder(order *types.Order, ctx sdk.Context, keeper orderkeeper.Keeper,
fillPrice, fillQuantity sdk.Dec, feeParams *types.Params) *types.Deal {
// update order
order.Fill(fillPrice, fillQuantity)
balanceAccount(order, ctx, keeper, fillPrice, fillQuantity)
// if fully filled and still need unlock coins
if order.Status == types.OrderStatusFilled && order.RemainLocked.IsPositive() {
needUnlockCoins := order.NeedUnlockCoins()
keeper.UnlockCoins(ctx, order.Sender, needUnlockCoins, token.LockCoinsTypeQuantity)
order.Unlock()
}
dealFee, feeReceiver := chargeFee(order, ctx, keeper, fillQuantity, feeParams)
keeper.UpdateOrder(order, ctx) // update order info on filled
return &types.Deal{OrderID: order.OrderID, Side: order.Side, Quantity: fillQuantity, Fee: dealFee.String(), FeeReceiver: feeReceiver}
}