Skip to content

Latest commit

 

History

History
923 lines (705 loc) · 92 KB

File metadata and controls

923 lines (705 loc) · 92 KB

poly-15min: Technical Reference

简体中文 · Project README

This manual describes the archived source and saved artifacts. It is intended for readers familiar with Python, quantitative trading, and PyTorch. Source links point to the corresponding files in this repository.

Warning

Do not connect this system to a funded account. Authentication material is logged in plaintext, and some safety checks terminate the process without canceling outstanding orders.

Use this repository at your own risk. It is provided for research and algorithm discussion, without warranties or investment advice. To the extent permitted by applicable law, the author accepts no liability for trading losses or other damages arising from its use. See the LICENSE for the governing terms.

Contents

Chapter Sections
01 Status and evidence
02 Contracts and pricing assumptions
03 Source map and runtime
04 The three Transformer models
Model A: return distribution · Model B: short-term quantiles · Model C: book mid and half-spread
05 Calibration and quote construction
06 Execution and risk controls
07 Configuration and troubleshooting
08 Training and saved artifacts
09 Issues and security

1. Status, history, and evidence

Important

Archived and unmaintained. All code and documentation in this repository were generated by AI. The code was generated through a chat interface using GPT-5, and the documentation was generated using Opus and GPT-6.

Neither the code nor the documentation has undergone human review for correctness. The code used in live trading was never reviewed by the author. The documentation may conflict with the implementation; consult the source code to determine what the system actually does.

The strategy was profitable on BTC for a period and stopped being profitable in late December 2025. Its profits were only a tiny fraction of those earned by the top accounts.

The live system was modified continuously. This repository broadly represents that system, but its code and model parameters may differ from those used during live trading and may not match any particular live version.

The strategy traded BTC profitably for a period and stopped being profitable in late December 2025. Latency is critical in high-frequency trading: secondhand exchange data left the system at least 100 ms behind participants with direct exchange access, erasing its trading advantage.

The code was generated entirely by AI and has not undergone human review. The system is archived and unmaintained.

All training data, the Model A training driver, and the Model B/C dataset builders were permanently lost. The current directory contains inference and training source, six checkpoints, and six JSON metadata files, but no training shards, historical fills, or reproducible performance experiment. The saved models remain available for structural inspection.

Evidence conventions

System behavior is described by the executable source, and saved architectures and settings by checkpoint tensors and JSON metadata. External documentation explains conceptual distinctions and compatibility constraints. Where comments conflict with code, the code takes precedence. Recorded statistics come from saved model metadata.

All feature indices are zero-based. In shape notation, N is batch size, L is sequence length, and D is feature width; B in contract timing denotes the next 15-minute boundary. Underlying prices use USD on Coinbase and USDT on Binance futures. Log returns, ratios, probabilities, and Student-t scale are dimensionless; bp means 0.0001 of a price. Polymarket sizes are measured in token shares. Model probabilities guide quote construction; executable prices depend on the order book.

Fenced text blocks contain mathematical pseudocode or explanatory diagrams. Sinusoidal position encodings use sin(pos / 10000^(2i/d_model)) and the corresponding cosine on alternating channels. Input and model tensors use float32 unless a training AMP option changes computation; asset IDs are torch integer indices, and C's mask is Boolean.


2. Contracts, reference prices, and pricing assumptions

The archived code targets BTC, ETH, SOL, and XRP up/down contracts with 900-second windows. A slug such as btc-updown-15m-1765306800 identifies the asset, product family, and window start S; expiration is B = S + 900. The code uses ceil(now / 900) * 900, so an exactly aligned timestamp returns that boundary. The live entrypoint authorizes trading only BTC, although data collection and model prediction cover all four assets. Boundary helper, engine construction.

The intended binary payoff is $1 for the winning token and $0 for the losing token. An Up outcome means the ending reference price is at or above the opening reference price. The code does not implement the venue's resolution process or preserve every historical market's rules; the individual contract's rules remain authoritative. YES/NO payouts are complementary. Their independently quoted bids, asks, last trades, and execution prices can sum to more or less than $1. Buying NO and selling YES have related directional exposure but different cash, collateral, and token-balance requirements.

Reference prices and time

Coinbase microprice is the opposite-side-size-weighted best bid/ask estimate (ask * bid_qty + bid * ask_qty) / (bid_qty + ask_qty). The ticker handler falls back to arithmetic midpoint, then trade price. Separately, the L2 feature processor centers depth bands on the arithmetic midpoint when both sides are valid; this arithmetic midpoint is stored in the local variable micro. Ticker, L2 features.

Value Construction Interpretation
coinbase Latest ticker microprice stored in the hub Current underlying proxy
prev_close Last locally observed price at or before S - 1.1 seconds Locally sampled strategy barrier proxy; the venue uses its designated oracle reference
prev_low, prev_high Extrema of local observations in [S - 2, S - 1], falling back to the close Reference-price band over the short sampling interval
tau Trading snapshots use local emission time; calibration uses Coinbase server time; both subtract 1.1 seconds and floor the pricing horizon at one second Two time-to-expiration proxies based on different clocks
chainlink_15m_close RTDS observation selected near a boundary Oracle reference recorded for boundary analysis

The local Coinbase history samples price changes through a polling task and starts without a backfill. Starting mid-window may leave prev_close unavailable until a subsequent boundary. The 1.1-second offset is implemented, but its effectiveness cannot be established from the available data. Differences among Binance futures, Coinbase, and Chainlink introduce reference-price and timing risk. Reference extraction, snapshot timing.

The trading worker obtains ts_s from its locally timestamped queue; the calibrator obtains time from coinbase_ts_server_ms. Their comments suggest the same horizon, but delayed exchange timestamps can produce different tau values or even different window boundaries. Model A separately uses the finalized Binance second for its horizon input.

The Chainlink service prefers the latest tick at or before a boundary, with a fallback allowing a tick up to five seconds afterward. Its scheduler waits only about 0.25 seconds, so the fallback does not guarantee a full five-second observation window. Its role is to write reference records and hub state; token settlement is handled by the venue. The duplicate event argument in its logging call can raise after those writes. Service, recording path.

Student-t probability and pricing assumptions

Model A supplies a zero-location Student-t distribution for log return. For positive price P, barrier K, remaining time tau, scale iv, and degrees of freedom nu, the pricing rule is given below. The notation p_up(P, K) makes the spot price and barrier explicit; iv, nu, and tau are held fixed when either price is varied.

s_tau = iv * sqrt(max(tau, 1) / 900)
r_star = log(K / P)
p_up(P, K) = 1 - F_nu(r_star / s_tau)

iv is the scale of a 900-second log return. Standard deviation is s_tau * sqrt(nu / (nu - 2)) only for nu > 2; the mean exists only for nu > 1. The distribution has zero mean when that mean exists. The forward transformation does not enforce either bound on nu. Model, probability helper, SciPy Student-t parameterization.

Symmetry gives p_up = 0.5 at P = K, and p_up > 0.5 when P > K. The square-root time rule and zero-location assumption are modeling choices whose empirical suitability for these contracts remains unverified. Risk-neutral valuation requires additional assumptions beyond a historical-return distribution. The rule omits fees, liquidity, queue position, collateral costs, and resolution uncertainty; its output guides the strategy, and actual trading value depends on those omitted factors. Here, the binary probability is computed from the return distribution.


3. Source map, runtime tasks, and data

Source Lines Responsibility
live_prediction.py 1,607 Startup, model scheduling, snapshots, trading handoff
live_lib.py 1,077 Model A loading, Binance features, HTTP, logging
market_lib.py 2,551 Shared state, market feeds, discovery, calibration
utils.py 1,356 Model A, historical features, training, Student-t numerics
train_seq.py 1,131 Model B training and metrics
quote_seq.py 872 Model B inference and directional policy
train_iv.py 1,225 Model C training and metrics
quote_iv.py 1,013 Model C event replay and inference
trade.py 1,819 Quote construction, order scheduling, inventory filters
trade_lib.py 1,448 Authentication, CLOB I/O, fill tracking, safety threads
hub_debug.py 135 Periodic public hub-state snapshots

Architecture and startup

Binance futures trades + minute bars --> Model A --> raw iv, df --> Student-t pricing
                                               \--> PM calibration --> multiplier --> inventory tilt
                                                                  \--> corrected scale --> Model C
Coinbase ticker + L2 + trades --> Model B --> directional skew --------------------------\
Coinbase features + PM book + Model A iv --> Model C --> mid + half-spread ----------------> quotes
PM book -------------------------------> calibration and quote guards ------------------/
quotes --> TradeEngine --> CLOB GTC submissions / cancellation requests
user WebSocket fills --> local inventory estimates --> action filters
positions API --> independent hard-exit check
Chainlink RTDS --> boundary reference records

Model C's schema also contains model_df, but the live update path omits it. The diagram shows the effective input path. The execution engine calculates Student-t probabilities with Model A's raw scale. The calibration multiplier affects inventory tilt, and the corrected scale is a Model C feature.

Startup creates the logger and hub, starts debugging and calibration, constructs the BTC-only trader, installs the prediction logging bridge, and starts the reference and Coinbase services. It initializes Models B/C, tick producers, per-asset workers, market discovery, and CLOB subscriptions. Four Model A checkpoints and 120 minutes of per-asset REST backfill are processed sequentially, followed by staggered minute updaters and a five-second warm-up before Binance trade streams. The second-level rings still need live observations. Entrypoint, Model A startup.

There are 22 top-level coroutine instances: hub dumper, calibrator, two Chainlink tasks, Coinbase recorder, C rollover clearer, tick producer, heartbeat, four market-making workers, slug refresher, CLOB stream, four minute updaters, and four Binance streams. L2 processors, prediction drain tasks, execution tasks, safety loops, and I/O threads create additional instances. Model A selects CUDA if available, otherwise CPU; live Models B/C are explicitly placed on CPU. PyTorch intra-op and inter-op threads are each set to three. These settings do not guarantee event-loop responsiveness.

