package lastcall // Every trade is an order that fills on the first desk price observed after it // was placed. The desk price is pushed every minute or so; without this rule a // trader who watches the real market could trade on a quote they already know // to be stale. // // Kinds: "market" and "limit" open a perp, "buy" and "sell" trade spot. Money is // taken when the order is placed (margin and fee, or the spot cost at the worst // price the order accepts; a sell burns the shares), so filling needs no // signature from the owner. Filling is permissionless: the keeper fills orders // right after each price, and anyone else may. // // A market order, buy or sell accepts a price up to marketBandBps worse than the // one it saw. If the next price is past that, or no new price comes within // orderTTL, it is refunded in full. A limit waits until its price is reached and // can be cancelled, except while it is fillable. import ( "time" "gno.land/p/nt/avl/v0" "gno.land/p/nt/ufmt/v0" ) const ( marketBandBps = 200 orderTTL = 900 ) type order struct { id uint64 owner address kind string ticker string isLong bool size int64 margin int64 fee int64 limit int64 basis int64 placedAt int64 } var ( nextOrderID uint64 results = avl.NewTree() ) func mustOrder(id uint64) *order { v := orders.Get(idKey(id)) if v == nil { panic("desk: unknown order") } return v.(*order) } func isPerpOrder(o *order) bool { return o.kind == "market" || o.kind == "limit" } func bandPrice(mark int64, worseUp bool) int64 { if worseUp { return mulDiv(mark, bpsDenom+marketBandBps, bpsDenom) } return mulDiv(mark, bpsDenom-marketBandBps, bpsDenom) } func pull(from address, amount int64) { if err := usdLedger.Transfer(from, deskAddr, amount); err != nil { panic(err.Error()) } } func pay(to address, amount int64) { if amount <= 0 { return } if err := usdLedger.Transfer(deskAddr, to, amount); err != nil { panic(err.Error()) } } func queue(o *order) uint64 { nextOrderID++ o.id = nextOrderID o.placedAt = time.Now().Unix() putItem(orders, ownerOrders, o.owner, o.id, o) emitOrder("OrderPlace", o) return o.id } // --- placing --- // OpenPerp places a market order for a long or short of `size` stock units // (6 dp) backed by `margin` tUSD micro, plus the open fee. It fills on the next // price if that is within marketBandBps of the price now, else it is refunded. // Returns the order id; the position id comes with the OrderFill event. func OpenPerp(cur realm, ticker string, isLong bool, size int64, margin int64) uint64 { return openMarket(cur.Previous().Address(), ticker, isLong, size, margin) } func openMarket(owner address, ticker string, isLong bool, size, margin int64) uint64 { mark := freshPrice(ticker) return placePerp(owner, "market", ticker, isLong, size, margin, bandPrice(mark, isLong), mark, maxLevOf(ticker)) } // PlaceLimit places an order to open a perp once the desk price reaches `limit` // (long: at or below, short: at or above). Returns the order id. func PlaceLimit(cur realm, ticker string, isLong bool, size, margin, limit int64) uint64 { _, _ = GetPrice(ticker) if limit <= 0 || limit > maxPrice { panic("desk: limit price out of range") } return placePerp(cur.Previous().Address(), "limit", ticker, isLong, size, margin, limit, limit, openLevOf(ticker)) } func placePerp(owner address, kind, ticker string, isLong bool, size, margin, limit, ref, lev int64) uint64 { _ = mustStock(ticker) assertPerpSize(size) assertMargin(margin) notional := notionalMicroUSD(ref, size) if notional <= 0 || notional > perpMaxNotional { panic("desk: notional out of range") } if notional > margin*lev { panic("desk: over this market's max leverage") } if kind == "market" && sideOI(ticker, isLong)+notional > oiCap(ticker) { panic("desk: open-interest cap reached for this side") } fee := mulDiv(notional, perpFeeBps, bpsDenom) pull(owner, margin+fee) lock(margin + fee) return queue(&order{owner: owner, kind: kind, ticker: ticker, isLong: isLong, size: size, margin: margin, fee: fee, limit: limit}) } // Buy places an order for stockAmount units (6 dp) of sTicker. It locks the cost // at the worst price it accepts and refunds the difference when it fills. // Returns the order id. func Buy(cur realm, ticker string, stockAmount int64) uint64 { assertTradeSize(stockAmount) _ = mustStock(ticker) limit := bandPrice(freshPrice(ticker), true) cost := mulDiv(notionalMicroUSD(limit, stockAmount), bpsDenom+feeBps, bpsDenom) if cost <= 0 { panic("desk: trade too small") } owner := cur.Previous().Address() pull(owner, cost) lock(cost) return queue(&order{owner: owner, kind: "buy", ticker: ticker, isLong: true, size: stockAmount, margin: cost, limit: limit}) } // Sell places an order to sell stockAmount units of sTicker. The shares are // burned now and minted back if the order is refunded. Returns the order id. func Sell(cur realm, ticker string, stockAmount int64) uint64 { assertTradeSize(stockAmount) s := mustStock(ticker) mark := freshPrice(ticker) if mulDiv(notionalMicroUSD(mark, stockAmount), bpsDenom-feeBps, bpsDenom) > freeReserve() { panic("desk: the reserve cannot cover this sale right now") } owner := cur.Previous().Address() held := s.token.BalanceOf(owner) if err := s.ledger.Burn(owner, stockAmount); err != nil { panic(err.Error()) } basis := costOf(owner, ticker) reduceCost(owner, ticker, stockAmount, held) return queue(&order{owner: owner, kind: "sell", ticker: ticker, size: stockAmount, limit: bandPrice(mark, false), basis: basis - costOf(owner, ticker)}) } // CancelOrder refunds the caller's pending limit order. Market orders, buys and // sells cannot be cancelled: they fill or are refunded on the next price. func CancelOrder(cur realm, id uint64) { o := mustOrder(id) if o.owner != cur.Previous().Address() { panic("desk: not your order") } if o.kind != "limit" { panic("desk: this order fills or is refunded on the next price") } if fillable(o) { panic("desk: this order fills at the current price, it cannot be cancelled now") } refund(o, "cancel") } // --- filling --- // FillOrder executes an order on the first price observed after it was placed, // or refunds a market order, buy or sell that the price moved past or that // waited longer than orderTTL. Permissionless. Returns the new position id for // a perp order that filled, otherwise 0. func FillOrder(cur realm, id uint64) uint64 { return fillOrder(id) } func fillOrder(id uint64) uint64 { o := mustOrder(id) if o.kind != "limit" && time.Now().Unix()-o.placedAt > orderTTL { refund(o, "expired") return 0 } if !pricedAfter(o.ticker, o.placedAt) { panic("desk: the order waits for the next price") } mark := freshPrice(o.ticker) switch o.kind { case "buy": fillBuy(o, mark) return 0 case "sell": fillSell(o, mark) return 0 } return fillPerp(o, mark) } func limitReady(o *order, mark int64) bool { if o.isLong { return mark <= o.limit } return mark >= o.limit } func waitsForOpen(o *order) bool { if o.kind != "limit" || notionalMicroUSD(o.limit, o.size) <= o.margin*closedMaxLeverage { return false } return !marketOpen || !pricedAfter(o.ticker, openedAt) } type perpFill struct { size, margin, fee, back, notional int64 } func quotePerp(o *order, mark int64) (perpFill, string) { if !limitReady(o, mark) { return perpFill{}, "price moved" } f := perpFill{} f.size, f.margin, f.fee, f.back = limitFill(o, mark) f.notional = notionalMicroUSD(mark, f.size) switch { case !limitReady(o, skewEntry(mark, skewImpactBps(o.ticker, o.isLong, f.notional), o.isLong)): return f, "skew impact moves the fill past the limit" case f.size < minTradeUnits || f.margin <= 0: return f, "size below minimum" case sideOI(o.ticker, o.isLong)+f.notional > oiCap(o.ticker): return f, "open-interest cap" } return f, "" } func fillable(o *order) bool { if !pricedAfter(o.ticker, o.placedAt) || !IsFresh(o.ticker) || waitsForOpen(o) { return false } mark, _ := GetPrice(o.ticker) _, why := quotePerp(o, mark) return why == "" } func fillPerp(o *order, mark int64) uint64 { if waitsForOpen(o) { panic("desk: this order's leverage waits for a price after the open") } f, why := quotePerp(o, mark) if why != "" { if o.kind == "limit" { panic("desk: the limit does not fill at this price: " + why) } refund(o, why) return 0 } unlock(o.margin + o.fee) pay(o.owner, f.back) pid := openPositionCore(o.owner, o.ticker, o.isLong, f.size, f.margin, mark, f.fee) done(o, "filled:"+ref(pid)) emitOrder("OrderFill", o, "position", ref(pid), "fill", num(mark)) return pid } func fillSize(o *order, 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) } func limitFill(o *order, 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 } func fillBuy(o *order, mark int64) { if mark > o.limit { refund(o, "price moved") return } notional := notionalMicroUSD(mark, o.size) cost := mulDiv(notional, bpsDenom+feeBps, bpsDenom) unlock(o.margin) pay(o.owner, o.margin-cost) if err := mustStock(o.ticker).ledger.Mint(o.owner, o.size); err != nil { panic(err.Error()) } addCost(o.owner, o.ticker, notional) accrueFee(cost - notional) done(o, "filled") emitSpot("Buy", o.owner, o.ticker, o.size, mark, cost) emitOrder("OrderFill", o, "fill", num(mark)) } func fillSell(o *order, mark int64) { if mark < o.limit { refund(o, "price moved") return } notional := notionalMicroUSD(mark, o.size) proceeds := mulDiv(notional, bpsDenom-feeBps, bpsDenom) if proceeds > freeReserve() { refund(o, "reserve") return } pay(o.owner, proceeds) accrueFee(notional - proceeds) done(o, "filled") emitSpot("Sell", o.owner, o.ticker, o.size, mark, proceeds) emitOrder("OrderFill", o, "fill", num(mark)) } func refund(o *order, reason string) { if o.kind == "sell" { if err := mustStock(o.ticker).ledger.Mint(o.owner, o.size); err != nil { panic(err.Error()) } addCost(o.owner, o.ticker, o.basis) } else { unlock(o.margin + o.fee) pay(o.owner, o.margin+o.fee) } done(o, "refunded:"+reason) emitOrder("OrderRefund", o, "reason", reason) } func done(o *order, result string) { dropItem(orders, ownerOrders, o.owner, o.id) results.Set(idKey(o.id), result) } // --- reads --- // OrderStatus is "pending", "filled", "filled:" for a perp order, // "refunded:", or "unknown". func OrderStatus(id uint64) string { if orders.Has(idKey(id)) { return "pending" } if v := results.Get(idKey(id)); v != nil { return v.(string) } return "unknown" } // OrdersOf returns an owner's pending orders, ';'-joined, fields comma-separated: // id,kind,ticker,L|S,size,margin,limit,mark,placedAt (money and size at 6 dp). func OrdersOf(owner address) string { out := "" eachOwned(ownerOrders, owner, func(item any) { o := item.(*order) mark, _ := GetPrice(o.ticker) 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)) }) return out } // ReadyOrders lists, within one page of pending orders, the ids FillOrder would // act on now, ';'-joined, for the keeper. func ReadyOrders(offset, count int) string { out := "" now := time.Now().Unix() eachPage(orders, offset, count, func(item any) { o := item.(*order) expired := o.kind != "limit" && now-o.placedAt > orderTTL ready := pricedAfter(o.ticker, o.placedAt) && IsFresh(o.ticker) if o.kind == "limit" { ready = fillable(o) } if expired || ready { out = joinRow(out, ufmt.Sprintf("%d", o.id)) } }) return out }