-
Notifications
You must be signed in to change notification settings - Fork 18
/
margins_calculation.go
385 lines (364 loc) · 15.4 KB
/
margins_calculation.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
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package risk
import (
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/logging"
)
var (
exp = num.UintZero().Exp(num.NewUint(10), num.NewUint(5))
expDec = num.DecimalFromUint(exp)
)
type scalingFactorsUint struct {
search *num.Uint
initial *num.Uint
release *num.Uint
}
func scalingFactorsUintFromDecimals(sf *types.ScalingFactors) *scalingFactorsUint {
search, _ := num.UintFromDecimal(sf.SearchLevel.Mul(expDec))
initial, _ := num.UintFromDecimal(sf.InitialMargin.Mul(expDec))
release, _ := num.UintFromDecimal(sf.CollateralRelease.Mul(expDec))
return &scalingFactorsUint{
search: search,
initial: initial,
release: release,
}
}
func newMarginLevels(maintenance num.Decimal, scalingFactors *scalingFactorsUint) *types.MarginLevels {
umaintenance, _ := num.UintFromDecimal(maintenance.Ceil())
return &types.MarginLevels{
MaintenanceMargin: umaintenance,
SearchLevel: num.UintZero().Div(num.UintZero().Mul(scalingFactors.search, umaintenance), exp),
InitialMargin: num.UintZero().Div(num.UintZero().Mul(scalingFactors.initial, umaintenance), exp),
CollateralReleaseLevel: num.UintZero().Div(num.UintZero().Mul(scalingFactors.release, umaintenance), exp),
}
}
// Implementation of the margin calculator per specs:
// https://github.com/vegaprotocol/product/blob/master/specs/0019-margin-calculator.md
func (e *Engine) calculateMargins(m events.Margin, markPrice *num.Uint, rf types.RiskFactor, withPotentialBuyAndSell, auction bool, inc num.Decimal) *types.MarginLevels {
var (
marginMaintenanceLng num.Decimal
marginMaintenanceSht num.Decimal
)
// convert volumn to a decimal number from a * 10^pdp
openVolume := num.DecimalFromInt64(m.Size()).Div(e.positionFactor)
var (
riskiestLng = openVolume
riskiestSht = openVolume
)
if withPotentialBuyAndSell {
// calculate both long and short riskiest positions
riskiestLng = riskiestLng.Add(num.DecimalFromInt64(m.Buy()).Div(e.positionFactor))
riskiestSht = riskiestSht.Sub(num.DecimalFromInt64(m.Sell()).Div(e.positionFactor))
}
// the party has no open positions that we need to calculate margin for
if riskiestLng.IsZero() && riskiestSht.IsZero() {
return &types.MarginLevels{
MaintenanceMargin: num.UintZero(),
SearchLevel: num.UintZero(),
InitialMargin: num.UintZero(),
CollateralReleaseLevel: num.UintZero(),
}
}
// negative increment == short positions require extra margin, otherwise long requires extra margin
longFP := inc.IsPositive()
mPriceDec := markPrice.ToDecimal()
// calculate margin maintenance long only if riskiest is > 0
// marginMaintenanceLng will be 0 by default
if riskiestLng.IsPositive() {
var (
slippageVolume = num.MaxD(openVolume, num.DecimalZero())
slippagePerUnit = num.UintZero()
noExit = true
)
if slippageVolume.IsPositive() {
if !auction {
svol, _ := num.UintFromDecimal(slippageVolume.Abs().Mul(e.positionFactor))
exitPrice, err := e.ob.GetCloseoutPrice(svol.Uint64(), types.SideBuy)
if err != nil {
if e.log.IsDebug() {
e.log.Debug("got non critical error from GetCloseoutPrice for Buy side",
logging.Error(err))
}
} else {
noExit = false
var negative bool
slippagePerUnit, negative = num.UintZero().Delta(markPrice, exitPrice)
if negative {
slippagePerUnit = num.UintZero()
}
}
}
}
minV := mPriceDec.Mul(e.linearSlippageFactor.Mul(slippageVolume).Add(e.quadraticSlippageFactor.Mul(slippageVolume.Mul(slippageVolume))))
if auction {
marginMaintenanceLng = minV.Add(slippageVolume.Mul(mPriceDec.Mul(rf.Long)))
if withPotentialBuyAndSell {
maintenanceMarginLongOpenOrders := m.BuySumProduct().ToDecimal().Div(e.positionFactor).Mul(rf.Long)
marginMaintenanceLng = marginMaintenanceLng.Add(maintenanceMarginLongOpenOrders)
}
} else {
// maintenance_margin_long_open_position =
// max(
// min(
// slippage_volume * slippage_per_unit,
// mark_price * (slippage_volume * market.maxSlippageFraction[1] + slippage_volume^2 * market.maxSlippageFraction[2])
// ),
// 0
// ) + slippage_volume * [ quantitative_model.risk_factors_long ] . [ Product.value(market_observable) ]
//
// maintenance_margin_long_open_orders = buy_orders * [ quantitative_model.risk_factors_long ] . [ Product.value(market_observable) ]
//
// if we don't have an exit price, the min() part of the formula above =
//
// mark_price * (slippage_volume * market.maxSlippageFraction[1] + slippage_volume^2 * market.maxSlippageFraction[2])
// changing the formula to:
// maintenance_margin_long_open_position =
// max(
// mark_price * (slippage_volume * market.linearSlippageFactor + slippage_volume^2 * market.quadraticSlippageFactor),
// 0
// ) + slippage_volume * [quantitative_model.risk_factors_long] . [ Product.value(market_observable) ]
if !noExit {
slip := slippagePerUnit.ToDecimal().Mul(slippageVolume)
minV = num.MinD(
slip,
minV,
)
}
marginMaintenanceLng = num.MaxD(
num.DecimalZero(),
minV,
).Add(slippageVolume.Mul(rf.Long).Mul(mPriceDec))
if withPotentialBuyAndSell {
bDec := num.DecimalFromInt64(m.Buy()).Div(e.positionFactor)
maintenanceMarginLongOpenOrders := bDec.Mul(rf.Long).Mul(mPriceDec)
marginMaintenanceLng = marginMaintenanceLng.Add(maintenanceMarginLongOpenOrders)
}
}
}
// calculate margin maintenance short only if riskiest is < 0
// marginMaintenanceSht will be 0 by default
if riskiestSht.IsNegative() {
var (
slippageVolume = num.MinD(openVolume, num.DecimalZero())
slippagePerUnit = num.UintZero()
noExit = true
)
// slippageVolume would be negative we abs it in the next phase
if slippageVolume.IsNegative() {
if !auction {
// convert back into vol * 10^pdp
svol, _ := num.UintFromDecimal(slippageVolume.Abs().Mul(e.positionFactor))
exitPrice, err := e.ob.GetCloseoutPrice(svol.Uint64(), types.SideSell)
if err != nil {
if e.log.IsDebug() {
e.log.Debug("got non critical error from GetCloseoutPrice for Sell side",
logging.Error(err))
}
} else {
noExit = false
var negative bool
slippagePerUnit, negative = num.UintZero().Delta(exitPrice, markPrice)
if negative {
slippagePerUnit = num.UintZero()
}
}
}
}
absSlippageVolume := slippageVolume.Abs()
linearSlippage := absSlippageVolume.Mul(e.linearSlippageFactor)
quadraticSlipage := absSlippageVolume.Mul(absSlippageVolume).Mul(e.quadraticSlippageFactor)
minV := mPriceDec.Mul(linearSlippage.Add(quadraticSlipage))
if auction {
marginMaintenanceSht = minV.Add(absSlippageVolume.Mul(mPriceDec.Mul(rf.Short)))
if withPotentialBuyAndSell {
maintenanceMarginShortOpenOrders := m.SellSumProduct().ToDecimal().Div(e.positionFactor).Mul(rf.Short)
marginMaintenanceSht = marginMaintenanceSht.Add(maintenanceMarginShortOpenOrders)
}
} else {
// maintenance_margin_short_open_position =
// max(
// min(
// abs(slippage_volume) * slippage_per_unit,
// mark_price * market.maxSlippageFraction[1] + abs(slippage_volume)^2 * market.maxSlippageFraction[2])
// ),
// 0
// ) + abs(slippage_volume) * [ quantitative_model.risk_factors_short ] . [ Product.value(market_observable) ]
//
// maintenance_margin_short_open_orders = abs(sell_orders) * [ quantitative_model.risk_factors_short ] . [ Product.value(market_observable) ]
//
// again the same applies here if the exit_price is invalid (+Infinity, or some other error):
// we replace the min part in the formula above, ignoring abs(slippage_volume) * slippage_per_unit:
// max(
// mark_price * market.maxSlippageFraction[1] + abs(slippage_volume)^2 * market.maxSlippageFraction[2])
// 0
// ) + abs(slippage_volume) * [ quantitative_model.risk_factors_short ] . [ Product.value(market_observable) ]
//
// maintenance_margin_short_open_orders = abs(sell_orders) * [ quantitative_model.risk_factors_short ] . [ Product.value(market_observable) ]
if !noExit {
minV = num.MinD(
absSlippageVolume.Mul(slippagePerUnit.ToDecimal()),
minV,
)
}
marginMaintenanceSht = num.MaxD(
num.DecimalZero(),
minV,
).Add(absSlippageVolume.Mul(mPriceDec).Mul(rf.Short))
if withPotentialBuyAndSell {
sDec := num.DecimalFromInt64(m.Sell()).Div(e.positionFactor)
maintenanceMarginShortOpenOrders := sDec.Abs().Mul(mPriceDec).Mul(rf.Short)
marginMaintenanceSht = marginMaintenanceSht.Add(maintenanceMarginShortOpenOrders)
}
}
}
if !inc.IsZero() && !openVolume.IsZero() {
// openVolume and inc are signed, but this is fine, we only apply the positive values
incD := num.MaxD(num.DecimalZero(), inc.Mul(openVolume))
if longFP {
marginMaintenanceLng = marginMaintenanceLng.Add(incD)
} else {
marginMaintenanceSht = marginMaintenanceSht.Add(incD)
}
}
// the greatest liability is the most positive number
if marginMaintenanceLng.GreaterThan(marginMaintenanceSht) && marginMaintenanceLng.IsPositive() {
return newMarginLevels(marginMaintenanceLng, e.scalingFactorsUint)
}
if marginMaintenanceSht.IsPositive() {
return newMarginLevels(marginMaintenanceSht, e.scalingFactorsUint)
}
// for some reason, margin is negative or zero, let's just use the increment if set:
if !inc.IsZero() {
return newMarginLevels(inc, e.scalingFactorsUint)
}
return &types.MarginLevels{
MaintenanceMargin: num.UintZero(),
SearchLevel: num.UintZero(),
InitialMargin: num.UintZero(),
CollateralReleaseLevel: num.UintZero(),
}
}
func CalculateMaintenanceMarginWithSlippageFactors(sizePosition int64, buyOrders, sellOrders []*OrderInfo, marketObservable, positionFactor, linearSlippageFactor, quadraticSlippageFactor, riskFactorLong, riskFactorShort, fundingPaymntPerUnitPosition num.Decimal, auction bool) num.Decimal {
buySumProduct, sellSumProduct := num.DecimalZero(), num.DecimalZero()
sizeSells, sizeBuys := int64(0), int64(0)
for _, o := range buyOrders {
size := int64(o.Size)
if o.IsMarketOrder {
// assume market order fills
sizePosition += size
} else {
buySumProduct = buySumProduct.Add(num.DecimalFromInt64(size).Mul(o.Price))
sizeBuys += size
}
}
for _, o := range sellOrders {
size := int64(o.Size)
if o.IsMarketOrder {
// assume market order fills
sizePosition -= size
} else {
sellSumProduct = sellSumProduct.Add(num.DecimalFromInt64(size).Mul(o.Price))
sizeSells += size
}
}
return computeMaintenanceMargin(sizePosition, sizeBuys, sizeSells, buySumProduct, sellSumProduct, marketObservable, positionFactor, linearSlippageFactor, quadraticSlippageFactor, riskFactorLong, riskFactorShort, fundingPaymntPerUnitPosition, auction, true, true, num.MaxUint(), num.MaxUint())
}
func calculateSlippageFactor(slippageVolume, linearSlippageFactor, quadraticSlippageFactor num.Decimal) num.Decimal {
return linearSlippageFactor.Mul(slippageVolume.Abs()).Add(quadraticSlippageFactor.Mul(slippageVolume.Mul(slippageVolume)))
}
func computeMaintenanceMargin(sizePosition, buySize, sellSize int64, buySumProduct, sellSumProduct, marketObservable, positionFactor, linearSlippageFactor, quadraticSlippageFactor, riskFactorLong, riskFactorShort, fundingPaymntPerUnitPosition num.Decimal, auction, longNoExit, shortNoExit bool, longSlippagePerUnit, shortSlippagePerUnit *num.Uint) num.Decimal {
var (
marginMaintenanceLng num.Decimal
marginMaintenanceSht num.Decimal
)
// convert volumn to a decimal number from a * 10^pdp
openVolume := num.DecimalFromInt64(sizePosition).Div(positionFactor)
// calculate both long and short riskiest positions
var (
riskiestLng = openVolume.Add(num.DecimalFromInt64(buySize).Div(positionFactor))
riskiestSht = openVolume.Sub(num.DecimalFromInt64(sellSize).Div(positionFactor))
)
// calculate margin maintenance long only if riskiest is > 0
// marginMaintenanceLng will be 0 by default
if riskiestLng.IsPositive() {
slippageVolume := num.MaxD(openVolume, num.DecimalZero())
slippageCap := marketObservable.Mul(calculateSlippageFactor(slippageVolume, linearSlippageFactor, quadraticSlippageFactor))
if auction {
marginMaintenanceLng = slippageCap.Add(slippageVolume.Mul(marketObservable.Mul(riskFactorLong)))
maintenanceMarginLongOpenOrders := buySumProduct.Div(positionFactor).Mul(riskFactorLong)
marginMaintenanceLng = marginMaintenanceLng.Add(maintenanceMarginLongOpenOrders)
} else {
if !longNoExit {
slippageCap = num.MinD(
longSlippagePerUnit.ToDecimal().Mul(slippageVolume),
slippageCap,
)
}
marginMaintenanceLng = num.MaxD(
num.DecimalZero(),
slippageCap,
).Add(slippageVolume.Mul(riskFactorLong).Mul(marketObservable))
if buySize > 0 {
maintenanceMarginLongOpenOrders := num.DecimalFromInt64(buySize).Div(positionFactor).Mul(riskFactorLong).Mul(marketObservable)
marginMaintenanceLng = marginMaintenanceLng.Add(maintenanceMarginLongOpenOrders)
}
}
}
// calculate margin maintenance short only if riskiest is < 0
// marginMaintenanceSht will be 0 by default
if riskiestSht.IsNegative() {
slippageVolume := num.MinD(openVolume, num.DecimalZero())
absSlippageVolume := slippageVolume.Abs()
slippageCap := marketObservable.Mul(calculateSlippageFactor(slippageVolume, linearSlippageFactor, quadraticSlippageFactor))
if auction {
marginMaintenanceSht = slippageCap.Add(absSlippageVolume.Mul(marketObservable.Mul(riskFactorShort)))
maintenanceMarginShortOpenOrders := sellSumProduct.Div(positionFactor).Mul(riskFactorShort)
marginMaintenanceSht = marginMaintenanceSht.Add(maintenanceMarginShortOpenOrders)
} else {
if !shortNoExit {
slippageCap = num.MinD(
absSlippageVolume.Mul(shortSlippagePerUnit.ToDecimal()),
slippageCap,
)
}
marginMaintenanceSht = num.MaxD(
num.DecimalZero(),
slippageCap,
).Add(absSlippageVolume.Mul(marketObservable).Mul(riskFactorShort))
if sellSize > 0 {
maintenanceMarginShortOpenOrders := num.DecimalFromInt64(sellSize).Div(positionFactor).Abs().Mul(marketObservable).Mul(riskFactorShort)
marginMaintenanceSht = marginMaintenanceSht.Add(maintenanceMarginShortOpenOrders)
}
}
}
if !fundingPaymntPerUnitPosition.IsZero() && !openVolume.IsZero() {
// calculate margin increase based on position
// incD = max(0, inc * open volume)
incD := num.MaxD(num.DecimalZero(), fundingPaymntPerUnitPosition.Mul(openVolume))
marginMaintenanceLng = marginMaintenanceLng.Add(incD)
marginMaintenanceSht = marginMaintenanceSht.Add(incD)
}
// the greatest liability is the most positive number
if marginMaintenanceLng.GreaterThan(marginMaintenanceSht) && marginMaintenanceLng.IsPositive() {
return marginMaintenanceLng
}
if marginMaintenanceSht.IsPositive() {
return marginMaintenanceSht
}
return num.DecimalZero()
}