perp.gno
10.58 Kb · 310 lines
1package lastcall
2
3// Perpetual stock positions against the desk. Isolated margin, the desk is the
4// counterparty. Margin is tUSD locked in the desk reserve; profit is paid from
5// the reserve on close, loss is kept by the desk, both capped at the margin
6// (isolated). Mark price = the desk reference price (same feed as spot), so
7// there is no perp-vs-spot basis and no funding in this version.
8//
9// All money is micro-USD (6 dp); size is stock units (6 dp), like spot.
10
11import (
12 "time"
13
14 "gno.land/p/nt/ufmt/v0"
15)
16
17const (
18 perpFeeBps = 10 // 0.10% of notional, each side (open + close)
19 maxLeverage = 10 // 10x: notional <= margin * 10
20 maintBps = 1000 // 10% maintenance: liquidatable when equity <= 10% of margin
21 minMargin = 1_000000 // $1 minimum margin, blocks dust
22 perpMaxNotional = 1_000_000_000000 // $1,000,000 notional cap
23 maxMargin = 1_000_000_000000
24 holdRateBpsYear = 1000 // 10%/yr borrow fee on notional while a position is open
25 secondsYear = 31_536_000 // 365d, for prorating the borrow fee
26)
27
28type perp struct {
29 id uint64
30 owner address
31 ticker string
32 isLong bool
33 size int64 // stock units (6 dp), > 0
34 entry int64 // micro-USD per share at open
35 margin int64 // tUSD micro locked for this position
36 openTime int64 // block time at open (unix seconds), for the borrow fee
37 stopLoss int64 // optional stop-loss trigger, micro-USD/share (0 = unset)
38 takeProfit int64 // optional take-profit trigger, micro-USD/share (0 = unset)
39}
40
41var nextPerpID uint64
42
43func mustPerp(id uint64) *perp {
44 v := perps.Get(idKey(id))
45 if v == nil {
46 panic("desk: unknown perp id")
47 }
48 return v.(*perp)
49}
50
51// perpPnL is size * (mark - entry) / 1e6 for a long, negated for a short.
52func perpPnL(p *perp, mark int64) int64 {
53 pnl := notionalMicroUSD(mark, p.size) - notionalMicroUSD(p.entry, p.size)
54 if !p.isLong {
55 pnl = -pnl
56 }
57 return pnl
58}
59
60// equity is the position's margin plus unrealized PnL.
61func perpEquity(p *perp, mark int64) int64 { return p.margin + perpPnL(p, mark) }
62
63// liquidatable: equity net of the accrued borrow fee has fallen to the
64// maintenance fraction of the margin.
65func liquidatable(p *perp, mark int64) bool {
66 return perpEquity(p, mark)-holdingFee(p, time.Now().Unix()) <= mulDiv(p.margin, maintBps, bpsDenom)
67}
68
69// liqPrice is the mark price at which the position becomes liquidatable.
70func liqPrice(p *perp) int64 {
71 // allowed loss before maintenance = margin * (1 - maintBps/1e4)
72 allowedLoss := mulDiv(p.margin, bpsDenom-maintBps, bpsDenom) - holdingFee(p, time.Now().Unix())
73 var drop int64 // micro-USD per share
74 if allowedLoss >= 0 {
75 drop = mulDiv(allowedLoss, microUSD, p.size)
76 } else {
77 drop = -mulDiv(-allowedLoss, microUSD, p.size)
78 }
79 if p.isLong {
80 return p.entry - drop
81 }
82 return p.entry + drop
83}
84
85// assertPerpSize bounds the size so price*size stays inside int64.
86func assertPerpSize(size int64) {
87 if size < minTradeUnits {
88 panic("desk: size below minimum (0.001 share)")
89 }
90 if size > maxTradeUnits {
91 panic("desk: size above maximum (10,000 shares)")
92 }
93}
94
95func assertMargin(margin int64) {
96 if margin < minMargin {
97 panic("desk: margin below minimum ($1)")
98 }
99 if margin > maxMargin {
100 panic("desk: margin above maximum ($1,000,000)")
101 }
102}
103
104// OpenPerp opens a long or short on `ticker` of `size` stock units (6 dp), backed
105// by `margin` tUSD micro pulled from the caller (plus the open fee). Market order.
106func OpenPerp(cur realm, ticker string, isLong bool, size int64, margin int64) uint64 {
107 _ = mustStock(ticker) // only real markets
108 if !marketOpen {
109 panic("desk: market closed — new perps open only during market hours")
110 }
111 assertPerpSize(size)
112 assertMargin(margin)
113 price := freshPrice(ticker)
114 notional := notionalMicroUSD(price, size)
115 fee := mulDiv(notional, perpFeeBps, bpsDenom)
116 owner := cur.Previous().Address()
117 if err := usdLedger.Transfer(owner, deskAddr, margin+fee); err != nil {
118 panic(err.Error())
119 }
120 return openPositionCore(owner, ticker, isLong, size, margin, price, fee)
121}
122
123// openPositionCore validates and creates a perp, assuming `margin`+`fee` tUSD are
124// ALREADY in the desk reserve (pulled from the owner by the caller) and not
125// locked. Shared by
126// market opens (OpenPerp) and limit-order execution (TriggerLimit). A panic here
127// reverts the whole tx, including the funds pull, so nothing is stranded.
128func openPositionCore(owner address, ticker string, isLong bool, size, margin, price, fee int64) uint64 {
129 assertPerpSize(size)
130 notional := notionalMicroUSD(price, size)
131 if notional <= 0 || notional > perpMaxNotional {
132 panic("desk: notional out of range")
133 }
134 if margin <= 0 || notional > margin*maxLevOf(ticker) {
135 panic("desk: over this market's max leverage")
136 }
137 if sideOI(ticker, isLong)+notional > oiCap(ticker) {
138 panic("desk: open-interest cap reached for this side")
139 }
140 // skew-priced entry on the pre-trade open interest.
141 entry := skewEntry(price, skewImpactBps(ticker, isLong, notional), isLong)
142 accrueFee(fee) // open fee -> liquidity pool yield
143 nextPerpID++
144 id := nextPerpID
145 putItem(perps, ownerPerps, owner, id, &perp{
146 id: id, owner: owner, ticker: ticker, isLong: isLong,
147 size: size, entry: entry, margin: margin,
148 openTime: time.Now().Unix(),
149 })
150 lock(margin)
151 // OI is tracked at entry-notional (same basis subOI uses on close) so skew
152 // impact doesn't silently drift the open-interest sum across many trades.
153 addOI(ticker, isLong, notionalMicroUSD(entry, size))
154 return id
155}
156
157// ClosePerp closes the caller's own position at the current mark and settles.
158func ClosePerp(cur realm, id uint64) {
159 p := mustPerp(id)
160 if p.owner != cur.Previous().Address() {
161 panic("desk: not your position")
162 }
163 mark := freshPrice(p.ticker)
164 settlePerp(p, mark)
165}
166
167// ClosePartial closes `closeSize` units (6 dp) of the caller's own position at the
168// current mark, leaving the rest open. Always allowed, even when the market is
169// closed. closeSize == the full size behaves like ClosePerp.
170func ClosePartial(cur realm, id uint64, closeSize int64) {
171 p := mustPerp(id)
172 if p.owner != cur.Previous().Address() {
173 panic("desk: not your position")
174 }
175 if closeSize <= 0 || closeSize > p.size {
176 panic("desk: invalid close size")
177 }
178 mark := freshPrice(p.ticker)
179 closePortion(p, closeSize, mark)
180}
181
182// Liquidate closes an underwater position. Permissionless: anyone (the desk's
183// keeper bot, or the UI) may call it once the position is at maintenance.
184func Liquidate(cur realm, id uint64) {
185 p := mustPerp(id)
186 mark := freshPrice(p.ticker)
187 if !liquidatable(p, mark) {
188 panic("desk: not liquidatable")
189 }
190 settlePerp(p, mark)
191}
192
193// holdingFee is the borrow fee owed to the pool for keeping a position open:
194// holdRateBpsYear of the entry notional, prorated by seconds held. It prices the
195// pool's directional risk over time — the honest substitute for funding on an
196// oracle-mark desk (there is no perp-vs-spot basis to correct, but the pool is
197// still carrying the position). Overflow-safe: perYear <= 1e11, elapsed clamped.
198func holdingFee(p *perp, now int64) int64 {
199 el := now - p.openTime
200 if el <= 0 {
201 return 0
202 }
203 if el > 60_000_000 { // ~1.9y clamp keeps perYear*el well inside int64
204 el = 60_000_000
205 }
206 perYear := mulDiv(notionalMicroUSD(p.entry, p.size), holdRateBpsYear, bpsDenom)
207 return mulDiv(perYear, el, secondsYear)
208}
209
210// sliceSettle computes the numbers for closing `sz` units of a position at `mark`:
211// pro-rata margin, the slice's PnL, the close fee and the borrow fee, and the owner
212// payout (floored at 0). Pure — no transfers — so it is unit-tested directly.
213func sliceSettle(p *perp, sz int64, mark int64, now int64) (payout, fee, hold, marginSlice int64) {
214 marginSlice = mulDiv(p.margin, sz, p.size)
215 pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz)
216 if !p.isLong {
217 pnl = -pnl
218 }
219 fee = mulDiv(notionalMicroUSD(mark, sz), perpFeeBps, bpsDenom)
220 hold = mulDiv(holdingFee(p, now), sz, p.size)
221 payout = marginSlice + pnl - fee - hold
222 if payout < 0 {
223 payout = 0
224 }
225 return payout, fee, hold, marginSlice
226}
227
228// collectedFee caps a close's fees at the equity the closed slice still had.
229func collectedFee(p *perp, sz, mark, marginSlice, owed int64) int64 {
230 pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz)
231 if !p.isLong {
232 pnl = -pnl
233 }
234 equity := marginSlice + pnl
235 if equity < 0 {
236 return 0
237 }
238 if equity < owed {
239 return equity
240 }
241 return owed
242}
243
244// closePortion closes `sz` units of the position at `mark`: pays the owner the slice
245// payout, routes the fees to the pool, releases the slice's open interest, and
246// shrinks the position (or removes it when `sz` is the whole size). Leverage, entry
247// and liq price of the remainder are unchanged (margin and size shrink together).
248func closePortion(p *perp, sz int64, mark int64) {
249 if sz <= 0 || sz > p.size {
250 panic("desk: invalid close size")
251 }
252 payout, fee, hold, marginSlice := sliceSettle(p, sz, mark, time.Now().Unix())
253 unlock(marginSlice)
254 if free := freeReserve(); payout > free {
255 payout = free // profit comes only from tUSD nobody else is owed
256 }
257 if payout > 0 {
258 if err := usdLedger.Transfer(deskAddr, p.owner, payout); err != nil {
259 panic(err.Error())
260 }
261 }
262 accrueFee(collectedFee(p, sz, mark, marginSlice, fee+hold)) // only what the margin covered
263 subOI(p.ticker, p.isLong, notionalMicroUSD(p.entry, sz))
264 if sz == p.size {
265 dropItem(perps, ownerPerps, p.owner, p.id)
266 } else {
267 p.size -= sz
268 p.margin -= marginSlice
269 }
270}
271
272// settlePerp fully closes and removes the position.
273func settlePerp(p *perp, mark int64) { closePortion(p, p.size, mark) }
274
275// --- reads for the UI ---
276
277// PerpsOf returns the caller's open positions, one per line, fields comma-
278// separated: id,ticker,L|S,size,entry,margin,mark,pnl,liq,stopLoss,takeProfit.
279// Money and size are integers at 6 dp; mark/pnl/liq are computed live. Stop prices
280// are 0 when unset. Empty string if none.
281func PerpsOf(owner address) string {
282 out := ""
283 eachOwned(ownerPerps, owner, func(item any) {
284 p := item.(*perp)
285 mark, _ := GetPrice(p.ticker)
286 side := "S"
287 if p.isLong {
288 side = "L"
289 }
290 out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d",
291 p.id, p.ticker, side, p.size, p.entry, p.margin, mark, perpPnL(p, mark), liqPrice(p), p.stopLoss, p.takeProfit))
292 })
293 return out
294}
295
296// AllLiquidatable lists, within one page of open positions, the ids at or below
297// maintenance on a fresh quote, ';'-joined, for the keeper.
298func AllLiquidatable(offset, count int) string {
299 out := ""
300 eachPage(perps, offset, count, func(item any) {
301 p := item.(*perp)
302 if !IsFresh(p.ticker) {
303 return
304 }
305 if mark, _ := GetPrice(p.ticker); liquidatable(p, mark) {
306 out = joinRow(out, ufmt.Sprintf("%d", p.id))
307 }
308 })
309 return out
310}