Shared state and scheduling

StateHub uses mutable dictionaries intended to be updated on the main asyncio loop. Per-asset queues of capacity one drop intermediate snapshots. Direct CLOB callbacks feed Model C; coalescing prediction drain tasks publish seq_quote and iv_pred. These predictions are stored in hub attributes attached at runtime. Model inference runs synchronously on the event-loop thread, even inside an async def with no suspension point. Model C's RLock covers event insertion and input assembly; the forward pass executes outside that lock. Hub, C inference.

Model A publishes through a monkey patch: the replacement live_mod.jlog first logs prediction, then writes iv, df, and exchange time into the hub. References imported earlier with from live_lib import jlog retain the original function. Disconnect events through the bridge can clear predictions; the independent age guard also removes predictions older than 20 seconds. Bridge.

The tick producer polls every 2 ms. Every observed price change enters a local history ring, but only a change meeting MP_THRESH—BTC 0.1, ETH 0.01, SOL 0.01, XRP 0.0001—feeds the downstream model/trade path. A heartbeat checked every 50 ms emits after 0.32 seconds without an emission. Actual scheduling latency can exceed these targets. Heartbeats reuse stored prices and can keep model windows active without fresh exchange data. Snapshot cb_last_ts is local emission time. Producers.

The market-making worker requires Model A age at most 20 seconds and Polymarket age at most 10 seconds. There is no equivalent independent Coinbase freshness gate. Model C predictions older than about 700 ms trigger an inline prediction attempt; failure can leave the old cache in use. Model B/C minimum prediction intervals default to 50 ms per asset. No shared contract-generation token prevents an already-running drain from repopulating a cleared cache.

Feeds, order books, and rollover

Feed Archived endpoint/channel Processing and failure behavior
Binance USD-M futures fstream.binance.com, aggTrade; fapi.binance.com futures/index klines Trade-time seconds; exception reconnect triggers reseed; REST exceptions get three attempts with 10-second timeout, non-200 responses return immediately
Coinbase Advanced Trade advanced-trade-ws.coinbase.com; heartbeats, ticker, level2, market_trades Ticker microprice and returns; separate L2 books; fixed one-second reconnect interval
Polymarket CLOB ws-subscriptions-clob.polymarket.com/ws/market Full snapshots and absolute per-level updates, complete depth retained; six-decimal price keys
Gamma discovery gamma-api.polymarket.com/public-search, /markets/slug/{slug} Search/probe results saved under temp/; 15-second request timeout
Chainlink via RTDS ws-live-data.polymarket.com, crypto_prices_chainlink Tolerant message parsing and boundary reference records

Coinbase L2 updates enter an unbounded queue. Each update modifies the local book, but derived features are recomputed no more often than every 0.10 seconds of exchange time. Sequence numbers are carried but not checked for gaps. Snapshot updates reset the book; reconnect and gap recovery remain incomplete. Market-trade windows are aged when trades arrive, so their “last 1/3/5 seconds” statistics can remain stale between trades. The feed's BUY/SELL field is used as received; the repository does not establish the historical exchange-side convention for that field. Coinbase recorder.

Gamma discovery probes nearby windows when needed. Its sleep calculation can space refreshes roughly 15–30 minutes apart. The CLOB local-market reader drops outcome metadata before YES selection, so that path effectively falls back to the first token; the separate execution TokenIndex does parse Up/Down outcomes. This difference can produce inconsistent token selection if the assumed ordering is wrong. Discovery, local reader, token index.

Around boundary B, the old CLOB reader stops near B - 10, and the new window beginning at B is subscribed near B - 5. Model C is cleared at B + 1; Model B survives rollover. Existing per-asset PM book state is not cleared or tagged with the new slug before a snapshot arrives. Price-only callback triggering also means quantity-only changes update the hub but do not directly emit a Model C book event. The socket staleness check uses the newest timestamp across all assets, although the trading worker has a per-asset check. CLOB stream, C clear.


4. The three Transformer models

Property Model A Model B Model C
Sequence (N,300,14) (N,32,75) (N,64,22)
Other inputs (N,19) static (N,229) static; (N,) asset ID (N,64) valid mask; (N,) asset ID
Width / attention heads / layers / FFN 96 / 4 / 4 / 288 256 / 8 / 4 / 512 192 / 8 / 4 / 384
Norm / readout post-norm / attention pooling pre-norm / last token pre-norm / last token
Outputs iv, df 3 horizons × 5 quantile estimates Mid residual, half-spread
Trainable parameters 420,995 per asset × 4 2,596,156 1,492,808
Asset IDs Separate model per asset BTC 0, ETH 1, XRP 2, SOL 3 BTC 0, ETH 1, SOL 2, XRP 3

All three use encoder self-attention without a causal mask: every position can attend to the supplied historical window. All input observations must be available at prediction time. Only C supplies a padding mask. Encoder FFNs use ReLU; outer MLP activations differ. Standard PyTorch encoder layers include attention/output projections, two residual connections, two LayerNorms, FFN biases, and dropout. For A each attention head has width 24; for B 32; for C 24. Padding-mask and optimized-kernel behavior can vary by PyTorch version, which is not pinned here.


Model A: distribution parameters

SeqTransformerT predicts the scale and degrees of freedom of a zero-location Student-t return distribution. Four separate checkpoints have the same architecture but different weights/scalers and asset symbols. The historical input feed is Binance futures despite helper names containing spot; there is no funding-rate feature. Architecture, feature construction, seconds aggregation.

A inputs: feature order and definitions

Sequence feature order is fixed by seconds_feature_cols() and SEC_COLS. Prices are USDT per underlying unit; quantities are underlying units. Historical aggregation reindexes to a complete one-second grid, forward-fills prices, and fills missing activity with zero. Returns are differences of log close; sec_trades counts aggregate trade records, each of which can group individual executions. Column order, live columns.

Index Feature Raw meaning and unit
0 sec_close Last trade price in the second; USDT
1 sec_vwap Sum of price × quantity divided by quantity; USDT
2 sec_vol Total quantity
3 sec_signed_vol Buy quantity minus sell quantity
4 sec_trades Aggregate trade record count
5 sec_buy_vol Quantity with buyer not marked maker
6 sec_sell_vol Quantity with buyer marked maker
7 sec_ret1 One-step log return
8 sec_ret3 Three-step log return
9 sec_ret5 Five-step log return
10 sec_ret10 Ten-step log return
11 sec_ret15 Fifteen-step log return
12 sec_ret30 Thirty-step log return
13 sec_imb (buy - sell) / (buy + sell + 1e-9); imbalance of executed buy and sell quantities

Static inputs combine 14 minute features and five horizon features. Minute rolling standard deviations use the pandas sample convention; no annualization is applied. Minute features, horizon block.

Offline minute rows with missing required values are dropped, including rolling-window warm-up rows and unmatched index prices. Zero closes become missing in the range calculation. The 60-minute log-volume z-score uses sample standard deviation plus 1e-9 in the denominator; time angles are 2*pi*UTC_minute_of_day/1440.

Index Feature Raw meaning and unit
0 ret_1 One-minute log-close difference
1 ret_3 Three-minute log-close difference
2 ret_5 Five-minute log-close difference
3 rv_5 Rolling standard deviation of one-minute returns over five rows
4 rv_15 Same over fifteen rows
5 rv_ratio rv_5 / (rv_15 + 1e-9)
6 hl_range (high - low) / close
7 taker_buy_ratio Taker buy volume / (volume + 1e-9), clipped to [0,1]
8 trades Minute kline trade count
9 vol_z_60 Rolling 60-minute z-score of log(volume + 1e-12)
10 basis_rel (futures_close - index_close) / (index_close + 1e-9)
11 tod_sin Sine of UTC minute-of-day angle
12 tod_cos Cosine of UTC minute-of-day angle
13 is_weekend Saturday/Sunday indicator
14 tau Remaining seconds
15 horizon transform sqrt(tau / 900)
16 horizon transform sqrt(900 / max(tau,1))
17 horizon transform sin(2*pi*tau/900)
18 horizon transform cos(2*pi*tau/900)

Two training-set StandardScaler statistics cover sequence channels flattened over samples/time and the static vectors. The artifacts retain plain mean/scale arrays of lengths 14 and 19, plus 66 float32 scaler-buffer elements in the state dictionary. Live NumpyScaler uses (X - mean) / (scale + 1e-9); raw price levels enter this standardization directly. If scaler reconstruction fails, helper fallbacks can pass raw inputs, so successful model construction alone does not prove correct preprocessing. Missing minute rows prevent inference except for the specific previous-minute grace rule. Scalers, live loading, transforms.

A layers and outputs

(N,300,14) --> Linear 14->96 --> additive sinusoidal PE --> 4 post-norm encoder layers
             --> attention pooling --> (N,96)
(N,19) --> Linear 19->64 --> SiLU --> ResidualMLP --> Linear 64->32 --> SiLU --> (N,32)
concat --> (N,128) --> Linear 128->64 --> SiLU --> ResidualMLP --> Dropout .2 --> Linear 64->2
raw[:,0] --> .0005 * softplus --> iv
raw[:,1] --> 16 / (softplus + 1e-8) --> df

Each ResidualMLP is LayerNorm(x + Linear96to64(Dropout(SiLU(Linear64to96(x))))), with dropout 0.2. Attention pooling computes softmax(v(tanh(W h))) over time, then a weighted sum of the encoder representations; W is 96→96 and v is 96→1. The persistent positional buffer has shape (1,4096,96). There is no enforced IV_FLOOR in forward; the docstring's 0.0004 coefficient is incorrect—the executable coefficient is 0.0005. Layer definitions.

