Causal Savitzky-Golay Kinematics in MQL5: Non-Repainting Velocity and Acceleration from Local Polynomial Fits
Introduction
Most of the momentum tools available natively in MQL5 come from finite differencing: subtract yesterday's price from today's, divide by the time step, call it velocity. Do it twice and call it acceleration. It works, but differencing amplifies noise badly — every tick of market microstructure noise gets multiplied, not averaged out, and a second difference multiplies it again. The Savitzky-Golay filter exists precisely to fix this: fit a low-degree polynomial to a local window of data by least squares, then read the value and derivatives off the fitted polynomial itself instead of off the raw, noisy samples.
The textbook Savitzky-Golay filter is centered: its fitting window uses samples from both before and after the estimated point. This is fine offline, but impossible on a live chart because the "future" bars do not exist yet. This article builds the one-sided variant instead. The fitting window is entirely trailing, made up of bars that have already closed, and the polynomial is evaluated only at the window's own rightmost point: the most recently closed bar. Nothing computed for a closed bar can ever change once that bar closes, because nothing after it was ever part of the computation. That is the non-repainting property this article sets out to prove, not just assert.
Every quantitative claim is backed by a specific check. Kernel identities are verified on a synthetic polynomial. Non-repainting extraction is checked on real history using two parameterizations of the same API. The demo EA is backtested on three instrument/timeframe combinations, and all results are reported as obtained, including failures.
The primitive built here is not limited to the entry/exit state machine this article demonstrates it with. A non-repainting velocity is a reasonable input to a breakout confirmation filter (did price actually accelerate through the level, or just touch it); a non-repainting acceleration is a candidate input to a volatility-aware trailing-stop distance, since a decelerating move is a different risk profile from an accelerating one even at the same instantaneous velocity. Neither of those is built or tested in this article — they are mentioned only to be clear that CSavGolFilter itself, not the specific EA built on top of it, is the reusable contribution here.
Architecture
The system has one piece of real math and three consumers of it. The math lives entirely in SavGolCore.mqh's CSavGolFilter class, which solves for a fixed set of convolution weights once per (window length, polynomial order, time step) combination and then answers every subsequent bar with a plain dot product. The three consumers are an indicator that plots velocity and acceleration, an EA that trades on their sign agreement, and a self-test script that verifies the class does what its own header box claims.
Pipeline from a closed-bar window to its three consumers

