The tape in late November 2026 has been unkind to anyone who came into the quarter long risk and short volatility. According to the news snapshot embedded in the research run I am dissecting today, the S&P 500 sat roughly 11.6% below its October 6 record, the Nasdaq-100 was down about 15% for November on AI-capex fears, the market was pricing roughly a 96% probability of a 25 bp hike at the December FOMC, the dollar index had pushed to a 19-month high near 104.53, and the crypto Fear and Greed gauge was stuck at 20 with spot bitcoin ETFs bleeding billions in outflows. That is the backdrop against which a batch of systematic futures bots was designed, backtested and then redesigned.
This piece is a forensic, numbers-first walk through one complete research run: fifteen PDF reports generated on November 25, 2026, covering sixteen distinct trading bots across two generations. The first generation was ten macro-thematic futures bots built straight off the news flow, covering a 10-year note short, a euro short, a gold long, a crude short, a micro-bitcoin contrarian long, four single-stock futures ideas and a micro S&P short. The second generation was six micro-futures bots built explicitly to fix what the first generation got wrong.
The results are more instructive than flattering, and that is exactly why they are worth a long read.
Here is the short version. Of the ten first-generation bots, only one actually produced trades in the backtest that its own term sheet reports, and that one, a hawkish-CPI short on micro S&P futures, lost $8,997.23 on a $10,000 test allocation across 60 trades. Its win rate was 26.7%, its Sharpe ratio was -1.507, its profit factor was 0.645, and its reported maximum drawdown was 118.7%. The AI planner had projected a +38% annualized return and a Sharpe of 1.50 for that same bot. The realized backtest printed -78.9%.
The second generation tells a different story. Four of six Gen-2 bots finished in the green for a combined $27,234.84 of backtested profit:
A micro gold uncertainty-hedge long made $12,241.50, the largest absolute profit, but with a punishing 52.3% peak-to-trough drawdown.
A micro Nasdaq-100 risk-off momentum short made $7,834.18 with a 20.5% drawdown.
A micro S&P regime-adaptive long, the direct replacement for the failed Gen-1 short, made $6,950.27 with the best risk-adjusted profile in the entire run: Sharpe 1.124, Sortino 3.920, Calmar 1.477 and only a 9.4% max drawdown.
A micro copper AI-infrastructure long essentially broke even at $208.89.
Two Gen-2 bots lost money. A micro crude short lost $1,595.14, and a micro bitcoin contrarian long reported an impossible loss of $9,806,071.43, which turns out to be a contract-multiplier bug rather than a trading result. More on that below, because spotting that kind of error is half of what separates a research desk from a backtest casino.
So what is the most profitable institutional options and futures strategy this run points to? It is not a single bot. When you line the Gen-2 sleeves up against each other, their monthly P&L correlations are low, and the structure that emerges is a three-legged book:
A gold trend sleeve, which carried the most raw profit, expressed with defined-risk call spreads or skew-financed risk reversals instead of naked futures, because its drawdown profile is too violent to carry outright.
An implicit long S&P / short Nasdaq relative-value pair. That is what you actually own when you run the Gen-2 MES long and the MNQ short side by side, and it had the smoothest equity curve in the run.
Event convexity in rates and index options around the December FOMC, using straddles and collars rather than directional futures, because the macro picture in the report is genuinely two-sided.
In the paid section I go through every number, every chart and every data error, and then build the full institutional toolkit around it. That means payoff diagrams for each options structure, Black-76 pricing and Greeks, Kelly sizing, VaR and CVaR, GARCH, the deflated Sharpe ratio, dealer gamma exposure, the volatility risk premium, Avellaneda-Stoikov market making, order-book microprice and Almgren-Chriss execution. It finishes with copyable Python analytics and an ultra-low-latency C++ infrastructure kit: a lock-free SPSC ring buffer, cache-line alignment, a fixed-point price type, an L2 book with microprice and imbalance, and a busy-poll event loop timed with rdtsc.
One ground rule before we go further. The specific entry and exit logic, parameters, filters and sizing caps of these bots are proprietary, so I describe them only conceptually and use pseudocode where logic needs to be illustrated. Everything quantitative beyond the bots themselves, meaning the formulas, the payoff math and the infrastructure code, is generic, textbook-grade material that you can lift straight into your own research stack.

Every figure in this article is hypothetical, simulated backtest output, not live trading. Backtests are built with hindsight and do not capture every cost, slippage event or liquidity gap. Nothing here is a recommendation to buy or sell anything, and past or simulated performance does not predict future results.
Part 1: What is actually in the fifteen PDFs
Before analyzing a single number, it is worth being precise about provenance, because the run contains duplicates, stale sections and AI projections that look like backtest results if you are not careful.
The fifteen files fall into three folders: the root run folder, a gen2 subfolder and a gen2/micro_futures subfolder. Here is what each contains.
trading_report (107 pages) is the macro research engine’s raw output. It holds several long-form institutional futures and options-on-futures write-ups built from the day’s news feed, covering rates, FX, equity index, volatility, commodities, crypto, cross-asset correlation and an event calendar, plus a single-stock-futures scan. It still contains the language model’s visible “Thinking...” scratchpads, six of them, which is a formatting artifact worth cleaning up before any of it is shared.
trading_analysis (24 pages) is the Gen-1 portfolio dashboard: ten bots, cost and margin estimates, AI-projected performance metrics for each bot, a stale options-chain context block, and per-bot backtest panels.
trading_bot_backtest (45 pages) is the Gen-1 term sheet with full failure diagnostics for the one bot that traded, the micro S&P hawkish-CPI short, and empty panels for the nine bots that produced no trades.
trading_bot_portfolio (8 pages) is a Gen-1 portfolio summary with capital, margins, projected risk metrics and a single-stock-futures symbology appendix.
trading_bot_profitable_rules, trading_bot_options_chain_analysis and trading_bot_integration_signals (13, 5 and 3 pages) each present two “profitable” Gen-1 bots, gold and the 10-year note, with paraphrased risk protocols, options-deployment guidance and integration-signal status. As I explain below, those two bots’ numbers contradict the main Gen-1 backtest.
gen2/trading_bot_backtest (35 pages) is the Gen-2 term sheet with full metrics, monthly return grids and recent trade lists for all six micro bots.
gen2/trading_bot_profitable_rules, gen2/trading_bot_options_chain_analysis and gen2/trading_bot_integration_signals (25, 10 and 5 pages) cover the four profitable Gen-2 bots.
The four gen2/micro_futures files duplicate the gen2 set. The backtest, options-chain and integration-signals files differ from their gen2 twins only in the folder label and a timestamp a few seconds apart. The profitable-rules file has the same numbers but different paraphrased protocol wording, by design, since the generator rewrites the protocol text to protect the underlying rule set. Both versions frame the four profitable bots as +27.2% on a $100,000 allocation, even though the Gen-2 term sheet tests each bot on its own $50,000, which is another normalization to watch.
So the fifteen PDFs reduce to eleven unique documents: seven root reports and four Gen-2 reports, with the micro_futures folder acting as a mirror.
The second provenance point is more important. These reports mix three very different kinds of numbers:
Backtest results: simulated trades on roughly a year of historical intraday futures bars from the broker feed.
AI planner projections: a projected annual return, Sharpe, win rate and so on for each bot, generated before the backtest ran.
Narrative market context: CPI prints, rate-hike odds and price levels extracted from the news feed by the language model.
Only the first category is evidence. The second is a hypothesis. The third is a claim that needs verifying against market data before you trade on it.
Part 2: The data-integrity audit
A research report is only as good as its weakest number. Here is every error, inconsistency or implausible value I found, in rough order of severity. None of this is a criticism of the idea-generation process. It is the normal output of any automated pipeline that has not yet had a reconciliation layer bolted on, and it is exactly what an institutional risk team would catch on day one.
1. A micro bitcoin contract-multiplier bug. The Gen-2 MBT contrarian long reports a net P&L of -$9,806,071.43, a max drawdown of $25,715,357.14, an annualized return of -62,247.2%, a VaR of 10,107.9% and a single best month of +18,830%, all on a $50,000 test allocation. The trade list makes the cause obvious. The first listed trade enters at $78,665.00 and exits at $77,527.14, a move of $1,137.86 per bitcoin, yet it books -$2,275,714.29. CME Micro Bitcoin is one-tenth of a bitcoin, so that move is worth about $113.79 per contract, and any realistic micro position should lose hundreds of dollars, not millions. At the bot’s position size, the engine is overstating MBT P&L by a factor of about 10,000, roughly four orders of magnitude. Divide everything by 10,000 and the bot’s corrected result is roughly -$981 over 22 trades: a small loser, not a portfolio-ending catastrophe. The same bug also poisons every portfolio-level aggregate in the Gen-2 term sheet. The “combined P&L” of -$9,780,431.73 and “worst DD 51431%” are meaningless until it is fixed.
2. Two contradictory Gen-1 result sets. The Gen-1 profitable-rules, options-chain and integration-signals PDFs, generated at 16:11, present the gold long as having made $111,227.14 (53% win rate, Sharpe 1.55, profit factor 2.40, 17 trades) and the 10-year note short as having made $1,673.85 (39% win rate, Sharpe 0.37, 28 trades). The main Gen-1 backtest and analysis PDFs, generated three minutes later at 16:14, show both bots with zero trades and $0.00. They cannot both be true. The likeliest explanation is that the 16:11 documents come from an earlier backtest pass that was later superseded.
3. Impossible drawdowns. Even taken at face value, the $111,227 gold figure comes with a 197.3% max drawdown and is framed as +444.9% on a $25,000 allocation. The Gen-1 MES short reports a 118.7% max drawdown ($11,874.64 on $10,000). A drawdown above 100% means the account went negative, which in live trading means a margin call and forced liquidation long before the curve could recover. The backtester needs either a hard equity floor (stop the simulation at zero) or proper margin-call logic.
4. Status labels that contradict themselves. The Gen-1 summary table labels nine zero-trade bots as “PROFITABLE” with $0.00 P&L, while the header of the same document says “Profitable: 0 | Unprofitable: 10”. The dashboard headline reports “Bots w/ trades: 0” and “Total trades: 0” while the MES panel lower down shows 60 trades. A zero-trade bot should be labelled NO_TRADES, never PROFITABLE.
5. Three different margin assumptions for the same contracts. The Gen-1 analysis assumes $8,000 of margin per contract for every instrument, from micro S&P to 10-year notes to micro single-stock futures. The portfolio summary uses $1,200 for MES, $2,200 for ZN, $3,500 for full-size gold and $800 for micro crude. The MES failure panel quotes $1,300. Real exchange margins move with volatility, but $8,000 per micro S&P contract is several times too high, and $3,500 for a full-size 100-ounce gold contract at gold prices above $4,500 is far too low. Margin feeds the leverage, Kelly and VaR calculations, so this matters.
6. “Micro futures” labels on full-size contracts. The Gen-1 gold and 10-year note bots trade GC and ZN, which are full-size contracts, yet several reports file them under “Micro Futures Only”. That is not cosmetic. A full-size GC contract is ten times the notional of MGC, and that may be part of why the Gen-1 gold figures look so extreme.
7. A stale and mislabelled options chain. Every options-overlay section relies on an “ESM26” chain dated November 19, six days stale, with a futures mid of 0.00, zero strikes with live Greeks, 40 clean quotes and total open interest of 55. ESM26 is the June 2026 contract code, yet it is listed with an active expiry of 2026-12-18, the December contract’s date. The resolution hints also suggest June-2026 codes (GCM6, ZNM6, MEM6 and so on), all of which expired months before this run. Every option Greek in the run is therefore missing, and the overlay guidance is generic. Fixing the contract-roll logic so the chain finder targets the live front month (December 2026, then March 2027) is the single highest-value repair for the options side of this pipeline.
8. Backtest windows that do not match. The term sheet says each backtest uses one year of history, yet the MGC bot reports 16 months of P&L (August 2025 through November 2026), while the MES Gen-2 bot reports 9 active months. Different warm-up periods and data availability are normal, but then the annualized metrics are not comparable across bots without normalizing.
9. Narrative numbers that contradict the price data. One section of the macro report says gold is “down 37% from Jan record, now below $3,500”. Yet the MGC backtest’s own trade list shows entries around $4,552 to $4,672 per ounce in late 2026. Core PCE is described as “≥3.0%” in one section and “3.3%” in another, and the CPI headline is cited as 3.8%. The language model’s extraction of the news feed is not a market-data source. Any level that drives a decision should be pulled from a price feed.
10. Projections that miss badly. The ten Gen-1 bots were projected to average a 39.0% annual return, a 1.57 Sharpe and a 53.4% win rate. The one bot with a backtest came in at -78.9%, -1.507 and 26.7%. That is not an error in the strict sense, but it shows that the planner’s projections carry essentially no information and should never be shown alongside backtest numbers without a heavy caveat.
The good news is that once you correct for these issues, the core Gen-2 numbers reconcile perfectly. I re-added every monthly P&L grid and they match the reported totals to the dollar. The per-trade arithmetic for MGC, MNQ, MES, MCL and MHG matches the published contract multipliers. The reported Kelly fractions match the textbook formula applied to the reported win rate and average win/loss. So the Gen-2 book is the part of the run you can actually reason about.
Part 3: Gen-1 post-mortem, or how a correct macro thesis lost 90% of its capital
The first-generation book was a set of ten macro-thematic ideas, each with a clean narrative:
Short 10-year note futures into a hawkish December FOMC after a hot inflation print.
Short the euro on dollar strength.
Long gold on geopolitical and regulatory uncertainty.
Short micro crude into an OPEC+ meeting where members were pushing for higher capacity baselines.
A contrarian long on micro bitcoin at extreme fear.
Four single-stock-futures ideas: a Micron “fire-sale” long, a Walmart visibility long, an Apple defensive-rotation long and an Alphabet credit-cost short.
A micro S&P short on the hawkish-CPI thesis.
Each idea came with a projected timeline of one to four weeks, a projected Sharpe between 1.40 and 1.80, a projected win rate between 50% and 58%, and a profit-potential range in the high hundreds to low thousands of dollars per bot. The book’s total planned capital was $114,000.
Nine of the ten never traded in the backtest. Every one of their panels shows zero trades, zero P&L and zero Sharpe. Conceptually, that means one of two things. Either the entry gate was so selective that it never fired across a full year of history, or historical data for that instrument was not available to the backtester. Some single-stock futures are thinly traded, and their historical bar data from a retail broker feed can be sparse or absent. The dashboards also show no data polling and no ticks processed for any bot, so the live side of the pipeline was not connected during this run either. Either way, a bot that cannot generate a trade cannot be evaluated, so these nine ideas remain hypotheses.
The one bot that did trade was the micro S&P hawkish-CPI short. Conceptually, it sold micro S&P futures when its momentum and volatility-regime logic confirmed the hawkish-inflation thesis, used a volatility-scaled protective stop, and cut size in high-volatility regimes. The result over one year of history:
Net P&L: -$8,997.23 on a $10,000 test allocation.
60 trades: 16 winners and 44 losers, a 26.7% win rate.
Average win $1,022.88 versus average loss $576.44, a payoff ratio of about 1.77.
Largest win $1,881.96, largest loss $1,153.66.
Profit factor 0.645, Sharpe -1.507, Sortino -5.245, Calmar -0.758.
Max drawdown $11,874.64, or 118.7% of the allocation.
95% VaR of 10.8%, and a longest losing streak of 8 trades.
Three profitable months out of twelve. The best month was March 2026 at +$1,197 (+12.0%). The worst was June 2026 at -$3,288 (-32.9%), followed by July at -$2,602 (-26.0%).
Full Kelly fraction: -14.7%. A negative Kelly is the mathematical way of saying “the edge has the wrong sign, so do not take this bet at any size.”

