Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

delever.gno

3.40 Kb · 113 lines
  1package lastcall
  2
  3// Last call before the close. A stock can gap between the close and the next
  4// open while the desk price stands still, and with isolated margin a losing
  5// position stops at its margin while the winning one is paid in full. An equal
  6// long and short at 10x would then earn from any gap beyond 10% at the desk's
  7// expense. So while the market is closed no position may stay above
  8// closedMaxLeverage: anyone (in practice the keeper) may cut one down to it with
  9// Delever. The cut part is settled like a close, and what it returns stays in
 10// the position as margin. AddMargin lets an owner keep the full size instead.
 11
 12import (
 13	"time"
 14
 15	"gno.land/p/nt/ufmt/v0"
 16)
 17
 18// AddMargin adds `amount` tUSD micro from the caller to their own position,
 19// lowering its leverage. It trades nothing, so it applies at once.
 20func AddMargin(cur realm, id uint64, amount int64) {
 21	p := mustPerp(id)
 22	owner := cur.Previous().Address()
 23	if p.owner != owner {
 24		panic("desk: not your position")
 25	}
 26	if amount <= 0 || p.margin+amount > maxMargin {
 27		panic("desk: margin out of range")
 28	}
 29	pull(owner, amount)
 30	lock(amount)
 31	p.margin += amount
 32	emitPerp("MarginAdd", p, "usd", num(amount), "margin", num(p.margin))
 33}
 34
 35func overLeveraged(p *perp, mark int64) bool {
 36	return notionalMicroUSD(mark, p.size) > p.margin*closedMaxLeverage
 37}
 38
 39// Delever cuts a position held above closedMaxLeverage while the market is
 40// closed, at the desk price, to the size its margin carries at that leverage.
 41// Permissionless.
 42func Delever(cur realm, id uint64) {
 43	if marketOpen {
 44		panic("desk: the market is open")
 45	}
 46	p := mustPerp(id)
 47	mark := freshPrice(p.ticker)
 48	if !overLeveraged(p, mark) {
 49		panic("desk: within the closed-market leverage")
 50	}
 51	if payout, _, _, _ := sliceSettle(p, p.size, mark, time.Now().Unix()); payout > freeReserve()+p.margin {
 52		panic("desk: the reserve cannot pay this cut in full right now")
 53	}
 54	if cut := deleverSize(p, mark, time.Now().Unix()); cut < p.size {
 55		cutToMargin(p, cut, mark)
 56		if !overLeveraged(p, mark) {
 57			return
 58		}
 59	}
 60	settlePerp(p, mark, "delever")
 61}
 62
 63func deleverSize(p *perp, mark, now int64) int64 {
 64	notional := notionalMicroUSD(mark, p.size)
 65	pnl := perpPnL(p, mark)
 66	fee := mulDiv(notional, perpFeeBps, bpsDenom)
 67	gain := pnl - fee - holdingFee(p, now)
 68	room := notional + closedMaxLeverage*gain
 69	if room <= 0 {
 70		return p.size
 71	}
 72	cut := mulDiv(notional-closedMaxLeverage*p.margin, p.size, room) + 1
 73	if cut < minTradeUnits {
 74		cut = minTradeUnits
 75	}
 76	if cut > p.size {
 77		return p.size
 78	}
 79	return cut
 80}
 81
 82func cutToMargin(p *perp, sz, mark int64) {
 83	payout, fee, hold, marginSlice := sliceSettle(p, sz, mark, time.Now().Unix())
 84	unlock(marginSlice)
 85	if free := freeReserve(); payout > free {
 86		payout = free
 87	}
 88	lock(payout)
 89	accrueFee(collectedFee(p, sz, mark, marginSlice, fee+hold))
 90	subOI(p.ticker, p.isLong, notionalMicroUSD(p.entry, sz))
 91	emitPerpClose(p, "delever", sz, mark, payout)
 92	p.size -= sz
 93	p.margin = p.margin - marginSlice + payout
 94}
 95
 96// Overleveraged lists, within one page of open positions, the ids Delever would
 97// cut now, ';'-joined, for the keeper. Empty while the market is open.
 98func Overleveraged(offset, count int) string {
 99	out := ""
100	if marketOpen {
101		return out
102	}
103	eachPage(perps, offset, count, func(item any) {
104		p := item.(*perp)
105		if !IsFresh(p.ticker) {
106			return
107		}
108		if mark, _ := GetPrice(p.ticker); overLeveraged(p, mark) {
109			out = joinRow(out, ufmt.Sprintf("%d", p.id))
110		}
111	})
112	return out
113}