Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

limit.gno

6.22 Kb · 183 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. While the market is closed only orders at
  8// up to closedMaxLeverage fill; the rest queue over the 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*openLevOf(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	o := &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	putItem(limits, ownerLimits, owner, id, o)
 67	lock(margin + fee)
 68	emitLimit("LimitPlace", o)
 69	return id
 70}
 71
 72// CancelLimit refunds a pending order's locked margin + fee to its owner.
 73func CancelLimit(cur realm, id uint64) {
 74	o := mustLimit(id)
 75	if o.owner != cur.Previous().Address() {
 76		panic("desk: not your order")
 77	}
 78	unlock(o.margin + o.fee)
 79	if err := usdLedger.Transfer(deskAddr, o.owner, o.margin+o.fee); err != nil {
 80		panic(err.Error())
 81	}
 82	dropItem(limits, ownerLimits, o.owner, id)
 83	emitLimit("LimitCancel", o)
 84}
 85
 86// limitReady reports whether an order's trigger condition holds at `mark`:
 87// a long fills at or below its limit, a short at or above.
 88func limitReady(o *limitOrder, mark int64) bool {
 89	if o.isLong {
 90		return mark <= o.limit
 91	}
 92	return mark >= o.limit
 93}
 94
 95// fillSize shrinks an order whose notional at the fill price would exceed the
 96// leverage its margin allows, so a price gap past the limit still fills.
 97func fillSize(o *limitOrder, mark int64) int64 {
 98	maxNotional := o.margin * maxLevOf(o.ticker)
 99	if maxNotional > perpMaxNotional {
100		maxNotional = perpMaxNotional
101	}
102	if notionalMicroUSD(mark, o.size) <= maxNotional {
103		return o.size
104	}
105	return mulDiv(maxNotional, microUSD, mark)
106}
107
108// limitFill settles the open fee on what actually fills at `mark`. A surplus of
109// the prepaid fee is refunded; a shortfall comes out of the margin, and the size
110// is capped so the smaller margin still carries it.
111func limitFill(o *limitOrder, mark int64) (size, margin, fee, refund int64) {
112	size = fillSize(o, mark)
113	fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom)
114	if fee <= o.fee {
115		return size, o.margin, fee, o.fee - fee
116	}
117	lev := maxLevOf(o.ticker)
118	maxNotional := mulDiv((o.margin+o.fee)*lev, bpsDenom, bpsDenom+lev*perpFeeBps)
119	if notionalMicroUSD(mark, size) > maxNotional {
120		size = mulDiv(maxNotional, microUSD, mark)
121		fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom)
122	}
123	if fee <= o.fee {
124		return size, o.margin, fee, o.fee - fee
125	}
126	return size, o.margin - (fee - o.fee), fee, 0
127}
128
129// TriggerLimit executes a ready order at the current oracle price, using the locked
130// margin + prepaid fee. Permissionless (keeper / UI). Requires the trigger reached,
131// including any skew impact on the entry, and while the market is closed a
132// leverage within closedMaxLeverage; panics otherwise so the keeper retries later.
133func TriggerLimit(cur realm, id uint64) uint64 {
134	o := mustLimit(id)
135	if !marketOpen && notionalMicroUSD(o.limit, o.size) > o.margin*closedMaxLeverage {
136		panic("desk: market closed, this order's leverage waits for the open")
137	}
138	mark := freshPrice(o.ticker)
139	if !limitReady(o, mark) {
140		panic("desk: limit not reached")
141	}
142	size, margin, fee, refund := limitFill(o, mark)
143	entry := skewEntry(mark, skewImpactBps(o.ticker, o.isLong, notionalMicroUSD(mark, size)), o.isLong)
144	if (o.isLong && entry > o.limit) || (!o.isLong && entry < o.limit) {
145		panic("desk: skew impact puts the fill past your limit")
146	}
147	unlock(o.margin + o.fee)
148	if refund > 0 {
149		if err := usdLedger.Transfer(deskAddr, o.owner, refund); err != nil {
150			panic(err.Error())
151		}
152	}
153	pid := openPositionCore(o.owner, o.ticker, o.isLong, size, margin, mark, fee)
154	dropItem(limits, ownerLimits, o.owner, id)
155	emitLimit("LimitFill", o, "position", ref(pid))
156	return pid
157}
158
159// --- reads ---
160
161// LimitsOf returns an owner's pending orders, ';'-joined, fields comma-separated:
162// id,ticker,L|S,size,margin,limit,mark  (size/money micro, 6 dp).
163func LimitsOf(owner address) string {
164	out := ""
165	eachOwned(ownerLimits, owner, func(item any) {
166		o := item.(*limitOrder)
167		mark, _ := GetPrice(o.ticker)
168		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))
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		out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d", o.id, o.ticker, sideOf(o.isLong), o.limit, mark))
181	})
182	return out
183}