package lastcall // Limit orders for perps. On an oracle-priced desk there is no order book, so a // limit is a queued instruction: lock the margin + open fee now, and open the perp // once the oracle price reaches the limit (long: at or below; short: at or above). // Execution is permissionless (TriggerLimit) — the price bot acts as the keeper, // and anyone can trigger a ready order. While the market is closed only orders at // up to closedMaxLeverage fill; the rest queue over the weekend and fire on reopen. import ( "time" "gno.land/p/nt/ufmt/v0" ) type limitOrder struct { id uint64 owner address ticker string isLong bool size int64 // stock units (6 dp) margin int64 // tUSD micro locked up-front fee int64 // prepaid open fee (at the limit price), settled at the fill limit int64 // trigger price, micro-USD per share placedAt int64 } var nextLimitID uint64 func mustLimit(id uint64) *limitOrder { v := limits.Get(idKey(id)) if v == nil { panic("desk: unknown limit order") } return v.(*limitOrder) } // PlaceLimit locks `margin` + the open fee and queues an order to open a perp when // the oracle price reaches `limit`. Returns the order id. func PlaceLimit(cur realm, ticker string, isLong bool, size, margin, limit int64) uint64 { _ = mustStock(ticker) _, _ = GetPrice(ticker) // an order on a never-quoted market could not be listed assertPerpSize(size) assertMargin(margin) if limit <= 0 || limit > maxPrice { panic("desk: limit price out of range") } notional := notionalMicroUSD(limit, size) if notional <= 0 || notional > perpMaxNotional { panic("desk: notional out of range") } if notional > margin*openLevOf(ticker) { panic("desk: over this market's max leverage") } fee := mulDiv(notional, perpFeeBps, bpsDenom) owner := cur.Previous().Address() if err := usdLedger.Transfer(owner, deskAddr, margin+fee); err != nil { panic(err.Error()) } nextLimitID++ id := nextLimitID o := &limitOrder{ id: id, owner: owner, ticker: ticker, isLong: isLong, size: size, margin: margin, fee: fee, limit: limit, placedAt: time.Now().Unix(), } putItem(limits, ownerLimits, owner, id, o) lock(margin + fee) emitLimit("LimitPlace", o) return id } // CancelLimit refunds a pending order's locked margin + fee to its owner. func CancelLimit(cur realm, id uint64) { o := mustLimit(id) if o.owner != cur.Previous().Address() { panic("desk: not your order") } unlock(o.margin + o.fee) if err := usdLedger.Transfer(deskAddr, o.owner, o.margin+o.fee); err != nil { panic(err.Error()) } dropItem(limits, ownerLimits, o.owner, id) emitLimit("LimitCancel", o) } // limitReady reports whether an order's trigger condition holds at `mark`: // a long fills at or below its limit, a short at or above. func limitReady(o *limitOrder, mark int64) bool { if o.isLong { return mark <= o.limit } return mark >= o.limit } // fillSize shrinks an order whose notional at the fill price would exceed the // leverage its margin allows, so a price gap past the limit still fills. func fillSize(o *limitOrder, mark int64) int64 { maxNotional := o.margin * maxLevOf(o.ticker) if maxNotional > perpMaxNotional { maxNotional = perpMaxNotional } if notionalMicroUSD(mark, o.size) <= maxNotional { return o.size } return mulDiv(maxNotional, microUSD, mark) } // limitFill settles the open fee on what actually fills at `mark`. A surplus of // the prepaid fee is refunded; a shortfall comes out of the margin, and the size // is capped so the smaller margin still carries it. func limitFill(o *limitOrder, mark int64) (size, margin, fee, refund int64) { size = fillSize(o, mark) fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom) if fee <= o.fee { return size, o.margin, fee, o.fee - fee } lev := maxLevOf(o.ticker) maxNotional := mulDiv((o.margin+o.fee)*lev, bpsDenom, bpsDenom+lev*perpFeeBps) if notionalMicroUSD(mark, size) > maxNotional { size = mulDiv(maxNotional, microUSD, mark) fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom) } if fee <= o.fee { return size, o.margin, fee, o.fee - fee } return size, o.margin - (fee - o.fee), fee, 0 } // TriggerLimit executes a ready order at the current oracle price, using the locked // margin + prepaid fee. Permissionless (keeper / UI). Requires the trigger reached, // including any skew impact on the entry, and while the market is closed a // leverage within closedMaxLeverage; panics otherwise so the keeper retries later. func TriggerLimit(cur realm, id uint64) uint64 { o := mustLimit(id) if !marketOpen && notionalMicroUSD(o.limit, o.size) > o.margin*closedMaxLeverage { panic("desk: market closed, this order's leverage waits for the open") } mark := freshPrice(o.ticker) if !limitReady(o, mark) { panic("desk: limit not reached") } size, margin, fee, refund := limitFill(o, mark) entry := skewEntry(mark, skewImpactBps(o.ticker, o.isLong, notionalMicroUSD(mark, size)), o.isLong) if (o.isLong && entry > o.limit) || (!o.isLong && entry < o.limit) { panic("desk: skew impact puts the fill past your limit") } unlock(o.margin + o.fee) if refund > 0 { if err := usdLedger.Transfer(deskAddr, o.owner, refund); err != nil { panic(err.Error()) } } pid := openPositionCore(o.owner, o.ticker, o.isLong, size, margin, mark, fee) dropItem(limits, ownerLimits, o.owner, id) emitLimit("LimitFill", o, "position", ref(pid)) return pid } // --- reads --- // LimitsOf returns an owner's pending orders, ';'-joined, fields comma-separated: // id,ticker,L|S,size,margin,limit,mark (size/money micro, 6 dp). func LimitsOf(owner address) string { out := "" eachOwned(ownerLimits, owner, func(item any) { o := item.(*limitOrder) mark, _ := GetPrice(o.ticker) out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d", o.id, o.ticker, sideOf(o.isLong), o.size, o.margin, o.limit, mark)) }) return out } // AllLimits lists one page of pending orders for the keeper to scan, ';'-joined: // id,ticker,L|S,limit,mark. The keeper triggers the ones whose condition holds. func AllLimits(offset, count int) string { out := "" eachPage(limits, offset, count, func(item any) { o := item.(*limitOrder) mark, _ := GetPrice(o.ticker) out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d", o.id, o.ticker, sideOf(o.isLong), o.limit, mark)) }) return out }