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