NexusFi: Find Your Edge


Home Menu

 





How to code a Simple Moving Average?


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one Fat Tails with 2 posts (0 thanks)
    2. looks_two MXASJ with 1 posts (1 thanks)
    3. looks_3 Big Mike with 1 posts (1 thanks)
    4. looks_4 Quick Summary with 1 posts (0 thanks)
    1. trending_up 11,108 views
    2. thumb_up 2 thanks given
    3. group 1 followers
    1. forum 5 posts
    2. attach_file 2 attachments




 
Search this Thread
  #1 (permalink)
 
Fat Tails's Avatar
 Fat Tails 
Berlin, Europe
Market Wizard
 
Experience: Advanced
Platform: NinjaTrader
Broker: Interactive Brokers
Trading: Futures & Stocks
Posts: 9,887 since Mar 2010
Thanks Given: 4,242
Thanks Received: 27,114

I always thought that the SMA - the simple moving average - was one of the simplest indicators. But as it appears, it is not easy to code one that is working correctly.


Standard Formula

The standard formula for the SMA is well-known. You add up the input values for the last n periods and divide it by n. If you code this in NinjaScript it will essentially look like this:

 
Code
 
protected override void OnBarUpdate()
{
if (CurrentBar == 0)
Value.Set(Input[0]);
else
{
if (CurrentBar >= Period)
{ 
double sum = 0;
for (int i = 0; i<Period; i++)
sum = sum + Input[i];
Value.Set(sum/Period);
}
else
Value.Set((Value[1]* Math.Min(CurrentBar, Period) + Input[0]) / (Math.Min(CurrentBar, Period) + 1));
}
}

Recursive Formula

Now, NinjaTrader developpers are clever. They use a recursive formula which calculates much faster, as it takes the previous SMA, multiplies it with the period, then adds the new input value and subtracts the value n periods ago. The NinjaTrader SMA therefore looks like this:

 
Code
 
protected override void OnBarUpdate()
{
if (CurrentBar == 0)
Value.Set(Input[0]);
else
{
double last = Value[1] * Math.Min(CurrentBar, Period);
if (CurrentBar >= Period)
Value.Set((last + Input[0] - Input[Period]) / Math.Min(CurrentBar, Period));
else
Value.Set((last + Input[0]) / (Math.Min(CurrentBar, Period) + 1));
}
}
Now, theoretically the two formulae should give the same results. Practically, however, there are rounding errors that seem to have an impact on the results.


False Results

Let me show a simple example. I have coded a CurrentSessionVWAP for the RTH session of ES, and to please the eye, I want to smooth it with a 3-period-SMA. I only apply the smoothing with the fourth bar of the session, so for the first 3 bars the original CurrentSessionVWAP is displayed.

Blue: CurrentSessionVWAP
Yellow: Smoothed with SMA Standard Formula
Red: Smoothed with Default NinjaTrader SMA

Below are two identical charts. The only difference is that the first one has a lookback period of 5 days, while the second one has a lookback period of 65 days

Do you still think that it is easy to code a SMA?

The NinjaTrader guys did not succeed in my opinion. Or am I simply wrong?


Attached Thumbnails
Click image for larger version

Name:	Lookback 5 days.jpg
Views:	459
Size:	101.9 KB
ID:	20870   Click image for larger version

Name:	Lookback 65 days.jpg
Views:	403
Size:	91.8 KB
ID:	20872  
Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
Trump Truth Social Fires Hormuz From 10% to 59% -- Arsen …
Prediction Markets & Event Contracts
The 50/50 Paradox: Peace and Invasion Each at 20% -- Ira …
Prediction Markets & Event Contracts
Eurex Eyes Prediction Markets -- Europes Biggest Derivat …
Prediction Markets & Event Contracts
GDP Day: The First Economic Reckoning -- Pahlavi at 6.55 …
Prediction Markets & Event Contracts
CME Raises Energy Futures Margins After Iran-War Volatil …
Commodities
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Sober Journey With S&P
21 thanks
2026 Jlab journal
10 thanks
Algo automated / semi-automated trading anyone?
6 thanks
Lady Vols Primer: Trading Volatility Journal
6 thanks
2026 Fire Horse
5 thanks
  #3 (permalink)
 MXASJ 
Asia
 
Experience: Beginner
Platform: NinjaTrader, TOS
Posts: 796 since Jun 2009
Thanks Given: 109
Thanks Received: 801


Check out TA-lib TA-Lib : Technical Analysis Library - Home

And read this thread: C# Sample for Moving Average

Particularly the last paragraph...


Reply With Quote
Thanked by:
  #4 (permalink)
 
Fat Tails's Avatar
 Fat Tails 
Berlin, Europe
Market Wizard
 
Experience: Advanced
Platform: NinjaTrader
Broker: Interactive Brokers
Trading: Futures & Stocks
Posts: 9,887 since Mar 2010
Thanks Given: 4,242
Thanks Received: 27,114

Hi MAXSJ

Thanks for the information.


I have now tried different settings, even changed the recursive formula. Finally I found the real problem:

The recursive indicators only work, if you change the default settings to MaximumBarsLookBack.Infinite.

So all indicators with recursive formulae need to use this setting. This shows again the problem of NinjaTrader. Because NT 7 is still a memory hog compared to MultiCharts, developpers tried to reduce memory load. Correct results were sacrified to reduce the memory usage.


Empirical Finding

For every indicator that uses a recursive formula you would need to modify the indicator code and add the line

 
Code
 
MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
in the Initialize section of the indicator.

This also applies to SMA and EMA. Once the change is made, NinjaTrader will use more memory, but the results will be correct.


Started this thread Reply With Quote
  #5 (permalink)
 
Big Mike's Avatar
 Big Mike 
Manta, Ecuador
Site Administrator
Developer
Swing Trader
 
Experience: Advanced
Platform: Custom solution
Broker: IBKR
Trading: Stocks & Futures
Frequency: Every few days
Duration: Weeks
Posts: 50,669 since Jun 2009
Thanks Given: 33,669
Thanks Received: 102,557

I believe @Richard from Move the Markets did some studies on a fast-starting EMA that does not require that kind of lookback, you wish to poke around his blog. I am not sure if he is still around or not.

Mike




We're here to help: just ask the community or contact our Help Desk

Quick Links: Change your Username or Register as a Vendor
Searching for trading reviews? Review this list
Lifetime Elite Membership: Sign-up for only $149 USD
Exclusive money saving offers from our Site Sponsors: Browse Offers
Report problems with the site: Using the NexusFi changelog thread
Follow me on X Visit my NexusFi Trade Journal Reply With Quote
Thanked by:
  #6 (permalink)
 
bizman70's Avatar
 bizman70 
toronto, ontario
 
Experience: Intermediate
Platform: ninja trader
Broker: sterling, iqfeed
Trading: es, nq, 6e
Posts: 363 since May 2010
Thanks Given: 41
Thanks Received: 140

how difficult or what would it take to convert ninja based indicators to the Ta-lib library


Visit my NexusFi Trade Journal Reply With Quote




Last Updated on October 20, 2010


© 2026 NexusFi®, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
All information is for educational use only and is not investment advice. There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Downloads - Top
no new posts