forked from InjectiveLabs/sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
positions.go
379 lines (308 loc) · 13.7 KB
/
positions.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
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type positionPayout struct {
Payout sdk.Dec
PnlNotional sdk.Dec
IsProfitable bool
}
func (p *Position) IsShort() bool { return !p.IsLong }
func (p *Position) Copy() *Position {
return &Position{
IsLong: p.IsLong,
Quantity: p.Quantity,
EntryPrice: p.EntryPrice,
Margin: p.Margin,
CumulativeFundingEntry: p.CumulativeFundingEntry,
}
}
func (p *DerivativePosition) Copy() *DerivativePosition {
return &DerivativePosition{
SubaccountId: p.SubaccountId,
MarketId: p.MarketId,
Position: p.Position.Copy(),
}
}
func (m *PositionDelta) IsShort() bool { return !m.IsLong }
// NewPosition initializes a new position with a given cumulativeFundingEntry (should be nil for non-perpetual markets)
func NewPosition(isLong bool, cumulativeFundingEntry sdk.Dec) *Position {
position := &Position{
IsLong: isLong,
Quantity: sdk.ZeroDec(),
EntryPrice: sdk.ZeroDec(),
Margin: sdk.ZeroDec(),
}
if !cumulativeFundingEntry.IsNil() {
position.CumulativeFundingEntry = cumulativeFundingEntry
}
return position
}
// GetEffectiveMarginRatio returns the effective margin ratio of the position, based on the input closing price.
// CONTRACT: position must already be funding-adjusted (if perpetual) and have positive quantity.
func (p *Position) GetEffectiveMarginRatio(closingPrice, closingFee sdk.Dec) (marginRatio sdk.Dec) {
// nolint:all
// marginRatio = (margin + quantity * PnlPerContract) / (closingPrice * quantity)
effectiveMargin := p.Margin.Add(p.GetPayoutFromPnl(closingPrice, p.Quantity)).Sub(closingFee)
return effectiveMargin.Quo(closingPrice.Mul(p.Quantity))
}
// ApplyProfitHaircutForDerivatives results in reducing the payout (pnl * quantity) by the given rate (e.g. 0.1=10%) by modifying the entry price.
// Formula for adjustment:
// newPayoutFromPnl = oldPayoutFromPnl * (1 - missingFundsRate)
// => Entry price adjustment for buys
// (newEntryPrice - settlementPrice) * quantity = (entryPrice - settlementPrice) * quantity * (1 - missingFundsRate)
// newEntryPrice = entryPrice - entryPrice * haircutPercentage + settlementPrice * haircutPercentage
// => Entry price adjustment for sells
// (settlementPrice - newEntryPrice) * quantity = (settlementPrice - entryPrice) * quantity * (1 - missingFundsRate)
// newEntryPrice = entryPrice - entryPrice * haircutPercentage + settlementPrice * haircutPercentage
func (p *Position) ApplyProfitHaircutForDerivatives(deficitAmount, totalProfits, settlementPrice sdk.Dec) {
// haircutPercentage = deficitAmount / totalProfits
// To preserve precision, the division by totalProfits is done last.
// newEntryPrice = haircutPercentage * (settlementPrice - entryPrice) + entryPrice
newEntryPrice := deficitAmount.Mul(settlementPrice.Sub(p.EntryPrice)).Quo(totalProfits).Add(p.EntryPrice)
p.EntryPrice = newEntryPrice
// profitable position but with negative margin, we didn't account for negative margin previously,
// so we can safely add it if payout becomes negative from haircut
newPositionPayout := p.GetPayoutIfFullyClosing(settlementPrice, sdk.ZeroDec()).Payout
if newPositionPayout.IsNegative() {
p.Margin = p.Margin.Add(newPositionPayout.Abs())
}
}
func (p *Position) ApplyTotalPositionPayoutHaircut(deficitAmount, totalPayouts, settlementPrice sdk.Dec) {
p.ApplyProfitHaircutForDerivatives(deficitAmount, totalPayouts, settlementPrice)
removedMargin := p.Margin.Mul(deficitAmount).Quo(totalPayouts)
p.Margin = p.Margin.Sub(removedMargin)
}
func (p *Position) ApplyProfitHaircutForBinaryOptions(deficitAmount, totalAssets sdk.Dec, oracleScaleFactor uint32) {
// haircutPercentage = deficitAmount / totalAssets
// To preserve precision, the division by totalAssets is done last.
// newMargin = p.Margin - p.Margin * haircutPercentage
newMargin := p.Margin.Sub(deficitAmount.Mul(p.Margin).Quo(totalAssets))
p.Margin = newMargin
// updating entry price just for consistency, but it has no effect since applied haircut is on margin, not on entry price during binary options refunds
if p.IsLong {
p.EntryPrice = p.Margin.Quo(p.Quantity)
} else {
scaledOne := GetScaledPrice(sdk.OneDec(), oracleScaleFactor)
p.EntryPrice = scaledOne.Sub(p.Margin.Quo(p.Quantity))
}
}
func (p *Position) ClosePositionWithSettlePrice(settlementPrice, closingFeeRate sdk.Dec) (payout, closeTradingFee sdk.Dec, positionDelta *PositionDelta) {
closingDirection := !p.IsLong
fullyClosingQuantity := p.Quantity
closeTradingFee = settlementPrice.Mul(fullyClosingQuantity).Mul(closingFeeRate)
positionDelta = &PositionDelta{
IsLong: closingDirection,
ExecutionQuantity: fullyClosingQuantity,
ExecutionMargin: sdk.ZeroDec(),
ExecutionPrice: settlementPrice,
}
// there should not be positions with 0 quantity
if fullyClosingQuantity.IsZero() {
return sdk.ZeroDec(), closeTradingFee, positionDelta
}
payout, _, _ = p.ApplyPositionDelta(positionDelta, closeTradingFee)
return payout, closeTradingFee, positionDelta
}
func (p *Position) ClosePositionWithoutPayouts() {
p.IsLong = false
p.EntryPrice = sdk.ZeroDec()
p.Quantity = sdk.ZeroDec()
p.Margin = sdk.ZeroDec()
p.CumulativeFundingEntry = sdk.ZeroDec()
}
func (p *Position) ClosePositionByRefunding(closingFeeRate sdk.Dec) (payout, closeTradingFee sdk.Dec, positionDelta *PositionDelta) {
return p.ClosePositionWithSettlePrice(p.EntryPrice, closingFeeRate)
}
func (p *Position) GetDirectionString() string {
directionStr := "Long"
if p.IsShort() {
directionStr = "Short"
}
return directionStr
}
func (p *Position) CheckValidPositionToReduce(
marketType MarketType,
reducePrice sdk.Dec,
isBuyOrder bool,
tradeFeeRate sdk.Dec,
funding *PerpetualMarketFunding,
orderMargin sdk.Dec,
) error {
if isBuyOrder == p.IsLong {
return ErrInvalidReduceOnlyPositionDirection
}
if marketType == MarketType_BinaryOption {
return nil
}
if err := p.checkValidClosingPrice(reducePrice, tradeFeeRate, funding, orderMargin); err != nil {
return err
}
return nil
}
func (p *Position) checkValidClosingPrice(closingPrice, tradeFeeRate sdk.Dec, funding *PerpetualMarketFunding, orderMargin sdk.Dec) error {
bankruptcyPrice := p.GetBankruptcyPriceWithAddedMargin(funding, orderMargin)
if p.IsLong {
// For long positions, Price ≥ BankruptcyPrice / (1 - TradeFeeRate) must hold
feeAdjustedBankruptcyPrice := bankruptcyPrice.Quo(sdk.OneDec().Sub(tradeFeeRate))
if closingPrice.LT(feeAdjustedBankruptcyPrice) {
return ErrPriceSurpassesBankruptcyPrice
}
} else {
// For short positions, Price ≤ BankruptcyPrice / (1 + TradeFeeRate) must hold
feeAdjustedBankruptcyPrice := bankruptcyPrice.Quo(sdk.OneDec().Add(tradeFeeRate))
if closingPrice.GT(feeAdjustedBankruptcyPrice) {
return ErrPriceSurpassesBankruptcyPrice
}
}
return nil
}
func (p *Position) GetBankruptcyPrice(funding *PerpetualMarketFunding) (bankruptcyPrice sdk.Dec) {
return p.GetLiquidationPrice(sdk.ZeroDec(), funding)
}
func (p *Position) GetBankruptcyPriceWithAddedMargin(funding *PerpetualMarketFunding, addedMargin sdk.Dec) (bankruptcyPrice sdk.Dec) {
return p.getLiquidationPriceWithAddedMargin(sdk.ZeroDec(), funding, addedMargin)
}
func (p *Position) GetLiquidationPrice(maintenanceMarginRatio sdk.Dec, funding *PerpetualMarketFunding) sdk.Dec {
return p.getLiquidationPriceWithAddedMargin(maintenanceMarginRatio, funding, sdk.ZeroDec())
}
func (p *Position) getLiquidationPriceWithAddedMargin(maintenanceMarginRatio sdk.Dec, funding *PerpetualMarketFunding, addedMargin sdk.Dec) sdk.Dec {
adjustedUnitMargin := p.getFundingAdjustedUnitMarginWithAddedMargin(funding, addedMargin)
// TODO include closing fee for reduce only ?
var liquidationPrice sdk.Dec
if p.IsLong {
// liquidation price = (entry price - unit margin) / (1 - maintenanceMarginRatio)
liquidationPrice = p.EntryPrice.Sub(adjustedUnitMargin).Quo(sdk.OneDec().Sub(maintenanceMarginRatio))
} else {
// liquidation price = (entry price + unit margin) / (1 + maintenanceMarginRatio)
liquidationPrice = p.EntryPrice.Add(adjustedUnitMargin).Quo(sdk.OneDec().Add(maintenanceMarginRatio))
}
return liquidationPrice
}
func (p *Position) GetEffectiveMargin(funding *PerpetualMarketFunding, closingPrice sdk.Dec) sdk.Dec {
fundingAdjustedMargin := p.Margin
if funding != nil {
fundingAdjustedMargin = p.getFundingAdjustedMargin(funding)
}
pnlNotional := sdk.ZeroDec()
if !closingPrice.IsNil() {
pnlNotional = p.GetPayoutFromPnl(closingPrice, p.Quantity)
}
effectiveMargin := fundingAdjustedMargin.Add(pnlNotional)
return effectiveMargin
}
// ApplyFunding updates the position to account for any funding payment.
func (p *Position) ApplyFunding(funding *PerpetualMarketFunding) {
if funding != nil {
p.Margin = p.getFundingAdjustedMargin(funding)
// update the cumulative funding entry to current
p.CumulativeFundingEntry = funding.CumulativeFunding
}
}
func (p *Position) getFundingAdjustedMargin(funding *PerpetualMarketFunding) sdk.Dec {
return p.getFundingAdjustedMarginWithAddedMargin(funding, sdk.ZeroDec())
}
func (p *Position) getFundingAdjustedMarginWithAddedMargin(funding *PerpetualMarketFunding, addedMargin sdk.Dec) sdk.Dec {
adjustedMargin := p.Margin.Add(addedMargin)
// Compute the adjusted position margin for positions in perpetual markets
if funding != nil {
unrealizedFundingPayment := p.Quantity.Mul(funding.CumulativeFunding.Sub(p.CumulativeFundingEntry))
// For longs, Margin -= Funding
// For shorts, Margin += Funding
if p.IsLong {
adjustedMargin = adjustedMargin.Sub(unrealizedFundingPayment)
} else {
adjustedMargin = adjustedMargin.Add(unrealizedFundingPayment)
}
}
return adjustedMargin
}
func (p *Position) getFundingAdjustedUnitMarginWithAddedMargin(funding *PerpetualMarketFunding, addedMargin sdk.Dec) sdk.Dec {
adjustedMargin := p.getFundingAdjustedMarginWithAddedMargin(funding, addedMargin)
// Unit Margin = PositionMargin / PositionQuantity
fundingAdjustedUnitMargin := adjustedMargin.Quo(p.Quantity)
return fundingAdjustedUnitMargin
}
func (p *Position) GetAverageWeightedEntryPrice(executionQuantity, executionPrice sdk.Dec) sdk.Dec {
num := p.Quantity.Mul(p.EntryPrice).Add(executionQuantity.Mul(executionPrice))
denom := p.Quantity.Add(executionQuantity)
return num.Quo(denom)
}
func (p *Position) GetPayoutIfFullyClosing(closingPrice, closingFeeRate sdk.Dec) *positionPayout {
isProfitable := (p.IsLong && p.EntryPrice.LT(closingPrice)) || (!p.IsLong && p.EntryPrice.GT(closingPrice))
fullyClosingQuantity := p.Quantity
positionMargin := p.Margin
closeTradingFee := closingPrice.Mul(fullyClosingQuantity).Mul(closingFeeRate)
payoutFromPnl := p.GetPayoutFromPnl(closingPrice, fullyClosingQuantity)
pnlNotional := payoutFromPnl.Sub(closeTradingFee)
payout := pnlNotional.Add(positionMargin)
return &positionPayout{
Payout: payout,
PnlNotional: pnlNotional,
IsProfitable: isProfitable,
}
}
func (p *Position) GetPayoutFromPnl(closingPrice, closingQuantity sdk.Dec) sdk.Dec {
var pnlNotional sdk.Dec
if p.IsLong {
// nolint:all
// pnl = closingQuantity * (executionPrice - entryPrice)
pnlNotional = closingQuantity.Mul(closingPrice.Sub(p.EntryPrice))
} else {
// nolint:all
// pnl = -closingQuantity * (executionPrice - entryPrice)
pnlNotional = closingQuantity.Mul(closingPrice.Sub(p.EntryPrice)).Neg()
}
return pnlNotional
}
func (p *Position) ApplyPositionDelta(delta *PositionDelta, tradingFeeForReduceOnly sdk.Dec) (
payout, closeExecutionMargin, collateralizationMargin sdk.Dec,
) {
// No payouts or margin changes if the position delta is nil
if delta == nil || p == nil {
return sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()
}
if p.Quantity.IsZero() {
p.IsLong = delta.IsLong
}
payout, closeExecutionMargin, collateralizationMargin = sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()
isNettingInSameDirection := (p.IsLong && delta.IsLong) || (p.IsShort() && delta.IsShort())
if isNettingInSameDirection {
p.EntryPrice = p.GetAverageWeightedEntryPrice(delta.ExecutionQuantity, delta.ExecutionPrice)
p.Quantity = p.Quantity.Add(delta.ExecutionQuantity)
p.Margin = p.Margin.Add(delta.ExecutionMargin)
collateralizationMargin = delta.ExecutionMargin
return payout, closeExecutionMargin, collateralizationMargin
}
// netting in opposing direction
closingQuantity := sdk.MinDec(p.Quantity, delta.ExecutionQuantity)
// closeExecutionMargin = execution margin * closing quantity / execution quantity
closeExecutionMargin = delta.ExecutionMargin.Mul(closingQuantity).Quo(delta.ExecutionQuantity)
pnlNotional := p.GetPayoutFromPnl(delta.ExecutionPrice, closingQuantity)
isReduceOnlyTrade := delta.ExecutionMargin.IsZero()
if isReduceOnlyTrade {
// deduct fees from PNL (position margin) for reduce-only orders
// only use the closing trading fee for now
pnlNotional = pnlNotional.Sub(tradingFeeForReduceOnly)
}
positionClosingMargin := p.Margin.Mul(closingQuantity).Quo(p.Quantity)
payout = pnlNotional.Add(positionClosingMargin)
// for netting opposite direction
newPositionQuantity := p.Quantity.Sub(closingQuantity)
p.Margin = p.Margin.Mul(newPositionQuantity).Quo(p.Quantity)
p.Quantity = newPositionQuantity
isFlippingPosition := delta.ExecutionQuantity.GT(closingQuantity)
if isFlippingPosition {
remainingExecutionQuantity := delta.ExecutionQuantity.Sub(closingQuantity)
remainingExecutionMargin := delta.ExecutionMargin.Sub(closeExecutionMargin)
newPositionDelta := &PositionDelta{
IsLong: !p.IsLong,
ExecutionQuantity: remainingExecutionQuantity,
ExecutionMargin: remainingExecutionMargin,
ExecutionPrice: delta.ExecutionPrice,
}
// recurse
_, _, collateralizationMargin = p.ApplyPositionDelta(newPositionDelta, tradingFeeForReduceOnly)
}
return payout, closeExecutionMargin, collateralizationMargin
}