package lastcall // Perpetual stock positions against the desk. Isolated margin, the desk is the // counterparty. Margin is tUSD locked in the desk reserve; profit is paid from // the reserve on close, loss is kept by the desk, both capped at the margin // (isolated). Mark price = the desk reference price (same feed as spot), so // there is no perp-vs-spot basis and no funding in this version. // // All money is micro-USD (6 dp); size is stock units (6 dp), like spot. import ( "time" "gno.land/p/nt/ufmt/v0" ) const ( perpFeeBps = 10 // 0.10% of notional, each side (open + close) maxLeverage = 10 // 10x: notional <= margin * 10 maintBps = 1000 // 10% maintenance: liquidatable when equity <= 10% of margin minMargin = 1_000000 // $1 minimum margin, blocks dust perpMaxNotional = 1_000_000_000000 // $1,000,000 notional cap maxMargin = 1_000_000_000000 holdRateBpsYear = 1000 // 10%/yr borrow fee on notional while a position is open secondsYear = 31_536_000 // 365d, for prorating the borrow fee ) type perp struct { id uint64 owner address ticker string isLong bool size int64 // stock units (6 dp), > 0 entry int64 // micro-USD per share at open margin int64 // tUSD micro locked for this position openTime int64 // block time at open (unix seconds), for the borrow fee stopLoss int64 // optional stop-loss trigger, micro-USD/share (0 = unset) takeProfit int64 // optional take-profit trigger, micro-USD/share (0 = unset) stopsAt int64 // when the stops were last set; they trigger only on a later price closeSize int64 // size of a requested close, 0 for all of it closeAt int64 // when a close was requested, 0 when none is waiting } var nextPerpID uint64 func mustPerp(id uint64) *perp { v := perps.Get(idKey(id)) if v == nil { panic("desk: unknown perp id") } return v.(*perp) } // perpPnL is size * (mark - entry) / 1e6 for a long, negated for a short. func perpPnL(p *perp, mark int64) int64 { pnl := notionalMicroUSD(mark, p.size) - notionalMicroUSD(p.entry, p.size) if !p.isLong { pnl = -pnl } return pnl } // equity is the position's margin plus unrealized PnL. func perpEquity(p *perp, mark int64) int64 { return p.margin + perpPnL(p, mark) } // liquidatable: equity net of the accrued borrow fee has fallen to the // maintenance fraction of the margin. func liquidatable(p *perp, mark int64) bool { return perpEquity(p, mark)-holdingFee(p, time.Now().Unix()) <= mulDiv(p.margin, maintBps, bpsDenom) } // liqPrice is the mark price at which the position becomes liquidatable. func liqPrice(p *perp) int64 { // allowed loss before maintenance = margin * (1 - maintBps/1e4) allowedLoss := mulDiv(p.margin, bpsDenom-maintBps, bpsDenom) - holdingFee(p, time.Now().Unix()) var drop int64 // micro-USD per share if allowedLoss >= 0 { drop = mulDiv(allowedLoss, microUSD, p.size) } else { drop = -mulDiv(-allowedLoss, microUSD, p.size) } if p.isLong { return p.entry - drop } return p.entry + drop } // assertPerpSize bounds the size so price*size stays inside int64. func assertPerpSize(size int64) { if size < minTradeUnits { panic("desk: size below minimum (0.001 share)") } if size > maxTradeUnits { panic("desk: size above maximum (10,000 shares)") } } func assertMargin(margin int64) { if margin < minMargin { panic("desk: margin below minimum ($1)") } if margin > maxMargin { panic("desk: margin above maximum ($1,000,000)") } } // openPositionCore validates and creates a perp, assuming `margin`+`fee` tUSD are // ALREADY in the desk reserve and not locked. Called when a perp order fills // (FillOrder). A panic here reverts the whole tx, so nothing is stranded. func openPositionCore(owner address, ticker string, isLong bool, size, margin, price, fee int64) uint64 { assertPerpSize(size) notional := notionalMicroUSD(price, size) if notional <= 0 || notional > perpMaxNotional { panic("desk: notional out of range") } if margin <= 0 || notional > margin*maxLevOf(ticker) { panic("desk: over this market's max leverage") } if sideOI(ticker, isLong)+notional > oiCap(ticker) { panic("desk: open-interest cap reached for this side") } // skew-priced entry on the pre-trade open interest. entry := skewEntry(price, skewImpactBps(ticker, isLong, notional), isLong) accrueFee(fee) // open fee -> liquidity pool yield nextPerpID++ id := nextPerpID p := &perp{ id: id, owner: owner, ticker: ticker, isLong: isLong, size: size, entry: entry, margin: margin, openTime: time.Now().Unix(), } putItem(perps, ownerPerps, owner, id, p) lock(margin) emitPerpOpen(p) // OI is tracked at entry-notional (same basis subOI uses on close) so skew // impact doesn't silently drift the open-interest sum across many trades. addOI(ticker, isLong, notionalMicroUSD(entry, size)) return id } // ClosePerp asks to close the caller's whole position. It closes on the first // price observed after the request (FillClose). func ClosePerp(cur realm, id uint64) { requestClose(cur.Previous().Address(), id, 0) } // ClosePartial asks to close `closeSize` units (6 dp) of the caller's position on // the first price observed after the request. Allowed while the market is closed. func ClosePartial(cur realm, id uint64, closeSize int64) { if closeSize <= 0 { panic("desk: invalid close size") } requestClose(cur.Previous().Address(), id, closeSize) } func requestClose(owner address, id uint64, size int64) { p := mustPerp(id) if p.owner != owner { panic("desk: not your position") } if size > p.size { panic("desk: invalid close size") } if p.closeAt > 0 && time.Now().Unix()-p.closeAt <= orderTTL { panic("desk: a close is already waiting for the next price") } if size == p.size { size = 0 } p.closeSize, p.closeAt = size, time.Now().Unix() emitPerp("CloseRequest", p, "size", num(closingSize(p))) } func closingSize(p *perp) int64 { if p.closeAt == 0 { return 0 } if p.closeSize == 0 || p.closeSize > p.size { return p.size } return p.closeSize } // FillClose closes a requested position on the first price observed after the // request, or drops a request that waited longer than orderTTL. Permissionless. func FillClose(cur realm, id uint64) { fillClose(id) } func fillClose(id uint64) { p := mustPerp(id) if p.closeAt == 0 { panic("desk: no close requested") } if time.Now().Unix()-p.closeAt > orderTTL { p.closeSize, p.closeAt = 0, 0 emitPerp("CloseExpire", p) return } if !pricedAfter(p.ticker, p.closeAt) { panic("desk: the close waits for the next price") } mark := freshPrice(p.ticker) size := closingSize(p) p.closeSize, p.closeAt = 0, 0 if size == p.size { settlePerp(p, mark, "close") return } closePortion(p, size, mark, "partial") } // Liquidate closes an underwater position. Permissionless: anyone (the desk's // keeper bot, or the UI) may call it once the position is at maintenance. func Liquidate(cur realm, id uint64) { p := mustPerp(id) mark := freshPrice(p.ticker) if !liquidatable(p, mark) { panic("desk: not liquidatable") } settlePerp(p, mark, "liquidate") } // holdingFee is the borrow fee owed to the pool for keeping a position open: // holdRateBpsYear of the entry notional, prorated by seconds held. It prices the // pool's directional risk over time — the honest substitute for funding on an // oracle-mark desk (there is no perp-vs-spot basis to correct, but the pool is // still carrying the position). Overflow-safe: perYear <= 1e11, elapsed clamped. func holdingFee(p *perp, now int64) int64 { el := now - p.openTime if el <= 0 { return 0 } if el > 60_000_000 { // ~1.9y clamp keeps perYear*el well inside int64 el = 60_000_000 } perYear := mulDiv(notionalMicroUSD(p.entry, p.size), holdRateBpsYear, bpsDenom) return mulDiv(perYear, el, secondsYear) } // sliceSettle computes the numbers for closing `sz` units of a position at `mark`: // pro-rata margin, the slice's PnL, the close fee and the borrow fee, and the owner // payout (floored at 0). Pure — no transfers — so it is unit-tested directly. func sliceSettle(p *perp, sz int64, mark int64, now int64) (payout, fee, hold, marginSlice int64) { marginSlice = mulDiv(p.margin, sz, p.size) pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz) if !p.isLong { pnl = -pnl } fee = mulDiv(notionalMicroUSD(mark, sz), perpFeeBps, bpsDenom) hold = mulDiv(holdingFee(p, now), sz, p.size) payout = marginSlice + pnl - fee - hold if payout < 0 { payout = 0 } return payout, fee, hold, marginSlice } // collectedFee caps a close's fees at the equity the closed slice still had. func collectedFee(p *perp, sz, mark, marginSlice, owed int64) int64 { pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz) if !p.isLong { pnl = -pnl } equity := marginSlice + pnl if equity < 0 { return 0 } if equity < owed { return equity } return owed } // closePortion closes `sz` units of the position at `mark`: pays the owner the slice // payout, routes the fees to the pool, releases the slice's open interest, and // shrinks the position (or removes it when `sz` is the whole size). Leverage, entry // and liq price of the remainder are unchanged (margin and size shrink together). func closePortion(p *perp, sz int64, mark int64, kind string) { if sz <= 0 || sz > p.size { panic("desk: invalid close size") } payout, fee, hold, marginSlice := sliceSettle(p, sz, mark, time.Now().Unix()) unlock(marginSlice) if free := freeReserve(); payout > free { payout = free // profit comes only from tUSD nobody else is owed } if payout > 0 { if err := usdLedger.Transfer(deskAddr, p.owner, payout); err != nil { panic(err.Error()) } } accrueFee(collectedFee(p, sz, mark, marginSlice, fee+hold)) // only what the margin covered subOI(p.ticker, p.isLong, notionalMicroUSD(p.entry, sz)) emitPerpClose(p, kind, sz, mark, payout) if sz == p.size { dropItem(perps, ownerPerps, p.owner, p.id) } else { p.size -= sz p.margin -= marginSlice } } // settlePerp fully closes and removes the position. func settlePerp(p *perp, mark int64, kind string) { closePortion(p, p.size, mark, kind) } // --- reads for the UI --- // PerpsOf returns the caller's open positions, one per line, fields comma- // separated: id,ticker,L|S,size,entry,margin,mark,pnl,liq,stopLoss,takeProfit,closing. // Money and size are integers at 6 dp; mark/pnl/liq are computed live. Stop prices // are 0 when unset; closing is the size of a close waiting for the next price. func PerpsOf(owner address) string { out := "" eachOwned(ownerPerps, owner, func(item any) { p := item.(*perp) mark, _ := GetPrice(p.ticker) out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d", p.id, p.ticker, sideOf(p.isLong), p.size, p.entry, p.margin, mark, perpPnL(p, mark), liqPrice(p), p.stopLoss, p.takeProfit, closingSize(p))) }) return out } // AllLiquidatable lists, within one page of open positions, the ids at or below // maintenance on a fresh quote, ';'-joined, for the keeper. func AllLiquidatable(offset, count int) string { out := "" eachPage(perps, offset, count, func(item any) { p := item.(*perp) if !IsFresh(p.ticker) { return } if mark, _ := GetPrice(p.ticker); liquidatable(p, mark) { out = joinRow(out, ufmt.Sprintf("%d", p.id)) } }) return out } // ReadyCloses lists, within one page of open positions, the ids FillClose would // act on now, ';'-joined, for the keeper. func ReadyCloses(offset, count int) string { out := "" now := time.Now().Unix() eachPage(perps, offset, count, func(item any) { p := item.(*perp) if p.closeAt == 0 { return } if now-p.closeAt > orderTTL || (pricedAfter(p.ticker, p.closeAt) && IsFresh(p.ticker)) { out = joinRow(out, ufmt.Sprintf("%d", p.id)) } }) return out }