The diagnosis in the report itself is blunt: poor entries, with signals triggering on noise. But there is a deeper lesson in the arithmetic. With a payoff ratio of 1.77, the breakeven win rate is
The bot won 26.7% of the time, nearly ten percentage points short of breakeven. Expectancy per trade was
That matches the report’s average trade P&L of -$150. The median trade lost $431, and the trade P&L distribution has a skew of +0.7. That is the signature of a strategy that bleeds small, frequent losses and occasionally lands a winner. It works only if the winners are much larger, or much more frequent, than they were here.
Now look at the timing. The last twenty trades run from early September to November 25, 2026. Through September and October the bot was repeatedly stopped out as the index held up. Then in mid-November, when the selloff finally came, it caught three consecutive target hits worth $1,391.25, $1,881.96 and $1,818.75 as micro S&P fell from the mid-7,500s to just under 7,000. It then gave back two stop-outs of about $1,100 each on the rebound.

This is the classic way a correct macro thesis loses money: being right about direction and wrong about timing. The hawkish-CPI story was in the market for months, but the index did not break until November. A short that pays a stop-out every time the market grinds higher bleeds capital for most of a year waiting for the move. By the time the move arrives, the account is so depleted that even the best stretch of trades cannot repair it.
Three institutional takeaways follow.
First, a macro thesis is not a signal. An institutional desk would express a hawkish-CPI view through instruments whose payoff does not require precise timing: long put spreads, put calendars or a short-NQ / long-ES relative-value trade. It would not use a naked short in an index that was still making highs.
Second, regime awareness matters more than signal precision. The Gen-1 short traded the same way in an uptrend as in a downtrend. The Gen-2 redesign, as we will see, solved this by flipping the logic to regime-adaptive.
Third, projections are not evidence. The planner projected +38% annualized and a 1.50 Sharpe. The backtest delivered -78.9% and -1.51, a miss of nearly three Sharpe units. Any process that mixes projected and backtested metrics on the same dashboard invites exactly this kind of overconfidence.
Part 4: The Gen-2 redesign, bot by bot
The Gen-2 book is explicitly a repair job. Its six bots are all micro contracts:
Micro gold (MGC).
Micro Nasdaq-100 (MNQ).
Micro S&P (MES).
Micro copper (MHG).
Micro crude (MCL).
Micro bitcoin (MBT).
Each carries a label naming the Gen-1 failure it was designed to fix, such as “Gen-1 Short Fix”, “Gen-1 OPEC+ Fix”, “Gen-1 Crypto Fix” and “Gen-1 GC Enhancement”. Each bot was tested on its own $50,000 allocation. Conceptually, all of them share a family resemblance: a composite momentum or trend-confirmation gate, volatility-scaled stops and targets with a positive reward-to-risk design, and volatility-regime size scaling. The specific scores, filters, timeframes and multiples are proprietary, and I will not go into them.
The easiest way to evaluate them is through the lens that matters most to a risk manager: how much margin each bot’s win rate has above its own breakeven win rate. The breakeven is set by the payoff ratio, as shown above.
MGC Uncertainty-Hedge Long: the biggest profit and the scariest ride
Net P&L: $12,241.50 over 115 trades (48 winners, 67 losers, a 41.7% win rate).
Average win $1,770.27 versus average loss $1,085.54, a payoff ratio of 1.63 and a breakeven win rate of about 38.0%. The cushion above breakeven is about 3.7 points.
Profit factor 1.17, Sharpe 0.726, Sortino 2.237, Calmar 0.468, annualized return 14.9%.
Max drawdown $26,137.14, or 52.3%. Longest losing streak: 12 trades.
Full Kelly 6.0%, 95% VaR 3.6%.
Sixteen months analyzed and 56% of them profitable. Average month +1.53%, best month +31.61%, worst month -24.12%.
The monthly path explains both the profit and the pain. The bot made money every month from August through December 2025 (+$1,666, +$4,391, +$4,041, +$1,493, +$1,200), then had an explosive January 2026 at +$15,804 and a strong February at +$7,173. By then it was up roughly $35,768. March gave back $12,060 in a single month, and from April through November 2026 the bot lost money in six of eight months, ending the window at $12,241.50.
In other words, almost all of MGC’s profit was earned in a seven-month gold trend. Since then it has been in a sustained drawdown.
The Sortino of 2.237, much higher than the Sharpe of 0.726, tells you the volatility is skewed to the upside: the big months are up months. That is exactly the profile of a trend-following long in a commodity with fat right tails, and it is the profile that benefits most from an options overlay. I will come back to that in the strategy section.
MNQ AI-Risk-Off Momentum Short: the profitable short Gen-1 never had
Net P&L: $7,834.18 over 70 trades (26 winners, 44 losers, a 37.1% win rate).
Average win $2,482.82 versus average loss $1,289.07, a payoff ratio of 1.93 and a breakeven win rate of 34.2%. The cushion is 2.9 points.
Profit factor 1.14, Sharpe 0.474, Sortino 1.760, Calmar 0.763, annualized 13.6%.
Max drawdown $10,263.75 (20.5%), longest losing streak 7, full Kelly 4.5%, VaR 4.6%.
Eleven months, 45% profitable. Best month July 2026 at +$10,138 (+20.3%), then October at +$6,571 (+13.1%). Worst month April at -$4,318 (-8.6%).
MNQ is the bot that got the Gen-1 idea right. It shorts tech beta, but only when a downtrend is confirmed rather than on the narrative alone. Its P&L is lumpy, with two months producing more than the full-period total, but it does not suffer the slow bleed that killed the Gen-1 S&P short.
MES Regime-Adaptive Composite Long: the best risk-adjusted bot in the run
Net P&L: $6,950.27 over 46 trades (21 winners, 25 losers, a 45.7% win rate).
Average win $1,024.01 versus average loss $582.16, a payoff ratio of 1.76 and a breakeven win rate of 36.2%. The cushion is about 9.5 points, by far the widest in the run.
Profit factor 1.48, Sharpe 1.124, Sortino 3.920, Calmar 1.477, annualized 12.2%.
Max drawdown only $4,705.18 (9.4%), longest losing streak 5, full Kelly 14.8%, VaR 2.2%.
Nine active months, 67% profitable. Best month February 2026 at +$2,997 (+6.0%), and no month worse than -$616.
This bot is the direct replacement for the Gen-1 S&P short, and the contrast is striking. Instead of fighting the index, it buys confirmed upswings with mean-reversion-style exits, and it sits out regimes where its composite gate does not agree. Its recent trades show exits labelled as mean-reversion targets, which is consistent with the design.
One curiosity is worth checking in the trade records: this long bot’s largest loss is exactly -$1,153.66, the same figure to the cent as the Gen-1 short’s largest loss. It could be a coincidence of identical stop distances on the same contract. It could also be a shared trade-record bug.
MHG AI-Infrastructure Thematic Long: a thesis without an edge
Net P&L: $208.89 over 68 trades, a 36.8% win rate.
Average win $323.11 versus average loss $183.00, a payoff ratio of 1.77 and a breakeven win rate of 36.2%. The cushion is 0.6 points, which is statistically zero.
Profit factor 1.03, Sharpe 0.098, max drawdown 4.5%, full Kelly 1.0%.
The copper data-center and electrification thesis is a perfectly respectable macro narrative, but over this window the bot’s trades were a coin flip after costs. The report counts it as “profitable”, and technically it is. An allocator would classify it as flat.
MCL Confirmed Momentum Short: better than Gen-1, still negative
Net P&L: -$1,595.14 over 65 trades, a 30.8% win rate.
Payoff ratio 1.96 and breakeven 33.8%, so the bot is 3.0 points below breakeven.
Profit factor 0.87, Sharpe -0.477, max drawdown $5,539.50 (11.1%), and a 10-trade losing streak.
Only 23% of months were profitable, though November 2026 produced +$3,921 (+7.8%).
Converting the crude short from an unconditional headline trade into a trend-confirmed trade reduced the damage but did not create an edge. Crude in this period was driven by competing forces: Middle East supply incidents, the OPEC+ capacity debate and dollar strength. That is exactly the kind of two-sided tape where a directional momentum short struggles, and where calendar spreads or options structures make more sense.
MBT Capitulation Contrarian Long: the multiplier bug
As discussed in the audit, the reported -$9.81 million is a factor-of-roughly-10,000 multiplier error. The scale-invariant statistics are still valid, though:
A 27.3% win rate over 22 trades.
A profit factor of 0.78 and a Sharpe of -0.513.
One profitable month out of four.
They say the contrarian long did not work. The corrected dollar loss is roughly $981.