All four A checkpoints record sec_d=14, static_d=19, d_model=96, n_head=4, depth=4, dropout=0.2, and l_sec=300. The constructor defaults to width 64, four attention heads, and three layers, with FFN width 3*d_model. The checkpoints record overrides of the constructor defaults; the missing driver leaves the original argument-passing procedure unknown.

Component Elements
Input projection 1,440
Four encoder layers 373,248
Attention pooling 9,409
Static MLP 15,936
Fusion MLP 20,832
Output layer 130
Trainable total 420,995
Positional buffer 393,216
Scaler buffers 66
Saved state total 814,277

A sampling, loss, and training

For each candidate minute index, make_samples draws integer tau uniformly from 5 through 900. The saved metadata specifies 12 draws per minute index; the library default is one. It sets end = floor_15min(minute) + 900 seconds - 1 second and t = end - tau. Samples can therefore fall outside the candidate minute, and draws can duplicate timestamps. Labels use r = log_close[end] - log_close[t] and z_true = r / (sqrt(tau/900) + 1e-12). Sampling, dataset.

The provided offline minute builder uses full-minute OHLC data indexed by minute opening time, while indexify_samples selects t.floor('min'). Used together for an intraminute sample, these helpers expose information from later in that minute. This is a confirmed look-ahead path in the available helpers; the missing driver prevents establishing exactly how historical checkpoint datasets were assembled. The day split randomly assigns 20% of UTC days to validation and purges 900 seconds on either side, but that purge alone does not fix intraminute look-ahead. Indexing, split.

The loss converts the normalized label back to raw horizon return and uses weighted Student-t negative log likelihood:

r_true = z_true * sqrt(max(tau,1)/900)
s = iv * sqrt(max(tau,1)/900)
u = r_true / (s + 1e-12)
log_f = lgamma((nu+1)/2) - lgamma(nu/2) - .5*log(nu*pi) - log(s+1e-12)
        - .5*(nu+1)*log1p(u*u / max(nu,1e-8))
w0 = clip(sum_k sqrt(abs(log_close[t]-log_close[t-k])/k + 1e-15), 1e-6, 50)
w = clip(w0 * prob_mult, 1e-8, 1e3)
loss = sum(w * -log_f) / (sum(w) + 1e-12)
k in {1,3,5,10,15,30}

At default r_thresh_bp=0, the probability-based update assigns a common 0.05 multiplier after initial weights of one. It therefore adds no prediction-dependent weighting. A common factor cancels in an ideal normalized mean, but clipping and denominator epsilon mean exact cancellation is not universal. Training uses weighted NLL, and validation uses unweighted NLL. Training loop.

Library defaults are AdamW lr=1e-3, wd=5e-4, four epochs, patience three, and improvement threshold 1e-4. Optional cosine scheduling steps every batch with T_max = epochs * len(train_loader) and minimum learning rate 0.1 times the starting rate. There is no AMP or gradient clipping in this function. It clones the best state to CPU and reloads it at the end. Sampling/splitting default to seed 42; the utility does not set a global torch seed. Saved artifacts contain eight epoch summaries, but do not establish the missing driver's exact optimizer overrides. Unconditional prefetch_factor=2 with a default zero-worker loader in helper functions is a dependency-sensitive failure path.

The training function accepts already-built loaders, so it does not set a training batch size. fit_scalers_lazy defaults to batch 512 with shuffling; predict_params_t_dataset defaults to batch 4096 without shuffling. Both default to zero workers, retain the last partial batch, enable pinned memory when CUDA is available, and enable persistent workers only for a positive worker count. The probability-weight update defaults to once per epoch; batch and off are other accepted modes. The historical driver's loader settings are unavailable.

A live behavior and calibration diagnostics

The loader selects an asset-matching checkpoint by path and otherwise can fall back to the newest checkpoint of any asset. It strips _orig_mod.base. or base. prefixes, discards wrapper state as appropriate, and strictly loads the base network. This fallback can silently choose the wrong asset. The current artifacts do not require executing a serialized scaler object for structural inspection. Loader.

The live ring finalizes the prior second when a trade with a different second arrives, computes returns before appending the current close, and predicts once 300 rows are available. It does not fill empty seconds or reject backward timestamps. Consequently, live row lags can differ from historical second lags. Exception reconnects reset the ring and reseed 120 minutes of minute data; normal WebSocket closure does not take exactly the same reseed path. Ring, stream.

The minute updater waits two seconds after a boundary and retries for missing data, but takes the final REST candle without checking whether it has closed. It accepts only a newer opening timestamp, so a forming candle can become a frozen feature row. Static selection uses the exact current-minute row or the immediately previous row within ten seconds of the boundary. Nested HTTP timeouts can make the total wait exceed seven seconds. Updater, static selection.

PIT is F_nu(r/s). The function named ece_uniform computes an occupancy-weighted distance between each occupied bin's mean PIT and that bin's midpoint. Its mce is the largest such within-bin distance. All observations at one bin midpoint can therefore produce zero error despite a nonuniform distribution. KS compares the empirical CDF with the uniform CDF; overlapping windows and serial dependence undermine the usual independent-sample interpretation of its p-value. Small saved scores do not prove calibration or tradability. Metric implementations.

Each A checkpoint stores a piecewise cubic PIT mapping split at 0.5, with endpoint constraints at 0, 0.5, and 1. The fitting driver is missing. Live loading does not apply this mapping; it is separate from the market-price calibration in Chapter 5.


Model B: short-horizon quantile estimates

Model B outputs five estimates for each target ret_2s, ret_5s, and ret_10s, in that order. They are intended as future log-return quantiles at levels [0.10,0.25,0.50,0.75,0.90]. The lost dataset builder prevents verifying exact label timestamp alignment and the original target-price convention. The live preprocessing is available in source; its parity with the historical training pipeline remains unverified. Trainer, inference.

B inputs: feature order and definitions

The 75 columns below follow meta_transformer.json. The producer is Coinbase processing, and ingestion is add_tick. Q denotes underlying quantity; R a dimensionless ratio/log return; bp basis points; counts and indicators are dimensionless. Every channel is subsequently standardized using the asset's saved statistics.

For a valid L2 midpoint M, band depth includes bids at or above M*(1-bp/10000) and asks at or below M*(1+bp/10000). tot = bid + ask, imb = (bid-ask)/tot with zero fallback, and lr = log(bid+1e-9)-log(ask+1e-9). The mp_skew fields use the same band-imbalance calculation. Missing or invalid midpoint handling can use one side or the last ticker microprice.

Index Feature Meaning; raw unit
0 cb_book_avg_dist_ask_bp Quantity-weighted ask distance over top five levels; bp
1 cb_book_avg_dist_bid_bp Quantity-weighted bid distance over top five levels; bp
2 cb_book_convexity Sum of ask/bid size-versus-distance slopes; Q/bp
3 cb_book_slope_ask OLS slope of level size on distance, top five asks; Q/bp
4 cb_book_slope_bid Same for bids; Q/bp
5 cb_buy_frac_1s BUY quantity fraction, trailing trade window; R
6 cb_buy_frac_3s Same over 3 seconds; R
7 cb_buy_frac_5s Same over 5 seconds; R
8 cb_depth_ask_10bp Ask depth inside 10 bp; Q
9 cb_depth_ask_1bp Ask depth inside 1 bp; Q
10 cb_depth_ask_2bp Ask depth inside 2 bp; Q
11 cb_depth_ask_5bp Ask depth inside 5 bp; Q
12 cb_depth_bid_10bp Bid depth inside 10 bp; Q
13 cb_depth_bid_1bp Bid depth inside 1 bp; Q
14 cb_depth_bid_2bp Bid depth inside 2 bp; Q
15 cb_depth_bid_5bp Bid depth inside 5 bp; Q
16 cb_depth_imb_10bp Depth imbalance inside 10 bp; R
17 cb_depth_imb_1bp Depth imbalance inside 1 bp; R
18 cb_depth_imb_1bp_diff Change since previous feature computation; R
19 cb_depth_imb_2bp Depth imbalance inside 2 bp; R
20 cb_depth_imb_5bp Depth imbalance inside 5 bp; R
21 cb_depth_lr_10bp Log bid/ask depth ratio inside 10 bp; R
22 cb_depth_lr_1bp Same inside 1 bp; R
23 cb_depth_lr_2bp Same inside 2 bp; R
24 cb_depth_lr_5bp Same inside 5 bp; R
25 cb_depth_near_far_ratio_ask Ask depth 1 bp / 5 bp; R
26 cb_depth_near_far_ratio_bid Bid depth 1 bp / 5 bp; R
27 cb_depth_tot_10bp Bid + ask depth inside 10 bp; Q
28 cb_depth_tot_1bp Same inside 1 bp; Q
29 cb_depth_tot_2bp Same inside 2 bp; Q
30 cb_depth_tot_5bp Same inside 5 bp; Q
31 cb_flow1s_net BUY minus SELL quantity over 1 second; Q
32 cb_flow3s_net Same over 3 seconds; Q
33 cb_flow5s_net Same over 5 seconds; Q
34 cb_jump_flag Absolute ticker return exceeds three updated EWMA sigmas; 0/1
35 cb_last_trade_at_ask Last trade within 1e-8 of current ask; 0/1
36 cb_last_trade_at_bid Last trade within 1e-8 of current bid; 0/1
37 cb_last_trade_px Last trade price, divided by current ticker microprice; R
38 cb_last_trade_side BUY +1, SELL -1, otherwise 0
39 cb_last_trade_ts_s Last trade time; seconds, recentered
40 cb_last_trade_vs_mid_bp (last_trade_px-ticker_microprice)/ticker_microprice*10000; bp
41 cb_last_ts Local downstream emission time; seconds, recentered
42 cb_mp_skew_10bp Band depth imbalance inside 10 bp; R
43 cb_mp_skew_1bp Same inside 1 bp; R
44 cb_mp_skew_2bp Same inside 2 bp; R
45 cb_mp_skew_5bp Same inside 5 bp; R
46 cb_n_ask_improve_1s Ask decreases counted over feature updates in 1 second
47 cb_n_ask_worsen_1s Ask increases counted over feature updates in 1 second
48 cb_n_bid_improve_1s Bid increases counted over feature updates in 1 second
49 cb_n_bid_worsen_1s Bid decreases counted over feature updates in 1 second
50 cb_n_spread_tighten_1s Positive-spread decreases counted over 1 second
51 cb_n_spread_widen_1s Positive-spread increases counted over 1 second
52 cb_net_add_ask_1bp_1s Sum of changes in ask band depth over 1 second; Q
53 cb_net_add_bid_1bp_1s Same for bid band depth; Q
54 cb_ret_10s Current ticker log price minus first retained log price at/after t-10; R
55 cb_ret_1s Same with t-1; R
56 cb_ret_3s Same with t-3; R
57 cb_ret_5s Same with t-5; R
58 cb_rv_3s Square root of summed event-return squares over 3 seconds; R
59 cb_rv_dn_3s Same using negative returns only; R
60 cb_rv_up_3s Same using positive returns only; R
61 cb_sigma_ewma EWMA event-return dispersion; R
62 cb_spread_abs L2 ask minus bid, divided by ticker microprice; R
63 cb_spread_bp L2 spread / L2 midpoint × 10000; bp
64 cb_tob_ask_px Best ask divided by ticker microprice; R
65 cb_tob_ask_qty Best ask quantity; Q
66 cb_tob_bid_px Best bid divided by ticker microprice; R
67 cb_tob_bid_qty Best bid quantity; Q
68 cb_ts_server_ms Server milliseconds converted to recentered seconds
69 cb_wall_ask_dist_bp Distance to largest aggregate ask level within 25 bp; bp
70 cb_wall_ask_size Total size aggregated at that price level; Q
71 cb_wall_bid_dist_bp Distance to largest aggregate bid level within 25 bp; bp
72 cb_wall_bid_size Size of that price level; Q
73 cb_wall_imbalance (bid_wall_size-ask_wall_size)/(sum) with zero fallback; R
74 log_ts_s Parsed local log/emission timestamp; seconds, recentered

