pnb

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package pnb is the probnode binary encoding: one fixed-width, little-endian record layout used in the engine's memory, on the wire and in the archive, so nothing is re-encoded between them (docs/LIVE.md, "Format: PNB"; after Databento's DBN).

Header (16 bytes, every record)

offset size field          meaning
0      1    Length         record length in 32-bit words, header included
1      1    RType          record type (constants below)
2      2    VenueID        1 = Polymarket
4      4    InstrumentID   the token, by id into the Symbol dictionary
8      8    TsEvent        event time, ns since the epoch: the venue's for book and trades, the block's for fills

A reader skips a record type it does not know by Length, so new types never break old clients.

Units

Prices are int64 in units of 1e-9 (PriceScale): 0.42 is 420_000_000. Sizes are int64 in units of 1e-6 (SizeScale): 120 shares is 120_000_000. Times are uint64 nanoseconds since the epoch. Wallets and tokens never appear as strings inside a record: they are uint32 ids into the Wallet and Symbol dictionaries, sent once per connection and again after every reconnect.

Timestamps

TsEvent is in the header. TsRecv (our receive time) and, on the live stream, TsOut (gateway send time) are in the body where the record has them. TsOut − TsRecv is the time spent inside probnode.

JSON

The JSON form (MarshalJSON on every record) is PNB-shaped: the same type names, field names and integer units. Nanosecond times are decimal strings, because they exceed 2^53 and a JSON number would round them; t_ms carries the event time in milliseconds as a number for display.

Index

Constants

View Source
const (
	RBookLevel uint8 = 0x01
	RTrade     uint8 = 0x02
	RFill      uint8 = 0x03
	RWallet    uint8 = 0x04
	RSymbol    uint8 = 0x05
	RStats     uint8 = 0x10
	RSignal    uint8 = 0x11
	RBookExt   uint8 = 0x12
	RTradeExt  uint8 = 0x13
	RGap       uint8 = 0x20
	RHeartbeat uint8 = 0x21
)

Record types.

View Source
const (
	PriceScale = 1_000_000_000 // 1 price unit = 1e-9
	SizeScale  = 1_000_000     // 1 size unit = 1e-6
)

Scales.

View Source
const (
	FLast         uint8 = 128 // last record of one event for this instrument
	FSnapshot     uint8 = 32  // part of a snapshot (replay, warm-up), not a live change
	FBadTsRecv    uint8 = 8   // ts_recv may be wrong (clock step, reorder)
	FMaybeBadBook uint8 = 4   // an unrecoverable gap was seen on this instrument
)

Flags (body byte where a record has one).

View Source
const (
	SideBid uint8 = 0 // book: bid; trade/fill: buy aggressor
	SideAsk uint8 = 1 // book: ask; trade/fill: sell aggressor

	ActionAdd    uint8 = 'A'
	ActionChange uint8 = 'C'
	ActionDelete uint8 = 'D'
)

Sides and actions.

View Source
const (
	HeaderSize    = 16
	BookLevelSize = 48
	TradeSize     = 48
	FillSize      = 112
	WalletSize    = 48
	SymbolSize    = 176
	StatsSize     = 304
	SignalSize    = 160
	BookExtSize   = 32 + StateSize          // 168
	TradeExtSize  = 32 + StateSize + 8 + 16 // 192
	GapSize       = 32
	HeartbeatSize = 32
)

Sizes in bytes; every one a multiple of 8.

View Source
const (
	StVolume1m = iota // USD ×1e6
	StTrades1m
	StWallets1m
	StNewWallets1m
	StTakerImbalance1m // ×1e6, -1..1
	StAvgTrade         // USD ×1e6
	StOrdersAdded1m
	StOrdersCancelled1m
	StUpdatesPerS // ×1e6
	StMid         // price units
	StMicroprice  // price units
	StSpread      // price units
	StDepthBid    // USD ×1e6, top 10 levels
	StDepthAsk
	StPriceChg1m // price units
	StRealizedVol5m
	StMarkout10s // price units: volume-weighted, signed for the taker, 10 s after each print, over the minute
	NStats
)

Stats fields, in their fixed order.

View Source
const (
	StateLive     uint8 = 0
	StateDegraded uint8 = 1
	StateDown     uint8 = 2
)

Channel states carried by a heartbeat.