What is working, and why
Strip away the labels and three ideas are clearly working in this sample.
Regime-conditional participation beats thesis-driven conviction. Every Gen-2 improvement over Gen-1 came from adding a confirmation gate, which means waiting for price to agree with the macro story. The MES long and MNQ short are both “trade with the tape” designs.
Positive skew through asymmetric exits. Every profitable bot has a payoff ratio between about 1.6 and 1.9. None of them needs a win rate above 50%. The edge comes from letting winners run further than losers.
Gold as an uncertainty asset. In a run where the dominant themes were AI-capex fears, export-control geopolitics, sticky inflation and Fed uncertainty, the uncertainty-hedge long on gold earned the most money, even after a large giveback.
Three ideas are clearly not working: thesis-only shorts without trend confirmation, contrarian longs into crypto capitulation, and narrative commodity longs, like copper on AI infrastructure, whose demand story does not show up in the price path over the test window.
Part 5: How the bots fit together as a portfolio
Single-bot statistics tell you whether an idea has an edge. Portfolio statistics tell you whether the ideas belong together. Because the Gen-2 term sheet publishes a full monthly P&L grid for every bot, we can actually measure this, with one caveat: the overlapping window, February to November 2026, is only ten months long, so treat every correlation below as indicative.
Here are the pairwise correlations of monthly P&L over those ten months:
MGC and MNQ: -0.29. Gold longs and Nasdaq shorts were mildly negatively correlated. Both are “uncertainty” trades in theory, but they paid off in different months.
MGC and MES: +0.37. This was the highest correlation in the book.
MNQ and MES: +0.08. The S&P long and the Nasdaq short are almost uncorrelated, which is exactly what you want from the two legs of a relative-value pair.
MHG and MCL: -0.49. The two industrial-commodity bots offset each other, which is one reason neither adds much on its own.
Everything else falls between -0.21 and +0.11.

Low correlations mean the bots diversify each other, and the combined numbers show it. Summing the four profitable Gen-2 bots month by month gives $27,235 of total backtested P&L. The month-end drawdown is about $22,589, almost all of it from the gold sleeve’s March-through-November giveback, and the annualized monthly Sharpe of the dollar P&L stream is about 0.57. Take only the MES long and the MNQ short, which together form an implicit long-S&P / short-Nasdaq spread, and the picture changes. From February onward the pair made about $16,207 with an annualized monthly Sharpe of about 1.21, roughly double the four-bot book’s ratio, with much shallower drawdowns.

This is the most important structural insight in the run. The Gen-2 equity bots, which the pipeline treats as two separate directional ideas, are economically a relative-value trade. That trade is exactly what the macro report recommends institutions run in this tape: long the broader index, short the AI-concentrated growth index, sized to be beta-neutral rather than contract-for-contract. When you see two bots behave like one spread, the right move is to manage them as one spread. That means a single risk budget, a beta-adjusted hedge ratio and a combined stop.
Mean-variance view, with a large health warning
Feed the four profitable sleeves’ monthly returns into a classic Markowitz optimizer, with each bot’s monthly P&L divided by its $50,000 allocation, and the maximum-Sharpe mix comes out at roughly 90% MES, 9% MNQ and near-zero gold and copper. That result is mathematically correct and practically useless as an allocation. Ten monthly data points cannot estimate a four-by-four covariance matrix with any precision, and mean-variance optimizers are famous for amplifying estimation error into extreme weights. What the frontier is really telling you is that MES has the highest return per unit of volatility in this sample. You already knew that from its Sharpe. The frontier just shows it graphically.

The textbook mean-variance problem is
with the unconstrained tangency solution
Institutional practice replaces the noisy sample covariance with a shrinkage estimator such as Ledoit-Wolf,
where S is the sample covariance, F is a structured target such as constant correlation, and δ is the optimal shrinkage intensity. Many desks skip expected returns altogether and use risk parity or equal-risk contribution:
With bots this young, equal-risk contribution is the only defensible starting allocation.
Sizing: Kelly, fractional Kelly and why the reported Kelly numbers matter
For a binary bet with win probability p and payoff ratio b, the Kelly fraction that maximizes expected log growth is
and the expected log growth per bet at fraction f is
Plugging in the reported statistics reproduces each bot’s published Kelly exactly:
MGC: 0.417 - 0.583/1.631 ≈ 6.0%.
MNQ: 0.371 - 0.629/1.926 ≈ 4.5%.
MES: 0.457 - 0.543/1.759 ≈ 14.8%.
MCL: 0.308 - 0.692/1.963 ≈ -4.5%.
The growth curve is asymmetric. Betting twice full Kelly drives long-run growth to roughly zero, and anything beyond that is negative growth, which means eventual ruin. That is why professional sizing almost always uses a fraction, typically a quarter to half Kelly, of an estimate that is itself uncertain.
For continuous returns, the Kelly leverage is the ratio of excess return to variance,
and the growth rate at the optimum is half the squared Sharpe ratio, g* = SR²/2. A strategy with an annual Sharpe of 0.5 has a theoretical optimal growth rate of only about 12.5% a year before estimation error and costs. That sobering number is worth remembering whenever a backtest promises triple digits.
Monte Carlo: how lucky was the gold bot?
A useful sanity check is to resample a bot’s own reported statistics. Take MGC’s 41.7% win rate, $1,770.27 average win and $1,085.54 average loss, and simulate 5,000 alternative histories of 115 trades each. The median path ends at about +$12,240, essentially matching the reported result. The 5th percentile ends near -$13,460, and the 95th percentile near +$37,940. About 19% of the simulated histories lose money over the full 115 trades. So even if the edge is exactly as measured, there is roughly a one-in-five chance of a losing year from bad sequencing alone. And the real edge is surely smaller than measured, because the measured edge was selected.

