forked from InjectiveLabs/sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
derivative_orders.go
507 lines (429 loc) · 16.3 KB
/
derivative_orders.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
package types
import (
"cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
)
func NewMarketOrderForLiquidation(position *Position, positionSubaccountID common.Hash, liquidator sdk.AccAddress) *DerivativeMarketOrder {
var (
worstPrice sdk.Dec
orderType OrderType
)
// if long position, market sell order at price 0
// if short position, market buy order at price infinity
if position.IsLong {
worstPrice = sdk.ZeroDec()
orderType = OrderType_SELL
} else {
worstPrice = MaxOrderPrice
orderType = OrderType_BUY
}
order := DerivativeMarketOrder{
OrderInfo: OrderInfo{
SubaccountId: positionSubaccountID.Hex(),
FeeRecipient: liquidator.String(),
Price: worstPrice,
Quantity: position.Quantity,
},
OrderType: orderType,
Margin: sdk.ZeroDec(),
MarginHold: sdk.ZeroDec(),
TriggerPrice: nil,
}
return &order
}
func (m *DerivativeLimitOrder) ToTrimmed() *TrimmedDerivativeLimitOrder {
return &TrimmedDerivativeLimitOrder{
Price: m.OrderInfo.Price,
Quantity: m.OrderInfo.Quantity,
Margin: m.Margin,
Fillable: m.Fillable,
IsBuy: m.IsBuy(),
OrderHash: common.BytesToHash(m.OrderHash).Hex(),
}
}
func (o *DerivativeMarketOrderCancel) GetCancelDepositDelta() *DepositDelta {
order := o.MarketOrder
// no market order quantity was executed, so refund the entire margin hold
if order.IsVanilla() && o.CancelQuantity.Equal(order.OrderInfo.Quantity) {
return &DepositDelta{
AvailableBalanceDelta: order.MarginHold,
TotalBalanceDelta: sdk.ZeroDec(),
}
}
// TODO: double check that partial market order executions are covered earlier upstream
return nil
}
func (o *DerivativeMarketOrder) GetCancelRefundAmount() sdk.Dec {
if o.IsVanilla() {
return o.MarginHold
}
return sdk.ZeroDec()
}
func (o *DerivativeMarketOrderCancel) ApplyDerivativeMarketCancellation(
depositDeltas DepositDeltas,
) {
order := o.MarketOrder
subaccountID := order.SubaccountID()
// For vanilla orders that were not executed at all, increment the available balance
if order.IsVanilla() {
depositDelta := o.GetCancelDepositDelta()
if depositDelta != nil {
depositDeltas.ApplyDepositDelta(subaccountID, depositDelta)
}
}
}
func NewDerivativeMarketOrder(o *DerivativeOrder, sender sdk.AccAddress, orderHash common.Hash) *DerivativeMarketOrder {
if o.OrderInfo.FeeRecipient == "" {
o.OrderInfo.FeeRecipient = sender.String()
}
return &DerivativeMarketOrder{
OrderInfo: o.OrderInfo,
OrderType: o.OrderType,
Margin: o.Margin,
MarginHold: sdk.ZeroDec(),
TriggerPrice: o.TriggerPrice,
OrderHash: orderHash.Bytes(),
}
}
func NewDerivativeLimitOrder(o *DerivativeOrder, sender sdk.AccAddress, orderHash common.Hash) *DerivativeLimitOrder {
if o.OrderInfo.FeeRecipient == "" {
o.OrderInfo.FeeRecipient = sender.String()
}
return &DerivativeLimitOrder{
OrderInfo: o.OrderInfo,
OrderType: o.OrderType,
Margin: o.Margin,
Fillable: o.OrderInfo.Quantity,
TriggerPrice: o.TriggerPrice,
OrderHash: orderHash.Bytes(),
}
}
func (o *DerivativeLimitOrder) ToDerivativeOrder(marketID string) *DerivativeOrder {
return &DerivativeOrder{
MarketId: marketID,
OrderInfo: o.OrderInfo,
OrderType: o.OrderType,
Margin: o.Margin,
TriggerPrice: o.TriggerPrice,
}
}
func (o *DerivativeMarketOrder) ToDerivativeOrder(marketID string) *DerivativeOrder {
return &DerivativeOrder{
MarketId: marketID,
OrderInfo: o.OrderInfo,
OrderType: o.OrderType,
Margin: o.Margin,
TriggerPrice: o.TriggerPrice,
}
}
func (o *DerivativeLimitOrder) HasEqualOrWorsePrice(price sdk.Dec) bool {
// the buy order has a worse price than the input price if it's less than
if o.IsBuy() {
return o.Price().LTE(price)
}
return o.Price().GTE(price)
}
func (o *DerivativeMarketOrder) HasEqualOrWorsePrice(price sdk.Dec) bool {
// the buy order has a worse price than the input price if it's less than
if o.IsBuy() {
return o.Price().LTE(price)
}
return o.Price().GTE(price)
}
func ResizeReduceOnlyOrder(o IMutableDerivativeOrder, newQuantity sdk.Dec) error {
if o.IsVanilla() {
return ErrOrderInvalid.Wrap("ResizeReduceOnlyOrder should only be used for reduce only orders!")
}
quantityDecrement := o.GetQuantity().Sub(newQuantity)
if !quantityDecrement.IsPositive() {
return nil
}
o.SetQuantity(newQuantity)
return nil
}
func (o *DerivativeMarketOrder) ResizeReduceOnlyOrder(
newQuantity sdk.Dec,
oracleScaleFactor uint32,
isBinaryOptionsOrder bool,
) {
quantityDecrement := o.OrderInfo.Quantity.Sub(newQuantity)
// No-op if increasing quantity or order is a vanilla order
if !quantityDecrement.IsPositive() || o.IsVanilla() {
return
}
if isBinaryOptionsOrder {
o.OrderInfo.Quantity = newQuantity
if o.IsVanilla() {
o.Margin = o.GetRequiredBinaryOptionsMargin(oracleScaleFactor)
}
} else {
o.Margin = o.Margin.Mul(newQuantity).Quo(o.OrderInfo.Quantity)
o.OrderInfo.Quantity = newQuantity
}
}
func (o *DerivativeLimitOrder) GetRequiredBinaryOptionsMargin(oracleScaleFactor uint32) sdk.Dec {
// Margin = Price * Quantity for buys
if o.IsBuy() {
notional := o.Price().Mul(o.OrderInfo.Quantity)
return notional
}
// Margin = (scaled(1) - Price) * Quantity for sells
return o.OrderInfo.Quantity.Mul(GetScaledPrice(sdk.OneDec(), oracleScaleFactor).Sub(o.Price()))
}
func (o *DerivativeMarketOrder) GetRequiredBinaryOptionsMargin(oracleScaleFactor uint32) sdk.Dec {
// Margin = Price * Quantity for buys
if o.IsBuy() {
notional := o.Price().Mul(o.OrderInfo.Quantity)
return notional
}
// Margin = (scaled(1) - Price) * Quantity for sells
return o.OrderInfo.Quantity.Mul(GetScaledPrice(sdk.OneDec(), oracleScaleFactor).Sub(o.Price()))
}
func (o *DerivativeLimitOrder) GetCancelDepositDelta(feeRate sdk.Dec) *DepositDelta {
return &DepositDelta{
AvailableBalanceDelta: o.GetCancelRefundAmount(feeRate),
TotalBalanceDelta: sdk.ZeroDec(),
}
}
func (o *DerivativeLimitOrder) GetCancelRefundAmount(feeRate sdk.Dec) sdk.Dec {
marginHoldRefund := sdk.ZeroDec()
if o.IsVanilla() {
// negative fees are only accounted for upon matching
positiveFeePart := sdk.MaxDec(sdk.ZeroDec(), feeRate)
//nolint:all
// Refund = (FillableQuantity / Quantity) * (Margin + Price * Quantity * feeRate)
notional := o.OrderInfo.Price.Mul(o.OrderInfo.Quantity)
marginHoldRefund = o.Fillable.Mul(o.Margin.Add(notional.Mul(positiveFeePart))).Quo(o.OrderInfo.Quantity)
}
return marginHoldRefund
}
func (o *DerivativeOrder) CheckTickSize(minPriceTickSize, minQuantityTickSize sdk.Dec) error {
if BreachesMinimumTickSize(o.OrderInfo.Price, minPriceTickSize) {
return errors.Wrapf(ErrInvalidPrice, "price %s must be a multiple of the minimum price tick size %s", o.OrderInfo.Price.String(), minPriceTickSize.String())
}
if BreachesMinimumTickSize(o.OrderInfo.Quantity, minQuantityTickSize) {
return errors.Wrapf(ErrInvalidQuantity, "quantity %s must be a multiple of the minimum quantity tick size %s", o.OrderInfo.Quantity.String(), minQuantityTickSize.String())
}
if !o.Margin.IsZero() {
if BreachesMinimumTickSize(o.Margin, minQuantityTickSize) {
return errors.Wrapf(ErrInvalidMargin, "margin %s must be a multiple of the minimum quantity tick size %s", o.Margin.String(), minQuantityTickSize.String())
}
}
return nil
}
func GetScaledPrice(price sdk.Dec, scaleFactor uint32) sdk.Dec {
return price.Mul(sdk.NewDec(10).Power(uint64(scaleFactor)))
}
func (o *DerivativeOrder) GetRequiredBinaryOptionsMargin(oracleScaleFactor uint32) sdk.Dec {
// Margin = Price * Quantity for buys
if o.IsBuy() {
notional := o.Price().Mul(o.OrderInfo.Quantity)
return notional
}
// Margin = (scaled(1) - Price) * Quantity for sells
return o.OrderInfo.Quantity.Mul(GetScaledPrice(sdk.OneDec(), oracleScaleFactor).Sub(o.Price()))
}
func (o *DerivativeOrder) CheckMarginAndGetMarginHold(initialMarginRatio, executionMarkPrice, feeRate sdk.Dec, marketType MarketType, oracleScaleFactor uint32) (marginHold sdk.Dec, err error) {
notional := o.OrderInfo.Price.Mul(o.OrderInfo.Quantity)
positiveFeeRatePart := sdk.MaxDec(feeRate, sdk.ZeroDec())
feeAmount := notional.Mul(positiveFeeRatePart)
marginHold = o.Margin.Add(feeAmount)
if marketType == MarketType_BinaryOption {
requiredMargin := o.GetRequiredBinaryOptionsMargin(oracleScaleFactor)
if !o.Margin.Equal(requiredMargin) {
return sdk.Dec{}, errors.Wrapf(ErrInsufficientOrderMargin, "margin check: need %s but got %s", requiredMargin.String(), o.Margin.String())
}
return marginHold, nil
}
// For perpetual and expiry futures margins
// Enforce that Margin ≥ InitialMarginRatio * Price * Quantity
if o.Margin.LT(initialMarginRatio.Mul(notional)) {
return sdk.Dec{}, errors.Wrapf(ErrInsufficientOrderMargin, "InitialMarginRatio Check: need at least %s but got %s", initialMarginRatio.Mul(notional).String(), o.Margin.String())
}
if err := o.CheckInitialMarginRequirementMarkPriceThreshold(initialMarginRatio, executionMarkPrice); err != nil {
return sdk.Dec{}, err
}
return marginHold, nil
}
func (o *DerivativeOrder) CheckInitialMarginRequirementMarkPriceThreshold(initialMarginRatio, markPrice sdk.Dec) (err error) {
markPriceThreshold := o.ComputeInitialMarginRequirementMarkPriceThreshold(initialMarginRatio)
// For Buys: MarkPrice ≥ (Margin - Price * Quantity) / ((InitialMarginRatio - 1) * Quantity)
// For Sells: MarkPrice ≤ (Margin + Price * Quantity) / ((1 + InitialMarginRatio) * Quantity)
if o.OrderType.IsBuy() && markPrice.LT(markPriceThreshold) {
return errors.Wrapf(ErrInsufficientOrderMargin, "Buy MarkPriceThreshold Check: mark/trigger price %s must be GTE %s", markPrice.String(), markPriceThreshold.String())
} else if !o.OrderType.IsBuy() && markPrice.GT(markPriceThreshold) {
return errors.Wrapf(ErrInsufficientOrderMargin, "Sell MarkPriceThreshold Check: mark/trigger price %s must be LTE %s", markPrice.String(), markPriceThreshold.String())
}
return nil
}
// CheckValidConditionalPrice checks that conditional order type (STOP or TAKE) actually valid for current relation between triggerPrice and markPrice
func (o *DerivativeOrder) CheckValidConditionalPrice(markPrice sdk.Dec) (err error) {
if !o.IsConditional() {
return nil
}
ok := true
switch o.OrderType {
case OrderType_STOP_BUY, OrderType_TAKE_SELL: // higher
ok = o.TriggerPrice.GT(markPrice)
case OrderType_STOP_SELL, OrderType_TAKE_BUY: // lower
ok = o.TriggerPrice.LT(markPrice)
}
if !ok {
return errors.Wrapf(ErrInvalidTriggerPrice, "order type %s incompatible with trigger price %s and markPrice %s", o.OrderType.String(), o.TriggerPrice.String(), markPrice.String())
}
return nil
}
// CheckBinaryOptionsPricesWithinBounds checks that binary options order prices don't exceed 1 (scaled)
func (o *DerivativeOrder) CheckBinaryOptionsPricesWithinBounds(oracleScaleFactor uint32) (err error) {
maxScaledPrice := GetScaledPrice(sdk.OneDec(), oracleScaleFactor)
if o.Price().GTE(maxScaledPrice) {
return errors.Wrapf(ErrInvalidPrice, "price must be less than %s", maxScaledPrice.String())
}
if o.IsConditional() && o.TriggerPrice.GTE(maxScaledPrice) {
return errors.Wrapf(ErrInvalidTriggerPrice, "trigger price must be less than %s", maxScaledPrice.String())
}
return nil
}
func (o *DerivativeOrder) ComputeInitialMarginRequirementMarkPriceThreshold(initialMarginRatio sdk.Dec) sdk.Dec {
notional := o.OrderInfo.Price.Mul(o.OrderInfo.Quantity)
var numerator, denominator sdk.Dec
if o.OrderType.IsBuy() {
numerator = o.Margin.Sub(notional)
denominator = initialMarginRatio.Sub(sdk.OneDec()).Mul(o.OrderInfo.Quantity)
} else {
numerator = o.Margin.Add(notional)
denominator = initialMarginRatio.Add(sdk.OneDec()).Mul(o.OrderInfo.Quantity)
}
return numerator.Quo(denominator)
}
func (o *DerivativeLimitOrder) CheckInitialMarginRequirementMarkPriceThreshold(initialMarginRatio, markPrice sdk.Dec) (err error) {
return o.ToDerivativeOrder("").CheckInitialMarginRequirementMarkPriceThreshold(initialMarginRatio, markPrice)
}
func (o *DerivativeMarketOrder) CheckInitialMarginRequirementMarkPriceThreshold(initialMarginRatio, markPrice sdk.Dec) (err error) {
return o.ToDerivativeOrder("").CheckInitialMarginRequirementMarkPriceThreshold(initialMarginRatio, markPrice)
}
func (o *DerivativeMarketOrder) ComputeOrderHash(nonce uint32, marketId string) (common.Hash, error) {
triggerPrice := ""
if o.TriggerPrice != nil {
triggerPrice = o.TriggerPrice.String()
}
return computeOrderHash(marketId, o.OrderInfo.SubaccountId, o.OrderInfo.FeeRecipient, o.OrderInfo.Price.String(), o.OrderInfo.Quantity.String(), o.Margin.String(), triggerPrice, string(o.OrderType), nonce)
}
// ComputeOrderHash computes the order hash for given derivative limit order
func (o *DerivativeOrder) ComputeOrderHash(nonce uint32) (common.Hash, error) {
triggerPrice := ""
if o.TriggerPrice != nil {
triggerPrice = o.TriggerPrice.String()
}
return computeOrderHash(o.MarketId, o.OrderInfo.SubaccountId, o.OrderInfo.FeeRecipient, o.OrderInfo.Price.String(), o.OrderInfo.Quantity.String(), o.Margin.String(), triggerPrice, string(o.OrderType), nonce)
}
func (o *DerivativeOrder) IsReduceOnly() bool {
return o.Margin.IsZero()
}
func (o *DerivativeMarketOrder) IsReduceOnly() bool {
return o.Margin.IsZero()
}
func (o *DerivativeLimitOrder) IsReduceOnly() bool {
return o.Margin.IsZero()
}
func (o *DerivativeLimitOrder) Hash() common.Hash {
return common.BytesToHash(o.OrderHash)
}
func (o *DerivativeMarketOrder) Hash() common.Hash {
return common.BytesToHash(o.OrderHash)
}
func (o *DerivativeLimitOrder) FeeRecipient() common.Address {
return o.OrderInfo.FeeRecipientAddress()
}
func (o *DerivativeMarketOrder) FeeRecipient() common.Address {
return o.OrderInfo.FeeRecipientAddress()
}
func (o *DerivativeOrder) IsVanilla() bool {
return !o.IsReduceOnly()
}
func (o *DerivativeMarketOrder) IsVanilla() bool {
return !o.IsReduceOnly()
}
func (o *DerivativeLimitOrder) IsVanilla() bool {
return !o.IsReduceOnly()
}
func (m *DerivativeMarketOrder) IsBuy() bool {
return m.OrderType.IsBuy()
}
func (m *DerivativeLimitOrder) IsBuy() bool {
return m.OrderType.IsBuy()
}
func (m *DerivativeOrder) IsBuy() bool {
return m.OrderType.IsBuy()
}
func (m *DerivativeMarketOrder) Quantity() sdk.Dec {
return m.OrderInfo.Quantity
}
func (m *DerivativeMarketOrder) FillableQuantity() sdk.Dec {
return m.OrderInfo.Quantity
}
func (m *DerivativeMarketOrder) Price() sdk.Dec {
return m.OrderInfo.Price
}
func (m *DerivativeLimitOrder) Price() sdk.Dec {
return m.OrderInfo.Price
}
func (m *DerivativeOrder) Price() sdk.Dec {
return m.OrderInfo.Price
}
func (o *DerivativeOrder) IsConditional() bool {
return o.OrderType.IsConditional()
}
func (o *DerivativeMarketOrder) IsConditional() bool {
return o.OrderType.IsConditional()
}
func (o *DerivativeLimitOrder) IsConditional() bool {
return o.OrderType.IsConditional()
}
func (o *DerivativeOrder) SubaccountID() common.Hash {
return o.OrderInfo.SubaccountID()
}
func (o *DerivativeOrder) IsFromDefaultSubaccount() bool {
return o.OrderInfo.IsFromDefaultSubaccount()
}
func (o *DerivativeOrder) MarketID() common.Hash {
return common.HexToHash(o.MarketId)
}
func (o *DerivativeMarketOrder) SubaccountID() common.Hash {
return o.OrderInfo.SubaccountID()
}
func (o *DerivativeLimitOrder) SubaccountID() common.Hash {
return o.OrderInfo.SubaccountID()
}
func (o *OrderInfo) SubaccountID() common.Hash {
return common.HexToHash(o.SubaccountId)
}
func (o *OrderInfo) FeeRecipientAddress() common.Address {
address, _ := sdk.AccAddressFromBech32(o.FeeRecipient)
return common.BytesToAddress(address.Bytes())
}
func (o *DerivativeLimitOrder) SdkAccAddress() sdk.AccAddress {
return sdk.AccAddress(o.SubaccountID().Bytes()[:common.AddressLength])
}
func (o *DerivativeLimitOrder) IsFromDefaultSubaccount() bool {
return o.OrderInfo.IsFromDefaultSubaccount()
}
func (o *DerivativeMarketOrder) SdkAccAddress() sdk.AccAddress {
return sdk.AccAddress(o.SubaccountID().Bytes()[:common.AddressLength])
}
func (o *DerivativeMarketOrder) IsFromDefaultSubaccount() bool {
return o.OrderInfo.IsFromDefaultSubaccount()
}
func (o *TrimmedDerivativeLimitOrder) IsReduceOnly() bool {
return o.Margin.IsZero()
}
func EmptyDerivativeMarketOrderResults() *DerivativeMarketOrderResults {
return &DerivativeMarketOrderResults{
Quantity: sdk.ZeroDec(),
Price: sdk.ZeroDec(),
Fee: sdk.ZeroDec(),
PositionDelta: PositionDelta{},
Payout: sdk.ZeroDec(),
}
}