Depth, slope, distance, and wall helpers generally return zero when unavailable; near/far ratios return one when far depth is zero; BUY fractions default to 0.5 with no volume. Slope returns zero for zero distance variance. The “net add” fields include changes caused by trades, cancellations, and moving price bands; they do not isolate new limit orders. Event counts measure changes between throttled feature computations, so intermediate exchange changes can be omitted. L2 formulas.

EWMA uses decay = exp(-dt/30) and var = decay*var + (1-decay)*r*r, with no division by elapsed time. Thirty seconds is the e-folding time; for nonpositive elapsed time the code sets decay to zero. The output measures variability over event intervals, whose durations can vary. Three-second realized measures use each observation within the window and its return from the preceding observation, then take the square root of the summed squared returns. A return can therefore begin before the window. Return features.

B normalization, time, and static vector

The per-asset buffer holds exactly the latest 32 ingested ticks. A backward, missing, nonfinite, or greater-than-one-second adjacent timestamp gap resets the segment; equal timestamps are allowed. Prediction requires 32 ticks in the new contiguous segment and uses no padding. Segmentation prefers the parsed log timestamp, then cb_last_ts, then server milliseconds converted to seconds. These checks use Python float timestamps before feature conversion; the gap check retains Python float precision, while the model features undergo the float32 conversion described below. UTC time-of-day uses a separately retained absolute timestamp, with all three time extras set to zero if it is unavailable. Segmentation, time helpers.

Ingestion allocates float32 rows before recentering timestamps. With a positive coinbase, _px columns excluding names containing vs_ or bp, plus cb_spread_abs, are divided by that price. If the price is absent, this division is skipped. At prediction time the code subtracts the maximum finite log_ts_s in the window from seconds columns, and subtracts it after dividing server milliseconds by 1000. It falls back to cb_last_ts only if the log_ts_s column is absent. A present column containing only missing values keeps the original selection path. Float32 epoch seconds near December 2025 have 128-second spacing, so subsecond precision has already been lost before this subtraction. Ingestion, window assembly.

Static indices Contents Unit before z-score
0 Asset ID Integer category represented as float
1–75 Latest 75-column row Same as sequence
76–150 Window column means Same as sequence
151–225 Window population standard deviations Same as sequence
226 UTC second-of-day sine Dimensionless
227 UTC second-of-day cosine Dimensionless
228 Weekend indicator 0/1

Static summaries are computed after time recentering but before replacing nonfinite values. One missing value can therefore invalidate a whole column's mean/std summary. Nonfinite sequence/static values are then replaced with raw zero, followed by asset-specific z-scoring. Raw zero becomes -mean/std after normalization. Saved arrays have 75 sequence and 229 static entries per asset. Training normalization samples up to two million sequence rows and static windows per asset, uses NaN-aware population statistics, substitutes one for very small/invalid standard deviations and zero for invalid means, and can reuse an existing statistics file. Statistics, dataset normalization.

B layers and output decoding

(N,32,75) --> Linear 75->256 --> sinusoidal PE + Dropout .1 --> 4 pre-norm encoders
             --> last token (N,256)
(N,229) --> Linear 229->256 --------------------------------------------\
concat (N,512) --> Linear 512->512 --> GELU --> Dropout .1 --> Linear 512->256 --> GELU
               --> one of four Linear 256->15 output heads --> (N,3,5)
               --> divide each horizon by [40000,30000,20000]

There is no learned asset embedding. Asset ID selects the output head and also enters the static vector. Sinusoidal PE is a nonpersistent buffer of length 32. Parameter counts are: sequence projection 19,456; encoder 2,108,416; static projection 58,880; body 393,984; four output heads 15,420; total 2,596,156. Runtime replaces nonfinite predictions with zero and can still report an otherwise successful prediction. Network, runtime prediction.

B loss, training, and metrics

For e = clip(y*scale,±1000) - clip(q_pred,±1000), the base Huber function is H_delta(e) = 0.5*min(abs(e),delta)^2 + delta*(abs(e)-min(abs(e),delta)), with delta 3. Let a_k be the quantile level when e >= 0, otherwise one minus that level; c_k = [0.3,0.4,2.5,0.4,0.3]; w_nt is the NPZ target weight multiplied by asset weight BTC 3, ETH 2, XRP 1, SOL 1. With finite-entry mask m_ntk, the actual reduction is:

loss = sum_ntk(m_ntk * w_nt * c_k * a_k * H_3(e_ntk))
       / max(sum_ntk(m_ntk * w_nt), 1e-12)

When all five quantiles are finite, the denominator is five times the sample-target weight sum. Quantile weights are not included in that denominator. This asymmetric smoothed loss can have a minimizer that differs from the exact conditional quantile at finite delta. Pinball loss has linear tails and bounded residual gradients. Loss.

NPZ shards supply x_seq, x_static, base_idx, target arrays, and weights. Nonfinite labels are replaced with zero and their weights zeroed; invalid weights are zeroed, but negative finite weights are not explicitly rejected. Workers receive contiguous shard subsets, shuffle shard order during training, and preserve within-shard order. The missing datasets prevent measuring the resulting within-batch correlation. Nonfinite batch loss skips the batch. Dataset, epoch loop.

For a shard with M samples, the required B arrays are x_seq (M,32,75), x_static (M,229), base_idx (M,), and y_ret_2s, y_ret_5s, y_ret_10s, w_ret_2s, w_ret_5s, w_ret_10s, each (M,). The loader stacks targets/weights to (M,3) and uses allow_pickle=False. Filename asset selects normalization; a conflicting stored base_idx can change head routing without changing those statistics. The builder is unavailable, so actual shard consistency cannot be tested.

Saved settings are batch 8192, 20 epochs, AdamW learning rate 2e-5, weight decay 3e-4, cosine per epoch to 2e-6, AMP disabled, six workers, seed 42, and no step limit. CLI defaults use 40 epochs, 1e-4, and 1e-2. Gradient clipping is hardcoded to 1.0 despite a parsed argument; B correctly unscales AMP gradients first. Validation selects strict improvement in its mean of batch losses, giving each batch equal weight in model selection; no early stopping is implemented. Seeds cover Python, NumPy, and torch without deterministic-kernel guarantees. Arguments, training main.

Diagnostics include weighted RMSE, R², correlation, sign accuracy, and empirical quantile coverage. Large-move diagnostics define a four-sigma event and use a normal distribution centered on the median with a fixed metadata-based sigma. Degenerate denominators/nonfinite values can be replaced with zero in metrics. No saved B validation results are present to establish predictive quality. Metrics.

B runtime consumer: direction and skew

The policy takes a local running maximum of quantiles to enforce nondecreasing order. It computes sigma_proxy = max(1e-12,(q75-q25)/1.349) and z = q50/sigma_proxy; the 1.349 conversion assumes a normal distribution. It linearly interpolates a CDF at zero and uses p_up = 1 - F(0), with endpoint probabilities limited by the available 0.1/0.9 quantiles. Ties and degenerate bands can yield unreliable probability estimates; for five zero outputs the helper returns 0.9, although the zero z prevents ordinary activation. Policy helpers.