The deflated Sharpe ratio: Gen-2 was fitted to the same history
This is the part most retail backtest reports skip. The Gen-2 bots were explicitly designed after looking at the Gen-1 failures, on the same one-year history. That is a textbook multiple-testing problem. Every redesign is another trial, and the best of many trials will look good by chance alone.
Bailey and López de Prado’s probabilistic Sharpe ratio (PSR) estimates the probability that the true Sharpe exceeds a benchmark SR*, given T observations, skewness γ₃ and kurtosis γ₄:
The deflated Sharpe ratio (DSR) sets the benchmark to the Sharpe you would expect from the best of N independent trials of skill-less strategies:
where γ ≈ 0.5772 is the Euler-Mascheroni constant. Treat the sixteen bots in this run as sixteen trials and assume a modest cross-trial Sharpe dispersion. The MES regime-adaptive long’s monthly Sharpe of about 2.1, measured over ten months, deflates to a DSR of roughly 0.75. The MES/MNQ pair’s deflates to about 0.48. The gold bot’s annualized monthly Sharpe of about 0.4, over sixteen months, deflates to about 0.17. None of them clears the conventional 95% confidence bar yet. That does not mean the bots are worthless. It means they need out-of-sample time, ideally live paper trading on new data, before anyone should size them as if the backtest were truth.

Risk metrics you should compute for every bot
The reports publish Sharpe, Sortino and Calmar. Here are the definitions, for completeness and so you can recompute them consistently across bots with different history lengths:
Here k is the number of periods per year. Value-at-Risk and expected shortfall (CVaR) at confidence α are
and under a Cornish-Fisher adjustment for skew S and excess kurtosis K, the parametric quantile becomes
Positively skewed trend strategies like MGC have Cornish-Fisher VaR below their Gaussian VaR. Negatively skewed short-volatility structures, like the iron condors discussed later, have the opposite. That difference is exactly why CVaR, not VaR, should be the risk budget for anything that sells optionality.
Part 6: The institutional drivers behind the trades
The macro report in this run is long and, at times, repetitive. Underneath, though, it identifies the same handful of forces that every institutional futures desk tracks. Here they are, with the formulas that make each one tradable.
1. The Fed path and the rates complex
The report’s core macro claim is a hawkish December: a hot inflation print (3.8% headline is cited), sticky core PCE, and roughly 96% odds of a 25 bp hike priced at the December 8-9 meeting. At the same time, the report describes a flight-to-quality bid in longer Treasuries as CTAs and quant funds unwind crowded bond shorts during the equity selloff, with the 10-year yield cited at 4.82%. A front end pinned by policy and a long end bid by growth fears is a bear-flattening, or outright flattening, curve, and the report’s preferred institutional expression is a 2s10s flattener: short 2-year note futures, long 10-year note futures, DV01-weighted.
The hedge ratio for a DV01-neutral curve trade is
using the cheapest-to-deliver bond’s DV01 divided by its conversion factor for each futures contract. Rate expectations are read straight off Fed funds futures, where the implied rate is 100 minus the price. The market-implied probability of a hike is approximately
with a day-weighting adjustment when the meeting falls mid-month.
2. The dollar
A 19-month high in the dollar index around 104.53 is the FX transmission of the same hawkish Fed. The report’s correlation section correctly warns that a long-dollar position and a short-gold position are largely the same bet, and that USD strength is a headwind for every dollar-denominated commodity. FX futures carry follows covered interest parity:
so the euro-futures basis is a direct read of the USD-EUR rate differential that the Gen-1 euro-short thesis was built on.
3. Equity index regime, dealer gamma and the volatility risk premium
With the S&P about 11.6% off its high and the Nasdaq-100 down about 15% in November, the report infers a VIX regime in the mid-20s to mid-30s. It does not actually quote a live VIX, which is another gap to fill from a data feed. Two institutional concepts dominate this regime.
Dealer gamma exposure (GEX). Options dealers who are net long gamma hedge by selling rallies and buying dips, which dampens volatility. When they are net short gamma, they must buy rallies and sell dips, which amplifies moves. Aggregate GEX by strike is commonly estimated as
where sign is +1 for calls and -1 for puts under the conventional assumption that dealers are long calls and short puts, M is the contract multiplier, and S² × 0.01 converts gamma into dollar delta change per 1% move. The price level where aggregate GEX crosses zero, the “gamma flip”, is the regime boundary. Above it, expect mean reversion and pinning. Below it, expect trend days and gaps. That is a useful lens on why the Gen-1 short spent months getting stopped out in a pinned, long-gamma market, and why the November break, once it came, moved fast.

The volatility risk premium (VRP). Implied volatility has historically exceeded subsequently realized volatility on average, which is the premium option sellers earn for bearing crash risk:
In stressed regimes the VRP can compress or flip negative right after a shock, so short-volatility structures should be sized off CVaR, and preferably kept defined-risk (iron condors rather than naked strangles).
4. Term structure and skew
Volatility futures term structure is the market’s map of fear across time. In calm markets the curve is in contango, with front months below back months, and short-front / long-back calendar trades earn roll-down. In stress it inverts into backwardation, front-month protection becomes expensive, and long-volatility hedges are priced at a premium. The report’s recommendation to sell front/back volatility-futures spreads on rebounds and buy front-month volatility for tail protection is the standard institutional playbook for each regime.
Skew matters just as much. Equity-index options carry a persistent put skew: downside strikes trade at higher implied volatility because institutions buy crash protection. In stress episodes, gold options often show a bid in upside calls as investors reach for convexity in the uncertainty asset. Skew determines which structures are cheap. Selling expensive put skew to finance calls, through a risk reversal, is attractive when skew is steep. Buying put spreads, rather than outright puts, partially neutralizes skew.

5. Carry and roll
Every futures position earns or pays carry. Under cost-of-carry the fair futures price is
with financing rate r, storage cost u and convenience yield y. The annualized roll yield between two contracts is
Backwardated commodities pay longs to hold them, and contango charges them. For crude, the report flags a likely OPEC+ supply overhang in 2027, a deferred-contango argument. That makes a calendar spread (long front, short deferred) a cleaner expression than the outright short that the MCL bots struggled with.
For crypto, the institutional carry trade is the CME-versus-perpetual basis. The annualized basis
compared with perpetual funding rates is what basis desks harvest market-neutrally. The report explicitly lists this cash-and-carry trade as the institutional play in a fear-driven crypto tape, which is the opposite of the directional contrarian long that failed in Gen-2.
6. CTA trend positioning
Trend-following CTAs are the largest systematic futures participants, and their positioning is mechanical enough to model. A stylized CTA signal on asset i is a volatility-scaled trend:
The practical implication is that when a trend that CTAs are positioned in reverses, they must cover, and that flow is itself a driver. The report’s “quants unwind bond shorts” headline is precisely this mechanism. In the same spirit, the Gen-2 gold bot’s strong early run and later drawdown look a lot like riding a trend that the systematic crowd was also long, and then sitting through the crowd’s de-risking.
7. Liquidity and microstructure
Finally, the report flags Thanksgiving-week liquidity (November 26-27). Thin sessions widen spreads, reduce book depth and raise gap risk. The report’s guidance, which is to reduce futures size, avoid opening short-volatility structures and prefer long optionality, is standard. At the microstructure level, liquidity shows up in the order book, and that is where the HFT toolkit at the end of this piece lives.
Part 7: The highest-expected-value options and futures playbook
With the evidence and the drivers in hand, we can answer the question the run was built to answer: what is the most profitable institutional strategy it points to? My answer is to keep the futures sleeves that have measured edge, re-express the ones whose edge comes with intolerable path risk through options, and use options for the macro events where the direction is genuinely uncertain. Below, each structure gets its payoff formula, its diagram and the specific evidence from the run that motivates it. All payoff diagrams use a normalized underlying of 100 and textbook parameters, so they are illustrative.
First, the pricing engine. Options on futures are priced with Black-76, the futures-options form of Black-Scholes:
Put-call parity for futures options is
For an equity-style underlying with dividend yield q, the classical Black-Scholes form is
The Greeks that drive every risk decision below (shown for Black-Scholes calls with q = 0) are
and the delta-hedged P&L identity, which explains why gamma and theta are two sides of one coin, is
A long-gamma position profits when realized volatility exceeds the implied volatility it paid for. A short-gamma position profits when it does not. That one line is the whole of options trading.

Strategy A: the gold sleeve, re-expressed with defined risk
Evidence: MGC is the largest profit generator in the run at $12,241.50, with a Sortino of 2.237 well above its Sharpe, so its upside months are its big months. It also has a 52.3% drawdown and a 12-trade losing streak.
Structure 1, the bull call spread. Buy a call at K₁ and sell a call at K₂ > K₁. The payoff at expiry is
where D is the net debit. The maximum loss is the debit and the maximum gain is (K₂ - K₁) - D. This converts the gold sleeve’s open-ended drawdown into a known, pre-paid premium per idea, while keeping most of the right-tail participation that generated the profit. With gold-style call skew, the short upper call is often relatively rich, which cheapens the spread.
Structure 2, the risk reversal. Buy an OTM call and sell an OTM put:
This is a synthetic long whose cost is set by skew. When puts are richer than calls, the structure can be near zero-cost. It has futures-like downside below the put strike, so it is a capital-efficient substitute for the futures leg, not a hedge. It suits the trend-confirmed phases of the gold bot, when the uncertainty bid is in force.
Strategy B: the ES/NQ relative-value pair plus a collar
Evidence: the Gen-2 MES long and MNQ short have a monthly correlation of only 0.08, and together they produced the smoothest equity curve in the run (about $16,207 from February to November 2026, with an annualized monthly Sharpe around 1.2). The macro report independently recommends long ES / short NQ, or long YM / short NQ, as the institutional expression of the AI-concentration unwind, and it warns not to stack outright ES and NQ positions given their roughly 0.9 correlation.
The beta-neutral hedge ratio between the two legs is
This gives the number of NQ contracts to short per ES contract held long, with M the contract multiplier and P the price. With micro S&P near 7,700 and micro Nasdaq near 30,700 in the backtest’s trade lists, and multipliers of $5 and $2, the dollar notional per contract is about $38,500 and $61,400. A notional-neutral pair therefore needs roughly 1.6 MES per MNQ before any beta adjustment.
The collar overlay on the long leg. Buy a put at K_p, sell a call at K_c, and hold long futures:
The report specifically cites collars as the “offense and defense” structure for high-volatility tape with gap risk. With equity put skew, the put is expensive, so the collar’s short call is what makes it affordable.
On the short leg, the bear put spread. For the MNQ thesis expressed in options, buy a put at K₁ and sell a put at K₂ < K₁:
This caps the loss if the AI-beta selloff reverses violently, which is what produced MNQ’s worst month of -$4,318 in April.
The cheap-downside variant, the 1x2 put ratio. Buy one put at K₁ and sell two puts at K₂ < K₁:
It is often near zero-cost when put skew is steep, and it pays most at K₂. Below K₂ - (K₁ - K₂) + D, however, it becomes a net short put with unlimited downside, which is exactly the wrong exposure in a crash. Use it only with a hard stop or a further-OTM long put to cap the tail.
Strategy C: event convexity into the December FOMC
Evidence: the report’s macro view is two-sided. A hawkish hike is priced at roughly 96%, yet the long end is bid on growth fears, gold is torn between dollar strength and uncertainty, and an “AI crash” tail scenario is circulating. Meanwhile, the Gen-1 10-year short never generated a single trade in the main backtest. When direction is unclear but a move is likely, you buy the move.
Long straddle and long strangle:
The straddle breaks even at a move equal to the premium paid. A useful rule of thumb for the ATM straddle price is
so you can compare the market’s implied move directly with your own forecast of the FOMC reaction. The report’s own expected-move guidance, one-sigma daily move ≈ σ_ATM / √252 × F, is the per-day version of the same idea.
Strategy D: post-holiday range harvest and term-structure trades
Evidence: the report suggests iron condors on index futures options only once the holiday and FOMC gap risk has passed, if the market settles into a range. It also suggests volatility-futures calendar spreads that harvest contango on rebounds.
Short iron condor. Sell the K₂ put and K₃ call, and buy the K₁ put and K₄ call, with K₁ < K₂ < K₃ < K₄:
The maximum gain is the credit Cr, and the maximum loss is the wing width minus the credit. This is a short-gamma, short-vega, positive-theta structure, so it earns the volatility risk premium when realized volatility stays below implied, and it must be sized off CVaR, not VaR.
Long calendar. Sell a near-dated option and buy a longer-dated one at the same strike. Its value at the front expiry T₁ is
It profits from time decay of the short leg and from a rise in back-month implied volatility. That makes it the natural structure when the front of the volatility curve is elevated relative to the back, as it typically is just before a scheduled event, and you expect the event premium to bleed out.

Strategy E: crude and crypto, from directional to relative value
Evidence: both Gen-2 directional bots in these markets lost money. The MCL short lost $1,595.14 with a 30.8% win rate, and the MBT contrarian long lost roughly $981 after correcting for the multiplier bug. The macro report’s own institutional suggestions for these markets are spreads: crude calendar spreads against a 2027 oversupply backdrop, crack spreads between crude and refined products, and CME-versus-perpetual basis in bitcoin and ether.
The crack spread, in the standard 3-2-1 form per barrel, is
with gasoline and heating oil quoted per gallon. A market-neutral basis trade’s carry is the annualized basis minus financing and funding costs. These are lower-volatility, lower-correlation return streams than outright directional bets, which is exactly what this run’s crude and crypto results suggest the pipeline should be testing next.
Putting it together: a conceptual allocation
Here is the shape of the book this run points to. These are conceptual weights and directions, not position sizes.
Core alpha: the ES/NQ relative-value pair, carrying the largest share of the risk budget because it has the best measured risk-adjusted profile. The long leg is collared, and the short leg can be expressed through put spreads during high-volatility windows.
Convex alpha: the gold trend sleeve, expressed through call spreads or risk reversals so that its 50%-style drawdowns become bounded premium outlays.
Event convexity: small, pre-budgeted long straddles or strangles on Treasury and index futures options into the December FOMC. Once the event is out, roll them into post-event range structures only if realized volatility collapses.
Research queue: crude calendars and cracks, plus crypto basis, as replacements for the failed directional bots.
Sizing for every sleeve: volatility targeting plus fractional Kelly, capped by CVaR, and halved again until each sleeve has out-of-sample history.
The volatility-targeting rule is
where the volatility forecast comes from a GARCH(1,1) process:
Its long-run variance is ω/(1 - α - β), and the h-step forecast mean-reverts toward it at rate (α + β)ʰ:
Vol targeting is what would have kept the Gen-1 S&P short from compounding its losses through the June and July drawdown months, and what keeps the gold sleeve’s exposure in check after a +31.6% month.
What the bots look like conceptually
For readers who want to see the flow without the proprietary details, here is the generic skeleton that every Gen-2 bot follows. Every gate and every number is abstracted away.
# Conceptual pseudocode — generic, not any bot's actual rules
on each closed bar:
regime = classify_volatility_and_trend(market_state)
thesis = macro_context_alignment(news_and_macro_inputs)
signal = composite_confirmation(price_action, regime)
if flat and signal agrees with thesis and regime allows participation:
size = vol_target_size(capital, forecast_vol) * fractional_kelly(edge_estimate)
size = min(size, risk_budget_limit, liquidity_limit)
place entry with protective stop at volatility-scaled distance
attach asymmetric profit objective (reward > risk)
if in position:
manage exit: stop, objective, trailing logic, or regime change
optional: overlay defined-risk options when implied vol is favourable
after each trade:
update performance stats, drawdown, losing-streak monitor
trigger halt if any portfolio-level circuit breaker firesPart 8: The microstructure layer, from order book to execution
Everything so far has been about which trades to put on. The last layer is about how to put them on. For the micro contracts in this run, a handful of ticks of slippage per round trip is a material fraction of the per-trade expectancy. MES Gen-2’s expectancy is about $151 per trade, while one MES tick is $1.25 per contract. If you ever push these ideas toward faster horizons, microstructure becomes the whole game.
Order-book imbalance and the microprice
The mid price, (bid + ask)/2, ignores the queue sizes at the touch. When the bid queue is much larger than the ask queue, the next price move is more likely to be up. Top-of-book imbalance is
and the simplest microprice, a size-weighted mid, is
Stoikov’s refined microprice defines it as the limit of expected future mids conditioned on the current imbalance and spread, P^micro = M + g(I, S), estimated from data as a Markov chain. The size-weighted form above is its first-order approximation. A multi-level, depth-decayed imbalance is
and the Cont-Kukanov-Stoikov order-flow imbalance (OFI), which is linearly related to short-horizon price changes, is