View Source
const (
	StagePrint   uint8 = 0 // at the print: the State right after it, its notional, whale_sweep
	StageWallets uint8 = 1 // about a block later, once the chain's fills join: taker, makers, Security
	StageMarkout uint8 = 2 // MarkoutMs later: the mid then against the print
)

TradeExt stages: one trade gets up to three, each a TradeExt with the trade's seq.

View Source
const (
	TXWhaleSweep uint8 = 1 // notional >= max(WhaleMinUSD, WhaleFactor x the minute's average trade before it)
	TXToxic      uint8 = 2 // stage markout: the taker was right by more than the spread at the print
)

TradeExt flags.

View Source
const (
	TSKnownWallet uint8 = 1 // a wallet of the trade is on a case watchlist
	TSNewWallet   uint8 = 2 // the taker's first fill this engine has seen
	TSSelfWash    uint8 = 4 // maker and taker are the same wallet
)

TradeExt security bits (stage wallets).

View Source
const (
	RProbnodeExt    uint8 = 0x14
	PNMetrics             = 19 // = probnode.NMetrics
	PNFactors             = 9  // = probnode.NFactors
	PNKindBook      uint8 = 0
	PNKindTrade     uint8 = 1
	PNFlagNone      uint8 = 0
	PNFlagAttack    uint8 = 1
	PNNone                = int32(math.MinInt32)
	PNNoPct         uint8 = 255
	ProbnodeExtSize       = 80 + PNMetrics*16 + PNFactors*8 // 456
)
View Source
const (
	BlockAnalytics uint8 = 1 << iota
	BlockRisk
	BlockSecurity
	BlockStats
	BlocksAll = BlockAnalytics | BlockRisk | BlockSecurity | BlockStats
)

Blocks of the probnode object a client can choose at subscribe (all by default).

View Source
const Missing = int64(-1 << 63)

Missing marks a baseline (or value) that is not known.

View Source
const ScoreNone uint32 = 0xFFFFFFFF

ScoreNone marks a signal with no rule confidence: a person's finding.

View Source
const StateSize = 9*8 + 4*16

StateSize is the State block's size inside a record.

View Source
const VenuePolymarket uint16 = 1

Venues.

View Source
const Version = 4

Version of the record set: it changes whenever a record type is added or a layout changes (docs/LIVE.md, Contract). 2: BookExt and TradeExt. 3: both carry one State (book + flow). 4: ProbnodeExt, the `probnode` object of the approved contract (2026-11-22).

Variables

View Source
var (
	ErrShort   = errors.New("pnb: buffer shorter than the record")
	ErrLength  = errors.New("pnb: header length does not match the record type")
	ErrUnknown = errors.New("pnb: unknown record type")
)
View Source
var BlockNames = map[string]uint8{"analytics": BlockAnalytics, "risk": BlockRisk, "security": BlockSecurity, "stats": BlockStats}

BlockNames maps the subscribe names to their bits.

View Source
var PNNames = [PNMetrics]string{
	"spread", "depth_bid", "depth_ask", "imbalance", "microprice_lean", "updates_per_s",
	"volume_1m", "trades_1m", "taker_imbalance_1m", "avg_trade",
	"cost_to_trade.buy", "cost_to_trade.sell", "depth", "resilience", "volatility.10s", "volatility.1m",
	"adverse_selection", "quote_stability", "resolution_jump",
}

PNNames are the metrics' names, in record order (probnode.Names).

View Source
var SignalTypes = []SignalType{
	{"spoofing", "attack", "security"},
	{"layering", "attack", "security"},
	{"self_wash", "attack", "security"},
	{"ring_wash", "attack", "security"},
	{"prearranged_trade", "attack", "security"},
	{"insider_trading", "attack", "security"},
	{"copycat_flow", "watch", "security"},
	{"resolution_vote_attack", "attack", "security"},
	{"false_proposal", "attack", "security"},
	{"whale_push", "attack", "security"},
	{"push_before_resolution", "attack", "security"},
	{"attack_unclassified", "attack", "security"},
	{"known_wallet_active", "watch", "security"},
	{"liquidity_drop", "health", "risk"},
	{"spread_blowout", "health", "risk"},
	{"book_vanish", "health", "risk"},
	{"volume_depth_anomaly", "health", "risk"},
	{"toxic_flow", "health", "risk"},

	{"book_collapse", "health", "risk"},

	{"phantom_liquidity", "attack", "security"},
	{"cancel_storm", "attack", "security"},
	{"one_sided_book", "health", "risk"},
	{"whale_sweep", "health", "risk"},
	{"stale_book", "health", "risk"},
}

