Support Board
Date/Time: Sat, 01 Mar 2025 08:09:44 +0000
[Programming Help] - How to apply EMA to an SMA in C++ and correctly warm-up with historical data.
View Count: 773
[2021-09-21 05:15:49] |
hanw - Posts: 15 |
Hi, I have the following code that computes the EMA of an SMA indicator and plotted them on an 1-minute grpah. What I have found is the sma indicator is correctly calculated, but the ema indicator is calculated with wrong data for the first 5 minutes or so. I suspect it is because the sma data is unavailable for the first 5 minutes after the algorithm starts. Is there any way to warming up the sma data with historical data in a program? When I tried to apply ema on a sma in a chart, everything works fine. I just could not get it to work in code. SCSubgraphRef sma = sc.Subgraph[0]; SCSubgraphRef ema_of_sma = sc.Subgraph[1]; sc.MovingAverage(sc.Close, sma, MOVAVGTYPE_SIMPLE, 5); sc.MovingAverage(sma, ema_of_sma, MOVAVGTYPE_EXPONENTIAL, 5); SCString message; float sma = sc.Subgraph[0][sc.Index]; float ema_of_sma = sc.Subgraph[1][sc.Index]; message.Format("%.2f %.2f %.2f", sc.Close[sc.Index], sma, ema_of_sma); sc.AddMessageToLog(message, 0); Date Time Of Last Edit: 2021-09-21 18:48:54
|
[2021-09-21 15:20:26] |
ForgivingComputers.com - Posts: 1015 |
The SMA needs 5 bars to calculate its first value, and the EMA needs 5 bars of the SMA, so you will want to avoid calculating the SMA if not on bar 5 or higher, and the EMA unless on bar 10 or higher: SCSubgraphRef sma = sc.Subgraph[0];
SCSubgraphRef ema_of_sma = sc.Subgraph[1]; if (sc.Index < 5) return; sc.MovingAverage(sc.Close, sma, MOVAVGTYPE_SIMPLE, 5); if (sc.Index < 10) return; sc.MovingAverage(sma, ema_of_sma, MOVAVGTYPE_EXPONENTIAL, 5); |
To post a message in this thread, you need to log in with your Sierra Chart account: