orders.gno
12.12 Kb · 410 lines
1package lastcall
2
3// Every trade is an order that fills on the first desk price observed after it
4// was placed. The desk price is pushed every minute or so; without this rule a
5// trader who watches the real market could trade on a quote they already know
6// to be stale.
7//
8// Kinds: "market" and "limit" open a perp, "buy" and "sell" trade spot. Money is
9// taken when the order is placed (margin and fee, or the spot cost at the worst
10// price the order accepts; a sell burns the shares), so filling needs no
11// signature from the owner. Filling is permissionless: the keeper fills orders
12// right after each price, and anyone else may.
13//
14// A market order, buy or sell accepts a price up to marketBandBps worse than the
15// one it saw. If the next price is past that, or no new price comes within
16// orderTTL, it is refunded in full. A limit waits until its price is reached and
17// can be cancelled, except while it is fillable.
18
19import (
20 "time"
21
22 "gno.land/p/nt/avl/v0"
23 "gno.land/p/nt/ufmt/v0"
24)
25
26const (
27 marketBandBps = 200
28 orderTTL = 900
29)
30
31type order struct {
32 id uint64
33 owner address
34 kind string
35 ticker string
36 isLong bool
37 size int64
38 margin int64
39 fee int64
40 limit int64
41 basis int64
42 placedAt int64
43}
44
45var (
46 nextOrderID uint64
47 results = avl.NewTree()
48)
49
50func mustOrder(id uint64) *order {
51 v := orders.Get(idKey(id))
52 if v == nil {
53 panic("desk: unknown order")
54 }
55 return v.(*order)
56}
57
58func isPerpOrder(o *order) bool { return o.kind == "market" || o.kind == "limit" }
59
60func bandPrice(mark int64, worseUp bool) int64 {
61 if worseUp {
62 return mulDiv(mark, bpsDenom+marketBandBps, bpsDenom)
63 }
64 return mulDiv(mark, bpsDenom-marketBandBps, bpsDenom)
65}
66
67func pull(from address, amount int64) {
68 if err := usdLedger.Transfer(from, deskAddr, amount); err != nil {
69 panic(err.Error())
70 }
71}
72
73func pay(to address, amount int64) {
74 if amount <= 0 {
75 return
76 }
77 if err := usdLedger.Transfer(deskAddr, to, amount); err != nil {
78 panic(err.Error())
79 }
80}
81
82func queue(o *order) uint64 {
83 nextOrderID++
84 o.id = nextOrderID
85 o.placedAt = time.Now().Unix()
86 putItem(orders, ownerOrders, o.owner, o.id, o)
87 emitOrder("OrderPlace", o)
88 return o.id
89}
90
91// --- placing ---
92
93// OpenPerp places a market order for a long or short of `size` stock units
94// (6 dp) backed by `margin` tUSD micro, plus the open fee. It fills on the next
95// price if that is within marketBandBps of the price now, else it is refunded.
96// Returns the order id; the position id comes with the OrderFill event.
97func OpenPerp(cur realm, ticker string, isLong bool, size int64, margin int64) uint64 {
98 return openMarket(cur.Previous().Address(), ticker, isLong, size, margin)
99}
100
101func openMarket(owner address, ticker string, isLong bool, size, margin int64) uint64 {
102 mark := freshPrice(ticker)
103 return placePerp(owner, "market", ticker, isLong, size, margin, bandPrice(mark, isLong), mark, maxLevOf(ticker))
104}
105
106// PlaceLimit places an order to open a perp once the desk price reaches `limit`
107// (long: at or below, short: at or above). Returns the order id.
108func PlaceLimit(cur realm, ticker string, isLong bool, size, margin, limit int64) uint64 {
109 _, _ = GetPrice(ticker)
110 if limit <= 0 || limit > maxPrice {
111 panic("desk: limit price out of range")
112 }
113 return placePerp(cur.Previous().Address(), "limit", ticker, isLong, size, margin, limit, limit, openLevOf(ticker))
114}
115
116func placePerp(owner address, kind, ticker string, isLong bool, size, margin, limit, ref, lev int64) uint64 {
117 _ = mustStock(ticker)
118 assertPerpSize(size)
119 assertMargin(margin)
120 notional := notionalMicroUSD(ref, size)
121 if notional <= 0 || notional > perpMaxNotional {
122 panic("desk: notional out of range")
123 }
124 if notional > margin*lev {
125 panic("desk: over this market's max leverage")
126 }
127 if kind == "market" && sideOI(ticker, isLong)+notional > oiCap(ticker) {
128 panic("desk: open-interest cap reached for this side")
129 }
130 fee := mulDiv(notional, perpFeeBps, bpsDenom)
131 pull(owner, margin+fee)
132 lock(margin + fee)
133 return queue(&order{owner: owner, kind: kind, ticker: ticker, isLong: isLong, size: size, margin: margin, fee: fee, limit: limit})
134}
135
136// Buy places an order for stockAmount units (6 dp) of sTicker. It locks the cost
137// at the worst price it accepts and refunds the difference when it fills.
138// Returns the order id.
139func Buy(cur realm, ticker string, stockAmount int64) uint64 {
140 assertTradeSize(stockAmount)
141 _ = mustStock(ticker)
142 limit := bandPrice(freshPrice(ticker), true)
143 cost := mulDiv(notionalMicroUSD(limit, stockAmount), bpsDenom+feeBps, bpsDenom)
144 if cost <= 0 {
145 panic("desk: trade too small")
146 }
147 owner := cur.Previous().Address()
148 pull(owner, cost)
149 lock(cost)
150 return queue(&order{owner: owner, kind: "buy", ticker: ticker, isLong: true, size: stockAmount, margin: cost, limit: limit})
151}
152
153// Sell places an order to sell stockAmount units of sTicker. The shares are
154// burned now and minted back if the order is refunded. Returns the order id.
155func Sell(cur realm, ticker string, stockAmount int64) uint64 {
156 assertTradeSize(stockAmount)
157 s := mustStock(ticker)
158 mark := freshPrice(ticker)
159 if mulDiv(notionalMicroUSD(mark, stockAmount), bpsDenom-feeBps, bpsDenom) > freeReserve() {
160 panic("desk: the reserve cannot cover this sale right now")
161 }
162 owner := cur.Previous().Address()
163 held := s.token.BalanceOf(owner)
164 if err := s.ledger.Burn(owner, stockAmount); err != nil {
165 panic(err.Error())
166 }
167 basis := costOf(owner, ticker)
168 reduceCost(owner, ticker, stockAmount, held)
169 return queue(&order{owner: owner, kind: "sell", ticker: ticker, size: stockAmount, limit: bandPrice(mark, false), basis: basis - costOf(owner, ticker)})
170}
171
172// CancelOrder refunds the caller's pending limit order. Market orders, buys and
173// sells cannot be cancelled: they fill or are refunded on the next price.
174func CancelOrder(cur realm, id uint64) {
175 o := mustOrder(id)
176 if o.owner != cur.Previous().Address() {
177 panic("desk: not your order")
178 }
179 if o.kind != "limit" {
180 panic("desk: this order fills or is refunded on the next price")
181 }
182 if fillable(o) {
183 panic("desk: this order fills at the current price, it cannot be cancelled now")
184 }
185 refund(o, "cancel")
186}
187
188// --- filling ---
189
190// FillOrder executes an order on the first price observed after it was placed,
191// or refunds a market order, buy or sell that the price moved past or that
192// waited longer than orderTTL. Permissionless. Returns the new position id for
193// a perp order that filled, otherwise 0.
194func FillOrder(cur realm, id uint64) uint64 { return fillOrder(id) }
195
196func fillOrder(id uint64) uint64 {
197 o := mustOrder(id)
198 if o.kind != "limit" && time.Now().Unix()-o.placedAt > orderTTL {
199 refund(o, "expired")
200 return 0
201 }
202 if !pricedAfter(o.ticker, o.placedAt) {
203 panic("desk: the order waits for the next price")
204 }
205 mark := freshPrice(o.ticker)
206 switch o.kind {
207 case "buy":
208 fillBuy(o, mark)
209 return 0
210 case "sell":
211 fillSell(o, mark)
212 return 0
213 }
214 return fillPerp(o, mark)
215}
216
217func limitReady(o *order, mark int64) bool {
218 if o.isLong {
219 return mark <= o.limit
220 }
221 return mark >= o.limit
222}
223
224func waitsForOpen(o *order) bool {
225 if o.kind != "limit" || notionalMicroUSD(o.limit, o.size) <= o.margin*closedMaxLeverage {
226 return false
227 }
228 return !marketOpen || !pricedAfter(o.ticker, openedAt)
229}
230
231type perpFill struct {
232 size, margin, fee, back, notional int64
233}
234
235func quotePerp(o *order, mark int64) (perpFill, string) {
236 if !limitReady(o, mark) {
237 return perpFill{}, "price moved"
238 }
239 f := perpFill{}
240 f.size, f.margin, f.fee, f.back = limitFill(o, mark)
241 f.notional = notionalMicroUSD(mark, f.size)
242 switch {
243 case !limitReady(o, skewEntry(mark, skewImpactBps(o.ticker, o.isLong, f.notional), o.isLong)):
244 return f, "skew impact moves the fill past the limit"
245 case f.size < minTradeUnits || f.margin <= 0:
246 return f, "size below minimum"
247 case sideOI(o.ticker, o.isLong)+f.notional > oiCap(o.ticker):
248 return f, "open-interest cap"
249 }
250 return f, ""
251}
252
253func fillable(o *order) bool {
254 if !pricedAfter(o.ticker, o.placedAt) || !IsFresh(o.ticker) || waitsForOpen(o) {
255 return false
256 }
257 mark, _ := GetPrice(o.ticker)
258 _, why := quotePerp(o, mark)
259 return why == ""
260}
261
262func fillPerp(o *order, mark int64) uint64 {
263 if waitsForOpen(o) {
264 panic("desk: this order's leverage waits for a price after the open")
265 }
266 f, why := quotePerp(o, mark)
267 if why != "" {
268 if o.kind == "limit" {
269 panic("desk: the limit does not fill at this price: " + why)
270 }
271 refund(o, why)
272 return 0
273 }
274 unlock(o.margin + o.fee)
275 pay(o.owner, f.back)
276 pid := openPositionCore(o.owner, o.ticker, o.isLong, f.size, f.margin, mark, f.fee)
277 done(o, "filled:"+ref(pid))
278 emitOrder("OrderFill", o, "position", ref(pid), "fill", num(mark))
279 return pid
280}
281
282func fillSize(o *order, mark int64) int64 {
283 maxNotional := o.margin * maxLevOf(o.ticker)
284 if maxNotional > perpMaxNotional {
285 maxNotional = perpMaxNotional
286 }
287 if notionalMicroUSD(mark, o.size) <= maxNotional {
288 return o.size
289 }
290 return mulDiv(maxNotional, microUSD, mark)
291}
292
293func limitFill(o *order, mark int64) (size, margin, fee, refund int64) {
294 size = fillSize(o, mark)
295 fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom)
296 if fee <= o.fee {
297 return size, o.margin, fee, o.fee - fee
298 }
299 lev := maxLevOf(o.ticker)
300 maxNotional := mulDiv((o.margin+o.fee)*lev, bpsDenom, bpsDenom+lev*perpFeeBps)
301 if notionalMicroUSD(mark, size) > maxNotional {
302 size = mulDiv(maxNotional, microUSD, mark)
303 fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom)
304 }
305 if fee <= o.fee {
306 return size, o.margin, fee, o.fee - fee
307 }
308 return size, o.margin - (fee - o.fee), fee, 0
309}
310
311func fillBuy(o *order, mark int64) {
312 if mark > o.limit {
313 refund(o, "price moved")
314 return
315 }
316 notional := notionalMicroUSD(mark, o.size)
317 cost := mulDiv(notional, bpsDenom+feeBps, bpsDenom)
318 unlock(o.margin)
319 pay(o.owner, o.margin-cost)
320 if err := mustStock(o.ticker).ledger.Mint(o.owner, o.size); err != nil {
321 panic(err.Error())
322 }
323 addCost(o.owner, o.ticker, notional)
324 accrueFee(cost - notional)
325 done(o, "filled")
326 emitSpot("Buy", o.owner, o.ticker, o.size, mark, cost)
327 emitOrder("OrderFill", o, "fill", num(mark))
328}
329
330func fillSell(o *order, mark int64) {
331 if mark < o.limit {
332 refund(o, "price moved")
333 return
334 }
335 notional := notionalMicroUSD(mark, o.size)
336 proceeds := mulDiv(notional, bpsDenom-feeBps, bpsDenom)
337 if proceeds > freeReserve() {
338 refund(o, "reserve")
339 return
340 }
341 pay(o.owner, proceeds)
342 accrueFee(notional - proceeds)
343 done(o, "filled")
344 emitSpot("Sell", o.owner, o.ticker, o.size, mark, proceeds)
345 emitOrder("OrderFill", o, "fill", num(mark))
346}
347
348func refund(o *order, reason string) {
349 if o.kind == "sell" {
350 if err := mustStock(o.ticker).ledger.Mint(o.owner, o.size); err != nil {
351 panic(err.Error())
352 }
353 addCost(o.owner, o.ticker, o.basis)
354 } else {
355 unlock(o.margin + o.fee)
356 pay(o.owner, o.margin+o.fee)
357 }
358 done(o, "refunded:"+reason)
359 emitOrder("OrderRefund", o, "reason", reason)
360}
361
362func done(o *order, result string) {
363 dropItem(orders, ownerOrders, o.owner, o.id)
364 results.Set(idKey(o.id), result)
365}
366
367// --- reads ---
368
369// OrderStatus is "pending", "filled", "filled:<position id>" for a perp order,
370// "refunded:<reason>", or "unknown".
371func OrderStatus(id uint64) string {
372 if orders.Has(idKey(id)) {
373 return "pending"
374 }
375 if v := results.Get(idKey(id)); v != nil {
376 return v.(string)
377 }
378 return "unknown"
379}
380
381// OrdersOf returns an owner's pending orders, ';'-joined, fields comma-separated:
382// id,kind,ticker,L|S,size,margin,limit,mark,placedAt (money and size at 6 dp).
383func OrdersOf(owner address) string {
384 out := ""
385 eachOwned(ownerOrders, owner, func(item any) {
386 o := item.(*order)
387 mark, _ := GetPrice(o.ticker)
388 out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%s,%d,%d,%d,%d,%d", o.id, o.kind, o.ticker, sideOf(o.isLong), o.size, o.margin, o.limit, mark, o.placedAt))
389 })
390 return out
391}
392
393// ReadyOrders lists, within one page of pending orders, the ids FillOrder would
394// act on now, ';'-joined, for the keeper.
395func ReadyOrders(offset, count int) string {
396 out := ""
397 now := time.Now().Unix()
398 eachPage(orders, offset, count, func(item any) {
399 o := item.(*order)
400 expired := o.kind != "limit" && now-o.placedAt > orderTTL
401 ready := pricedAfter(o.ticker, o.placedAt) && IsFresh(o.ticker)
402 if o.kind == "limit" {
403 ready = fillable(o)
404 }
405 if expired || ready {
406 out = joinRow(out, ufmt.Sprintf("%d", o.id))
407 }
408 })
409 return out
410}