StateFlow names State.Flow in order (the Stats keys they carry).

Functions

func BookPlusJSON

func BookPlusJSON(levels []*BookLevel, x *BookExt, pn *ProbnodeExt, blocks uint8) []byte

BookPlusJSON is one book+ record (docs/LIVE.md, Channels): a venue book event's levels and the State after it in one JSON object, joined at delivery and never stored. The header is the event's last level's; seq is its seq.

func StatName

func StatName(i int) string

StatName returns the JSON name of a stats field.

func TradePlusJSON

func TradePlusJSON(t *Trade, x *TradeExt, pn *ProbnodeExt, blocks uint8) []byte

TradePlusJSON is one trades+ record: the trade and its print-stage TradeExt in one JSON object.

func TypeIndex

func TypeIndex(key string) int

TypeIndex returns the wire index of a signal type key, or -1.

func USD

func USD(price, size int64) int64

USD is price (×1e9) × size (×1e6) in USD ×1e6, exact for any size: the product goes through 128 bits. price × size in int64 overflows past ~9.2 million shares at price 1 (a long event market's book holds more), which is where negative depth came from (2026-11-22: 38 of 1,412 tokens on the 11-21 19:00 hour). Negative inputs give 0.

Types

type BookExt

type BookExt struct {
	Header
	TsRecv uint64
	Seq    uint32 // seq of the event's last BookLevel
	Flags  uint8
	State
}

BookExt is our enrichment of one venue book event (book.ext): the State after it. It goes out once per event, after the event's last level (Seq refers to it), and only when the event moved a book field of the State (a change below the top 10 levels moves none of them).

func (*BookExt) AppendTo

func (r *BookExt) AppendTo(b []byte) []byte

func (*BookExt) Hdr

func (r *BookExt) Hdr() *Header

func (*BookExt) MarshalJSON

func (r *BookExt) MarshalJSON() ([]byte, error)

type BookLevel

type BookLevel struct {
	Header
	TsRecv uint64
	Price  int64
	Size   int64 // new size of the level; 0 with ActionDelete
	Seq    uint32
	Side   uint8
	Action uint8
	Flags  uint8
}

BookLevel is one change of one price level.

func (*BookLevel) AppendTo

func (r *BookLevel) AppendTo(b []byte) []byte

func (*BookLevel) Hdr

func (r *BookLevel) Hdr() *Header

func (*BookLevel) MarshalJSON

func (r *BookLevel) MarshalJSON() ([]byte, error)

type Fill

type Fill struct {
	Header
	TsRecv   uint64
	Price    int64
	Size     int64
	Fee      int64 // in size units of the asset paid
	Block    uint64
	LogIndex uint32
	Maker    uint32 // wallet id
	Taker    uint32 // wallet id
	TradeSeq uint32 // seq of the joined trade; 0 = not joined
	Side     uint8  // maker's order side
	Flags    uint8
	Tx       [32]byte
}

Fill is an OrderFilled from our node, joined to the venue trade it belongs to (TradeSeq).

func (*Fill) AppendTo

func (r *Fill) AppendTo(b []byte) []byte

func (*Fill) Hdr

func (r *Fill) Hdr() *Header

func (*Fill) MarshalJSON

func (r *Fill) MarshalJSON() ([]byte, error)

type Gap

type Gap struct {
	Header
	From uint64
	To   uint64
}

Gap: no data between From and To (To 0 = still open). Nothing is drawn inside it.

func (*Gap) AppendTo

func (r *Gap) AppendTo(b []byte) []byte

func (*Gap) Hdr

func (r *Gap) Hdr() *Header

func (*Gap) MarshalJSON

func (r *Gap) MarshalJSON() ([]byte, error)
type Header struct {
	RType        uint8
	VenueID      uint16
	InstrumentID uint32
	TsEvent      uint64
}

Header starts every record.

type Heartbeat

type Heartbeat struct {
	Header
	LastSeq uint64
	State   uint8
}

Heartbeat: the channel is alive; LastSeq lets a client see what it missed.

func (*Heartbeat) AppendTo

func (r *Heartbeat) AppendTo(b []byte) []byte

func (*Heartbeat) Hdr

func (r *Heartbeat) Hdr() *Header

func (*Heartbeat) MarshalJSON

func (r *Heartbeat) MarshalJSON() ([]byte, error)

type PNAfter

type PNAfter struct{ P50, P90 int32 }

PNAfter is the next minute's absolute mid move at the factor's percentile, price x1e6 (PNNone).

type PNMetric

type PNMetric struct {
	Value   int64
	XNorm   int32
	PBucket uint8
	PSelf   uint8
}

PNMetric is one metric: value x1e6 (Missing), x_norm x1e4 (PNNone), percentiles 0..100 (255 none).

type ProbnodeExt

type ProbnodeExt struct {
	Header
	TsRecv  uint64
	Ref     uint32 // the BookExt's seq (Kind book) or the trade's seq (Kind trade)
	Kind    uint8  // PNKindBook | PNKindTrade
	Flag    uint8  // security: PNFlagNone | PNFlagAttack (a confirmed case names the market)
	Open    uint8  // security episodes open on the market
	Bucket  [32]byte
	Version [16]byte // the norms' version
	M       [PNMetrics]PNMetric
	After   [PNFactors]PNAfter
}

ProbnodeExt (0x14, record set version 4) is the `probnode` object of one book event or one print (owner, 2026-11-22, the approved contract): every metric's value against the norms of our archive - x_norm, the percentile among similar markets, the percentile against the market's own last 30 minutes - and, for the risk factors, what the mid did over the next minute on similar markets at that percentile. Risk is statistics, never a verdict. It goes out right before the BookExt / TradeExt it belongs to (same Ref), is stored with them (D2: enrichment stored as Probe records) and is joined into book+ / trades+.

func (*ProbnodeExt) AppendBlocks

func (r *ProbnodeExt) AppendBlocks(b []byte, blocks uint8) []byte

AppendBlocks appends the `probnode` JSON object with the chosen blocks: analytics, risk (factors), security, stats. Norms themselves are not repeated here: they go once per version (the `norms` message).

func (*ProbnodeExt) AppendObject

func (r *ProbnodeExt) AppendObject(b []byte) []byte

AppendObject appends the whole `probnode` JSON object.

func (*ProbnodeExt) AppendTo

func (r *ProbnodeExt) AppendTo(b []byte) []byte

func (*ProbnodeExt) BucketName

func (r *ProbnodeExt) BucketName() string

BucketName and NormsVersion read the fixed-size strings.

func (*ProbnodeExt) Hdr

func (r *ProbnodeExt) Hdr() *Header

func (*ProbnodeExt) MarshalJSON

func (r *ProbnodeExt) MarshalJSON() ([]byte, error)

func (*ProbnodeExt) NormsVersion

func (r *ProbnodeExt) NormsVersion() string

type Record

type Record interface {
	Hdr() *Header
	// AppendTo appends the record's bytes to b.
	AppendTo(b []byte) []byte
	MarshalJSON() ([]byte, error)
}

Record is any PNB record.

func Decode

func Decode(b []byte) (Record, int, error)

Decode reads one record from the front of b and returns it and its length in bytes. An unknown record type returns ErrUnknown and its length, so a reader can skip it.

type Signal

type Signal struct {
	Header
	ID         [48]byte // zero-padded text, e.g. live-liq-<hash>-<s>
	Type       uint16   // index into SignalTypes
	State      uint8    // 0 suspected, 1 confirmed, 2 retracted
	Severity   uint8    // 1..3
	Score      uint32   // 0..1 ×1e6; ScoreNone for a person's finding
	TStart     uint64   // ns
	TEnd       uint64   // ns; 0 = still open
	Value      int64    // the measurement now; Missing when none
	ValueWorst int64
	Baseline   int64
	Wallets    [4]uint32
	NWallets   uint8
	Case       [16]byte // zero-padded case id
}

Signal is one Risk or Security signal: opened, moved or closed (a transition).

func (*Signal) AppendTo

func (r *Signal) AppendTo(b []byte) []byte

func (*Signal) Hdr

func (r *Signal) Hdr() *Header

func (*Signal) MarshalJSON

func (r *Signal) MarshalJSON() ([]byte, error)

type SignalType

type SignalType struct {
	Key, Class, Lane string
}

SignalType describes one signal type: its key, class (attack | watch | health) and lane (security | risk). The order is the wire index and never changes; new types are appended. It mirrors pmd_api.integrity.TAXONOMY.

type StatField

type StatField struct {
	Value    int64
	Baseline int64
}

StatField is one statistic: the value now and this market's normal (Missing when unknown).

type State

type State struct {
	BestBid, BestAsk   int64        // price units; Missing on an empty side
	Mid, Microprice    int64        // price units; Missing unless both sides
	Spread             int64        // price units; Missing unless both sides
	DepthBid, DepthAsk int64        // USD x1e6, top 10 levels
	Imbalance          int64        // x1e6, -1..1: (bid - ask) / (bid + ask) depth; Missing on an empty book
	UpdatesPerS        int64        // x1e6, book updates per second over the last minute
	Flow               [4]StatField // StateFlow keys: value and normal
}

State is the market state every enrichment record carries, the same on a tick and on a trade (docs/LIVE.md, Contract): a bot reads one shape whatever event it got. Book: the token's book now; flow: the minute's trade windows now (each with this market's normal for the hour of week, Missing until the box has one). Read live at the event, never from a stale cache.

func NoState

func NoState() State

NoState is a State with every field unknown (the trade amendments carry no state).

type Stats

type Stats struct {
	Header
	TsRecv uint64
	Seq    uint32
	Fields [NStats]StatField
}

Stats is the whole market's statistics at one step.

func (*Stats) AppendTo

func (r *Stats) AppendTo(b []byte) []byte

func (*Stats) Hdr

func (r *Stats) Hdr() *Header

func (*Stats) MarshalJSON

func (r *Stats) MarshalJSON() ([]byte, error)

type Symbol

type Symbol struct {
	Header
	Token   [32]byte // uint256, big-endian
	Outcome [16]byte // zero-padded text
	Market  [112]byte
}

Symbol maps an instrument id to its token, market and outcome.

func (*Symbol) AppendTo

func (r *Symbol) AppendTo(b []byte) []byte

func (*Symbol) Hdr

func (r *Symbol) Hdr() *Header

func (*Symbol) MarshalJSON

func (r *Symbol) MarshalJSON() ([]byte, error)

type Trade

type Trade struct {
	Header
	TsRecv uint64
	Price  int64
	Size   int64
	Seq    uint32
	Side   uint8 // aggressor
	Flags  uint8
}

Trade is a print on the venue.

func (*Trade) AppendTo

func (r *Trade) AppendTo(b []byte) []byte

func (*Trade) Hdr

func (r *Trade) Hdr() *Header

func (*Trade) MarshalJSON

func (r *Trade) MarshalJSON() ([]byte, error)

type TradeExt

type TradeExt struct {
	Header
	TsRecv   uint64
	TradeSeq uint32
	Stage    uint8
	Flags    uint8
	Security uint8
	NMakers  uint8
	State
	Taker    uint32 // wallet id, stage wallets
	Notional int64  // USD x1e6
	Markout  int64  // price units, signed for the taker; stage markout
}

TradeExt is our enrichment of one trade (trades.ext). Stage print: the State right after the trade (its book and flow), the notional, whale_sweep. Stage wallets: the taker, the number of makers, the Security bits (each maker's wallet is in its Fill, by the same TradeSeq). Stage markout: the mark-out. Fields a stage does not set are Missing (ids and counts 0).

func (*TradeExt) AppendTo

func (r *TradeExt) AppendTo(b []byte) []byte

func (*TradeExt) Hdr

func (r *TradeExt) Hdr() *Header

func (*TradeExt) MarshalJSON

func (r *TradeExt) MarshalJSON() ([]byte, error)

type Wallet

type Wallet struct {
	Header
	ID   uint32
	Addr [20]byte
}

Wallet maps a wallet id to its address, once per connection.

func (*Wallet) AppendTo

func (r *Wallet) AppendTo(b []byte) []byte

func (*Wallet) Hdr

func (r *Wallet) Hdr() *Header

func (*Wallet) MarshalJSON

func (r *Wallet) MarshalJSON() ([]byte, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL