Part 4 of 5 · Applied AI engineering
How I train my trading models
Early in October I checked how long the pretend trades in my trading system’s training data lasted and found a cluster that ended within two seconds. About one row in forty, 2,471 of roughly 99,000 in the span I checked, closed on its first price check. The fault was in my label code, not in the market. A label is the answer key a model learns from: I replay a moment, pretend to buy, and record how that trade ended. In thin markets, where little is for sale, my pretend buy was larger than the market itself, yet the label sold back into the market as it was before my buy. A model trained on those rows would have learned that thin markets always lose, and I would have read that as a finding about the market.
That is what training is mostly about for me: protecting what the model learns from, because the model will believe whatever the data says. This is the fourth article in my series on applied AI engineering. The first, Apps that fix themselves and get better on their own, describes the two loops around my trading system. The second, The telemetry that lets an agent fix bugs, covers what the system writes about itself, and the third, The self-improvement loop in my trading system, covers the gate a new model must pass. This one is about the training itself. Today the system trains on Solana data. Later it may learn other networks, and even traditional markets such as stock exchanges and B3, the Brazilian one.
Record everything, then replay it like a film
The system writes down every raw message that its live inputs deliver, in hourly files, before it interprets any of them. Training then plays those files again in order, like a film. At each moment of the film the code may use only what had happened by then. My written training rules call this the most important rule in training: a model that sees the future looks brilliant in tests and fails when the stakes are real.
The replay uses the same Rust code that makes live decisions, so the rows that training reads are what the live system would have seen. The live system sees messages in the order they arrive, so the replay uses arrival order too. When I once sorted them by their own timestamps, a late message slipped into a decision: live it held 8 trades and in the replay it held 9. A test would not have caught it, and the model would have trained on a world that never existed.
I keep all the data. I don’t know yet how much a good model needs, and I have room to find out, so I would rather keep too much than delete something I can’t record again.
Labels: an answer key for decisions I never took
The label of a row is a pretend trade. It starts a small delay after the decision, because a real order also arrives late. It pays every cost, such as fees and the price moving against me. It ends at the first of three events: a gain target, a loss limit or a time limit, the idea known as the triple barrier from Marcos López de Prado’s book on financial machine learning. I don’t print my values for the three.
Every decision moment gets a label, including the ones the system would skip. That is the point of labeling by pretending: a model can learn from the decisions it never took, and it can learn before it has traded at all.
I let a label claim only what the system actually saw:
- Confirmed means the system watched the price from the entry to the end of the label.
- Inferred means there was a short hole in the recording and the next trade restored the state.
- Unknown means anything else, and a model never learns from an unknown label.
A label that lands far above the rest gets one more check. The dataset rebuilds the market from the recorded events alone and prices the same sale there. If the two prices agree, the label stays. If not, it becomes unknown. The system never changes a label only because it is large, because a large label may be the one real winner.
Features: what the model sees
A model reads a list of numbers, and mine come in a few kinds. They describe the age of the token and the pace of its activity, the size and depth of its market, how concentrated its holders are, what its creator did before and the state of the market around it. Each is a whole number, so that the training code (Ruby) and the live code (Rust) read exactly the same value. A number that can’t be known stays empty, and the model learns what empty means.
One trap taught me a rule. A count of “everything this creator did since the recording began” grows with the age of the data, so it drifted every week and made the same creator look more experienced with the clock alone. A feature that only grows with the age of the data cannot be an input. Mine now count a window of their own, and the first window of a recording is left out of training, because the live system never shows rows with empty windows.
Keeping the future out
Five things keep the future out of the model:
- Time-ordered splits. I cut the recorded hours into five time slices. Each of the last three is a test once, and the model learns only from the slices before it. A gap equal to the longest a pretend trade can last separates them, so a trade that ends inside the test can’t teach the model.
- No shared creators. When a creator appears in the test, none of that creator’s rows teach the model. Otherwise it learns “this creator wins”, which looks good for a bad reason. It is walk-forward testing with one more rule, and the rule costs me many rows.
- Data nobody reads. The newest days, two by default, are sealed: training and evaluation never open them.
- Everything else stays inside training. Calibration, which turns a model’s raw score into a frequency I can trust, uses the newest part of the training rows that the trees never saw. The tuning of the model’s own settings also happens inside the training rows, in three blocks, and never touches test, calibration or sealed rows.
- A test of the test. One test hands the code a fold whose test rows carry a poisoned feature and an absurd return. If the code read them anywhere, the model would change. It does not change.
The model itself is LightGBM, a library for gradient-boosted trees. I train it from Ruby through Andrew Kane’s lightgbm-ruby gem inside the Rails app, and the Rust core reads the stored model with a small reader of its own. A check compares the two on fixed rows, bit for bit. The raw scores go through a Platt-style calibration, because “20%” should mean that about 20 of 100 such cases happen. A model scores a moment in two ways: by the expected return of the pretend trade after costs, and by how likely that trade is to end at its target before its stop or its time limit. I wrote the plan and the specs; the libraries and the method are other people’s work.
Once a day, on everything
A timer starts a training run every day, because a day without a run is a day the model never saw. A run is due whenever no run covers the latest hour, so a machine that was off for ten days trains once when it returns, not ten times. It builds its data from the first recorded hour up to the sealed days, and it never appends one day to an old file. Some features read the whole history, so a build of one day alone would give other rows than a long one. The latest run read about 58 days of recording. A full replay takes hours, so the program saves what it remembers between two hour files, and the next run plays only the new hours.
The run is its own program, inside a memory fence, so training never starves the recorder, and it works from a copy of the code at one commit. Since early October, 57 daily runs have finished and 2 have failed. A failed run raises one alert, and silence for 30 hours raises another. I keep every model as a numbered version, because I want to compare model families over time.
What a refit changes
The fold tests answer one question: does this design work on the future? They leave serial creators out and stop before the newest days, which is right for a test. A model that trades has no such need, so after the tests the run fits the same design again on every row whose label is final and keeps only the newest three days for calibration. A model from a test fold was 19 days old on its first day of trading, and a refit is about five days old. It also learns from roughly 60% more rows.
I found out how fragile this step is when I looked at the refit table 15 days after the feature shipped and it held zero rows. The refit serves only a model of today’s design, and the design includes the label and feature versions, which had moved on since the models in use were trained. Nothing was broken, but the run recorded only “the new model shows no gain”, which hid the cause. So now every step that can skip writes down why, in words I read, a rule that the telemetry article also lists among my mistakes. A silent skip can hide a stuck loop for weeks. As I write this, the refit has never produced a model in use.
Comparing with the model in use
The model in use is the champion, and a new model is a challenger, as the third article names them. A challenger starts in paper mode, where the system places simulated orders against the live market, and a move to live waits for my decision. A challenger never replaces the champion because it looks good on its own score. The run scores the same held-out decisions with both models and tests the paired difference, so the comparison is on identical rows that the new model never saw. The test and the limit on tries are the subject of the third article.
Put together, one day of training looks like this:
- askThe timer fires and no run covers the latest hour
- └ toolCopy the code at one commit and replay the recorded hours, resuming from the saved state
- thinkLabel every decision moment with a pretend trade and drop unknown labels
- checkCut time-ordered folds with a gap, keep creators on one side, never open the sealed days
- └ toolFit the trees, calibrate on rows they never saw, check the Rust reader bit for bit
- └ toolRefit the same design on every row whose label is final
- checkCompare the new model with the one in use on decisions it never saw
- answerRecord the run and the reason for each skipped step; a model goes to paper or shadow, and a move to live waits for my decision
What a bad paper result taught me
At the start of November my paper results looked bad, and I read them as a verdict on the models. A study of the paper trades showed something else. Nearly all of the damage came from the control arm, a baseline with no model behind it, which loses by design. The model strategies together had too few trades to claim anything, and their results sorted in the right order, higher expectation with higher realized return. The paper engine matched the label rule, so execution was not the cause. The lessons are plain. Keep a control arm, never read its result as a model result, and don’t call a handful of trades a proof.
What I’d tell someone building the same
- Treat the data as the product. Check the rows behind a number before you trust the number.
- Replay with the same code that decides live, in the order it arrives.
- Label the decisions you didn’t take, so the model can learn before it trades.
- Let a label claim only what you saw, and mark the rest unknown.
- Cut by time, add a gap, keep related rows on one side and seal the newest days.
- Prove that the test is clean with a test that poisons it.
- Train on a schedule, and make every skipped step say why.
- Keep a control arm beside the models.
The next article is the software factory. The jail and factory article covers the first part.