active_h = (p_up >= .58 or p_up <= .42) and abs(z) >= .20
score_h = sign(p_up-.5) * tanh(abs(z)/2) if active_h else 0
score = clip(.50*score_2s + .35*score_5s + .15*score_10s, -1, 1)
If the first qualifying horizon in [2s,5s,10s] has (q10>0 or q90<0) and abs(z)>=.60:
    score = its tail direction (+1 or -1)
delta_p = .02 * score
one_sided = abs(score)>=.80 or tail-strong mode

The execution engine uses delta_p as seq_skew, but independently derives one-sided behavior at abs(score)>0.1. The policy's 0.80 flag is unused by the trader. Its conditional crossing threshold is 0.5. A separate diagnostics adapter expects a list while quote_debug is a dictionary, leaving aggregate quote_z, quote_mu, and quote_sigma at zero; these fields are not used for trading. Policy, adapter.


Model C: book mid residual and half-spread

Model C consumes mixed Coinbase and Polymarket events. Its output reconstructs mid_pred = mid_base + delta_mid, then bid_pred = mid_pred - hs and ask_pred = mid_pred + hs. A residual parameterization does not force the model to learn useful structure or exclude an identity-like solution. The historical target timing remains unknown; the available labels leave both same-timestamp nowcast and future-forecast interpretations unverified. Trainer loss, runtime engine.

C inputs: feature order and definitions

The order comes from dataset_stats.json. Rows carry forward fields not changed by an event; explicit missing updates can replace a field with NaN. Before z-scoring, remaining nonfinite values become raw zero. Every numeric channel, including event flags and padded rows, is standardized per asset; padding keys are then masked in attention. Means/stds come from norm_stats_iv.json; runtime replaces invalid or at-most-1e-6 standard deviations with one.

Index Feature Meaning and raw unit
0 log_rel_px log(coinbase/prev_close); moneyness proxy, dimensionless
1 cb_sigma_ewma Coinbase event-return dispersion; dimensionless
2 cb_rv_3s Three-second realized return measure; dimensionless
3 cb_buy_frac_1s One-second BUY quantity fraction
4 cb_buy_frac_5s Five-second BUY quantity fraction
5 cb_flow1s_net One-second BUY minus SELL quantity; underlying units
6 cb_depth_imb_1bp Coinbase 1 bp depth imbalance
7 cb_spread_bp Coinbase spread; bp
8 pm_iv_implied_900 Smoothed market-adjusted 900-second Student-t scale; pm_iv_mult supplies its calibration multiplier
9 model_iv Raw Model A 900-second scale
10 model_df Intended Model A degrees of freedom; omitted by live ingestion
11 tau Remaining seconds
12 pm_best_bid PM best bid; dollars per share
13 pm_best_ask PM best ask; dollars per share
14 pm_mid Arithmetic midpoint; dollars per share
15 pm_spread Ask minus bid; dollars per share
16 pm_size_bid_top Sum of top five bid-level shares
17 pm_size_ask_top Sum of top five ask-level shares
18 pm_imb_top Intended top-five size imbalance; producer uses a different key
19 is_ticker_update Current event is ticker; 0/1
20 is_book_update Current event is book; 0/1
21 time_lag Latest event time minus this event time; nonnegative seconds

Index 8 is the ninth feature; indices 9 and 10 are the tenth and eleventh features. The live paths never populate model_df and pm_imb_top under their expected names: the latter is emitted as pm_imbalance_top. These channels become raw zero and then generally nonzero standardized constants. Saved nonzero means confirm a mismatch with the saved normalization distribution, but do not reconstruct individual training rows. tau is populated by the live path. Book summary, ticker ingestion.

C event replay, masks, and base mid

_BaseSeq retains up to 4096 timestamp-ordered events. Equal timestamps preserve arrival order through right insertion. In-order updates append a new carried state; late events are inserted and every later state is replayed. The last evicted state becomes the new base state; events older than that base timestamp are discarded. time_lag and event flags are protected from arbitrary sparse updates. Event store.

Input assembly walks backward through the latest contiguous segment with adjacent gaps from zero through one second. It requires at least 16 events, takes at most 64, and right-aligns them in a zero-filled (64,22) array with a Boolean valid mask. time_lag is computed before float32 conversion, avoiding Model B's absolute timestamp precision problem. B resets its buffer on a segment break. C selects the latest contiguous suffix and can retain earlier stored history. Assembly.

Before nonfinite cleanup, mid_base scans backward for the latest finite positive bid/ask pair with ask >= bid, then falls back to a midpoint strictly inside (-0.25,1.25). If no reference is found, decoding can use zero and still return a result. Forward-carried prices may be old even when the event timestamp is new; no per-field age is enforced. The current trainer reconstructs the base from the final row's unstandardized bid/ask, replacing nonfinite values with zero. The different missing-data rules can produce different reference mids. Runtime reference, training reference.

C layers, decoding, and loss

(N,64,22) --> Linear 22->192 --> sinusoidal PE + Dropout .1 --> 4 pre-norm encoders
valid mask (N,64) --> src_key_padding_mask = NOT valid
last token (N,192) + Embedding(4,192)[asset_id]
    --> selected asset output head: Linear 192->384 --> GELU --> Dropout .1 --> Linear 384->2
provided runtime metadata: delta_mid = z0/100; hs = softplus(z1)/50
current training source:   delta_mid = z0/100; hs = ReLU(z1)

PE has length 64 and is nonpersistent. Explicit asset embedding is added after the shared encoder, although asset-specific feature distributions can still carry identity information. Parameter counts are sequence projection 4,416; encoder 1,188,096; embedding 768; four output heads 299,528; total 1,492,808. The constructor defaults to width 256/FFN 512, while the CLI and saved tensors use 192/384. Network.

The current trainer reads seven-label rows in the saved order: bid, ask, mid, spread, bid top size, ask top size, top imbalance. It optimizes only Y[:,2] and Y[:,3]/2. With raw-unit standard deviations s_mid=0.2581641412550873 and s_hs=0.009014349689407113, its loss is:

loss = mean(H_1((mid_base + z0/100 - mid_true) / s_mid))
       + .2 * mean(H_1((ReLU(z1) - half_spread_true) / s_hs))

There are no sample or asset weights. Nonfinite batch losses cause the entire batch to be skipped; the loss has no per-label finite mask. Diagnostics include mid/half-spread RMSE, residual summaries, and rates at which predicted bid exceeds labeled ask or predicted ask falls below labeled bid. These rates compare predictions with labels. Estimating actual crossing rates would additionally require label timing, exchange latency, and order-submission information. Loss and epoch metrics.

C training settings and compatibility

Saved args specify batch 8192, 32 epochs, learning rate 3e-4, weight decay 5e-5, six workers, seed 42, AMP disabled, and no step limit. The current CLI defaults differ in learning rate (1e-4). AdamW and per-epoch cosine scheduling would reduce 3e-4 to 3e-5 over 32 epochs under the current loop. No early stopping is implemented. Gradient clipping is hardcoded at 1.0. C clips scaled gradients before AMP unscaling; B unscales first. That defect is conditional on AMP, which the saved arguments disable. CLI, epoch loop.

Feature statistics use valid sequence timesteps from training data; label scales are population standard deviations. Existing statistics can be reused. The current trainer writes mid_std and half_spread_std, whereas the saved decoding artifact uses mid_std_ref, half_spread_std_ref, MID_SCALE=100, HS_SCALE=50, and spread_activation="softplus". With this artifact, runtime chooses softplus(z1)/50; the current training loss uses bare ReLU. The decoder contracts differ. The historical training activation and source-version chronology remain unknown. Pairing newly trained weights with the retained decoder metadata without reconciling them is unsafe. Statistics, decoder selection.

C requires NPZ arrays X (M,64,22), mask (M,64), and Y (M,7) under the retained schema, with the asset inferred from the filename. Its worker partitioning and file-order shuffle preserve within-file sample order. Best-model selection uses strict improvement in validation loss. Both B/C saved runs use log interval 50; B's optional metadata/normalization path overrides are null, normalization recomputation is not forced, and both sampling caps are 2,000,000. The current C loader uses allow_pickle=True, an additional reason not to load untrusted replacement datasets. C's two statistics files differ in decimal precision but produce identical float32 feature means/stds.

C's live inputs arrive from Coinbase emissions and PM price-change callbacks; quantity-only PM updates are not direct triggers. The live coalescer replaces the engine's optional internal prediction workers. Cache clearing at a contract boundary does not join a pending prediction drain, and failed readiness checks do not guarantee cache invalidation. Consequently, the nominal 50 ms interval can coexist with stale cached predictions.


5. Volatility calibration, signal combination, and quotes

The following formulas describe the source implementation. They use probability-unit prices, so 0.01 is one cent per share. Model B's skew is bounded by 0.02; Model A's direct correction is bounded by 0.01; Model C supplies the primary center and half-spread.

Market-price volatility calibration

The calibrator loops across four assets with a nominal 0.1-second interval. It uses p_obs = (bid*bid_qty + ask*ask_qty)/(bid_qty+ask_qty), a quote weighted by each side's own displayed size. The Coinbase microprice defined above uses opposite-side weights. Positive sizes, valid prices, reference price, raw Model A scale/df, and expiration time are required. Observations on the wrong side of 0.5 for the symmetric model are skipped; possible causes include a mismatch between the model and its reference price, as well as data errors. Calibration loop.

It bisects the Student-t probability over scale [1e-5,5e-3], up to 50 iterations with 1e-6 probability tolerance. Out-of-bracket or degenerate cases return no update. At exact moneyness zero the probability is always 0.5, so scale is unidentifiable. Moving away from 0.5 does not universally guarantee good numerical conditioning. The quality rule is heuristic:

