limit.gno
6.01 Kb · 187 lines
1package lastcall
2
3// Limit orders for perps. On an oracle-priced desk there is no order book, so a
4// limit is a queued instruction: lock the margin + open fee now, and open the perp
5// once the oracle price reaches the limit (long: at or below; short: at or above).
6// Execution is permissionless (TriggerLimit) — the price bot acts as the keeper,
7// and anyone can trigger a ready order. Orders only execute while the market is
8// open, so they naturally queue over a weekend and fire on reopen.
9
10import (
11 "time"
12
13 "gno.land/p/nt/ufmt/v0"
14)
15
16type limitOrder struct {
17 id uint64
18 owner address
19 ticker string
20 isLong bool
21 size int64 // stock units (6 dp)
22 margin int64 // tUSD micro locked up-front
23 fee int64 // prepaid open fee (at the limit price), settled at the fill
24 limit int64 // trigger price, micro-USD per share
25 placedAt int64
26}
27
28var nextLimitID uint64
29
30func mustLimit(id uint64) *limitOrder {
31 v := limits.Get(idKey(id))
32 if v == nil {
33 panic("desk: unknown limit order")
34 }
35 return v.(*limitOrder)
36}
37
38// PlaceLimit locks `margin` + the open fee and queues an order to open a perp when
39// the oracle price reaches `limit`. Returns the order id.
40func PlaceLimit(cur realm, ticker string, isLong bool, size, margin, limit int64) uint64 {
41 _ = mustStock(ticker)
42 _, _ = GetPrice(ticker) // an order on a never-quoted market could not be listed
43 assertPerpSize(size)
44 assertMargin(margin)
45 if limit <= 0 || limit > maxPrice {
46 panic("desk: limit price out of range")
47 }
48 notional := notionalMicroUSD(limit, size)
49 if notional <= 0 || notional > perpMaxNotional {
50 panic("desk: notional out of range")
51 }
52 if notional > margin*maxLevOf(ticker) {
53 panic("desk: over this market's max leverage")
54 }
55 fee := mulDiv(notional, perpFeeBps, bpsDenom)
56 owner := cur.Previous().Address()
57 if err := usdLedger.Transfer(owner, deskAddr, margin+fee); err != nil {
58 panic(err.Error())
59 }
60 nextLimitID++
61 id := nextLimitID
62 putItem(limits, ownerLimits, owner, id, &limitOrder{
63 id: id, owner: owner, ticker: ticker, isLong: isLong,
64 size: size, margin: margin, fee: fee, limit: limit, placedAt: time.Now().Unix(),
65 })
66 lock(margin + fee)
67 return id
68}
69
70// CancelLimit refunds a pending order's locked margin + fee to its owner.
71func CancelLimit(cur realm, id uint64) {
72 o := mustLimit(id)
73 if o.owner != cur.Previous().Address() {
74 panic("desk: not your order")
75 }
76 unlock(o.margin + o.fee)
77 if err := usdLedger.Transfer(deskAddr, o.owner, o.margin+o.fee); err != nil {
78 panic(err.Error())
79 }
80 dropItem(limits, ownerLimits, o.owner, id)
81}
82
83// limitReady reports whether an order's trigger condition holds at `mark`:
84// a long fills at or below its limit, a short at or above.
85func limitReady(o *limitOrder, mark int64) bool {
86 if o.isLong {
87 return mark <= o.limit
88 }
89 return mark >= o.limit
90}
91
92// fillSize shrinks an order whose notional at the fill price would exceed the
93// leverage its margin allows, so a price gap past the limit still fills.
94func fillSize(o *limitOrder, mark int64) int64 {
95 maxNotional := o.margin * maxLevOf(o.ticker)
96 if maxNotional > perpMaxNotional {
97 maxNotional = perpMaxNotional
98 }
99 if notionalMicroUSD(mark, o.size) <= maxNotional {
100 return o.size
101 }
102 return mulDiv(maxNotional, microUSD, mark)
103}
104
105// limitFill settles the open fee on what actually fills at `mark`. A surplus of
106// the prepaid fee is refunded; a shortfall comes out of the margin, and the size
107// is capped so the smaller margin still carries it.
108func limitFill(o *limitOrder, mark int64) (size, margin, fee, refund int64) {
109 size = fillSize(o, mark)
110 fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom)
111 if fee <= o.fee {
112 return size, o.margin, fee, o.fee - fee
113 }
114 lev := maxLevOf(o.ticker)
115 maxNotional := mulDiv((o.margin+o.fee)*lev, bpsDenom, bpsDenom+lev*perpFeeBps)
116 if notionalMicroUSD(mark, size) > maxNotional {
117 size = mulDiv(maxNotional, microUSD, mark)
118 fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom)
119 }
120 if fee <= o.fee {
121 return size, o.margin, fee, o.fee - fee
122 }
123 return size, o.margin - (fee - o.fee), fee, 0
124}
125
126// TriggerLimit executes a ready order at the current oracle price, using the locked
127// margin + prepaid fee. Permissionless (keeper / UI). Requires the market open and
128// the trigger reached, including any skew impact on the entry; panics otherwise so
129// the keeper simply retries later.
130func TriggerLimit(cur realm, id uint64) uint64 {
131 o := mustLimit(id)
132 if !marketOpen {
133 panic("desk: market closed")
134 }
135 mark := freshPrice(o.ticker)
136 if !limitReady(o, mark) {
137 panic("desk: limit not reached")
138 }
139 size, margin, fee, refund := limitFill(o, mark)
140 entry := skewEntry(mark, skewImpactBps(o.ticker, o.isLong, notionalMicroUSD(mark, size)), o.isLong)
141 if (o.isLong && entry > o.limit) || (!o.isLong && entry < o.limit) {
142 panic("desk: skew impact puts the fill past your limit")
143 }
144 unlock(o.margin + o.fee)
145 if refund > 0 {
146 if err := usdLedger.Transfer(deskAddr, o.owner, refund); err != nil {
147 panic(err.Error())
148 }
149 }
150 pid := openPositionCore(o.owner, o.ticker, o.isLong, size, margin, mark, fee)
151 dropItem(limits, ownerLimits, o.owner, id)
152 return pid
153}
154
155// --- reads ---
156
157// LimitsOf returns an owner's pending orders, ';'-joined, fields comma-separated:
158// id,ticker,L|S,size,margin,limit,mark (size/money micro, 6 dp).
159func LimitsOf(owner address) string {
160 out := ""
161 eachOwned(ownerLimits, owner, func(item any) {
162 o := item.(*limitOrder)
163 mark, _ := GetPrice(o.ticker)
164 side := "S"
165 if o.isLong {
166 side = "L"
167 }
168 out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d", o.id, o.ticker, side, o.size, o.margin, o.limit, mark))
169 })
170 return out
171}
172
173// AllLimits lists one page of pending orders for the keeper to scan, ';'-joined:
174// id,ticker,L|S,limit,mark. The keeper triggers the ones whose condition holds.
175func AllLimits(offset, count int) string {
176 out := ""
177 eachPage(limits, offset, count, func(item any) {
178 o := item.(*limitOrder)
179 mark, _ := GetPrice(o.ticker)
180 side := "S"
181 if o.isLong {
182 side = "L"
183 }
184 out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d", o.id, o.ticker, side, o.limit, mark))
185 })
186 return out
187}