NexusFi: Find Your Edge


Home Menu

 





Backtesting with Intrabar (Bid Ask) granularity


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one SodyTexas with 3 posts (1 thanks)
    2. looks_two RJay with 1 posts (1 thanks)
    3. looks_3 grankus with 1 posts (0 thanks)
    4. looks_4 Big Mike with 1 posts (1 thanks)
    1. trending_up 5,033 views
    2. thumb_up 3 thanks given
    3. group 2 followers
    1. forum 4 posts
    2. attach_file 1 attachments




 
Search this Thread
  #1 (permalink)
 
SodyTexas's Avatar
 SodyTexas 
Austin TX
 
Experience: Advanced
Platform: Ninjatrader, Python, & R
Broker: RJO
Trading: Futures, Spreads
Posts: 424 since Sep 2013
Thanks Given: 118
Thanks Received: 1,097

Hey NexusFi (formerly BMT) forum and friends,

I am trying to solve a issue with backtesting within Ninjatrader 7. What I am trying to do is backtest based on tick data, not the OHLC of a bar.

I found this site: Accurate NinjaTrader backtests - MetaTrader Expert Advisor

And it claims that I can backtest with Bid/Ask tick granularity.

First what I did was download Bid/Ask data for GC ##-## from 01/01/2013 to 03/31/2013.

From there I created a very very simple strategy following the instructions posted in the website mentioned above.

Here is my code
 
Code
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Indicator;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Strategy;
#endregion

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    /// <summary>
    /// Reference sample demonstrating how to achieve intrabar backtesting.
    /// </summary>
    [Description("Reference sample demonstrating how to achieve intrabar backtesting.")]
    public class sIntraBar : Strategy
    {
        #region Variables
		private int	fast	= 10;
		private int	slow	= 25;
        #endregion

        /// <summary>
        /// This method is used to configure the strategy and is called once before any strategy method is called.
        /// </summary>
        protected override void Initialize()
        {
			/* Add a secondary bar series. 
			Very Important: This secondary bar series needs to be smaller than the primary bar series.
			
			Note: The primary bar series is whatever you choose for the strategy at startup. In this example I will
			reference the primary as a 5min bars series. */
			Add("GC ##-##", PeriodType.Tick, 1, MarketDataType.Bid);
			Add("GC ##-##", PeriodType.Tick, 1, MarketDataType.Ask);

			
			// Add two EMA indicators to be plotted on the primary bar series
			Add(EMA(Fast));
			Add(EMA(Slow));
			
			/* Adjust the color of the EMA plots.
			For more information on this please see this tip: http://www.ninjatrader-support.com/vb/showthread.php?t=3228 */
			EMA(Fast).Plots[0].Pen.Color = Color.Blue;
			EMA(Slow).Plots[0].Pen.Color = Color.Green;
			
            CalculateOnBarClose = true;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
			 if (CurrentBars[0] < BarsRequired || CurrentBars[1] < BarsRequired)
                return;
			
			if (BarsInProgress == 0)
			{
				if (CrossAbove(EMA(Fast), EMA(Slow), 1))
				{
					//BarsInProgress = 1
					EnterLong(1, "Long: 1min");	
					//Print(ToTime(Time[0]));
				}
				else if (CrossBelow(EMA(Fast), EMA(Slow), 1))
				{
					//BarsInProgress = 1
					EnterShort(1, "Short: 1min");
					//Print(ToTime(Time[0]));
				}
			}
			// When the OnBarUpdate() is called from the secondary bar series, do nothing.
			else
			{
				return;
			}
        }

        #region Properties
		/// <summary>
		/// </summary>
		[Description("Period for fast MA")]
		[Category("Parameters")]
		public int Fast
		{
			get { return fast; }
			set { fast = Math.Max(1, value); }
		}

		/// <summary>
		/// </summary>
		[Description("Period for slow MA")]
		[Category("Parameters")]
		public int Slow
		{
			get { return slow; }
			set { slow = Math.Max(1, value); }
		}
        #endregion
    }
}
If you look at the attached image, it looks like the exit is executing not on the close of the bar, but the trade opening the trade are filling at the open.

Has anyone ran into a similar issue when trying to create a intrabar backtest?

Cheerrs,

SodyTexas