quality = 1/(1+(spread/.02)^2) * clip(2*abs(p_obs-.5),0,1)
y = log(clip(iv_observed/model_iv, .2, 5))
R = .04 / quality
gain = P / (P+R)
k_new = k + gain*(y-k)
P_new = (1-gain)*P + 1e-5
pm_iv_mult = exp(k_new)
pm_iv_implied_900 = pm_iv_mult * model_iv

The normal initial state is log multiplier zero and variance 0.1; an invalid variance is reinitialized from the observation with variance 0.04. Process variance is added after the measurement update, as implemented. Model C receives pm_iv_implied_900 at index 8. The trader requires pm_iv_mult for inventory tilt and uses raw Model A scale for its probability calculation. The stored corrected scale updates only on successful calibration and can lag a newer raw scale. The calibrator also depends on coinbase_prev_close written by the market-making worker. Filter state, inversion.

Quote center and cancellation band

The trader requires finite positive reference price, Coinbase price, raw model_iv, model_df, tau, and pm_iv_mult; a finite low/high reference band; a strictly positive observed spread; and usable C mid/half-spread. It clips C mid to [0,1], takes the absolute half-spread, and requests cancellation when abs(delta_mid)>0.03, hs_pred>0.04, or [pred_mid-2*hs_pred,pred_mid+2*hs_pred] is disjoint from the observed spread. Predictions passing these gates can still be inaccurate. Snapshot guards.

The low reference is floored and high reference ceiled to two decimals, or four for XRP. The code averages the two raw-Model-A probabilities at the current spot S_now, then combines signals. In p_up(spot, barrier), the scale, degrees of freedom, and remaining time stay fixed:

t_fair_mid = .5 * (p_up(S_now, K_low_floor) + p_up(S_now, K_high_ceil))
center0 = clip(pred_mid + seq_skew, 0, 1)
iv_skew = clip(.15*(t_fair_mid-center0), -.01, .01)
fair_center = clip(center0 + iv_skew, 0, 1)
fair_yes_lo = clip(fair_center - .5*hs_pred, 0, 1)
fair_yes_hi = clip(fair_center + .5*hs_pred, 0, 1)

The final two values define the cancellation band. New-order width is calculated separately below. YES buys at or above its low edge and sells at or below its high edge are cancellation candidates; NO orders use complementary values. There is no implemented Avellaneda–Stoikov inventory-skew formula: MMParams, DEFAULT_MM_BY_BASE, SPREAD_BPS, REF_PRICE, and MM_MULT do not enter this pricing path. rho is logged only. Center, legacy configuration.

Width, tick rounding, and conditional crossing

The additional width uses sigma_proxy = max(cb_sigma_ewma, cb_rv_3s/sqrt(3), 0). It inverts fair_center back to an underlying price around prev_close, with up to 32 bracket expansions and 48 bisections, perturbs that price by exp(±sigma_proxy), and reprices both points. The resulting half difference is added to hs_pred, with a floor of one tick. The proxy reflects event-return variability. The proxy's one-second standard-deviation interpretation remains unverified. Monotonic widening near expiration is also unproven. Failed inversion falls back to zero extra width. In the pseudocode, inverse_p_up solves for spot price with the barrier fixed at prev_close. Width.

S_center = inverse_p_up(fair_center, K=prev_close)
extra_half = .5 * max(p_up(S_center*exp(sigma_proxy), prev_close)-p_up(S_center*exp(-sigma_proxy), prev_close),0)
quote_half = max(hs_pred + extra_half, tick)
bid = clip(fair_center-quote_half,0,1)
ask = clip(fair_center+quote_half,0,1)
if abs(seq_score) <= .5:
    bid = min(bid, clip(pred_mid+hs_pred,0,1)-.01)
    ask = max(ask, clip(pred_mid-hs_pred,0,1)+.01)

The engine rejects edge prices outside [0.01,0.99], rounds bids down and asks up by tick size, reapplies guards, and attempts to repair a collapsed spread. NO prices derive from 1-YES_ask and 1-YES_bid, rounded outward. Floating-point arithmetic and later clamps also affect the final prices; profitability depends on subsequent executions and market movements. Quote construction.

The crossing guard is conditional and references the predicted book. The actual best bid/ask can differ when an order reaches the exchange. Submissions use GTC with no explicit post-only flag. A marketable GTC limit order can execute immediately as taker and leave a remainder resting. Exchange-enforced post-only protection requires a separate order flag. The official Polymarket order lifecycle explains these order semantics. The archived client's historical behavior remains unverified; its submission path permits taker execution. GTC submission.


6. Execution, inventory, concurrency, and shutdown

Local order lifecycle and exchange uncertainty

snapshot --> allowed asset / token lookup --> latest pending version --> per-YES worker
worker --> quote + risk filters --> cancel candidates removed from local registry
                                |--> detached cancellation request --> success / failure / unknown
                                \--> capacity check --> detached GTC submit --> response / timeout
response --> accepted IDs --> local registry --> optional stale-version cancellation sweep
user MATCHED event --> inventory delta (remaining live order quantity stays unchanged)
shutdown / inactivity / tail --> cancellation attempts (venue orders or positions may remain)

on_tick resolves a slug through TokenIndex, records local activity, and overwrites the latest pending snapshot. A per-YES-token worker processes desired versions until caught up. Synchronous ingress can block on filesystem token-index refreshes. “Atomic” in _quote_and_trade_atomic refers to local quote-cycle organization; the exchange processes the resulting requests separately. Ingress, worker scheduling.

Stale-price and opposite-direction cancellations remove orders from local bookkeeping before a fire-and-forget network request. The code awaits capacity-driven cancellation requests. The wrapper does not verify from the response body whether every requested order was canceled. Submission can overlap cancellation. The two-millisecond post-submit wait begins after task scheduling and can elapse before exchange acknowledgment. Orders may remain active even when the local registry is empty or a done log has been emitted. Cancellation, capacity.

An in-flight submit records its version and a stale flag. A newer submission attempt may mark it stale and discard the newer batch; a post-response sweep then checks the latest fair band. Newer quotes can bypass that scheduling path, allowing stale orders to remain on the book despite the mitigation. The response list is filtered to accepted IDs, which are then paired positionally with the original order specifications; rejection before acceptance can associate an accepted ID with the wrong price/token metadata. Submission state, ID association.

I/O uses eight executor workers, a semaphore of eight, two attempts, and jittered backoff 0.05*(1+0.5*random()). The outer 0.8-second asyncio timeout covers semaphore waiting and retries; it does not stop an already-running blocking thread. Handwritten signed requests lack an HTTP timeout. Retrying an ambiguously acknowledged submission creates/signs orders again and can duplicate exposure; no application-level idempotency mechanism resolves this ambiguity. The log salt is only a correlation key. I/O, signed requests.

Capacity defaults are one submit batch per second per slug, four live orders per side, and two at the same token/side/price. “Side” groups BUY or SELL orders across both tokens; YES exposure direction also depends on the token being traded. When capacity is full, orders farthest from the fair center in YES-price space are canceled first, with newer orders first on ties. The submit-rate value is converted to an integer; a positive value below one can prevent all submissions. Remaining quantities in the live registry stay unchanged after fills, so its capacity estimate can diverge from exchange state.

Inventory filters and position tracking

Local inventory is estimated from user-WebSocket MATCHED deltas, starting at zero with existing account balances omitted. BUY adds shares and SELL subtracts them. Attribution checks the top-level owner and matching maker entries; message fingerprints are deduplicated in a bounded FIFO history, default 20,000. Settlement failure and later status transitions are not reconciled into this tracker. Position API polling checks limits independently and leaves the local inventory estimate unchanged. Fill tracking.

Asset Quote size Inventory cap Cumulative fill-share cap per slug
BTC 5 20 20,000
ETH 5 15 2,500
SOL 5 15 1,500
XRP 5 15 1,500

All four configurations read MM_BTC_QSIZE, MM_BTC_INVCAP, and MM_BTC_VOLCAP; setting one affects all assets. Effective order size also respects the market minimum. The default action pair buys YES at the bid and NO at the complementary ask. If estimated YES balance exceeds five times effective quote size, the NO buy is replaced with a YES sell; the converse applies for NO balance. No complete free-balance or outstanding-order reservation calculation guarantees that a fixed-size sell is fundable. Configuration, actions.

Let net = YES_balance - NO_balance, C = inv_cap, a = 1-clip(tau,0,900)/900, and d = sign(coinbase-prev_close)*sign(pm_iv_mult-1). Bounds are:

d > 0: [C*(1.2*a-1), C]
d < 0: [-C, C*(1-1.2*a)]
d = 0: [-C, C]

The code removes exposure-increasing actions only when current net inventory is strictly outside a bound. It does not reserve for pending orders or enforce projected post-fill inventory, and it cannot force a fill or flatten the account. When not over cap, a nonflat Model B direction with abs(score)>0.1 filters new actions; over-cap risk filters take precedence for new actions. The earlier opposite-direction cancellation sweep is still a separate step. Inventory policy.

Timing and safety threads

Window starts S                                     Expires S+900
S .. S+8          no new orders under head guard
S+8 .. S+885      nominal quote interval (877 seconds, subject to all other gates)
S+885 onward     one account-wide tail cancellation attempt per start timestamp
Every ~.10 s     check .5-second local snapshot inactivity
Every ~5 s       independent account-position limit check

The tail branch uses account-wide cancellation, including orders outside the current slug; earlier validation failures can return before reaching it. Inactivity measures the arrival time of accepted local snapshots. These snapshots can carry stale venue data, and cancellations remain best-effort. TTL defaults to disabled; its comment mentions preserving queue priority, but the repository does not establish a measured queue-priority contribution to profitability. Timing, safety loops.

