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) } var ( perps = map[uint64]*perp{} nextPerpID uint64 ) func mustPerp(id uint64) *perp { p, ok := perps[id] if !ok { panic("desk: unknown perp id") } return p } // 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 has fallen to the maintenance fraction of the margin. func liquidatable(p *perp, mark int64) bool { return perpEquity(p, mark) <= 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) drop := mulDiv(allowedLoss, microUSD, p.size) // micro-USD per share 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)") } } // OpenPerp opens a long or short on `ticker` of `size` stock units (6 dp), backed // by `margin` tUSD micro pulled from the caller (plus the open fee). Market order. func OpenPerp(cur realm, ticker string, isLong bool, size int64, margin int64) uint64 { _ = mustStock(ticker) // only real markets if !marketOpen { panic("desk: market closed — new perps open only during market hours") } assertPerpSize(size) assertMargin(margin) price := freshPrice(ticker) notional := notionalMicroUSD(price, size) fee := mulDiv(notional, perpFeeBps, bpsDenom) owner := cur.Previous().Address() if err := usdLedger.Transfer(owner, deskAddr, margin+fee); err != nil { panic(err.Error()) } return openPositionCore(owner, ticker, isLong, size, margin, price, fee) } // openPositionCore validates and creates a perp, assuming `margin`+`fee` tUSD are // ALREADY in the desk reserve (pulled from the owner by the caller). Shared by // market opens (OpenPerp) and limit-order execution (TriggerLimit). A panic here // reverts the whole tx, including the funds pull, 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") } assertMargin(margin) if 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 perps[id] = &perp{ id: id, owner: owner, ticker: ticker, isLong: isLong, size: size, entry: entry, margin: margin, openTime: time.Now().Unix(), } // 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 closes the caller's own position at the current mark and settles. func ClosePerp(cur realm, id uint64) { p := mustPerp(id) if p.owner != cur.Previous().Address() { panic("desk: not your position") } mark := freshPrice(p.ticker) settlePerp(p, mark) } // ClosePartial closes `closeSize` units (6 dp) of the caller's own position at the // current mark, leaving the rest open. Always allowed, even when the market is // closed. closeSize == the full size behaves like ClosePerp. func ClosePartial(cur realm, id uint64, closeSize int64) { p := mustPerp(id) if p.owner != cur.Previous().Address() { panic("desk: not your position") } if closeSize <= 0 || closeSize > p.size { panic("desk: invalid close size") } mark := freshPrice(p.ticker) closePortion(p, closeSize, mark) } // 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) } // 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) { if sz <= 0 || sz > p.size { panic("desk: invalid close size") } payout, fee, hold, marginSlice := sliceSettle(p, sz, mark, time.Now().Unix()) 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)) if sz == p.size { delete(perps, p.id) } else { p.size -= sz p.margin -= marginSlice } } // settlePerp fully closes and removes the position. func settlePerp(p *perp, mark int64) { closePortion(p, p.size, mark) } // --- 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. // Money and size are integers at 6 dp; mark/pnl/liq are computed live. Stop prices // are 0 when unset. Empty string if none. func PerpsOf(owner address) string { out := "" for id := uint64(1); id <= nextPerpID; id++ { p, ok := perps[id] if !ok || p.owner != owner { continue } mark, _ := GetPrice(p.ticker) side := "S" if p.isLong { side = "L" } if out != "" { out += ";" } out += ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d", p.id, p.ticker, side, p.size, p.entry, p.margin, mark, perpPnL(p, mark), liqPrice(p), p.stopLoss, p.takeProfit) } return out } // AllLiquidatable lists the ids of positions at or below maintenance on a fresh // quote, ';'-joined, for the keeper. func AllLiquidatable() string { out := "" for id := uint64(1); id <= nextPerpID; id++ { p, ok := perps[id] if !ok || !IsFresh(p.ticker) { continue } mark, _ := GetPrice(p.ticker) if !liquidatable(p, mark) { continue } if out != "" { out += ";" } out += ufmt.Sprintf("%d", p.id) } return out }