Avellaneda-Stoikov market making
The canonical model for a market maker who wants to earn the spread without accumulating dangerous inventory sets a reservation price that is skewed against inventory q, and an optimal total spread:
Here γ is risk aversion, σ is volatility, and k describes how fast fill intensity decays with distance from the mid, λ(δ) = A e^(-kδ). Long inventory pushes both quotes down, so the maker sells more readily. Short inventory pushes both quotes up.
Almgren-Chriss optimal execution
Unwinding X contracts over horizon T trades off market impact, which pushes you to go slow, against price risk, which pushes you to go fast. With linear temporary impact η and risk aversion λ, the optimal inventory path is
and the efficient frontier of execution minimizes
A risk-neutral trader (κ → 0) executes TWAP. A highly risk-averse one front-loads. For a bot that exits on a stop in a fast market, the front-loaded schedule is the right mental model: when the stop triggers, you are buying certainty with impact.
Part 9: Copyable Python research toolkit
The following snippets are generic, self-contained and runnable with NumPy, SciPy and pandas. They reproduce every derived statistic in this article. None of them contains any bot’s trading logic.
Black-76 pricing, Greeks and implied volatility for options on futures:
import numpy as np
from scipy.stats import norm
def black76(F, K, T, r, sigma, cp="c"):
"""Black-76 price and Greeks for options on futures. Vectorized over any argument."""
F, K, T, sigma = map(np.asarray, (F, K, T, sigma))
sqrtT = np.sqrt(np.maximum(T, 1e-12))
d1 = (np.log(F / K) + 0.5 * sigma**2 * T) / (sigma * sqrtT)
d2 = d1 - sigma * sqrtT
disc = np.exp(-r * T)
if cp == "c":
price = disc * (F * norm.cdf(d1) - K * norm.cdf(d2))
delta = disc * norm.cdf(d1)
else:
price = disc * (K * norm.cdf(-d2) - F * norm.cdf(-d1))
delta = -disc * norm.cdf(-d1)
gamma = disc * norm.pdf(d1) / (F * sigma * sqrtT)
vega = disc * F * norm.pdf(d1) * sqrtT / 100 # per 1 vol point
theta = (-disc * F * norm.pdf(d1) * sigma / (2 * sqrtT) + r * price) / 365 # per calendar day
return dict(price=price, delta=delta, gamma=gamma, vega=vega, theta=theta)
def implied_vol(price, F, K, T, r, cp="c", lo=1e-4, hi=5.0, tol=1e-8):
"""Robust bisection IV solver (monotone in sigma)."""
for _ in range(200):
mid = 0.5 * (lo + hi)
if black76(F, K, T, r, mid, cp)["price"] > price: hi = mid
else: lo = mid
if hi - lo < tol: break
return 0.5 * (lo + hi)
g = black76(F=100.0, K=100.0, T=30/365, r=0.04, sigma=0.20)
print({k: round(float(v), 4) for k, v in g.items()})
print(round(implied_vol(float(g["price"]), 100, 100, 30/365, 0.04), 4))A multi-leg payoff engine for verticals, condors, collars, ratios and anything else:
import numpy as np
from dataclasses import dataclass
@dataclass
class Leg:
kind: str # "call", "put", or "fut"
strike: float # ignored for futures (use entry price)
qty: float # +long / -short
premium: float = 0.0 # paid (+) per unit for longs, received for shorts via negative qty
def payoff(legs, S):
S = np.asarray(S, dtype=float); total = np.zeros_like(S)
for L in legs:
if L.kind == "call": intrinsic = np.maximum(S - L.strike, 0.0)
elif L.kind == "put": intrinsic = np.maximum(L.strike - S, 0.0)
else: intrinsic = S - L.strike
total += L.qty * (intrinsic - L.premium)
return total
def breakevens(legs, S):
p = payoff(legs, S); idx = np.where(np.diff(np.sign(p)) != 0)[0]
return [S[i] - p[i] * (S[i+1] - S[i]) / (p[i+1] - p[i]) for i in idx]
iron_condor = [Leg("put", 90, +1, 0.30), Leg("put", 95, -1, 1.10),
Leg("call", 105, -1, 1.00), Leg("call", 110, +1, 0.25)]
S = np.linspace(80, 120, 4001)
pnl = payoff(iron_condor, S)
print("max gain", pnl.max().round(2), "max loss", pnl.min().round(2), "BE", np.round(breakevens(iron_condor, S), 2))Performance metrics, trade statistics, and the probabilistic and deflated Sharpe ratios. Running it reproduces the Gen-2 MES bot’s published Kelly (14.8%) and profit factor (1.48) from its reported win rate and average win and loss. Its deflated Sharpe, with skew and kurtosis adjusted, comes out near 0.84 across 16 trials, versus about 0.75 under the Gaussian assumption in the chart above. Neither clears 95%.
import numpy as np
from scipy.stats import norm, skew, kurtosis
def perf_metrics(returns, periods_per_year=12, rf=0.0, mar=0.0):
r = np.asarray(returns, dtype=float); ex = r - rf / periods_per_year
sharpe = ex.mean() / ex.std(ddof=1) * np.sqrt(periods_per_year)
downside = np.sqrt(np.mean(np.minimum(r - mar, 0.0) ** 2))
sortino = ex.mean() / downside * np.sqrt(periods_per_year) if downside > 0 else np.inf
equity = np.cumprod(1 + r); peak = np.maximum.accumulate(equity)
max_dd = (equity / peak - 1).min()
cagr = equity[-1] ** (periods_per_year / len(r)) - 1
calmar = cagr / abs(max_dd) if max_dd < 0 else np.inf
var95 = -np.percentile(r, 5); cvar95 = -r[r <= -var95].mean()
return dict(sharpe=sharpe, sortino=sortino, max_dd=max_dd, cagr=cagr, calmar=calmar, var95=var95, cvar95=cvar95)
def trade_stats(win_rate, avg_win, avg_loss):
b = avg_win / abs(avg_loss); q = 1 - win_rate
return dict(payoff_ratio=b, breakeven_wr=1 / (1 + b),
expectancy=win_rate * avg_win - q * abs(avg_loss), kelly=win_rate - q / b,
profit_factor=(win_rate * avg_win) / (q * abs(avg_loss)))
def probabilistic_sharpe(sr, n_obs, sr_bench=0.0, g3=0.0, g4=3.0):
"""PSR: P(true SR > benchmark). sr and sr_bench are per-period (not annualized)."""
return norm.cdf((sr - sr_bench) * np.sqrt(n_obs - 1) / np.sqrt(1 - g3 * sr + (g4 - 1) / 4 * sr**2))
def deflated_sharpe(sr, n_obs, n_trials, sr_var, g3=0.0, g4=3.0):
"""DSR (Bailey & Lopez de Prado): benchmark = expected max SR of n_trials null strategies."""
emc = 0.5772156649
sr0 = np.sqrt(sr_var) * ((1 - emc) * norm.ppf(1 - 1 / n_trials) + emc * norm.ppf(1 - 1 / (n_trials * np.e)))
return probabilistic_sharpe(sr, n_obs, sr0, g3, g4)
# Reported Gen-2 MES stats reproduce the published Kelly (14.8%) and profit factor (1.48):
print({k: round(v, 4) for k, v in trade_stats(0.457, 1024.01, -582.16).items()})
monthly = np.array([2997, 804, 474, 0, -616, 971, 458, 2193, -214, -116]) / 50_000
m = perf_metrics(monthly); print({k: round(float(v), 4) for k, v in m.items()})
sr_m = monthly.mean() / monthly.std(ddof=1)
print("DSR (16 trials):", round(float(deflated_sharpe(sr_m, len(monthly), 16, 0.5 / 12, skew(monthly), kurtosis(monthly, fisher=False))), 3))GARCH(1,1) by maximum likelihood, multi-step variance forecasts, and volatility-target sizing. Note the sobering output of the last line: at a 10% volatility target on $50,000, with index volatility at 20%, even a single micro S&P contract is about 1.5 times too large. Micro contracts are small, but not small enough for conservative vol targeting on small accounts.
import numpy as np
from scipy.optimize import minimize
def garch11_fit(returns):
"""Gaussian MLE for GARCH(1,1): sigma2_t = w + a*e_{t-1}^2 + b*sigma2_{t-1}."""
r = np.asarray(returns, float) - np.mean(returns)
def nll(params):
w, a, b = params
if w <= 0 or a < 0 or b < 0 or a + b >= 0.999: return 1e10
s2 = np.empty_like(r); s2[0] = r.var()
for t in range(1, len(r)): s2[t] = w + a * r[t-1]**2 + b * s2[t-1]
return 0.5 * np.sum(np.log(2 * np.pi * s2) + r**2 / s2)
x0 = [r.var() * 0.05, 0.08, 0.90]
res = minimize(nll, x0, method="Nelder-Mead", options=dict(maxiter=4000, xatol=1e-10, fatol=1e-10))
w, a, b = res.x
return dict(omega=w, alpha=a, beta=b, persistence=a + b, long_run_vol=np.sqrt(w / (1 - a - b)))
def garch_forecast(params, last_r, last_s2, h):
w, a, b = params["omega"], params["alpha"], params["beta"]; lr = w / (1 - a - b)
s2_next = w + a * last_r**2 + b * last_s2
return np.array([lr + (a + b) ** (k - 1) * (s2_next - lr) for k in range(1, h + 1)])
def vol_target_contracts(capital, target_vol_ann, forecast_vol_ann, multiplier, price):
raw = target_vol_ann * capital / (forecast_vol_ann * multiplier * price)
return raw, int(np.floor(raw)) # fractional need vs whole contracts you can actually trade
rng = np.random.default_rng(1); n = 2000; w, a, b = 2e-6, 0.08, 0.90
e = np.empty(n); s2 = np.empty(n); s2[0] = w / (1 - a - b)
for t in range(n):
if t: s2[t] = w + a * e[t-1]**2 + b * s2[t-1]
e[t] = np.sqrt(s2[t]) * rng.standard_normal()
fit = garch11_fit(e); print({k: round(float(v), 5) for k, v in fit.items()})
# At a 10% vol target on $50k with 20% index vol, even ONE micro S&P is ~1.5x too big:
print("MES contracts:", vol_target_contracts(50_000, 0.10, 0.20, 5, 7_700))Monte Carlo resampling of trade statistics, and a dealer gamma-exposure calculator. The Monte Carlo run on MGC’s reported stats shows a median maximum drawdown of roughly 20% across simulated paths, even before any regime change.
import numpy as np
import pandas as pd
def mc_trade_paths(p_win, avg_win, avg_loss, n_trades, n_paths=5000, start=50_000, seed=7):
rng = np.random.default_rng(seed)
wins = rng.random((n_paths, n_trades)) < p_win
pnl = np.where(wins, avg_win, -abs(avg_loss)).cumsum(axis=1) + start
dd = (pnl / np.maximum.accumulate(pnl, axis=1) - 1).min(axis=1)
return dict(p_loss=float((pnl[:, -1] < start).mean()),
pct=np.percentile(pnl[:, -1] - start, [5, 50, 95]).round(0),
median_max_dd=float(np.median(dd)))
print(mc_trade_paths(0.417, 1770.27, 1085.54, 115)) # reported Gen-2 MGC statistics
def gamma_exposure(chain: pd.DataFrame, spot: float, multiplier: float) -> pd.Series:
"""chain columns: strike, type ('C'/'P'), gamma, open_interest. Dealer-long-calls/short-puts convention."""
sign = np.where(chain["type"].str.upper() == "C", 1.0, -1.0)
gex = sign * chain["gamma"] * chain["open_interest"] * multiplier * spot**2 * 0.01
return pd.Series(gex.values, index=chain["strike"]).groupby(level=0).sum()
def gamma_flip(chain, spots, multiplier, gamma_fn):
"""Scan spot levels, recompute gamma with gamma_fn(strike, spot), return the zero crossing."""
totals = []
for s in spots:
c = chain.assign(gamma=[gamma_fn(k, s) for k in chain["strike"]])
totals.append(gamma_exposure(c, s, multiplier).sum())
totals = np.array(totals); i = np.where(np.diff(np.sign(totals)) != 0)[0]
return spots[i[0]] if len(i) else NoneExecution and microstructure: the Almgren-Chriss schedule, microprice, depth imbalance, OFI and Avellaneda-Stoikov quotes:
import numpy as np
def almgren_chriss(X, T, N, sigma, eta, lam):
"""Optimal liquidation schedule (linear temporary impact eta, risk aversion lam)."""
tau = T / N; kappa = np.arccosh(1 + 0.5 * lam * sigma**2 * tau**2 / eta) / tau if lam > 0 else 1e-9
t = np.linspace(0, T, N + 1)
holdings = X * np.sinh(kappa * (T - t)) / np.sinh(kappa * T)
return t, holdings, -np.diff(holdings) # times, inventory path, child-order sizes
def microprice(bid, ask, qb, qa):
I = qb / (qb + qa); return ask * I + bid * (1 - I)
def order_book_imbalance(qb_levels, qa_levels, decay=0.5):
w = decay ** np.arange(len(qb_levels)); qb = np.dot(w, qb_levels); qa = np.dot(w, qa_levels)
return (qb - qa) / (qb + qa)
def order_flow_imbalance(prev, cur):
"""Cont-Kukanov-Stoikov OFI for one book update; prev/cur = (bid, qb, ask, qa)."""
pb, qb0, pa, qa0 = prev; cb, qb1, ca, qa1 = cur
e_b = (qb1 if cb >= pb else 0) - (qb0 if cb <= pb else 0)
e_a = (qa0 if ca >= pa else 0) - (qa1 if ca <= pa else 0)
return e_b + e_a
def avellaneda_stoikov(mid, q, gamma, sigma, k, tau):
r = mid - q * gamma * sigma**2 * tau
half = 0.5 * (gamma * sigma**2 * tau + (2 / gamma) * np.log1p(gamma / k))
return r - half, r + half
t, x, child = almgren_chriss(X=100, T=1.0, N=10, sigma=0.3, eta=0.05, lam=2.0)
print(np.round(child, 2), round(microprice(99.75, 100.00, 40, 12), 4),
round(order_book_imbalance([40, 65, 80], [12, 55, 70]), 3), avellaneda_stoikov(100, 5, 0.1, 2.0, 1.5, 0.5))Part 10: Ultra-low-latency C++ infrastructure for HFT research
If any of these futures ideas migrate toward intraday or market-making horizons, Python becomes a research tool and the production path becomes C++. Below is a complete, generic, header-only skeleton for the critical path:
A feed thread pushes book updates through a wait-free single-producer / single-consumer ring.
A pinned, busy-polling strategy thread pulls them off and applies them to a flat-array L2 book.
That thread computes the microprice and imbalance in fixed point.
Latency is timestamped with the CPU’s time-stamp counter.
It compiles cleanly with g++ -std=c++20 -O3 -march=native -pthread. It is educational infrastructure. It contains no strategy logic, and it is not a trading system.
The design principles are the ones every HFT shop converges on:
No locks, allocation or system calls on the hot path.
One writer per cache line, to kill false sharing.
Integer prices, never doubles, for book keys and P&L.
Power-of-two ring sizes, so index wrap is a bitmask.
Acquire/release atomics rather than sequentially consistent ones.
Threads pinned to isolated cores, so the scheduler never preempts the strategy.
core.hpp: cache-line alignment, branch hints and spin-wait primitives
// core.hpp — low-latency building blocks (generic, educational)
#pragma once
#include <atomic>
#include <cstdint>
#include <cstddef>
#include <new>
#include <type_traits>
#if defined(__GNUC__) || defined(__clang__)
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#define ALWAYS_INLINE inline __attribute__((always_inline))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#define ALWAYS_INLINE inline
#endif
// 64 bytes on x86-64; use 128 on some ARM cores to defeat adjacent-line prefetch.
inline constexpr std::size_t kCacheLine = 64;
// Pad a value to its own cache line so two threads never false-share it.
template <typename T>
struct alignas(kCacheLine) CachePadded {
T value{};
char pad[kCacheLine - (sizeof(T) % kCacheLine == 0 ? kCacheLine : sizeof(T) % kCacheLine)]{};
};
ALWAYS_INLINE void compiler_barrier() noexcept { std::atomic_signal_fence(std::memory_order_seq_cst); }
ALWAYS_INLINE void cpu_relax() noexcept {
#if defined(__x86_64__) || defined(__i386__)
__builtin_ia32_pause(); // PAUSE: polite spin, saves power, avoids pipeline flush
#elif defined(__aarch64__)
asm volatile("yield" ::: "memory");
#endif
}fixed_price.hpp: a fixed-point price type and integer P&L accounting. Integer ticks make price comparison exact and hashing trivial, and P&L in integer cents removes floating-point drift from accounting. For any futures contract,
// fixed_price.hpp — integer ticks instead of doubles: exact, fast, hashable
#pragma once
#include <cstdint>
#include <cmath>
#include <compare>
struct Price {
int64_t ticks{0}; // price expressed in minimum ticks
static constexpr Price from_double(double px, double tick) noexcept {
return Price{static_cast<int64_t>(px / tick + (px >= 0 ? 0.5 : -0.5))};
}
constexpr double to_double(double tick) const noexcept { return static_cast<double>(ticks) * tick; }
constexpr Price operator+(int64_t n) const noexcept { return Price{ticks + n}; }
constexpr Price operator-(int64_t n) const noexcept { return Price{ticks - n}; }
constexpr int64_t operator-(Price o) const noexcept { return ticks - o.ticks; }
constexpr auto operator<=>(const Price&) const noexcept = default;
};
// Fixed-point quantity-weighted value with 1e-8 resolution (for microprice etc.)
struct Fixed8 {
static constexpr int64_t kScale = 100'000'000;
int64_t raw{0};
static constexpr Fixed8 from_ratio(int64_t num, int64_t den) noexcept {
return Fixed8{den ? static_cast<int64_t>((static_cast<__int128>(num) * kScale) / den) : 0};
}
constexpr double to_double() const noexcept { return static_cast<double>(raw) / kScale; }
};
// Contract spec: P&L in integer cents to avoid floating drift in accounting.
struct ContractSpec {
double tick_size; // e.g. 0.25 index points
int64_t tick_value_c; // value of one tick in cents, e.g. 125 = $1.25
constexpr int64_t pnl_cents(Price entry, Price exit, int64_t qty) const noexcept {
return (exit - entry) * tick_value_c * qty; // qty > 0 long, < 0 short
}
};spsc_ring.hpp: a lock-free (wait-free) SPSC ring buffer. Each side caches the other side’s index and only reloads it, with an acquire load, when the ring looks full or empty. That cuts cross-core cache-line traffic dramatically, and it is the main trick that takes a naive SPSC queue from hundreds of nanoseconds per message down to tens.
// spsc_ring.hpp — wait-free single-producer / single-consumer ring buffer
#pragma once
#include "core.hpp"
#include <array>
#include <optional>
template <typename T, std::size_t N>
class SpscRing {
static_assert((N & (N - 1)) == 0, "capacity must be a power of two");
static_assert(std::is_trivially_copyable_v<T>, "keep payloads POD for speed");
public:
// Producer side. Returns false when full (caller decides: drop, spin, or back-pressure).
ALWAYS_INLINE bool try_push(const T& v) noexcept {
const std::size_t head = head_.value.load(std::memory_order_relaxed);
const std::size_t next = head + 1;
if (UNLIKELY(next - tail_cache_ > N)) { // looks full: refresh cached tail
tail_cache_ = tail_.value.load(std::memory_order_acquire);
if (next - tail_cache_ > N) return false;
}
buf_[head & kMask] = v;
head_.value.store(next, std::memory_order_release); // publish slot
return true;
}
// Consumer side.
ALWAYS_INLINE bool try_pop(T& out) noexcept {
const std::size_t tail = tail_.value.load(std::memory_order_relaxed);
if (UNLIKELY(tail == head_cache_)) { // looks empty: refresh cached head
head_cache_ = head_.value.load(std::memory_order_acquire);
if (tail == head_cache_) return false;
}
out = buf_[tail & kMask];
tail_.value.store(tail + 1, std::memory_order_release); // free slot
return true;
}
private:
static constexpr std::size_t kMask = N - 1;
CachePadded<std::atomic<std::size_t>> head_{}; // written by producer only
CachePadded<std::atomic<std::size_t>> tail_{}; // written by consumer only
alignas(kCacheLine) std::size_t tail_cache_{0}; // producer-local copy of tail
alignas(kCacheLine) std::size_t head_cache_{0}; // consumer-local copy of head
alignas(kCacheLine) std::array<T, N> buf_{};
};tsc_clock.hpp: rdtsc and rdtscp timing plus an allocation-free latency histogram. Use plain rdtsc for cheap stamps inside the loop. Use rdtscp followed by lfence when you need a measurement fence, so earlier instructions retire first. Calibrate cycles per nanosecond once at startup, and check that the CPU reports an invariant TSC.
// tsc_clock.hpp — cycle-accurate timestamps with rdtsc / rdtscp
#pragma once
#include <cstdint>
#include <chrono>
#include <thread>
#if defined(__x86_64__)
#include <x86intrin.h>
#endif
struct TscClock {
static inline uint64_t now() noexcept { // cheap, not serializing
#if defined(__x86_64__)
return __rdtsc();
#else
return static_cast<uint64_t>(std::chrono::steady_clock::now().time_since_epoch().count());
#endif
}
static inline uint64_t now_fenced() noexcept { // waits for prior instructions to retire
#if defined(__x86_64__)
unsigned aux; uint64_t t = __rdtscp(&aux); _mm_lfence(); return t;
#else
return now();
#endif
}
// Calibrate ticks-per-nanosecond against steady_clock (requires invariant TSC).
static double ticks_per_ns(std::chrono::milliseconds window = std::chrono::milliseconds(50)) {
const auto w0 = std::chrono::steady_clock::now(); const uint64_t t0 = now_fenced();
std::this_thread::sleep_for(window);
const auto w1 = std::chrono::steady_clock::now(); const uint64_t t1 = now_fenced();
const double ns = std::chrono::duration<double, std::nano>(w1 - w0).count();
return static_cast<double>(t1 - t0) / ns;
}
};
// Log-linear latency histogram: O(1) record, no allocation on the hot path.
struct LatencyHist {
uint64_t buckets[64]{};
inline void record(uint64_t cycles) noexcept {
const int b = cycles ? 63 - __builtin_clzll(cycles) : 0; // floor(log2)
++buckets[b];
}
uint64_t percentile_cycles(double p) const noexcept {
uint64_t total = 0; for (auto c : buckets) total += c;
uint64_t target = static_cast<uint64_t>(p * total), run = 0;
for (int i = 0; i < 64; ++i) { run += buckets[i]; if (run >= target) return 1ull << (i + 1); }
return ~0ull;
}
};l2_book.hpp: a flat-array L2 book with O(1) updates, microprice and imbalance. The book is a price ladder indexed by ticks relative to an anchor, so every update is a single array write plus a best-price fix-up, with no tree, no hash map and no allocation. The microprice and imbalance are computed in 128-bit-safe fixed point.
// l2_book.hpp — flat-array L2 book with O(1) updates, microprice and imbalance
#pragma once
#include "core.hpp"
#include "fixed_price.hpp"
#include <array>
#include <cstring>
struct L2Update { // POD message as delivered by a feed handler
int64_t price_ticks;
int64_t qty; // new aggregate size at level; 0 = delete
uint8_t side; // 0 = bid, 1 = ask
uint64_t exch_ts_ns;
};
template <std::size_t Levels = 4096> // ladder window around an anchor price
class L2Book {
public:
explicit L2Book(int64_t anchor_ticks) : base_(anchor_ticks - static_cast<int64_t>(Levels / 2)) {
bid_.fill(0); ask_.fill(0);
}
ALWAYS_INLINE void apply(const L2Update& u) noexcept {
const int64_t idx = u.price_ticks - base_;
if (UNLIKELY(idx < 0 || idx >= static_cast<int64_t>(Levels))) return; // out of window: recentre offline
if (u.side == 0) {
bid_[idx] = u.qty;
if (u.qty > 0 && idx > best_bid_) best_bid_ = idx;
else if (u.qty == 0 && idx == best_bid_) while (best_bid_ > 0 && bid_[best_bid_] == 0) --best_bid_;
} else {
ask_[idx] = u.qty;
if (u.qty > 0 && (best_ask_ < 0 || idx < best_ask_)) best_ask_ = idx;
else if (u.qty == 0 && idx == best_ask_) {
while (best_ask_ < static_cast<int64_t>(Levels) - 1 && ask_[best_ask_] == 0) ++best_ask_;
if (ask_[best_ask_] == 0) best_ask_ = -1;
}
}
}
bool valid() const noexcept { return best_bid_ >= 0 && best_ask_ >= 0 && bid_[best_bid_] > 0 && ask_[best_ask_] > 0; }
Price bid() const noexcept { return Price{base_ + best_bid_}; }
Price ask() const noexcept { return Price{base_ + best_ask_}; }
int64_t bid_qty() const noexcept { return bid_[best_bid_]; }
int64_t ask_qty() const noexcept { return ask_[best_ask_]; }
// Top-of-book imbalance in [-1, 1], fixed-point.
Fixed8 imbalance() const noexcept {
const int64_t qb = bid_qty(), qa = ask_qty();
return Fixed8::from_ratio(qb - qa, qb + qa);
}
// Microprice in ticks (fixed-point): ask*I + bid*(1-I), with I = qb / (qb + qa).
Fixed8 microprice_ticks() const noexcept {
const int64_t qb = bid_qty(), qa = ask_qty();
const int64_t num = (base_ + best_ask_) * qb + (base_ + best_bid_) * qa;
return Fixed8::from_ratio(num, qb + qa);
}
// Depth-weighted imbalance over k levels each side.
Fixed8 depth_imbalance(int k) const noexcept {
int64_t qb = 0, qa = 0;
for (int i = 0; i < k && best_bid_ - i >= 0; ++i) qb += bid_[best_bid_ - i];
for (int i = 0; i < k && best_ask_ + i < static_cast<int64_t>(Levels); ++i) qa += ask_[best_ask_ + i];
return Fixed8::from_ratio(qb - qa, qb + qa);
}
private:
int64_t base_;
int64_t best_bid_{-1}, best_ask_{-1};
alignas(kCacheLine) std::array<int64_t, Levels> bid_;
alignas(kCacheLine) std::array<int64_t, Levels> ask_;
};main.cpp: a pinned busy-poll event loop. Run on an isolated core (isolcpus and nohz_full on Linux), it never sleeps and never yields to the kernel. In this self-contained demo the producer floods the ring, so the reported percentiles measure queueing under saturation rather than pure hop latency. Rate-limit the producer to measure the true per-message cost on your hardware.
// main.cpp — pinned busy-poll loop: feed thread -> SPSC -> strategy thread
#include "core.hpp"
#include "fixed_price.hpp"
#include "spsc_ring.hpp"
#include "tsc_clock.hpp"
#include "l2_book.hpp"
#include <cstdio>
#include <thread>
#if defined(__linux__)
#include <pthread.h>
#include <sched.h>
#endif
static void pin_to_core(int core) {
#if defined(__linux__)
cpu_set_t set; CPU_ZERO(&set); CPU_SET(core, &set);
pthread_setaffinity_np(pthread_self(), sizeof(set), &set); // pair with isolcpus/nohz_full
#endif
}
struct Msg { L2Update u; uint64_t tsc_rx; };
int main() {
static SpscRing<Msg, 1 << 16> ring; // static: no page faults on first touch at runtime
std::atomic<bool> done{false};
constexpr int kN = 1'000'000;
std::thread feed([&] { // simulated feed handler (replace with kernel-bypass NIC rx)
pin_to_core(2);
uint64_t seq = 0;
for (int i = 0; i < kN; ++i) {
const int64_t px = 400'000 + (i % 8) - 4; // jitter around an anchor
Msg m{{px, 1 + static_cast<int64_t>(seq++ % 50), static_cast<uint8_t>(px >= 400'000), 0}, TscClock::now()};
while (!ring.try_push(m)) cpu_relax();
}
done.store(true, std::memory_order_release);
});
pin_to_core(3);
L2Book<4096> book(400'000);
LatencyHist hist;
Msg m{};
long processed = 0;
double last_micro = 0.0;
for (;;) { // hot loop: never sleeps, never allocates, never locks
if (ring.try_pop(m)) {
book.apply(m.u);
if (LIKELY(book.valid())) last_micro = book.microprice_ticks().to_double();
hist.record(TscClock::now() - m.tsc_rx);
++processed;
} else if (UNLIKELY(done.load(std::memory_order_acquire))) {
if (!ring.try_pop(m)) break;
book.apply(m.u); ++processed;
} else {
cpu_relax();
}
}
feed.join();
const double tpn = TscClock::ticks_per_ns();
std::printf("processed=%ld micro=%.3f p50=%.0fns p99=%.0fns\n", processed, last_micro,
hist.percentile_cycles(0.50) / tpn, hist.percentile_cycles(0.99) / tpn);
}as_quoter.hpp: generic Avellaneda-Stoikov quoting. This is the textbook model from Part 8, rounded conservatively to the tick grid. It is a starting point for research, not a production quoter. Real quoters add queue-position models, adverse-selection filters, kill switches and exchange-specific throttles.
// as_quoter.hpp — Avellaneda–Stoikov inventory-aware quoting (generic textbook model)
#pragma once
#include <cmath>
struct ASParams { double gamma; double sigma; double k; double horizon_s; };
struct Quotes { double bid; double ask; double reservation; double half_spread; };
inline Quotes as_quotes(double mid, double inventory, double t_remaining_s, const ASParams& p) noexcept {
const double tau = t_remaining_s / p.horizon_s; // normalized time left
const double var = p.sigma * p.sigma * tau;
const double r = mid - inventory * p.gamma * var; // reservation price
const double half = 0.5 * (p.gamma * var + (2.0 / p.gamma) * std::log1p(p.gamma / p.k));
return {r - half, r + half, r, half};
}
// Snap to tick grid conservatively (never cross the touch on rounding).
inline void snap(Quotes& q, double tick) noexcept {
q.bid = std::floor(q.bid / tick) * tick;
q.ask = std::ceil (q.ask / tick) * tick;
}A note on what this skeleton deliberately leaves out:
Kernel-bypass networking (DPDK, ef_vi, Onload or similar).
Exchange-specific binary protocols for market data and order entry.
Pre-trade risk checks: fat-finger limits, position limits, a kill switch.
Sequence-gap recovery, and persistent logging off the hot path through a second SPSC ring to a logger thread.
Each of those is a project in its own right. The core above is the part that is the same everywhere.
Part 11: A research-to-production checklist for this book
Pulling the threads together, here is what I would do next with this run, in priority order.
Fix the data layer before trusting any aggregate. Correct the MBT contract multiplier. Add an equity floor so drawdowns cannot exceed 100%. Reconcile the conflicting Gen-1 result sets. Unify margin assumptions per contract. Relabel full-size contracts correctly. Make zero-trade bots read NO_TRADES rather than PROFITABLE.
Fix the options-chain roll. Point the chain finder at live front-month contracts (December 2026, then March 2027) so every overlay section has real implied volatility, skew and Greeks instead of a stale, empty chain.
Pull market levels from data, not narrative. Treat every level the language model extracts from news, such as CPI, PCE, the dollar index, gold or the VIX, as a claim to verify against a price feed.
Manage MES and MNQ as one spread. Give it a beta-neutral hedge ratio, a single risk budget and a combined stop.
Re-express the gold sleeve in options. Use call spreads or risk reversals, so that its edge, which lives in the right tail, survives its drawdowns.
Retire or re-specify the losing directional ideas as relative-value trades. That means crude calendars and cracks, plus crypto basis.
Normalize and deflate. Compute every metric on the same calendar window and the same return definition, and report the deflated Sharpe alongside the raw Sharpe.
Paper trade on new data. No sleeve gets more than a quarter-Kelly allocation of its deflated edge until it has out-of-sample history.
Keep the AI planner’s projections off the results page. They missed the one testable bot by almost three Sharpe units.
Conclusion
The headline of this run is not “a bot made $12,000”. It is that a disciplined second iteration turned a book that lost almost its entire test allocation into a diversified set of micro-futures sleeves with positive expectancy, and that the way those sleeves fit together points straight at institutional structures. Those are a beta-neutral S&P/Nasdaq spread, a convex gold sleeve expressed through options, and event optionality around the Fed.
The highest backtested profit came from gold: $12,241.50 with a 52.3% drawdown. The highest risk-adjusted result came from the regime-adaptive S&P long: Sharpe 1.124 with a 9.4% drawdown. The highest-quality combination was the two equity bots together, with near-zero correlation and roughly double the Sharpe of the full book.
Just as important are the lessons from what failed. Thesis-only shorts bleed while waiting for the move. Contrarian crypto longs into capitulation lost. A single multiplier bug can turn a $981 loss into a $9.8 million headline. Projected Sharpes of 1.5 can become realized Sharpes of -1.5. None of this should be traded as-is. All of it is the raw material from which a real, institutional-grade systematic book gets built: data hygiene first, structure second, sizing third and speed last.
Disclaimer: This article is for educational and informational purposes only and is not financial, investment, tax or legal advice, nor a solicitation or recommendation to buy or sell any security, futures contract or option. All performance figures discussed are hypothetical, simulated backtest results with inherent limitations, including hindsight bias, and they may not reflect real-world slippage, commissions, liquidity, margin changes or market impact. Backtested and past performance is not indicative of future results. Futures and options involve substantial risk of loss, losses can exceed deposits, and they are not suitable for every investor. Market levels quoted from the research run’s news snapshot have not been independently verified. Code samples are generic educational material provided without warranty and are not a trading system. Consult a qualified professional before making any trading decision.


