Fig. 1. Architecture: one shared CSavGolFilter instance feeding an indicator, an EA, and a self-test script.
The reason the design separates "solve for the kernels" ( Init ) from "apply the kernels" ( Apply ) is cost. Solving the normal equations involves a matrix transpose, a matrix product, and a matrix inverse — not something you want to repeat on every incoming tick. Because the kernels depend only on the window length, the polynomial order, and the bar period, and never on the price data itself, they can be solved exactly once and reused for the life of the chart. Apply() afterwards is three running sums over a window of at most a few dozen numbers, cheap enough to call on every closed bar without a second thought.
SavGolCore.mqh: Solving for the Kernels
The class declaration below is the only header box CSavGolFilter needs as a whole — the member variables and method signatures inside the class body use plain //--- -style inline comments rather than their own bordered boxes, since MQL5's own declaration-listing convention collapses to one box per class. The out-of-line method bodies further down each get their own header box, because those are separate top-level definitions, not part of the declaration listing.
//+------------------------------------------------------------------+ //| CSavGolFilter | //| CSavGolFilter fits a one-sided (causal) Savitzky-Golay polynomial| //| to a trailing window of N closed bars and returns the fitted | //| value together with its first and second analytic derivatives | //| (velocity, acceleration). The fit is evaluated only at the | //| window's rightmost (most recent) point, so nothing computed for a| //| closed bar ever changes once that bar closes -- the defining | //| property that separates this from the classic centered Savitzky- | //| Golay filter, which needs future samples and therefore repaints. | //+------------------------------------------------------------------+ class CSavGolFilter { private: int m_window; // trailing window length N used for every fit int m_order; // polynomial degree d (order>=2 is required for acceleration) double m_dt; // seconds per bar, scales the raw polynomial coefficients into real units vector m_w_value; // length-N kernel: dot(kernel,window) = smoothed value vector m_w_velocity; // length-N kernel: dot(kernel,window) = first derivative vector m_w_accel; // length-N kernel: dot(kernel,window) = second derivative bool m_ready; // true once Init() has solved the normal equations successfully public: CSavGolFilter(void); ~CSavGolFilter(void); bool Init(const int window,const int order,const double delta_t_seconds); bool Apply(const double &prices[],double &value,double &velocity,double &acceleration) const; bool IsReady(void) const { return(m_ready); } int Window(void) const { return(m_window); } int Order(void) const { return(m_order); } vector WeightsValue(void) const { return(m_w_value); } vector WeightsVelocity(void) const { return(m_w_velocity); } vector WeightsAccel(void) const { return(m_w_accel); } }; CSavGolFilter has seven private data members. Three of them — m_w_value, m_w_velocity and m_w_accel — store the cached convolution kernels, each a length-N vector. The remaining four hold the window length, polynomial order, time step in seconds, and an initialization flag that prevents Apply() from running before the filter is ready. Init() — the Vandermonde fit. A degree-d polynomial p(x) = c0 + c1 x + c2 x^2 +... + cd x^d fitted to N points by ordinary least squares reduces to the normal equations below, solved once for a design matrix that depends only on the window geometry: V = N x (d+1) Vandermonde matrix, V[i][j] = x_i ^ j c = (V^T V)^-1 V^T y // the least-squares solution P = (V^T V)^-1 V^T // (d+1) x N; P applied to ANY window y gives c directly
Two design decisions determine whether this fit is correct and well-behaved. The first is what x_i means: setting x_i = i, with i=0 at the oldest bar, is the more obvious indexing and the wrong one — a polynomial's coefficient c0 is p(0), the fitted value at wherever x=0 sits, so an oldest-bar-at-zero basis gives the value and slope AT THE OLDEST BAR, not the bar the filter is meant to describe. Centering the basis on the evaluation point instead avoids this, so x=0 lands on the newest bar and every older bar gets a negative offset.
The second decision is scale, and it is purely about numerical conditioning, not correctness. Centering alone still leaves x_i ranging from -(N-1) to 0, so the design matrix's column magnitudes grow with window length, and so does V^T V's own scale. Dividing x through by N-1 before raising it to any power keeps x bounded to [-1, 0] regardless of window size; the chain rule then needs one extra factor of that scale per derivative order to get back to real units.
//+------------------------------------------------------------------+ //| CSavGolFilter::Init | //| Solves the one-sided Savitzky-Golay normal equations for a given | //| (window, order, dt) and caches the three resulting convolution | //| kernels. This is the only place matrix algebra happens -- Apply()| //| afterwards is a plain dot product, cheap enough to call every | //| bar. | //+------------------------------------------------------------------+ bool CSavGolFilter::Init(const int window,const int order,const double delta_t_seconds) { m_ready = false; //--- guard: a least-squares fit needs STRICTLY more rows than columns //--- (window > order+1); window==order+1 makes V square, which is //--- exact interpolation through every point in the window, not an //--- overdetermined fit, so it is rejected here too, matching this //--- guard's own wording rather than just excluding window<=order if(window<=order+1 || order<0 || delta_t_seconds<=0.0) return(false); m_window = window; m_order = order; m_dt = delta_t_seconds; //--- scale x into a fixed [-1,0] range instead of leaving it as raw //--- bar offsets i-(N-1): unnormalized, V's column magnitudes grow //--- with the window length (powers of values up to N-1), which both //--- worsens the normal-equations conditioning as the window grows //--- and makes the fixed determinant threshold below increasingly //--- meaningless across different window sizes, since determinant //--- magnitude is scale-dependent, not a true conditioning measure. //--- Normalizing keeps V on a bounded scale regardless of window //--- length; the fitted kernels this produces are mathematically //--- identical to the unnormalized basis once the chain-rule factors //--- below are applied -- only the conditioning of the intermediate //--- solve changes, not the result double x_scale = (m_window>1) ? (double)(m_window-1) : 1.0; matrix V(m_window,m_order+1); for(int i=0;i<m_window;i++) { double x = (double)(i-(m_window-1)) / x_scale; for(int j=0;j<=m_order;j++) V[i][j] = MathPow(x,(double)j); } //--- normal equations: c = (V'V)^-1 V' y. Only the WEIGHTS depend on //--- (window, order, dt) -- never on the price data itself -- so they //--- are solved once here and reused as a fixed convolution kernel on //--- every subsequent bar, the same principle behind the classic SG //--- coefficient tables, just re-derived for a one-sided window matrix Vt = V.Transpose(); matrix VtV = Vt.MatMul(V); //--- this determinant threshold is still not a true condition-number //--- test -- a small-but-nonzero determinant can still coexist with a //--- poorly conditioned matrix -- but normalizing x above keeps VtV's //--- own scale roughly constant across different window lengths, //--- which is what makes a single fixed threshold a reasonable guard //--- here rather than one that silently stops meaning anything as the //--- window grows if(MathAbs(VtV.Det())<1e-12) return(false); matrix P = VtV.Inv().MatMul(Vt); // (d+1) x N pseudo-inverse rows //--- because the basis above is centered on x=0 at the evaluation //--- point, row 0 of P IS the value kernel with no further shift; //--- row 1 is the slope at x=0 and row 2 the curvature at x=0, BOTH //--- still in the normalized x' = x/x_scale units, so the chain rule //--- needs one extra factor of 1/x_scale per derivative order on top //--- of the existing dt scaling: velocity divides by x_scale once, //--- acceleration by x_scale squared m_w_value = P.Row(0); if(m_order>=1) m_w_velocity = P.Row(1)/(m_dt*x_scale); else m_w_velocity = vector::Zeros(m_window); if(m_order>=2) m_w_accel = P.Row(2)*(2.0/(m_dt*m_dt*x_scale*x_scale)); else m_w_accel = vector::Zeros(m_window); m_ready = true; return(true); }
Two things are worth being precise about here. The guard above checks window<=order+1, not merely window<=order, since window==order+1 makes the design matrix square — exact interpolation, not an overdetermined fit, and is rejected for the same reason an underdetermined one is. The determinant threshold below it is still not a genuine condition-number test; a small-but-nonzero determinant can coexist with a badly conditioned matrix in principle. What normalizing x buys is narrower but real and measured: run the same math outside MQL5 at order 2, unnormalized det(V^T V) grows from ~3.6×10^8 at a 21-bar window to ~5.1×10^14 at 101 bars, with condition number growing from ~2.7×10^5 to ~1.8×10^8 — a fixed 1e-12 threshold would reject almost nothing at the larger size regardless of true conditioning. Normalized, both stay roughly flat across the same range (determinant 5.7-506, condition number ~440-500), which is what makes one fixed threshold mean the same thing at any window length. More in Limitations below.
Normalizing changes none of the kernel VALUES that come out the other end — verified, not just argued, by running both bases through the same window/order and confirming the kernels match to floating-point precision; only the intermediate solve's conditioning differs. The centering choice itself protects something specific: a quadratic's acceleration term is a constant ( 2*c2, independent of evaluation point), so an x=i version centered at the oldest bar would still get acceleration right by coincidence while silently getting value and velocity wrong. That split is the exact failure signature SGKinematics_SelfTest.mq5 's identity check is built to catch, discussed in its own section below.
CSavGolFilter::Apply: What the Kernels Actually Look Like
Once Init() has solved for the three kernels, applying them is deliberately uninteresting: three running sums over the same window, guarded by a size check so a caller with an off-by-one in its own rolling-buffer bookkeeping gets a clean false back instead of silently reading garbage.
//+------------------------------------------------------------------+ //| CSavGolFilter::Apply | //| Applies the cached kernels to one trailing window of prices. This| //| is the function called once per closed bar by the indicator, the | //| EA, and the self-test script -- it never allocates, never touches| //| market data itself, and has no notion of time, which is exactly | //| what keeps it reusable across all three. | //+------------------------------------------------------------------+ bool CSavGolFilter::Apply(const double &prices[],double &value,double &velocity,double &acceleration) const { value = 0.0; velocity = 0.0; acceleration = 0.0; //--- refuse rather than compute on a mismatched window: the kernels //--- were solved for an exact length N, and a caller passing a //--- different-sized array almost certainly has an off-by-one in its //--- own rolling-buffer bookkeeping if(!m_ready || ArraySize(prices)!=m_window) return(false); //--- one pass, three running dot products; prices[0] must be the //--- OLDEST bar in the window and prices[m_window-1] the most recently //--- closed bar, matching the i=0..N-1 convention the kernels were //--- solved under in Init() for(int i=0;i<m_window;i++) { value += m_w_value[i] *prices[i]; velocity += m_w_velocity[i] *prices[i]; acceleration += m_w_accel[i] *prices[i]; } return(true); }
It is worth actually looking at what these kernels contain, rather than taking "convolution kernel" on faith. For the project's default window of 21 bars and polynomial order 2, the three kernels look like this:
The three solved kernels for window=21, order=2