The positions thread requests at most 500 positions with offset zero and no pagination, every five seconds with a 2.5-second timeout. It checks current indexed tokens for all four assets, even in the BTC-only trader. A token balance above four times its configured cap calls os._exit(2); three consecutive request failures or an unresolved account address call os._exit(3). No cancellation precedes these hard exits, so resting orders may remain. An empty token map causes the check to be skipped, leaving balances unchecked. Position guard.

The user WebSocket uses a separate thread, an initial connection plus two retries, and one-second retry waits. A health thread checks whether more than five seconds have elapsed since the latest submit with no subsequent user message. Repeated submissions can postpone that condition. A live thread can still be waiting for its authenticated subscription to become ready. Soft-death handling clears position/session-volume estimates while retaining deduplication history; the engine retains its maximum volume estimate across the disconnect. Subsequent fill counts can still be understated. WebSocket, soft death.

Concurrency and shutdown limits

The inventory callback runs on the WebSocket thread and changes pending snapshots/version counters before scheduling onto the main loop. These compound state transitions violate the intended single-loop ownership; they require synchronization beyond the GIL. Two independently refreshed TokenIndex instances and a shared HTTP session add conditional consistency risks whose occurrence has not been reproduced. Callback.

Shutdown disables trading, attempts per-slug and account-wide cancellation, and clears local maps, but does not join every worker, detached submit/cancel, or underlying I/O thread. It does not fully close the session/executor or unregister all callbacks. The service invokes this before canceling producers. An already-running request can finish afterward. The calibrator's handle is not retained in the explicit shutdown list, although asyncio.run normally cancels remaining tasks at loop teardown. Engine shutdown, service teardown.

The inactivity loop stays alive and sleeps when disabled, while resume starts another loop, permitting duplicates. Deferred reconnect handling also lacks a comprehensive stop/join protocol. These paths, hard exits, and ambiguous network acknowledgments mean shutdown cannot certify that the account has no active orders or positions.


7. Configuration, dependencies, logging, and troubleshooting

Configuration reference

The table lists source defaults; training CLI defaults and saved run arguments are documented in the model chapters. Credential values are omitted. During TradeSession initialization, the parser reads key.env from the process's working directory, accepts simple KEY=VALUE lines, and applies os.environ.setdefault. Existing environment variables take precedence. Quotes are retained literally, and shell export/multiline syntax is unsupported. Parser.

Loading order affects overrides. The asset limits in BASE_CFG, the module-level order/timing settings, and the model switches, paths, and prediction intervals in live_prediction.py are evaluated during import. In the live entrypoint, TradeEngine also reads its I/O settings before creating the session that loads key.env. Overrides for these values must already be in the process environment; later file loading leaves their initialized values unchanged. Session settings such as PM_OWNER_ID and WS_SEEN_LIMIT are read after the file has been loaded. Asset limits, order settings, model settings, engine initialization, session initialization.

Environment variable Default Effect
PRIVATE_KEY / PM_PRIVATE_KEY / PK Required, first available Signing key
PM_FUNDER / FUNDER Unset Funder; signature type 1 when set, 0 when unset
PM_ADDRESS Unset Fallback address for position checks
PM_OWNER_ID Derived API key Fill-attribution owner override
PM_TEMP_DIR temp Session token-index directory
WS_SEEN_LIMIT 20000 Matched-event deduplication capacity
MM_BTC_QSIZE 5 Quote size for every asset
MM_BTC_INVCAP BTC 20, others 15 Inventory cap for every asset
MM_BTC_VOLCAP 20000 / 2500 / 1500 / 1500 Fill-share caps: BTC / ETH / SOL / XRP
MM_POST_SUBMIT_WAIT_S .002 Pause after scheduling submission
MM_ORDER_TTL_S 0 Per-order TTL; zero disables
MM_TTL_POLL_INTERVAL_S .25 TTL scan interval
MM_ORDER_TTS_CANCEL_S .5 Local snapshot inactivity threshold
MM_INACTIVITY_POLL_S .10 Scan interval, minimum .05
MM_MAX_SUBMITS_PER_SEC 1.0 Per-slug batch rate, integerized in check
MM_MAX_LIVE_PER_SIDE 4 Local live-order cap per BUY/SELL side
MM_MAX_SAME_PRICE 2 Local cap per token/side/price
MM_IO_EXEC_WORKERS 8 Blocking I/O worker pool
MM_MAX_PARALLEL_IO 8 I/O semaphore capacity
MM_IO_TIMEOUT_S .8 Outer asynchronous timeout
MM_IO_RETRIES 2 Total I/O attempts
MM_IO_BACKOFF_S .05 Base randomized retry delay
ENABLE_SEQ 1 Enable Model B
SEQ_RUN_DIR runs_seq_t B checkpoint/config directory
SEQ_DATA_DIR data_seq32 B feature/normalization metadata
SEQ_CKPT model_best.pt B checkpoint filename
SEQ_PRED_MIN_INTERVAL_MS 50 B per-asset prediction interval
ENABLE_IV 1 Enable Model C
IV_RUN_DIR runs_iv_delta C checkpoint/decoder directory
IV_DATA_DIR data_iv64 C normalization metadata
IV_PRED_MIN_INTERVAL_MS 50 C per-asset prediction interval
IV_ROLL_CLEAR_EPS_SEC 1 C clearing delay after boundary
CB_MISSING_LOG_GRACE_SEC 2.0 Missing-data warning startup grace
CB_MISSING_LOG_RATE_SEC 2.0 Missing-data warning interval
CB_L2_FEATURE_INTERVAL_S .10 L2 recomputation interval
CB_ROTATE_MAX_BYTES 67108864 Raw Coinbase file rotation when enabled
CB_FLUSH_EVERY 200 Raw Coinbase flush cadence when enabled
LIVE_LOG_STDOUT 1 Main log stdout mirror

The trader requires C-derived mid/half-spread fields; disabling C leaves the quoting path without these inputs. Several paths and asset lists are hardcoded. Authentication initializes a Polygon chain-ID-137 CLOB client and derives API credentials through the venue; launching the live entrypoint initiates authenticated network activity. Session construction.

Dependencies and checkpoint loading

Imports require PyTorch, NumPy, pandas, SciPy, scikit-learn, matplotlib, aiohttp, websockets, websocket-client, requests, and py-clob-client. There is no dependency lockfile or tested environment specification. Syntax such as slotted dataclasses implies Python 3.10 or newer for normal execution. Compatibility still depends on the specific dependency versions. Training code supports CPU/CUDA selection.

Model A explicitly calls torch.load(..., weights_only=False), allowing pickle execution. B/C omit that argument, making behavior version-dependent: PyTorch documents a default of weights_only=True starting in 2.6 when no pickle_module is supplied; older defaults were permissive. Restricted loading still carries security risks. Never substitute an untrusted checkpoint. A loader, B loader, PyTorch serialization documentation.

Logs and runtime files

Each main-log line contains a timestamp/level prefix followed by JSON; parsers must handle the prefix before decoding the JSON payload. The formatter can produce duplicate/misplaced UTC Z markers. Rotation is 10,000,000 bytes with up to 4096 backups. A per-decision salt joins prediction, quote, and order logs; the submission retry path lacks an idempotency protocol. hub_debug.py writes public-attribute snapshots in JSONL format once per second, excluding private trade rings, EWMA state, and calibration state. There is no implemented terminal dashboard; refresh_event has no consumer. Logger, hub dumper.

