Building a Trading Model That Learns One Bar at a Time

Wait 5 sec.

Building a Trading Model That Learns One Bar at a Time EUR/USDOANDA:EURUSDRabieg“Machine learning” sounds complicated, but a useful online trading model can be built from a surprisingly small process. It does not need to retrain an enormous neural network every minute. At its core, it can repeat five steps: Measure the current market. Make a probability forecast. Save the information used for that forecast. Wait until the outcome is known. Update the model. The difficult part is not the equation. The difficult part is respecting time. 1. Start with one clearly defined question Before choosing features, decide what the model predicts. Example: Will price reach +1 ATR before reaching −1 ATR during the next twelve bars? This is more useful than asking whether the next candle will be green. The label contains: A direction A profit threshold A risk threshold A time horizon Alternative events might include: Forward return greater than estimated costs Breakout continuation Mean reversion to VWAP Volatility expansion Trend persistence A higher high before a lower low The event should match the intended trading decision. 2. Build features using information available now At bar t, possible features include: Adaptive momentum Z-score Trend-slope Z-score Volume-surprise Z-score ATR percentile Price position inside a channel Distance from VWAP Directional efficiency Higher-timeframe trend Current regime probabilities Every feature must be calculable with information available at bar t. A centered moving average using future bars is not allowed. A confirmed pivot that requires several future bars cannot be treated as known at the pivot bar. Historical perfection created through future confirmation is not real-time predictability. 3. Predict before training The model should first calculate its probability using the current weights: pₜ = sigmoid(b + w · xₜ) Only after making and recording the prediction should the model eventually train on that observation. This distinction matters. If a historical script updates its weights using the current outcome and then displays the probability produced by the updated weights on that same bar, it is showing a probability the model could not have produced in real time. The correct historical probability is the forecast generated before the outcome was known. 4. Store the observation For a fixed twelve-bar label, store: Bar index Feature vector Predicted probability Reference price ATR or target distance Any information needed to construct the future label After twelve bars—or after one barrier is reached—the observation becomes eligible for training. In Pine Script, this can be managed with arrays or a circular buffer. The broader concept is independent of programming language: Predictions and labels must remain aligned through time. 5. Resolve the label Suppose the event uses two barriers: Upper barrier: entry price + 1 ATR Lower barrier: entry price − 1 ATR During the next twelve bars: If the upper barrier is reached first, y = 1. If the lower barrier is reached first, y = 0. If neither is reached, the observation can be discarded or assigned according to a clearly stated timeout rule. If both are touched inside the same candle, intrabar ordering may be unknowable from standard OHLC data. That final issue is important. A backtest using only bar-level data cannot always determine which level was reached first. The honest solution is to: Use lower-timeframe data when available Apply a conservative assumption Exclude ambiguous observations Disclose the limitation 6. Train on the delayed observation Once the outcome is known: Error = yₜ − pₜ Then update: w ← (1 − ηλ)w + η × sample weight × Error × xₜ This single observation slightly changes the model. The next prediction uses the updated weights. Over time, the process creates a path-dependent model whose state reflects the sequence of previous observations. 7. The warm-up period An online model should not be trusted immediately. It needs enough observations to establish: Feature means Feature variances Model weights Class balance Error statistics Calibration estimates During warm-up, the indicator can display: Learning—insufficient completed outcomes The chart may still show probability estimates, but they should not be presented as mature signals. A minimum observation requirement prevents a handful of early bars from creating false confidence. 8. Class imbalance Suppose the event occurs only 25% of the time. A useless model that always predicts “no event” would be directionally correct 75% of the time. This demonstrates why accuracy alone can be misleading. Possible responses include: Weight positive examples more heavily Adjust the decision threshold Redefine the event Measure precision and recall Compare against the base rate Use probability scoring rather than accuracy alone The model must outperform a reasonable baseline, not merely produce a high headline percentage. 9. Evaluate probabilities as probabilities A model predicting 0.60 is not claiming certainty. Over a sufficiently large sample of similar forecasts, approximately 60% should ideally resolve positively. The Brier score measures squared probability error: Brier = average Lower values are better. A forecast of 0.90 that fails receives a much larger penalty than a forecast of 0.55 that fails. This rewards models that are accurate and appropriately confident. The Brier score originates from probability-forecast evaluation, while proper scoring-rule research formalizes methods that reward honest probabilistic forecasts. 10. Build a reliability table Group completed forecasts into probability ranges: Forecast rangeNumber of observationsActual positive rate 0.40–0.5012044% 0.50–0.6018054% 0.60–0.7014063% 0.70–0.807068% 0.80–0.902060% This hypothetical example reveals overconfidence at higher probabilities. The model may be directionally useful while still requiring calibration. A strategy should not size risk aggressively from an uncalibrated probability. 11. Use a benchmark Compare the adaptive model against: A constant base-rate forecast A simple trend rule A fixed logistic model A single-feature model A random or neutral forecast where appropriate A complicated model that barely improves on a simple benchmark may not justify its added instability. Complexity should earn its place. 12. Use feature ablation Remove one feature and repeat the evaluation. If performance does not deteriorate, that feature may be redundant. If performance improves, the feature may be adding noise. Ablation helps answer: Does volume add information beyond momentum? Does volatility improve timing? Does the higher-timeframe trend reduce false signals? Does regime filtering genuinely improve calibration? This is more informative than assuming every additional input makes the model stronger. 13. Avoid overlapping-label deception If each label spans twenty bars but a new prediction is created every bar, neighboring observations share much of the same future period. This makes the sample appear larger and more independent than it really is. Possible solutions include: Train less frequently Use non-overlapping observations Account for dependence in evaluation Separate training and evaluation periods carefully Use walk-forward validation The important point is that 10,000 overlapping labels do not necessarily provide 10,000 independent pieces of evidence. 14. Real-time versus historical recalculation When a script is applied to a chart, Pine recalculates historical bars in sequence. An online model can therefore reconstruct the state it would have reached historically—provided the script never accesses future information. But the result remains sensitive to: Starting date Available history Symbol Timeframe Session settings Feature initialization Missing bars Corporate actions or data revisions Online learning is path-dependent. Starting the model at a different point can produce different weights. This should be disclosed rather than hidden. Final takeaway A real-time learning model is not defined by how complicated its mathematics appears. It is defined by whether it respects the order in which information becomes available. A trustworthy process is: Observe → Predict → Store → Wait → Resolve → Score → Update Breaking that sequence can create beautiful historical results that were impossible to achieve live. Respecting it creates something far more valuable: An honest adaptive experiment. Closing discussion question Which label would be most useful to you: forward return, target-before-stop, breakout continuation, or mean reversion?