limit.gno
4.61 Kb · 164 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)
24 limit int64 // trigger price, micro-USD per share
25 placedAt int64
26}
27
28var (
29 limits = map[uint64]*limitOrder{}
30 nextLimitID uint64
31)
32
33// PlaceLimit locks `margin` + the open fee and queues an order to open a perp when
34// the oracle price reaches `limit`. Returns the order id.
35func PlaceLimit(cur realm, ticker string, isLong bool, size, margin, limit int64) uint64 {
36 _ = mustStock(ticker)
37 assertPerpSize(size)
38 assertMargin(margin)
39 if limit <= 0 || limit > maxPrice {
40 panic("desk: limit price out of range")
41 }
42 notional := notionalMicroUSD(limit, size)
43 if notional <= 0 || notional > perpMaxNotional {
44 panic("desk: notional out of range")
45 }
46 if notional > margin*maxLevOf(ticker) {
47 panic("desk: over this market's max leverage")
48 }
49 fee := mulDiv(notional, perpFeeBps, bpsDenom)
50 owner := cur.Previous().Address()
51 if err := usdLedger.Transfer(owner, deskAddr, margin+fee); err != nil {
52 panic(err.Error())
53 }
54 nextLimitID++
55 id := nextLimitID
56 limits[id] = &limitOrder{
57 id: id, owner: owner, ticker: ticker, isLong: isLong,
58 size: size, margin: margin, fee: fee, limit: limit, placedAt: time.Now().Unix(),
59 }
60 return id
61}
62
63// CancelLimit refunds a pending order's locked margin + fee to its owner.
64func CancelLimit(cur realm, id uint64) {
65 o, ok := limits[id]
66 if !ok {
67 panic("desk: unknown limit order")
68 }
69 if o.owner != cur.Previous().Address() {
70 panic("desk: not your order")
71 }
72 if err := usdLedger.Transfer(deskAddr, o.owner, o.margin+o.fee); err != nil {
73 panic(err.Error())
74 }
75 delete(limits, id)
76}
77
78// limitReady reports whether an order's trigger condition holds at `mark`:
79// a long fills at or below its limit, a short at or above.
80func limitReady(o *limitOrder, mark int64) bool {
81 if o.isLong {
82 return mark <= o.limit
83 }
84 return mark >= o.limit
85}
86
87// fillSize shrinks an order whose notional at the fill price would exceed the
88// leverage its margin allows, so a price gap past the limit still fills.
89func fillSize(o *limitOrder, mark int64) int64 {
90 maxNotional := o.margin * maxLevOf(o.ticker)
91 if maxNotional > perpMaxNotional {
92 maxNotional = perpMaxNotional
93 }
94 if notionalMicroUSD(mark, o.size) <= maxNotional {
95 return o.size
96 }
97 return mulDiv(maxNotional, microUSD, mark)
98}
99
100// TriggerLimit executes a ready order at the current oracle price, using the locked
101// margin + prepaid fee. Permissionless (keeper / UI). Requires the market open and
102// the trigger reached; panics otherwise so the keeper simply retries later.
103func TriggerLimit(cur realm, id uint64) uint64 {
104 o, ok := limits[id]
105 if !ok {
106 panic("desk: unknown limit order")
107 }
108 if !marketOpen {
109 panic("desk: market closed")
110 }
111 mark := freshPrice(o.ticker)
112 if !limitReady(o, mark) {
113 panic("desk: limit not reached")
114 }
115 pid := openPositionCore(o.owner, o.ticker, o.isLong, fillSize(o, mark), o.margin, mark, o.fee)
116 delete(limits, id)
117 return pid
118}
119
120// --- reads ---
121
122// LimitsOf returns an owner's pending orders, ';'-joined, fields comma-separated:
123// id,ticker,L|S,size,margin,limit,mark (size/money micro, 6 dp).
124func LimitsOf(owner address) string {
125 out := ""
126 for id := uint64(1); id <= nextLimitID; id++ {
127 o, ok := limits[id]
128 if !ok || o.owner != owner {
129 continue
130 }
131 mark, _ := GetPrice(o.ticker)
132 side := "S"
133 if o.isLong {
134 side = "L"
135 }
136 if out != "" {
137 out += ";"
138 }
139 out += ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d", o.id, o.ticker, side, o.size, o.margin, o.limit, mark)
140 }
141 return out
142}
143
144// AllLimits lists every pending order for the keeper to scan, ';'-joined:
145// id,ticker,L|S,limit,mark. The keeper triggers the ones whose condition holds.
146func AllLimits() string {
147 out := ""
148 for id := uint64(1); id <= nextLimitID; id++ {
149 o, ok := limits[id]
150 if !ok {
151 continue
152 }
153 mark, _ := GetPrice(o.ticker)
154 side := "S"
155 if o.isLong {
156 side = "L"
157 }
158 if out != "" {
159 out += ";"
160 }
161 out += ufmt.Sprintf("%d,%s,%s,%d,%d", o.id, o.ticker, side, o.limit, mark)
162 }
163 return out
164}