Runtime path Contents
data/logs/live_predictor.log Timestamp/level-prefixed JSON events
data/debug/hub-NNNNN.jsonl Public hub snapshots, 50 MB rotation
data/polymarket/resolution/*.jsonl Chainlink boundary records
data/polymarket/rtds-other.jsonl Other RTDS messages
temp/{slug}.json Discovered market metadata
logs/ws_user/sent/ Plaintext API key, secret, and passphrase in subscription payloads
logs/ws_user/recv/, logs/ws_user/matches/ User-channel events and matched trades
logs/inv_watch/ Wallet address, token IDs, and account positions

Read-only troubleshooting guide

Symptom in existing logs Source-level explanation to inspect
No A prediction Ring below 300 emitted rows; missing minute row; reseed; incompatible checkpoint/scaler
waiting_prevclose_coinbase No local pre-boundary history; startup did not backfill Coinbase
skip_cb_tick_pred_no_fresh_model A prediction missing or over 20 seconds old
skip_stale_pm_ts Per-asset PM age over 10 seconds; subscription gap or stale book
B/C not ready B needs 32 contiguous ticks; C needs 16 events with gaps at most one second
C delta/half-spread rejection Model output exceeds .03/.04 gates or predicted band misses observed spread
Successful cancel log but venue order remains Local removal precedes confirmation; failed/ambiguous response or in-flight submit
Unexpected zero diagnostics B quote_debug type mismatch; the trading signal is computed separately
resolution failure after record creation Duplicate event keyword in Chainlink logging
Silent process disappearance Position guard os._exit; inspect retained local logs without publishing secrets

Use this reference to interpret existing logs offline. Current exchange API compatibility remains unverified.


8. Training procedures, artifacts, and reproducibility

Saved model inventory

Artifact ZIP members / storages State elements Trainable parameters
runs/BTC/artifacts/model_checkpoint.pt 85 / 79 814,277 420,995
runs/ETH/artifacts/model_checkpoint.pt 85 / 79 814,277 420,995
runs/SOL/artifacts/model_checkpoint.pt 85 / 79 814,277 420,995
runs/XRP/artifacts/model_checkpoint.pt 85 / 79 814,277 420,995
runs_seq_t/model_best.pt 70 / 64 2,596,156 2,596,156
runs_iv_delta/model_best.pt 73 / 67 1,492,808 1,492,808

The saved tensor storages use float32, and all tensor values are finite. Total trainable parameters are 4*420995 + 2596156 + 1492808 = 5772944. Tensor structure alone does not establish that model inference will succeed. B/C checkpoints are state dictionaries; architecture and decoding also depend on external JSON. A contains model config, scalers, date ranges, epoch summaries, selected-epoch metrics, a PIT calibrator, and a save timestamp.

Recorded A results and data ranges

All A checkpoints record training dates 2025-02-14 through 2025-12-14 and test dates 2024-12-01 through 2025-02-13. The evaluation uses a test period earlier than the training period. Each selected-epoch metric set records 4,198,319 training, 1,036,795 validation, and 1,295,282 test samples. All four were saved on December 16, 2025. The values below are rounded from the metrics stored in the checkpoint metadata.

Asset Selected epoch Validation NLL Stored ece KS D Mean iv Mean df
BTC 6 -5.553313 .000490308 .0106356 .001499341 6.824050
ETH 6 -5.022279 .000246560 .0061785 .002364110 5.951548
SOL 7 -4.792816 .000575636 .0176308 .003028617 7.614213
XRP 8 -4.935689 .000498811 .0091836 .002699561 7.406803

Selected epoch need not have the numerically lowest last-decimal NLL because the training improvement threshold is 1e-4. Negative NLL is valid for a continuous density in small return units. Stored KS p-values are very small. Temporal dependence, missing dataset construction, and the identified feature-timing concerns limit interpretation of these values and the nonstandard ece. Future calibration quality and trading performance remain unverified by these metrics.

B/C metadata and training artifacts

Model B metadata lists 3019 training and 756 validation shards, with 6,574,548 and 2,123,004 samples. The shard lists are split at slug granularity and place validation later than training within each asset. History-root labels reference six collection directories; directory names alone do not establish continuous collection coverage. The weighting metadata records power_law_per_base, z0=1, lambda=1, p=1.5, and wmax=16; the exact builder formula is unavailable.

Target sigma BTC ETH XRP SOL
ret_2s .00011779 .00016510 .00018418 .00018367
ret_5s .00018863 .00026412 .00029160 .00028869
ret_10s .00026799 .00037589 .00041408 .00040852

C normalization and decoder files preserve feature/label names and scales but no full dataset or validation results. The current training programs save arguments, normalization, epoch telemetry, optimizer-bearing epoch checkpoints, and best model state; most historical outputs of those types are absent. Saved args.json records the run settings.

What cannot be reproduced or established

The repository cannot regenerate the six historical models without lost datasets/builders and the missing A driver. It cannot establish exact B/C label timing, collection completeness, historical environment versions, model quality on a new market regime, fills, P&L, fee impact, or measured latency. Preprocessing compatibility, decoder compatibility, and deployment readiness each require separate verification beyond tensor architecture. Reimplementing a builder from runtime code would produce a new experimental dataset with its own construction choices.

Historical training details still unresolved include whether B was fine-tuned, C's horizon-sampling distribution, the source-version chronology, and the exact shell commands and source revisions used for training. The surviving code is useful for studying implementation choices and failure modes within these limits.


9. Verified findings, limitations, and security

Publication and runtime security

The WebSocket subscription payload writes the derived API key, secret, and passphrase to logs/ws_user/sent/; the position guard writes wallet/account holdings to logs/inv_watch/. These files are generated during runtime. The checkout currently contains none of these generated logs. The owner ID is resolved from PM_OWNER_ID or the derived API key. Subscription dump, position snapshot.

The .gitignore excludes data/, temp/, key.env, and logs/, but does not comprehensively cover environment-file variants, private-key files, caches, or outputs written into other directories. Ignore rules do not protect archives or already-tracked files. Checkpoints and saved arguments can contain metadata and paths. Check authentication files and generated account data before publishing. Permissive checkpoint loading is covered in dependencies.

Issues and implementation limitations

The table covers defects, conditional risks, configuration and compatibility constraints, and metric definitions. The category identifies the nature of each entry. “Confirmed” means the behavior follows from source inspection; its financial consequences remain unverified. Each entry links to its technical explanation and supporting evidence.

ID Category Behavior, impact, and evidence
1 Unused configuration MMParams does not drive quote pricing; rho is logged. Center
2 Confirmed defect Every asset reads BTC-named configuration variables. Inventory
3 Documentation mismatch The position guard uses 4× cap; its comment specifies 3× and understates the threshold. Timing
4 Conditional safety risk Hard exit bypasses cancellation; outstanding orders may remain. Timing
5 Compatible fallback buy/sell falls through to score-sign interpretation; no demonstrated direction reversal. B policy
6 Confirmed diagnostic defect Dict/list mismatch leaves aggregate B diagnostics zero. B policy
7 Confirmed input defect pm_imbalance_top does not populate pm_imb_top; raw zero precedes z-score. C inputs
8 Confirmed input defect Live ingestion omits model_df; raw zero precedes z-score. C inputs
9 Conditional correctness defect Partial acceptance can misassociate accepted IDs with original order metadata. Orders
10 Conditional safety risk Ambiguous submit/retry can duplicate exposure; no resolving idempotency protocol. Orders
11 Policy divergence The trader's >.1 threshold can activate one-sided behavior before B's .8 flag. Inventory
12 Qualified accounting risk Soft-death resets session counters while the engine retains the previous maximum; subsequent counts can lag actual fills. Timing
13 Operational limitation No dedicated 429 policy; retry behavior differs by request path, and some non-200 responses return immediately. Feeds
14 Conditional concurrency risk Shared mutable HTTP session has no explicit per-request synchronization; failure not reproduced. Shutdown
15 Conditional consistency risk Two token indices refresh independently. Shutdown
16 Policy scope risk Four-asset position checks can terminate a BTC-only session. Timing
17 Confirmed state defect PM book state survives rollover before a new snapshot. Feeds
18 Lifecycle limitation Calibrator omitted from explicit task teardown; loop teardown can still cancel it. Shutdown
19 Unused signal refresh_event has no consumer, so emitting it produces no dashboard update. Logging
20 Confirmed configuration defect Both trainers ignore --grad-clip-norm and use 1.0. B loss, C compatibility
21 Conditional training defect C clips scaled gradients under AMP; saved args disable AMP. C compatibility
22 Default-objective limitation A's default probability multiplier has no prediction dependence; exact cancellation depends on clipping/epsilon. A training
23 Metric distinction Training optimizes weighted NLL; validation measures unweighted NLL, so their values reflect different weighting. A training
24 Unused constant No hard IV_FLOOR is applied in forward. A network
25 Documentation mismatch A uses .0005 for its output scale coefficient; the docstring specifies .0004. A network
26 Unused artifact Saved PIT mapping is not used live; market calibration is separate. A runtime
27 Confirmed contract mismatch Current C training and retained runtime metadata decode spread differently; chronology unknown. C compatibility
28 Compatibility constraint B and C swap SOL/XRP IDs but each engine uses its own mapping correctly. Models
29 Training-order limitation No within-shard shuffle; actual correlation cannot be measured without data. B loss
30 Training-data risk Available A helpers select full-minute features at the minute-open index, creating intraminute look-ahead; the historical driver is unknown. A training
31 Live-data risk Forming REST candles can be frozen as live minute features: there is no close-time check, and insertion requires a later opening timestamp. A runtime
32 Train/serve skew A's live second-level sequence omits empty seconds and accepts backward timestamps; historical inputs use a complete grid, creating a timing mismatch. A runtime
33 Confirmed precision defect B loses timestamp precision before recentering; float32 epoch seconds have 128-second spacing near the saved period. B preprocessing
34 Metric-definition limitation A's ece measures within-bin mean offsets; all observations at one bin midpoint can yield zero error despite nonuniform PIT. A runtime
35 Conditional order-state risk Cancellation bookkeeping can diverge from the venue through removal before confirmation, incomplete response interpretation, and incomplete fill reconciliation. Orders
36 Conditional execution risk Async timeout or shutdown does not stop blocking submissions; an in-flight thread can complete a submission afterward. Orders, shutdown
37 Position-accounting limitation Position estimates omit startup balances and settlement reconciliation, so they can diverge from actual account holdings. Inventory
38 Conditional concurrency risk The inventory callback mutates loop-owned state from another thread without synchronizing compound pending-snapshot/version changes. Shutdown
39 Freshness-check limitation Heartbeat can repeat stale Coinbase data; field and cache ages are not comprehensively checked. Shared state
40 Conditional state risk Rollover reset does not cancel pending Model C prediction drain tasks, which can repopulate the cache with results for the preceding contract. Shared state
41 Token-mapping consistency risk Token-selection paths differ: the CLOB reader drops outcomes, while the execution index retains them. Feeds
42 Input-update limitation Quantity-only PM changes do not trigger C book ingestion, so hub updates and the C event stream can diverge. Feeds
43 Conditional logging defect Chainlink logging can raise after state/file writes because event is passed both positionally and by keyword. Reference prices
44 Conditional lifecycle risk Resume can duplicate inactivity loops: disabled loops survive, and resume creates additional instances. Shutdown
45 Model/loading compatibility risk Fallbacks can select a wrong-asset A model or omit its scaler; data-loader prefetch settings also have zero-worker compatibility constraints. A runtime, A training
46 Order and risk-control limitation Taker fills and post-fill inventory beyond the limits remain possible: crossing checks use the predicted book and inventory filters use current balances. Width, inventory
47 Invalid-output handling risk Invalid model outputs can become apparently usable results: B sanitizes nonfinite outputs, and C can decode from a zero reference. B network, C sequences

Additional issues may remain. The entries describe code behavior and its limitations; any causal relationship with historical trading losses remains unverified.

License and scope

Sustainable Use License 1.0 © QuantumSlayer. This project is source-available; see the project README for a permissions summary and the full English license for the governing terms. This manual documents archived code for technical research. The system is unmaintained and unsafe to connect to a funded account. Current exchange behavior, eligibility rules, and compatibility were not tested.