"The great Traders have always been humbled by the market early on in their careers creating a deep respect for the market. Until one has this respect indelibly engraved in their makeup, the concept of money management and discipline will never be treated seriously."
Attached Thumbnails
Click image for larger version

Name:	NinjaTrader Trade List, 1_1_2013 - 3_31_2013.jpg
Views:	305
Size:	453.2 KB
ID:	156157  
Visit my NexusFi Trade Journal Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
Bookmap Global Plus Lifetime + Lifetime Addons For Sale
Platforms and Indicators
One Wallet Made $200K in Hours: AP Probes Polymarket Cea …
Prediction Markets & Event Contracts
Saylors 41-Month HODL Breaks: Strategy Sells 32 BTC as $ …
Prediction Markets & Event Contracts
CME Launches Bitcoin Volatility Futures June 1 -- First …
Cryptocurrency
Kharg Island at 6%, Regime Fall at 1.5% -- The Black Swa …
Prediction Markets & Event Contracts
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Sober Journey With S&P
24 thanks
2026 Jlab journal
10 thanks
Lady Vols Primer: Trading Volatility Journal
8 thanks
Algo automated / semi-automated trading anyone?
6 thanks
Trying to learn Volume and price action correlation
5 thanks
  #3 (permalink)
 
RJay's Avatar
 RJay 
Hartford, CT. USA
 Vendor: www.innovative-trading-solutions-online.com 
 
Experience: Intermediate
Platform: NinjaTrader
Broker: AMP/CQG, Kinetick
Trading: ES
Posts: 687 since Jun 2009
Thanks Given: 765
Thanks Received: 789


Hi SodyTexas,

Yea, in my opinion, that code's not going to work very well.

NinjaTrader 7 does not sequence its Bid, Ask, Last back test data in a single file.

The Bid, Ask, and Last historic data are stored in three separate files.

On a one second granularity, there is no way to correctly re-sequence these three files for back testing.

Using Tick like in your code won't work because The Bid, Ask, and Last tables do not have equal numbers of entries in the stored data table for accurate back testing.

The data gets retrieved out of sequence.

I did the same thing talked about in that article, tested it, then scrapped the project.

I'm glad they found it usable, I did not.

In my opinion, try using Market Replay or wait for NinjaTrader 8 . Any year now. Sigh...

RJay


Reply With Quote
Thanked by:
  #4 (permalink)
 
SodyTexas's Avatar
 SodyTexas 
Austin TX
 
Experience: Advanced
Platform: Ninjatrader, Python, & R
Broker: RJO
Trading: Futures, Spreads
Posts: 424 since Sep 2013
Thanks Given: 118
Thanks Received: 1,097


RJay View Post
Hi SodyTexas,

Yea, in my opinion, that code's not going to work very well.

NinjaTrader 7 does not sequence its Bid, Ask, Last back test data in a single file.

The Bid, Ask, and Last historic data are stored in three separate files.

On a one second granularity, there is no way to correctly re-sequence these three files for back testing.

Using Tick like in your code won't work because The Bid, Ask, and Last tables do not have equal numbers of entries in the stored data table for accurate back testing.

The data gets retrieved out of sequence.

I did the same thing talked about in that article, tested it, then scrapped the project.

I'm glad they found it usable, I did not.

In my opinion, try using Market Replay or wait for NinjaTrader 8 . Any year now. Sigh...

RJay

Right, "sigh..." NT8 would solve this problem..

I have been using Replay for most everything, but now I am looking to optimize a system which can not without the back test functionality.

At the moment, I am trying to find a solution until NT8 comes out, since I can't count on NT time-frame on the release of NT8 Beta so, I thought I would explore my options. NT is going to lose customers if they don't get there act together, but then again I already bought there Muti-Broker option, so in there mind they go there money out of me.

Thanks for the reply,

Cheers,

Sody


"The great Traders have always been humbled by the market early on in their careers creating a deep respect for the market. Until one has this respect indelibly engraved in their makeup, the concept of money management and discipline will never be treated seriously."
Visit my NexusFi Trade Journal Started this thread Reply With Quote
Thanked by:
  #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

Accurate bid/ask data (associated with proper last) is in Elite section of NexusFi (formerly BMT). If you want, you could make this work with some custom programming. But it would be better to write your own app to do it like others have done, or just wait for NT8 which should be around the corner in beta form.

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:




Last Updated on September 12, 2014


© 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