package lastcall // The price feed. Off-chain updaters push quotes; the desk trusts them by // address, so no single one sets a price alone once the quorum is above one. // // Each updater's latest quote is kept per ticker. A desk price is formed when a // quorum of updaters have quoted after the current desk price, within // quoteWindow of the newest of those quotes and within agreeBps of their // median: the median of those quotes, stamped with the oldest observation it // used. A quote far from the others is left out, so one updater can delay a // price but not move it beyond the band. Every input to a price was observed at // or after that stamp, which is what lets an order placed at time t fill only // on a price observed after t (pricedAfter). // // Market hours follow the same rule: the market counts as open only while a // quorum of updaters say it is. import ( "strconv" "strings" "time" ) // Price is quoted in micro-USD per whole share. type Price struct { Value int64 // micro-USD per share ObservedAt int64 // unix seconds, the oldest observation behind this price } const ( maxPriceAge = 600 maxClockSkew = 60 maxPrice = 1_000_000_000000 quoteWindow = 120 agreeBps = 100 maxUpdaters = 7 ) var ( updaters []address quorum = 1 prices = map[string]Price{} submitted = map[string]map[address]Price{} openVotes = map[address]bool{} marketOpen = true openedAt int64 ) // --- updaters (admin) --- func AddUpdater(cur realm, u address) { assertAdmin(cur) if !u.IsValid() { panic("desk: invalid updater address") } if isUpdater(u) { panic("desk: already an updater") } if len(updaters) >= maxUpdaters { panic("desk: too many updaters") } updaters = append(updaters, u) } func RemoveUpdater(cur realm, u address) { assertAdmin(cur) if !isUpdater(u) { panic("desk: not an updater") } if len(updaters)-1 < quorum { panic("desk: lower the quorum first") } kept := []address{} for _, a := range updaters { if a != u { kept = append(kept, a) } } updaters = kept delete(openVotes, u) for _, subs := range submitted { delete(subs, u) } tallyMarket() } func SetQuorum(cur realm, n int) { assertAdmin(cur) if n < 1 || n > len(updaters) { panic("desk: quorum out of range") } quorum = n tallyMarket() } // Updaters lists the updater addresses, comma-separated. func Updaters() string { out := "" for i, u := range updaters { if i > 0 { out += "," } out += u.String() } return out } func Quorum() int { return quorum } func isUpdater(a address) bool { for _, u := range updaters { if u == a { return true } } return false } func assertUpdater(cur realm) address { from := cur.Previous().Address() if !isUpdater(from) { panic("desk: updater only") } return from } // --- quotes --- // SetPrices records the caller's quotes, "TICKER:microUSD" pairs joined by ',', // all observed at observedAt, and forms a desk price where a quorum agrees. A // stamp ahead of the block time is lowered to it, so no price is ever dated // after a request that could already see it. func SetPrices(cur realm, quotes string, observedAt int64) { from := assertUpdater(cur) now := time.Now().Unix() if observedAt > now+maxClockSkew { panic("desk: observation is in the future") } if observedAt > now { observedAt = now } for _, pair := range strings.Split(quotes, ",") { ticker, raw, ok := strings.Cut(pair, ":") value, err := strconv.ParseInt(raw, 10, 64) if !ok || err != nil { panic("desk: malformed quote: " + pair) } submit(from, ticker, value, observedAt) } } func submit(from address, ticker string, value, observedAt int64) { _ = mustStock(ticker) if value <= 0 || value > maxPrice { panic("desk: price out of range") } subs := submitted[ticker] if subs == nil { subs = map[address]Price{} submitted[ticker] = subs } if prev, ok := subs[from]; ok && observedAt < prev.ObservedAt { panic("desk: observation is older than your last quote") } subs[from] = Price{Value: value, ObservedAt: observedAt} aggregate(ticker) } func aggregate(ticker string) { since := int64(-1) if p, ok := prices[ticker]; ok { since = p.ObservedAt } fresh := []Price{} newest := int64(0) for _, u := range updaters { q, ok := submitted[ticker][u] if !ok || q.ObservedAt <= since { continue } fresh = append(fresh, q) if q.ObservedAt > newest { newest = q.ObservedAt } } quotes := []Price{} vals := []int64{} for _, q := range fresh { if newest-q.ObservedAt <= quoteWindow { quotes = append(quotes, q) vals = append(vals, q.Value) } } if len(vals) < quorum { return } mid := median(vals) band := mulDiv(mid, agreeBps, bpsDenom) agreed := []int64{} oldest := newest for _, q := range quotes { if q.Value < mid-band || q.Value > mid+band { continue } agreed = append(agreed, q.Value) if q.ObservedAt < oldest { oldest = q.ObservedAt } } if len(agreed) < quorum { return } prices[ticker] = Price{Value: median(agreed), ObservedAt: oldest} } func median(vals []int64) int64 { s := append([]int64{}, vals...) for i := 1; i < len(s); i++ { for j := i; j > 0 && s[j] < s[j-1]; j-- { s[j], s[j-1] = s[j-1], s[j] } } m := len(s) / 2 if len(s)%2 == 1 { return s[m] } return s[m-1] + (s[m]-s[m-1])/2 } // GetPrice returns the desk price for a ticker and its observation time. Panics if unknown. func GetPrice(ticker string) (int64, int64) { p, ok := prices[ticker] if !ok { panic("desk: no price for " + ticker) } return p.Value, p.ObservedAt } // IsFresh reports whether a ticker has a price young enough to trade against. func IsFresh(ticker string) bool { p, ok := prices[ticker] return ok && time.Now().Unix()-p.ObservedAt <= maxPriceAge } // LastCallAt is the time after which the stored price no longer allows a trade, // or 0 before the first price. func LastCallAt(ticker string) int64 { p, ok := prices[ticker] if !ok { return 0 } return p.ObservedAt + maxPriceAge } func freshPrice(ticker string) int64 { value, _ := GetPrice(ticker) if !IsFresh(ticker) { panic("desk: price is stale, last call has passed for " + ticker) } return value } // pricedAfter reports whether the ticker's price was observed after t, so a // request made at t may fill on it. func pricedAfter(ticker string, t int64) bool { p, ok := prices[ticker] return ok && p.ObservedAt > t } // --- market hours --- // SetMarketOpen records the caller's view of the US stock market. func SetMarketOpen(cur realm, open bool) { from := assertUpdater(cur) openVotes[from] = open tallyMarket() } // MarketVoteOf returns an updater's recorded view of the market: "open", // "closed" or "none". func MarketVoteOf(u address) string { open, ok := openVotes[u] switch { case !ok: return "none" case open: return "open" } return "closed" } func tallyMarket() { if len(openVotes) == 0 { return } n := 0 for _, u := range updaters { if openVotes[u] { n++ } } was := marketOpen marketOpen = n >= quorum if marketOpen && !was { openedAt = time.Now().Unix() } } // IsMarketOpen reports whether a quorum of updaters say the stock market is open. // While it is not, new perps are held to closedMaxLeverage and positions above it // can be cut down to it (Delever). A limit above that leverage fills only on a // price observed after the open, never on the last pre-open quote. func IsMarketOpen() bool { return marketOpen }