Fig. 2. Kernel shapes: the value kernel is a smooth, slightly front-loaded weighting; the velocity kernel is antisymmetric with the heaviest weight on the newest bars; the acceleration kernel is U-shaped, weighting both ends of the window against the middle.
The value kernel sums to exactly 1.0 — a constant input signal must be reproduced unchanged by any least-squares polynomial fit, and that identity is one of the two checks SGKinematics_SelfTest.mq5 runs before anything else. The velocity kernel is close to antisymmetric around the window's center of mass but skews its heaviest weights toward the newest bars, which makes sense: those are the bars closest to, and most informative about, the point the derivative is actually being evaluated at. None of this shape is data-dependent — it falls straight out of the window length and polynomial order chosen at Init() time, which is exactly why solving it once and reusing it is correct.
"Better-behaved than differencing" deserves an actual number, not just a design argument. Standard noise-gain analysis: any derivative estimate that is a fixed linear combination of window prices, sum(w_i * p_i), has noise variance σ² * sum(w_i²) against independent per-bar noise of variance σ². The naive two-point difference (weights [1,-1]/dt ) and three-point second difference (weights [1,-2,1]/dt² ) give noise variances 2σ²/dt² and 6σ²/dt⁴ respectively. Summing the squared kernel weights from Fig. 2 for window=21, order=2 and comparing directly: the SG velocity kernel's noise variance is roughly 99.0% lower than the naive difference's, and the acceleration kernel's roughly 99.997% lower — the real, computed reason local polynomial fitting outperforms direct differencing on noisy input.
This is an analytic noise-gain comparison, not a backtested one, so it says nothing about the smoothing lag a 21-bar window also introduces. The table below is the actual trace behind those two percentages, computed directly from the same kernel-solving code shown in the SavGolCore.mqh section above (dt=1 throughout, since it cancels out of every ratio):
| Quantity | Velocity | Acceleration |
|---|---|---|
| SG kernel: sum(w_i²) | 0.019130 | 0.000178 |
| Naive differencing: sum(w_i²) | 2.0 | 6.0 |
| Ratio (SG/naive) | 0.009565 | 0.0000297 |
| Noise reduction | 99.04% | 99.997% |
The same evaluation-point-centering argument generalizes past order 2, even though this article only ships value/velocity/acceleration (orders 0, 1 and 2). For a polynomial of any degree d fitted with the centered basis, the k-th derivative at the evaluation point is k! · c_k. Extracting a third derivative (jerk) from an order-3 fit would follow the identical pattern — one more cached kernel, P.Row(3) * 6.0 / dt^3 — but it is not something this shipped Apply() computes: its signature is fixed to exactly the three outputs this article uses, and adding a fourth would mean widening that signature, not just adding a kernel.
SGKinematics.mq5: The Indicator
The indicator exposes three buffers but only plots two of them. Velocity and acceleration are on a completely different numeric scale from price, so overlaying the smoothed value on the chart alongside them would make one or the other unreadable. The smoothed value is kept as a hidden calculation buffer instead, reachable from an external script or EA via iCustom()/CopyBuffer() by MQL5's documented buffer-registration mechanism — scope note in Limitations below.
//+------------------------------------------------------------------+ //| Includes | //| one-sided Savitzky-Golay engine (value, velocity, acceleration) | //+------------------------------------------------------------------+ #include <SavGolKinematics\SavGolCore.mqh>
Three inputs cover everything the indicator needs: the window length, the polynomial order, and which of MQL5's applied-price modes to feed into the filter.
//+------------------------------------------------------------------+ //| Inputs | //| fitting window, polynomial order and price source | //+------------------------------------------------------------------+ input int InpWindow = 21; // Trailing window length N (bars per local polynomial fit) input int InpOrder = 2; // Polynomial order d (order>=2 is required for acceleration) input ENUM_APPLIED_PRICE InpAppliedPrice = PRICE_CLOSE; // Applied price fed into the filter
The buffer declarations follow, with the shared CSavGolFilter instance that every function below operates on:
//+------------------------------------------------------------------+ //| Indicator buffers and globals | //| buffer 0 is a hidden calculation buffer (the smoothed value, kept| //| available for iCustom() callers but not drawn); buffers 1-2 are | //| the two plotted lines | //+------------------------------------------------------------------+ double g_buf_value[]; // smoothed value, DRAW_NONE (calculation buffer) double g_buf_velocity[]; // first derivative, plotted double g_buf_accel[]; // second derivative, plotted CSavGolFilter g_filter; // one-sided SG engine shared by every bar
OnInit() refuses to load below polynomial order 2, for a reason specific to this indicator rather than a blanket rule: its whole purpose is to plot BOTH velocity and acceleration, and acceleration is identically zero below order 2, which would otherwise mean silently shipping a flat-zero plot that looks like a real "no acceleration" reading rather than a configuration that was never capable of producing one.
It then wires the three buffers, tells the two plotted lines not to draw until a full window of history actually exists behind them, and fails loading outright if the chosen window/order combination cannot be solved rather than silently drawing zeros. Important detail: the first argument of PlotIndexSetInteger() is a plot index, not a buffer index. This indicator registers three buffers (0, 1, 2) but only two plots exist (indicator_plots=2), because buffer 0 was registered as INDICATOR_CALCULATIONS and never becomes a plot at all. Plot 0 is therefore the first INDICATOR_DATA buffer registered — velocity, buffer 1 — and plot 1 is the second — acceleration, buffer 2. PlotIndexSetInteger(0,...) below addresses velocity, not the hidden calculation buffer, despite the matching "0".
//+------------------------------------------------------------------+ //| OnInit | //| Wires the calculation/plot buffers, tells the two plotted lines | //| not to draw until a full window is available, and solves the SG | //| kernels once via g_filter.Init() -- a bad (window, order) | //| combination fails loading outright instead of silently drawing | //| zeros. This indicator's whole purpose is to show velocity AND | //| acceleration, so it refuses to load below order 2 rather than | //| silently plotting a flat-zero acceleration line, the same | //| requirement SGKinematics_EA.mq5 enforces. | //+------------------------------------------------------------------+ int OnInit(void) { if(InpOrder<2) { Print("SGKinematics: InpOrder must be >=2 -- this indicator plots both " "velocity and acceleration, and acceleration is identically zero " "below order 2."); return(INIT_PARAMETERS_INCORRECT); } SetIndexBuffer(0,g_buf_value,INDICATOR_CALCULATIONS); SetIndexBuffer(1,g_buf_velocity,INDICATOR_DATA); SetIndexBuffer(2,g_buf_accel,INDICATOR_DATA); //--- keep every buffer in plain ascending (non-series) order, matching //--- the oldest-to-newest convention OnCalculate() receives its price //--- arrays in -- this is the same convention CSavGolFilter::Apply() //--- expects, so no reversal is needed anywhere in this file ArraySetAsSeries(g_buf_value,false); ArraySetAsSeries(g_buf_velocity,false); ArraySetAsSeries(g_buf_accel,false); //--- the first InpWindow-1 bars of any run never have a full trailing //--- window behind them, so hide those points instead of plotting a //--- misleading partial fit. PLOT_DRAW_BEGIN's first argument is a //--- PLOT index (0 and 1 here, since indicator_plots=2), not a BUFFER //--- index: plot 0 is the first buffer registered as INDICATOR_DATA //--- above (velocity, buffer 1), plot 1 is the second (acceleration, //--- buffer 2); buffer 0, the hidden INDICATOR_CALCULATIONS buffer, //--- has no plot index of its own and is never addressed here PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,InpWindow-1); PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,InpWindow-1); //--- the still-forming current bar is never drawn either (see //--- OnCalculate() below) -- an explicit empty-value marker, rather //--- than the default of 0.0, keeps that gap from being drawn as a //--- line dropping to zero PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,EMPTY_VALUE); PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,EMPTY_VALUE); if(!g_filter.Init(InpWindow,InpOrder,(double)PeriodSeconds())) { Print("SGKinematics: Init failed for window=",InpWindow, " order=",InpOrder,"; window must exceed order+1."); return(INIT_PARAMETERS_INCORRECT); } IndicatorSetString(INDICATOR_SHORTNAME, StringFormat("SG Kinematics(%d,%d)",InpWindow,InpOrder)); return(INIT_SUCCEEDED); }
A small free function resolves whichever ENUM_APPLIED_PRICE the user picked for one bar index at a time. It is pure array arithmetic with no dependency on the filter's state, which is why it stands alone rather than living inside the class.
//+------------------------------------------------------------------+ //| GetAppliedPrice | //| Resolves the user-selected ENUM_APPLIED_PRICE for one bar index. | //| Kept as a free function (not a method) because it is pure price- | //| array arithmetic with no dependency on the filter state. | //+------------------------------------------------------------------+ double GetAppliedPrice(const ENUM_APPLIED_PRICE applied_price,const int i, const double &open[],const double &high[], const double &low[],const double &close[]) { switch(applied_price) { case PRICE_OPEN: return(open[i]); case PRICE_HIGH: return(high[i]); case PRICE_LOW: return(low[i]); case PRICE_MEDIAN: return((high[i]+low[i])/2.0); case PRICE_TYPICAL: return((high[i]+low[i]+close[i])/3.0); case PRICE_WEIGHTED: return((high[i]+low[i]+2.0*close[i])/4.0); default: return(close[i]); } }
OnCalculate() is what makes the non-repainting claim auditable rather than asserted, and it rests on two separate things, not one. The first is the loop bound itself. A naive incremental loop runs through every index up to rates_total-1 inclusive — which includes the still-forming current bar, since rates_total counts it. Plotting that bar would not quite be a bug (any live indicator's newest point is expected to move until the bar closes), but it sits awkwardly next to "only closed bars are shown," and a casual reader could call it repainting even though the closed bars behind it never change. closed_total = rates_total-1 removes the ambiguity instead: the forming bar's three buffer slots are explicitly set to EMPTY_VALUE every call, and the main loop is bounded at closed_total, never rates_total.
The second is the indexing direction of OnCalculate()'s own price-array parameters. Every index this function computes — closed_total, the loop's start, idx inside the inner window-fill loop — assumes window_prices[0] lands on the oldest bar and the forming bar sits at rates_total-1. That assumption only holds if time[], open[], high[], low[] and close[] are indexed oldest-to-newest, so the function fixes that explicitly with ArraySetAsSeries(...,false) on each one rather than relying on whatever direction they would otherwise arrive in. With both of those in place, the indicator computes, stores, and draws values only for closed bars, with no exceptions. For every bar i that IS computed, the loop builds that bar's OWN trailing window ending at i, never touching anything beyond it.
//+------------------------------------------------------------------+ //| OnCalculate | //| Recomputes only the bars a normal incremental indicator would: on| //| the very first call every closed bar from InpWindow-1 onward; on | //| every later call, only newly-closed bars. The still-forming bar | //| at rates_total-1 is deliberately excluded from the loop entirely | //| and marked empty instead -- this indicator never computes, | //| stores, or draws a value for a bar that has not closed, so there | //| is nothing for the non-repainting claim to carve an exception | //| around: every value this indicator ever shows is for a bar at or | //| before the one being evaluated, full stop, not 'every value | //| except the newest.' The price-array parameters' indexing | //| direction is fixed explicitly below, rather than assumed, since | //| every index in this function depends on it being oldest-to-newest| //+------------------------------------------------------------------+ int OnCalculate(const int rates_total,const int prev_calculated, const datetime &time[],const double &open[],const double &high[], const double &low[],const double &close[],const long &tick_volume[], const long &volume[],const int &spread[]) { //--- every index below (closed_total, the window-fill loop, idx = //--- i-InpWindow+1+k) assumes oldest-to-newest order: index 0 is the //--- oldest bar, index rates_total-1 is the forming one. OnCalculate's //--- own price-array parameters are declared const, so this indicator //--- cannot rely on whatever direction the terminal happens to hand //--- them in by default -- it fixes the direction explicitly instead ArraySetAsSeries(time,false); ArraySetAsSeries(open,false); ArraySetAsSeries(high,false); ArraySetAsSeries(low,false); ArraySetAsSeries(close,false); //--- rates_total-1 is the still-forming current bar; this indicator //--- only ever has closed bars to work with once that one is excluded int closed_total = rates_total-1; if(closed_total<InpWindow) return(0); //--- always clear the forming bar's slot to empty before anything //--- else, since prev_calculated's incremental range below never //--- revisits it once it stops being the newest index g_buf_value[rates_total-1] = EMPTY_VALUE; g_buf_velocity[rates_total-1] = EMPTY_VALUE; g_buf_accel[rates_total-1] = EMPTY_VALUE; //--- prev_calculated equals the previous call's rates_total, so on a //--- tick that closes no new bar it already equals the current //--- closed_total+1 -- start lands on the still-forming index, the //--- loop below (bounded at closed_total) then runs zero iterations, //--- exactly right since nothing new actually closed. On a tick that //--- DOES close a new bar, start lands on exactly that one bar. Either //--- way this is the standard incremental-indicator pattern, just //--- bounded at closed_total instead of rates_total int start = (prev_calculated>InpWindow) ? prev_calculated-1 : InpWindow-1; double window_prices[]; ArrayResize(window_prices,InpWindow); for(int i=start;i<closed_total;i++) { //--- window_prices[0] must land on the OLDEST bar of the window and //--- window_prices[InpWindow-1] on bar i itself, matching the //--- i=0..N-1 convention CSavGolFilter::Init() solved the kernels //--- under -- getting this index backwards does not just flip a //--- sign, it evaluates the fit at the window's other end, against //--- a kernel solved for the opposite time direction for(int k=0;k<InpWindow;k++) { int idx = i-InpWindow+1+k; window_prices[k] = GetAppliedPrice(InpAppliedPrice,idx,open,high,low,close); } double value,velocity,acceleration; if(g_filter.Apply(window_prices,value,velocity,acceleration)) { g_buf_value[i] = value; g_buf_velocity[i] = velocity; g_buf_accel[i] = acceleration; } else { //--- structurally unreachable once OnInit() has succeeded, since //--- window_prices is always sized InpWindow above -- logged //--- anyway rather than left silent, once per occurrence, so a //--- future edit that breaks that invariant is not invisible PrintFormat("SGKinematics: g_filter.Apply() failed unexpectedly at bar %d",i); } } return(rates_total); }
Getting the inner index backwards here — putting the newest bar at window_prices[0] instead of window_prices[InpWindow-1] — would not crash anything, but it reuses kernels solved for one time direction on data running the other way, and that is not simply a sign flip. The kernels are always evaluated at the same grid position (x=0, index InpWindow-1), so handing them a reversed window is equivalent to fitting p(-1-x) instead of p(x) and reading the result off at that same spot — which lands on what was originally the window's oldest bar, not its newest. Velocity comes out as the negative of the original derivative at the oldest bar, not the negated derivative at the newest one, and for anything above a straight-line fit those two generally have different magnitudes, not just opposite signs.
Acceleration is the one piece that survives this unscathed for the default order=2 fit, for any input, not merely as a coincidence of symmetric test data: a quadratic's second derivative is the constant term 2*c2, the same wherever it's evaluated, so reading it off the mirrored fit returns exactly the same value. That invariance is specific to order 2 — a cubic or higher fit's second derivative varies across the window, so the same reversal would generally change it too.
The non-repainting self-test in SGKinematics_SelfTest.mq5, discussed in its own section below, is designed to surface exactly that class of indexing error — though it is worth being precise that the self-test exercises CSavGolFilter::Apply() and its own window-slicing directly, not this file's OnCalculate() itself; the closed-bars-only guarantee described above is a property of this loop's own bounds, confirmed by reading the code, not something the self-test separately re-verifies against this specific file. OnDeinit() has nothing to release — the buffers and the CSavGolFilter member both clean up after themselves when the indicator unloads.
SGKinematics_EA.mq5: Trading the Kinematics
The EA exists to give the filter one concrete, testable consumer beyond an indicator overlay. Its trading rule is deliberately simple: classify velocity and acceleration by sign on every closed bar, enter when acceleration has just turned in the same direction velocity already points (momentum building on an existing drift, not merely price moving), and exit on either deceleration against the position or an outright velocity reversal.
//+------------------------------------------------------------------+ //| Includes | //| the one-sided SG engine, plus the standard trade wrapper for | //| order placement and position management | //+------------------------------------------------------------------+ #include <SavGolKinematics\SavGolCore.mqh> #include <Trade\Trade.mqh>
Risk settings are kept deliberately minimal — a fixed lot size and optional point-distance SL/TP — so that any change in backtest behavior traces back to the kinematics rule itself rather than to a sizing or risk layer sitting on top of it.
//+------------------------------------------------------------------+ //| Inputs | //| fitting parameters plus fixed-lot risk settings; InpOrder must | //| stay >=2 since the state machine trades on acceleration, not just| //| value | //+------------------------------------------------------------------+ input int InpWindow = 21; // Trailing window length N (bars per local polynomial fit) input int InpOrder = 2; // Polynomial order d (must be >=2, acceleration is required) input double InpLots = 0.10; // Fixed lot size per entry input int InpSLPoints = 500; // Stop-loss distance in points (0 disables) input int InpTPPoints = 1000; // Take-profit distance in points (0 disables) input ulong InpMagic = 20260930; // Magic number for this EA's positions
Only one piece of state persists between bars: the previous bar's acceleration sign, needed to detect the exact moment acceleration "just turned" rather than merely "is positive."
//+------------------------------------------------------------------+ //| Globals | //| one filter instance and one trade wrapper shared across all | //| calls; the previous bar's acceleration sign is the only state the| //| trading logic itself needs to remember between bars | //+------------------------------------------------------------------+ CSavGolFilter g_filter; // one-sided SG engine, shared by every bar CTrade g_trade; // order execution / position management wrapper datetime g_last_bar_time; // guards against re-processing the same bar mid-tick int g_prev_accel_sign; // previous closed bar's acceleration sign (-1/0/1)
OnInit() refuses to load on a polynomial order below 2, since the state machine reads acceleration directly and there is no fallback mode that trades on velocity alone.
//+------------------------------------------------------------------+ //| OnInit | //| Refuses to load on an order below 2, since the trading logic | //| reads acceleration directly -- there is no fallback mode that | //| trades on velocity alone. | //+------------------------------------------------------------------+ int OnInit(void) { if(InpOrder<2) { Print("SGKinematics_EA: InpOrder must be >=2, acceleration is required by the state machine."); return(INIT_PARAMETERS_INCORRECT); } if(!g_filter.Init(InpWindow,InpOrder,(double)PeriodSeconds())) { Print("SGKinematics_EA: filter Init failed for window=",InpWindow," order=",InpOrder); return(INIT_PARAMETERS_INCORRECT); } g_trade.SetExpertMagicNumber(InpMagic); g_last_bar_time = 0; g_prev_accel_sign = 0; return(INIT_SUCCEEDED); }
A tiny three-way sign function keeps the state machine below readable as plain comparisons instead of a wall of >0.0 checks repeated everywhere:
//+------------------------------------------------------------------+ //| Sign | //| Three-way sign used to classify velocity and acceleration; kept | //| as a tiny free function so the state machine below reads as plain| //| English rather than a wall of comparison operators. | //+------------------------------------------------------------------+ int Sign(const double x) { if(x>0.0) return(1); if(x<0.0) return(-1); return(0); }
Order placement is a thin wrapper around CTrade, with both the stop-loss and take-profit distances optional (0 disables either one), so the state machine's own exit condition can be tested in isolation from a hard stop fighting it. CTrade's Buy() / Sell() return value only confirms the request was SENT, not that it filled as expected — a request can be accepted by the server and still not produce the position the caller assumes exists, so the actual result code is checked separately and logged on anything other than TRADE_RETCODE_DONE:
//+------------------------------------------------------------------+ //| OpenPosition | //| Places a fixed-lot market order in the given direction with SL/TP| //| measured in points from the fill price. Both distances are | //| optional (0 disables) so the state machine's own exit rule can be| //| tested alone, without a hard stop fighting it. CTrade's return | //| value is a send-success flag, not a fill guarantee -- the | //| position's own result code is checked separately, since a request| //| can be accepted by the server and still not produce the position | //| the caller expects. | //+------------------------------------------------------------------+ void OpenPosition(const ENUM_ORDER_TYPE dir) { double price = (dir==ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol,SYMBOL_ASK) : SymbolInfoDouble(_Symbol,SYMBOL_BID); double point = SymbolInfoDouble(_Symbol,SYMBOL_POINT); double sl = (InpSLPoints<=0) ? 0.0 : (dir==ORDER_TYPE_BUY ? price-InpSLPoints*point : price+InpSLPoints*point); double tp = (InpTPPoints<=0) ? 0.0 : (dir==ORDER_TYPE_BUY ? price+InpTPPoints*point : price-InpTPPoints*point); bool sent = (dir==ORDER_TYPE_BUY) ? g_trade.Buy(InpLots,_Symbol,price,sl,tp,"SGKinematics") : g_trade.Sell(InpLots,_Symbol,price,sl,tp,"SGKinematics"); //--- a false return, or a send that the server accepted but did not //--- actually fill, both need a Journal trace -- otherwise the state //--- machine's next-bar decision would be based on a position that //--- was never really opened if(!sent || g_trade.ResultRetcode()!=TRADE_RETCODE_DONE) PrintFormat("SGKinematics_EA: open %s failed, retcode=%d (%s)", EnumToString(dir),g_trade.ResultRetcode(), g_trade.ResultRetcodeDescription()); }
The state machine itself is the entire trading decision for one closed bar, and it is worth reading end to end because every line in it is either a data-integrity guard or a directly statable trading rule — there is no hidden logic elsewhere.
//+------------------------------------------------------------------+ //| ProcessNewBar | //| The entire trading decision for one closed bar: build the | //| trailing window, fit it, classify velocity/acceleration by sign, | //| check whether any existing position on the symbol is actually | //| this EA's own (by magic number) before acting on it, then act. | //| Entry requires acceleration to have JUST turned in the direction | //| velocity already points -- momentum building on an existing | //| drift, not merely price moving. Exit fires on either deceleration| //| against the position or an outright velocity reversal, whichever | //| comes first. No hysteresis band is applied here; see Limitations | //| in the article for what that costs on noisy instruments. | //+------------------------------------------------------------------+ void ProcessNewBar(void) { double prices[]; ArrayResize(prices,InpWindow); //--- CopyClose with start=1 skips the still-forming bar 0, so this //--- window is built entirely from bars that have already closed; the //--- array keeps its default ascending (non-series) order, matching //--- the oldest-to-newest convention CSavGolFilter::Apply() expects int copied = CopyClose(_Symbol,_Period,1,InpWindow,prices); if(copied!=InpWindow) { //--- a silent return here would leave no Journal trace of why the //--- EA never trades, e.g. on a freshly attached chart before the //--- broker has served InpWindow bars of history -- log it instead PrintFormat("SGKinematics_EA: CopyClose returned %d of %d bars, skipping this bar", copied,InpWindow); return; } double value,velocity,acceleration; if(!g_filter.Apply(prices,value,velocity,acceleration)) { //--- structurally unreachable once OnInit() has succeeded and //--- prices[] is sized correctly above, but logged anyway rather //--- than left silent, in case that invariant is ever broken by a //--- future edit Print("SGKinematics_EA: g_filter.Apply() failed unexpectedly, skipping this bar"); return; } int vel_sign = Sign(velocity); int accel_sign = Sign(acceleration); bool symbol_has_position = PositionSelect(_Symbol); //--- PositionSelect(_Symbol) finds ANY position on this symbol, not //--- just this EA's own -- a manual trade or a different EA sharing //--- the chart would otherwise be silently managed by this state //--- machine. own_position is only true when the magic number also //--- matches; a foreign position is never opened, closed or modified //--- by this EA, but its mere presence still blocks this bar's entry //--- logic below via the early return right after this check bool own_position = symbol_has_position && PositionGetInteger(POSITION_MAGIC)==(long)InpMagic; if(symbol_has_position && !own_position) return; if(!own_position) { //--- enter only when acceleration has JUST turned positive while //--- velocity is already positive, and symmetrically for shorts if(vel_sign>0 && accel_sign>0 && g_prev_accel_sign<=0) OpenPosition(ORDER_TYPE_BUY); else if(vel_sign<0 && accel_sign<0 && g_prev_accel_sign>=0) OpenPosition(ORDER_TYPE_SELL); } else { long pos_type = PositionGetInteger(POSITION_TYPE); bool should_close = (pos_type==POSITION_TYPE_BUY && (accel_sign<0 || vel_sign<=0)) || (pos_type==POSITION_TYPE_SELL && (accel_sign>0 || vel_sign>=0)); //--- exit on deceleration against the open position or an outright //--- velocity reversal, whichever condition fires first if(should_close && !g_trade.PositionClose(_Symbol)) PrintFormat("SGKinematics_EA: PositionClose failed, retcode=%d (%s)", g_trade.ResultRetcode(),g_trade.ResultRetcodeDescription()); } g_prev_accel_sign = accel_sign; }
Two details here matter for correctness, not just style: CopyClose starts at shift 1, deliberately skipping the still-forming bar, so every decision is based strictly on closed bars; and the returned array stays in its default ascending order, matching what Apply() expects — calling ArraySetAsSeries on it would silently reverse the array and flip the sign of every derivative without raising any error. Both early returns above are logged rather than silent: a CopyClose() shortfall (realistically, a freshly attached chart before the broker has served enough history) prints exactly how many bars came back against how many were needed, so an EA that never trades leaves a Journal trace explaining why instead of none at all.
PositionSelect(_Symbol) finds ANY position on the symbol, not specifically this EA's own, so own_position additionally checks PositionGetInteger(POSITION_MAGIC) against InpMagic before acting. A position on the symbol with a different magic number is never opened, closed or modified by this EA — that part is correct — but it is not simply left out of the picture either: the early return right after the ownership check means ProcessNewBar() does nothing else for that bar, so a foreign position does block this EA from opening a new entry of its own for as long as that foreign position stays open, even though the EA never touches it directly. The edge case that decision introduces, and the remaining single-position-only scope, are covered in Limitations below.
OnTick() is intentionally thin: it exists only to detect a new closed bar and hand off to ProcessNewBar() exactly once per bar, since re-running the same decision on every incoming tick within an unchanged bar would just repeat the same verdict while burning cycles.
SGKinematics_SelfTest.mq5: Proving It Rather Than Assuming It
This script is not a formality. It exists specifically to catch the class of error described in the SavGolCore.mqh section above — a plausible-looking but wrong evaluation point — before it can reach a backtest, where a systematically wrong velocity and acceleration would be much harder to notice than an outright crash. It runs two independent checks and prints a plain PASS/FAIL verdict for each.
//+------------------------------------------------------------------+ //| Inputs | //| window/order match the indicator and EA defaults so the | //| identities checked here are the ones actually shipped; | //| InpTestBars/Samples control how much real history the non- | //| repainting check pulls from | //+------------------------------------------------------------------+ input int InpWindow = 21; // Trailing window length N, same convention as the indicator/EA input int InpOrder = 2; // Polynomial order d (must be >=2 to exercise acceleration) input int InpTestBars = 600; // Real closed bars pulled for the non-repainting check input int InpNonRepaintSamples = 8; // Sample bar offsets checked within that history
The first check has nothing to do with market data. It tests two closed-form identities against the solved kernels themselves: the value kernel must sum to exactly 1.0 (a constant signal has to be reproduced unchanged by any least-squares polynomial fit, by definition), and a synthetic sequence deliberately built to BE an exact degree-2 polynomial must come back with value, velocity and acceleration matching that polynomial's own closed-form derivatives, since an order-2 fit of order-2 data has zero residual.
//+------------------------------------------------------------------+ //| TestWeightIdentities | //| Two independent correctness checks on the solved kernels | //| themselves, with no market data involved. (1) The value kernel | //| must sum to exactly 1.0, the textbook identity that a constant | //| signal is reproduced unchanged by any least-squares polynomial | //| fit. (2) A synthetic sequence built to BE an exact degree-2 | //| polynomial must come back with value/velocity/acceleration | //| matching the closed-form derivatives of that polynomial, since a | //| degree-2 fit of degree-2 data has zero residual by construction. | //+------------------------------------------------------------------+ bool TestWeightIdentities(void) { bool all_passed = true; //--- identity 1: sum of the value kernel must equal 1.0 vector w_value = g_filter.WeightsValue(); double weight_sum = w_value.Sum(); double sum_error = MathAbs(weight_sum-1.0); PrintFormat(" [1] value-kernel sum = %.10f (error %.2e) -> %s", weight_sum,sum_error,(sum_error<1e-8 ? "PASS" : "FAIL")); if(sum_error>=1e-8) all_passed = false; //--- identity 2: a hand-built exact quadratic y_i = a + b*i + c*i^2 //--- must be reproduced exactly (up to floating-point noise) because //--- an order-2 least-squares fit of order-2 data has zero residual double a = 100.0, b = 0.5, c = -0.02; double dt = 60.0; // arbitrary fixed seconds-per-bar for this synthetic check CSavGolFilter probe; if(!probe.Init(InpWindow,InpOrder,dt)) { Print(" [2] probe filter failed to Init -- cannot run polynomial-recovery check"); return(false); } double synthetic[]; ArrayResize(synthetic,InpWindow); for(int i=0;i<InpWindow;i++) synthetic[i] = a+b*i+c*i*i; double value,velocity,acceleration; probe.Apply(synthetic,value,velocity,acceleration); int n = InpWindow-1; double expect_value = a+b*n+c*n*n; double expect_vel = (b+2.0*c*n)/dt; double expect_accel = 2.0*c/(dt*dt); double value_err = MathAbs(value-expect_value); double vel_err = MathAbs(velocity-expect_vel); double accel_err = MathAbs(acceleration-expect_accel); PrintFormat(" [2] value computed=%.8f expected=%.8f error=%.2e -> %s", value,expect_value,value_err,(value_err<1e-6 ? "PASS" : "FAIL")); PrintFormat(" velocity computed=%.8f expected=%.8f error=%.2e -> %s", velocity,expect_vel,vel_err,(vel_err<1e-6 ? "PASS" : "FAIL")); PrintFormat(" accel computed=%.8f expected=%.8f error=%.2e -> %s", acceleration,expect_accel,accel_err,(accel_err<1e-6 ? "PASS" : "FAIL")); if(value_err>=1e-6 || vel_err>=1e-6 || accel_err>=1e-6) all_passed = false; return(all_passed); }
The second check is narrower than "non-repainting" might suggest, worth stating precisely. Both windows compared come from the identical CopyClose() API against the identical terminal history cache — two differently-parameterized calls to one mechanism, not two independent retrieval methods. For several real calendar bars deep in recent history, it compares the window this script's own slicing builds for that bar against a second window re-fetched with a tighter call bounded at the exact same bar; both should be bit-identical, since neither extraction reads past the bar being evaluated.
It does not simulate a live deployment before those future bars existed (every bar already exists in history when the script runs), and it does not exercise OnCalculate() or ProcessNewBar() directly — only CSavGolFilter::Apply() and this script's own slicing, which both consumer files are separately built on top of. What it establishes: the extraction never depends on data falling after the bar it is computing, the exact mechanism that would break first if a future bar leaked into a window.
//+------------------------------------------------------------------+ //| TestNonRepainting | //| What this actually checks, stated precisely: both windows below | //| come from the SAME CopyClose() API against the SAME terminal | //| history cache -- this is not two different retrieval mechanisms, | //| only two differently-parameterized calls to the one mechanism | //| available. For several real calendar bars deep inside recent | //| history, the window this article's extraction logic builds for | //| that bar -- and therefore the filter's output at that bar -- is | //| identical whether it is sliced out of one large history pull or | //| re-fetched with a tighter call bounded exactly at that bar. It | //| does not simulate deploying the indicator live before those | //| future bars existed, and it does not exercise the indicator's or | //| EA's own window-extraction code paths (OnCalculate/ProcessNewBar)| //| directly -- only CSavGolFilter::Apply() and this script's own | //| slicing. What it does check: the extraction never reads past the | //| bar being evaluated, which is the mechanism that would break | //| first if a future bar ever leaked into the window. | //+------------------------------------------------------------------+ bool TestNonRepainting(void) { double big_history[]; int copied = CopyClose(_Symbol,_Period,1,InpTestBars,big_history); if(copied!=InpTestBars) { PrintFormat(" could not pull %d closed bars (got %d) -- skipping",InpTestBars,copied); return(false); } double max_abs_diff = 0.0; int checked = 0; //--- spread the sample offsets evenly across the middle of the pulled //--- history, away from both edges, so this is several separate //--- checks rather than one convenient point for(int s=0;s<InpNonRepaintSamples;s++) { int k = InpWindow-1+(s+1)*(InpTestBars-InpWindow)/(InpNonRepaintSamples+1); if(k<InpWindow-1 || k>=InpTestBars) continue; //--- view A: slice the window straight out of the already-pulled //--- big_history array, which also contains hundreds of bars AFTER //--- calendar position k double window_a[]; ArrayResize(window_a,InpWindow); for(int i=0;i<InpWindow;i++) window_a[i] = big_history[k-InpWindow+1+i]; //--- view B: a second CopyClose() call, same API and same terminal //--- source as view A, just a different (window,shift) request //--- bounded exactly at the same calendar bar int shift_k = InpTestBars-k; double window_b[]; if(CopyClose(_Symbol,_Period,shift_k,InpWindow,window_b)!=InpWindow) continue; double val_a,vel_a,acc_a,val_b,vel_b,acc_b; g_filter.Apply(window_a,val_a,vel_a,acc_a); g_filter.Apply(window_b,val_b,vel_b,acc_b); double diff = MathMax(MathAbs(val_a-val_b), MathMax(MathAbs(vel_a-vel_b),MathAbs(acc_a-acc_b))); max_abs_diff = MathMax(max_abs_diff,diff); checked++; PrintFormat(" sample %d (bar shift %d): value diff=%.3e velocity diff=%.3e accel diff=%.3e", s+1,shift_k,MathAbs(val_a-val_b),MathAbs(vel_a-vel_b),MathAbs(acc_a-acc_b)); } PrintFormat(" checked %d sample bars, max abs difference = %.3e -> %s", checked,max_abs_diff,(checked>0 && max_abs_diff<1e-9 ? "PASS" : "FAIL")); return(checked>0 && max_abs_diff<1e-9); }
Both checks run from one entry point, which fails fast if the shipped window/order combination cannot even be solved. Running this script is the first thing that should happen with any new (window, order) combination, before the indicator or EA loads live — a filter solved under a wrong convention still loads and runs without complaint, since Apply() has no way to know its kernels were built on a wrong basis. A passing run confirms the chosen indexing and the two closed-form identities for the specific (window, order, dt) tested; it says nothing about tradeability, about whether a different window or order stays as well-conditioned (see SavGolCore.mqh above), or about numerical stability outside the parameters this article tested.
//+------------------------------------------------------------------+ //| OnStart | //| Runs both checks in sequence and prints one final verdict line. | //| Exits early if the shipped (InpWindow, InpOrder) combination | //| cannot even solve -- that failure mode belongs to Init(), already| //| covered by the guard clauses documented in SavGolCore.mqh. | //+------------------------------------------------------------------+ void OnStart(void) { Print("=== SGKinematics_SelfTest ==="); if(!g_filter.Init(InpWindow,InpOrder,(double)PeriodSeconds())) { Print("g_filter.Init() failed for the configured window/order -- aborting."); return; } Print("-- Weight identities --"); bool identities_ok = TestWeightIdentities(); Print("-- Non-repainting extraction check --"); bool norepaint_ok = TestNonRepainting(); PrintFormat("=== RESULT: weight identities %s, non-repainting %s ===", (identities_ok ? "PASS" : "FAIL"), (norepaint_ok ? "PASS" : "FAIL")); }
The failure signature of the wrong-evaluation-point mistake on this same check is worth knowing, since acceleration is the one output that mistake does not corrupt: value and velocity fail while the sum-to-one identity and acceleration recovery still pass, because a quadratic's second derivative is constant regardless of evaluation point. That split — two failing, two passing, specifically which two — is the signature to watch for if this class of error resurfaces. The identities were independently re-verified outside MQL5 for the normalized basis (kernels came back numerically identical to the unnormalized version, per SavGolCore.mqh above), but a live console run of this script against real history, inside the MQL5 terminal itself, is the only confirmation that actually counts for the MQL5 implementation specifically.
Testing in the Strategy Tester
Three real Strategy Tester runs on SGKinematics_EA.mq5, same defaults throughout ( InpWindow=21, InpOrder=2, InpLots=0.10, InpSLPoints=500, InpTPPoints=1000 ), same 2026.01.01–2026.09.26 window, same $100,000 deposit, 1-minute OHLC modeling. The instrument/timeframe matrix was chosen to span a wide range of bar counts over the same real calendar period: XAUUSD M5 (the most bars), GBPUSD M15, and EURUSD H1 (the fewest). None of the five EA parameters were tuned for this table: window=21/order=2 is the same filter default discussed in the Apply() section above, a fixed 0.10 lot keeps position sizing out of the comparison entirely, and SL=500/TP=1000 points is a plain 1:2 risk/reward with no optimization pass run against it.
These fixed point distances are demonstration parameters rather than volatility-normalized risk limits. Their effective size relative to market volatility and trading costs differs across instruments, so the results should not be interpreted as a controlled comparison of trading performance between symbols. This is a single-configuration smoke test of the filter feeding a trading decision, not a tuned strategy result, and no parameter sweep (window, hysteresis, SL/TP, or otherwise) was run to find a better-performing configuration.Test environment. All three runs used the same USD-denominated demo trading account, with 1:100 leverage and a $100,000 initial deposit, on terminal build 6230. The Strategy Tester reports indicated 100% history quality for all three symbols. Commission is recorded as 0.00 per trade in every exported report — this is a demo account with no commission charged, not a commission-free claim about live trading. The exported reports do not record a spread value or an explicit execution/fill-model setting, so this table does not claim a particular spread regime or slippage assumption held constant across the three runs; a broker/account combination with meaningfully different spread or execution behavior on these symbols could change the trade counts and net results shown below, and that has not been tested here.
| Metric | XAUUSD M5 | GBPUSD M15 | EURUSD H1 |
|---|---|---|---|
| Total trades | 2,198 | 671 | 164 |
| Win rate | 33.62% | 32.04% | 35.98% |
| Profit factor | 0.89 | 0.70 | 0.69 |
| Net profit, USD | -6,816.86 | -1,267.78 | -507.95 |
| Sharpe ratio | -5.00 | -5.00 | -3.50 |
| Max equity drawdown | 7.64% | 1.38% | 0.83% |
Trade count and net profit across the three tested combinations

Fig. 3. Real Strategy Tester results: all three combinations lost money, and net loss scales with trade count, not against it.
All three combinations lost money. Profit factor stayed under 1.0 on every one, and win rate clustered in the same narrow 32–36% band regardless of instrument or timeframe, which is itself informative: a state machine whose entry condition is this permissive (any sign agreement between velocity and acceleration, no minimum magnitude, no hysteresis) does not discriminate well between genuine momentum and ordinary noise, and that shows up as a fairly constant, fairly poor hit rate rather than a hit rate that varies meaningfully with the instrument.
Observed correlation, with only three data points: net loss increases with trade count (XAUUSD M5: 2,198 trades, the biggest loss; EURUSD H1: 164 trades over the identical calendar window, the smallest). One plausible mechanism fits — more bars means more noise-driven sign flips, each a potential entry/exit with no magnitude threshold or hysteresis — but trade count is itself a downstream consequence of timeframe, so the same three runs also differ in spread-to-move ratio, pip value, SL/TP geometry, and OHLC-modeling accuracy (below), any of which could independently correlate with both trade count and loss without the sign-flip mechanism driving it. Three combinations sharing default settings is too small and too confounded a sample to call the mechanism demonstrated rather than merely consistent with the data; a real test would isolate trade count as the deliberately varied axis (the same instrument/timeframe swept across hysteresis thresholds) rather than three points differing in several ways at once.
All three runs used 1-minute OHLC modeling, not full tick simulation, with identical default inputs and no parameter sweep. OHLC modeling matters specifically for the SL/TP numbers: when a bar's range touches both levels, it infers an intrabar touch order rather than observing real ticks, and that inferred order can differ from what actual ticks would do, more so on wider-range XAUUSD bars. More broadly, three runs cannot separate the entry/exit rule's own contribution from spread, commission, the chosen SL/TP distances, this modeling limitation, each instrument's cost regime, and the window/order parameters — none varied independently of the rule itself. A profit factor consistently under 1.0 across three unrelated instruments is still a real signal this configuration lacks edge under these settings; it is not, on its own, proof no parameterization could ever be profitable, nor a clean isolation of the rule's effect from everything else listed here.
Limitations and Practical Considerations
No hysteresis band on the sign flips. The entry and exit conditions react to the bare sign of velocity and acceleration, with no minimum magnitude and no requirement that the sign hold for more than one bar. On a noisy instrument this means a kernel output that oscillates near zero — which any real acceleration series will do constantly, since acceleration is the more noise-sensitive of the two derivatives — can flip the state machine's decision on consecutive bars. The real testing results are consistent with this: the combination with the most bars and the most opportunities for small sign flips (XAUUSD M5) lost the most.
A wrong evaluation point is a specific, catchable failure mode, not a generic "test your code" reminder. The evaluation-point-centering choice explained in the SavGolCore.mqh section is worth restating as a general lesson for anyone adapting this approach to a different derivative order or a different basis: any one-sided local-polynomial derivative estimator has to make an explicit choice about where its basis is centered, and a natural-looking but wrong choice can still pass a partial correctness check. For a quadratic fit specifically, the acceleration kernel is evaluation-point-independent, so a wrong centering choice would corrupt value and velocity while leaving acceleration looking correct by coincidence. For a cubic or higher-order fit, none of the derivative kernels have that protection — a wrong evaluation point corrupts every output, with no coincidental survivor to hint that something is off. Testing every output the filter produces, not just the ones that happen to look reasonable, is what actually catches this class of error.
The acceleration kernel is the noisiest by construction. Differentiating a least-squares polynomial fit twice concentrates more of the fit's remaining residual into the second derivative than the first, and the first more than the raw value. The noise-gain figures in the Apply() section above are the actual measure of this, not a restatement of it — they quantify the noise reduction, not the responsiveness cost. A larger window or a lower polynomial order trades responsiveness (more smoothing lag) for a smoother acceleration output; this article ships window=21, order=2 as a reasonable default, not a tuned optimum, and no lag-versus-noise sweep across window sizes was run.
The non-repainting proof has a specific, stated scope — summarizing the self-test section's own precision rather than repeating it in full here: it verifies CSavGolFilter::Apply() and its own window-slicing, not OnCalculate() or ProcessNewBar() directly, and it checks that the extraction never reads past the evaluated bar, not what a live trader would have seen in the past. The property actually relied on in production — a closed bar's value never changing later — follows from the fixed, backward-looking loop bounds shown directly in those two files' own sections above.
Normal equations square the condition number; the singularity guard improves scale-stability, but is not a true conditioning test. Solving via (V^T V)^-1 V^T squares the design matrix's condition number compared to a QR- or SVD-based solve, a standard tradeoff accepted here rather than engineered around. Normalizing x keeps that squared number from growing with window length, measured directly in the SavGolCore.mqh section above, but a small-but-nonzero determinant can still coexist with a poorly conditioned matrix in principle, at orders or ratios untested here. For window=21, order=2, V^T V's condition number is a modest few hundred and normal equations are adequate; a QR/SVD solve would be the more robust choice at substantially higher orders.
Real-time delay is unaddressed. The non-repainting guarantee is about values never changing retroactively once a bar closes, not about how soon after that the EA or indicator acts — at most one bar period here, the same latency any bar-close-triggered system has.
Single position per symbol, no portfolio awareness. The EA checks POSITION_MAGIC before treating a symbol's position as its own, so it never opens, closes or modifies a manual trade or a different EA's position — but a foreign position on the same symbol does still block it: ProcessNewBar() returns early whenever any position exists on the symbol that is not its own, so this EA cannot open a new entry of its own while that foreign position is open, even though it never acts on the foreign position directly. It also still manages only one position of its own at a time: no pyramiding, no partial closes. One edge case follows from the same early return: on a bar where a foreign position causes ProcessNewBar() to return early, g_prev_accel_sign is not updated, so "just turned" detection on regaining control can compare against a stale value. This only matters if something else trades the identical symbol while this EA is attached.
The hidden calculation buffer's external accessibility is a documented mechanism, not independently verified here. CopyBuffer() addresses a custom indicator's buffers by SetIndexBuffer() registration order, which includes INDICATOR_CALCULATIONS buffers — the documented basis for the SGKinematics.mq5 section's claim that the smoothed-value buffer stays reachable externally. No companion script demonstrating that call ships with this article, so treat it as the intended mechanism, not something numerically confirmed here.
Conclusion
A one-sided Savitzky-Golay fit gives velocity and acceleration that are, for every closed bar, provably non-repainting, and that have a measured, analytic noise-gain advantage over naive finite differencing (roughly 99% lower noise variance on velocity, roughly 99.997% lower on acceleration, for this article's default window/order), at the cost of one matrix solve per configuration change rather than per bar. The key contribution is the verified primitive: CSavGolFilter, with two identity checks and a non-repainting extraction check. Their scope is stated explicitly: they validate the core extraction logic, but do not validate the consumer code, tradeability, or behavior outside the tested parameters.
The demonstration EA built on top of it is honestly reported as a net loser on every instrument tested, correlated with trade count in a pattern consistent with (but not proof of) a no-hysteresis sign-flip explanation, alongside several other differences between the three runs that the testing could not separate out. Anyone building on this should treat the filter as the reusable, verified part and the trading rule as a starting point that needs at minimum a hysteresis band and a wider, deliberately-controlled test matrix before it is worth testing further.
| File | Type | Description |
|---|---|---|
| SavGolCore.mqh | Include | CSavGolFilter: solves the one-sided SG normal equations once, applies the cached kernels every bar |
| SGKinematics.mq5 | Indicator | Plots velocity and acceleration; smoothed value kept as a hidden calculation buffer for iCustom() |
| SGKinematics_EA.mq5 | Expert Advisor | Trades on velocity/acceleration sign agreement, fixed lot, optional SL/TP |
| SGKinematics_SelfTest.mq5 | Script | Verifies the value-kernel identity, synthetic-polynomial recovery, and the non-repainting extraction logic |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.