Global variables in NT - NinjaTrader Programming | futures io social day trading
futures io futures trading


Global variables in NT
Updated: Views / Replies:7,936 / 24
Created: by Geir Attachments:5

Welcome to futures io.

(If you already have an account, login at the top of the page)

futures io is the largest futures trading community on the planet, with over 90,000 members. At futures io, our goal has always been and always will be to create a friendly, positive, forward-thinking community where members can openly share and discuss everything the world of trading has to offer. The community is one of the friendliest you will find on any subject, with members going out of their way to help others. Some of the primary differences between futures io and other trading sites revolve around the standards of our community. Those standards include a code of conduct for our members, as well as extremely high standards that govern which partners we do business with, and which products or services we recommend to our members.

At futures io, our focus is on quality education. No hype, gimmicks, or secret sauce. The truth is: trading is hard. To succeed, you need to surround yourself with the right support system, educational content, and trading mentors Ė all of which you can find on futures io, utilizing our social trading environment.

With futures io, you can find honest trading reviews on brokers, trading rooms, indicator packages, trading strategies, and much more. Our trading review process is highly moderated to ensure that only genuine users are allowed, so you donít need to worry about fake reviews.

We are fundamentally different than most other trading sites:
  • We are here to help. Just let us know what you need.
  • We work extremely hard to keep things positive in our community.
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts.
  • We firmly believe in and encourage sharing. The holy grail is within you, we can help you find it.
  • We expect our members to participate and become a part of the community. Help yourself by helping others.

You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

Reply
 5  
 
Thread Tools Search this Thread
 

Global variables in NT

  #1 (permalink)
Elite Member
Oslo, Norway
 
Futures Experience: Intermediate
Platform: Ninja Trader
Favorite Futures: ES
 
Posts: 6 since Jan 2011
Thanks: 29 given, 29 received

Global variables in NT

Hi

I have been looking for a way to share data between indicators and charts, i.e. replicating the Global Variable dll on TradeStation. The reason for this is that I would like to avoid having to recalculate stuff and spend CPU when I already have the values somewhere else.

I have come up with a very simple solution involving user methods, and it seems to work fine real time.

My lack of C# skills have prevented me from implementing historical data, but the way I see it is that it would be required to store a link to some sort of array per global variable. And then it would be necessary with some logic to retrieve the correct data when historical data is processed.

Would someone like to contribute to make this work on historical data, or does someone have a better idea?


The core are two methods
- SetGlobalVariable -> called by the calculating indicator with a uniqueue identifier (I use the following naming convention <Symbol><chart length><sending indicator>)
- GetGlobalVariable -> called by the receiving indicator, obviously using the same uniqueue identifier

Here is the code for the methods:

 
Code
#region Using declarations
using System;
using System.ComponentModel;
using System.Drawing;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
using System;
using System.Collections.Generic;
	
#endregion

namespace NinjaTrader.Indicator
{

    partial class Indicator
    {
		public static Dictionary<string, double> gvHist = new Dictionary<string, double>();
				
		public bool SetGlobalVariable(string identifier, DateTime timeStamp, double value)
		{
			gvHist[identifier] = value;
			return true;
		}
		
		public double GetGlobalVariable(string identifier, DateTime timeStamp)
		{
			if(Historical)
				return 0;
			double value;
			gvHist.TryGetValue(identifier, out value);
			return value;
		}
    }
}
Here a modified SMA which sets a global variable:
 
Code
// 
// Copyright (C) 2006, NinjaTrader LLC <www.ninjatrader.com>.
// NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
//

#region Using declarations
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Xml.Serialization;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
#endregion

// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
	/// <summary>
	/// The SMAGVExample (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
	/// </summary>
	[Description("The SMAGVExample (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.")]
	public class SMAGVExample : Indicator
	{
		#region Variables
		private int		period	= 14;
		private string identifier = @"test";
		#endregion

		/// <summary>
		/// This method is used to configure the indicator and is called once before any bar data is loaded.
		/// </summary>
		protected override void Initialize()
		{
			Add(new Plot(Color.Orange, "SMAGVExample"));

			Overlay = true;
		}

		/// <summary>
		/// Called on each bar update event (incoming tick).
		/// </summary>
		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));
			}
			SetGlobalVariable(identifier, Time[0], Value[0]);
		}

		#region Properties
		/// <summary>
		/// </summary>
		[Description("Numbers of bars used for calculations")]
		[GridCategory("Parameters")]
		public int Period
		{
			get { return period; }
			set { period = Math.Max(1, value); }
		}
		
        [Description("Global variable identifier")]
        [GridCategory("Parameters")]
        public string Identifier
        {
            get { return identifier; }
            set { identifier = value; }
        }		
        #endregion
	}
}
And here the indicator for plotting
 
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.Gui.Chart;
#endregion

// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    /// <summary>
    /// Plots global variables RT
    /// </summary>
    [Description("Plots global variables")]
    public class GlobalVariablePlot : Indicator
    {
        #region Variables
        // Wizard generated variables
            private string identifier = @""; // Default setting for Identifier
        // User defined variables (add any user defined variables below)
        #endregion

        protected override void Initialize()
        {
            Add(new Plot(Color.FromKnownColor(KnownColor.OrangeRed), PlotStyle.Line, "GlobalVariable"));
            Overlay				= false;
        }

        protected override void OnBarUpdate()
        {
			// Do not plot if historical values
			if (Historical)
				return;
			
            GlobalVariable.Set(GetGlobalVariable(identifier, Time[0]));
        }

        #region Properties
        [Browsable(false)]	// this line prevents the data series from being displayed in the indicator properties dialog, do not remove
        [XmlIgnore()]		// this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
        public DataSeries GlobalVariable
        {
            get { return Values[0]; }
        }

        [Description("Global variable identifier")]
        [GridCategory("Parameters")]
        public string Identifier
        {
            get { return identifier; }
            set { identifier = value; }
        }
        #endregion
    }
}
The simplest way of testing it is probably to set up a 10 second chart pushing the data, and a 5 seconds chart plotting the global variable.

Added 22.01.2013: See my later post for historical global variables

Attached Thumbnails
Global variables in NT-globalvariables-example.png  

Last edited by Geir; January 22nd, 2013 at 09:14 AM. Reason: fixed screen shot and removed hard coding of GV name
Reply With Quote
The following 18 users say Thank You to Geir for this post:
 
  #2 (permalink)
Quick Summary
Quick Summary Post

Quick Summary is created and edited by users like you... Add FAQ's, Links and other Relevant Information by clicking the edit button in the lower right hand corner of this message.

 
  #3 (permalink)
Site Administrator
Manta, Ecuador
 
Futures Experience: Advanced
Platform: My own custom solution
Favorite Futures: E-mini ES S&P 500
 
Big Mike's Avatar
 
Posts: 46,238 since Jun 2009
Thanks: 29,350 given, 83,219 received


Very nice, thank you for sharing.

Mike

Due to time constraints, please do not PM me if your question can be resolved or answered on the forum.

Need help?
1) Stop changing things. No new indicators, charts, or methods. Be consistent with what is in front of you first.
2) Start a journal and post to it daily with the trades you made to show your strengths and weaknesses.
3) Set goals for yourself to reach daily. Make them about how you trade, not how much money you make.
4) Accept responsibility for your actions. Stop looking elsewhere to explain away poor performance.
5) Where to start as a trader? Watch this webinar and read this thread for hundreds of questions and answers.
6)
Help using the forum? Watch this video to learn general tips on using the site.

If you want
to support our community, become an Elite Member.

Reply With Quote
 
  #4 (permalink)
Elite Member
Phoenix, Arizona
 
Futures Experience: Advanced
Platform: Ninja Trader
Favorite Futures: Oil
 
Posts: 52 since Jul 2009
Thanks: 1 given, 6 received

Do a search over on the Ninja Trader forum for: Gloabal Variables?

There is a thread with 55 responses about using the Globalvariable.dll written for TradeStation. There is also a full example of the SMA.

I'm following that thread right now and have questions about the inner workings because I can't get it to fully work.

I too have needs and believe Global Variable is the best solution. I also used it in TradeStatoin and it worked well.

regards,

taddypole...

Reply With Quote
The following user says Thank You to Taddypole for this post:
 
  #5 (permalink)
Elite Member
Oslo, Norway
 
Futures Experience: Intermediate
Platform: Ninja Trader
Favorite Futures: ES
 
Posts: 6 since Jan 2011
Thanks: 29 given, 29 received


Taddypole View Post
Do a search over on the Ninja Trader forum for: Gloabal Variables?

There is a thread with 55 responses about using the Globalvariable.dll written for TradeStation. There is also a full example of the SMA.

I will follow it as well and see if a solution with historic data is provided. Thanks for pointing mentioning the thread..

Regards
Geir


Last edited by Geir; April 9th, 2012 at 02:58 AM.
Reply With Quote
 
  #6 (permalink)
Elite Member
Oslo, Norway
 
Futures Experience: Intermediate
Platform: Ninja Trader
Favorite Futures: ES
 
Posts: 6 since Jan 2011
Thanks: 29 given, 29 received

updated code - now supporting historical data

In the mean time I have updated the code slightly to support historical global variables.

Methods required:
 
Code
// GlobalVariableMethods
// by Geir Nilsen
// 
// use SetGlobalVariable to push the global variable value. Note that this method has to be called at CurrentBar 0
// in order to do some house keeping.
#region Using declarations
using System;
using System.ComponentModel;
using System.Drawing;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
using System;
using System.Data;
using System.Collections.Generic;
	
#endregion

namespace NinjaTrader.Indicator
{
    partial class Indicator
    {		
		// the following dictionaries hold real time values. When new time stamp comes in then data is sent to 
		// table for historic data
		public static Dictionary<string, DateTime> gvTime 	= new Dictionary<string, DateTime>();
		public static Dictionary<string, double> gvPrice 	= new Dictionary<string, double>();
		
		public static DataTable	gvTable = new DataTable(); // stores all historical data
				
		public void SetGlobalVariable(string identifier, DateTime timeStamp, double value)
		{
			// prepare table first time the method is used
			if(gvTable.Columns.Count == 0)
			{
				gvTable.Columns.Add("ID", typeof(string));
				gvTable.Columns.Add("Time", typeof(DateTime));
				gvTable.Columns.Add("Price", typeof(double));
			}
			
			// clean up table in case data is already available (when refreshing chart)
			if(CurrentBar == 0)
			{
				string criteria = "ID = '" + identifier + "'";		// sql string
				DataRow[] toBeDeleted = gvTable.Select(criteria);	// perform sql
				if(toBeDeleted.Length > 0)
					foreach (DataRow row in toBeDeleted)
						gvTable.Rows.Remove(row);
			}	
			
			// add new values. For historical data table a row can just be added
			if(Historical)
				gvTable.Rows.Add(identifier, timeStamp, value);
			else
			{
				// check if new timestamp is <> from what is held in dictionary -> new bar
				// ==> add row to gvTable. store current value in dictionary.
				DateTime oldTimeStamp;
				gvTime.TryGetValue(identifier, out oldTimeStamp);
				
				// if we get a new timeStamp, then real time time stamp has changed. Send to table
				if(timeStamp != oldTimeStamp)
				{
					gvTable.Rows.Add(identifier, timeStamp, value);
				}
				
				// cache updated global variable
				gvTime[identifier] = timeStamp;
				gvPrice[identifier] = value;
			}	
		}
		
		public double GetGlobalVariable(string identifier, DateTime timeStamp)
		{
			double toBeReturned = -1;
			
			if(!Historical)
				// check if timeStamp is cached in dictionary. If yes, then return value
				gvPrice.TryGetValue(identifier, out toBeReturned);
			else
			{
				// select specified global variable data from table
				string criteria = "ID = '" + identifier + "'"; 		// sql string
				DataRow[] valuesForID = gvTable.Select(criteria);	// perform sql
				
				// walk through from oldest until time stamp in table is younger than what we are looking for
				foreach(DataRow row in valuesForID)
				{
					if((DateTime)row[1] <= timeStamp)
						toBeReturned = (double)row[2];
					else
						break;
				}
			}
			return toBeReturned;
		}
	}	
}

Here a sample indicator to push a value - it is the same indicator as above, but it pushes with Time[1] in order to get the data right on the receiving chart(s):

 
Code
// 
// Copyright (C) 2006, NinjaTrader LLC <www.ninjatrader.com>.
// NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
//

#region Using declarations
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Xml.Serialization;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
#endregion

// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
	/// <summary>
	/// The SMAGVExample (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
	/// </summary>
	[Description("The SMAGVExample (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.")]
	public class SMAGVExample : Indicator
	{
		#region Variables
		private int		period	= 14;
		private string identifier = @"test";
		#endregion

		/// <summary>
		/// This method is used to configure the indicator and is called once before any bar data is loaded.
		/// </summary>
		protected override void Initialize()
		{
			Add(new Plot(Color.Orange, "SMAGVExample"));

			Overlay = true;
		}

		/// <summary>
		/// Called on each bar update event (incoming tick).
		/// </summary>
		protected override void OnBarUpdate()
		{
			if (CurrentBar == 0)
			{
				Value.Set(Input[0]);
				SetGlobalVariable(identifier, Time[0], Value[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));
			}
			SetGlobalVariable(identifier, Time[1], Value[0]);
		}

		#region Properties
		/// <summary>
		/// </summary>
		[Description("Numbers of bars used for calculations")]
		[GridCategory("Parameters")]
		public int Period
		{
			get { return period; }
			set { period = Math.Max(1, value); }
		}
		
        [Description("Global variable identifier")]
        [GridCategory("Parameters")]
        public string Identifier
        {
            get { return identifier; }
            set { identifier = value; }
        }		
        #endregion
	}
}

And finally the code for plotting global variables. Be aware that you need to ensure that the sending chart is calculated before the receiver. In case that does not happen when loading ninja you need to go and recalculate manually using F5.

 
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.Gui.Chart;
#endregion

// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    /// <summary>
    /// Plots global variables RT
    /// </summary>
    [Description("Plots global variables")]
    public class GlobalVariablePlot : Indicator
    {
        #region Variables
        // Wizard generated variables
            private string identifier = @""; // Default setting for Identifier
        // User defined variables (add any user defined variables below)
        #endregion

        protected override void Initialize()
        {
            Add(new Plot(Color.FromKnownColor(KnownColor.OrangeRed), PlotStyle.Line, "GlobalVariable"));
            Overlay				= false;
        }

        protected override void OnBarUpdate()
        {
	            GlobalVariable.Set(GetGlobalVariable(identifier, Time[0]));
        }

        #region Properties
        [Browsable(false)]	// this line prevents the data series from being displayed in the indicator properties dialog, do not remove
        [XmlIgnore()]		// this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
        public DataSeries GlobalVariable
        {
            get { return Values[0]; }
        }

        [Description("Global variable identifier")]
        [GridCategory("Parameters")]
        public string Identifier
        {
            get { return identifier; }
            set { identifier = value; }
        }
        #endregion
    }
}

Reply With Quote
The following 6 users say Thank You to Geir for this post:
 
  #7 (permalink)
Elite Member
Portland, OR
 
Futures Experience: Intermediate
Platform: NinjaTrader mostly
Broker/Data: I've tried 'em all
Favorite Futures: ZN, ES, 6E, TF, CL
 
drmartell's Avatar
 
Posts: 92 since Mar 2010
Thanks: 175 given, 78 received

When I add this user defined method, it compiles fine, but it causes all my custom indicators to stop appearing on the Indicator chart dialog. Can anyone see what might be causing that?

Update: It appears to be this line:

 
Code
public static DataTable	gvTable = new DataTable(); // stores all historical data

but I still don't know why. . .


Last edited by drmartell; October 4th, 2013 at 01:56 PM. Reason: further information
Reply With Quote
 
  #8 (permalink)
Elite Member
Oslo, Norway
 
Futures Experience: Intermediate
Platform: Ninja Trader
Favorite Futures: ES
 
Posts: 6 since Jan 2011
Thanks: 29 given, 29 received


drmartell View Post
When I add this user defined method, it compiles fine, but it causes all my custom indicators to stop appearing on the Indicator chart dialog. Can anyone see what might be causing that?

Update: It appears to be this line:

 
Code
public static DataTable	gvTable = new DataTable(); // stores all historical data

but I still don't know why. . .

Hi drmartell

I have not heard of similar problems and I have no idea what this could be.

I guess that Ninja Trader does not provide support when it comes to custom code, but they do provide a framework in which it is possible to program the platform. And when this framework starts behaving strangely in some instances, then I assume that they would be interested in investigating the issue.

I hope this helps.

Regards
Geir

Reply With Quote
 
  #9 (permalink)
Elite Member
Portland, OR
 
Futures Experience: Intermediate
Platform: NinjaTrader mostly
Broker/Data: I've tried 'em all
Favorite Futures: ZN, ES, 6E, TF, CL
 
drmartell's Avatar
 
Posts: 92 since Mar 2010
Thanks: 175 given, 78 received


Geir View Post
I have not heard of similar problems and I have no idea what this could be.

Thanks for the reply, this turned out to be a Reference issue. Somehow a reference to .NET 4.0 snuck in and I had to point it back to 2.0.

I also made some changes that I have not thoroughly tested, but seem to be working for me.

I moved the GV list into its own class to further insulate it conceptually and I changed up the indicator codes. The intended function is now that you would set the sending indicator's "Input series" to whatever you like. So in other words you can choose any indicator available within your platform as an Input. In order to make this work I had to change from Time[0] to Bars.GetTime(CurrentBar).

Anyhow hope it is helpful:

Global Variable User Defined Method

 
Code
// by Geir Nilsen
// https://futures.io/ninjatrader-programming/18967-global-variables-ninjatrader.html
// use SetGlobalVariable to push the global variable value. Note that this method has to be called at CurrentBar 0
// in order to do some house keeping.

#region Using declarations
using System;
using System.ComponentModel;
using System.Drawing;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
using System.Data;
using System.Collections.Generic;
	
#endregion

namespace NinjaTrader.Indicator
{
    partial class Indicator
    {		
		// the following dictionaries hold real time values. When new time stamp comes in then data is sent to 
		// table for historic data
		public class GV
		{
			public static Dictionary<string, DateTime> gvTime 	= new Dictionary<string, DateTime>();
			public static Dictionary<string, double> gvPrice 	= new Dictionary<string, double>();
			
			public static DataTable	gvTable = new DataTable(); // stores all historical data
		}
		
		public void SetGlobalVariable(string identifier, DateTime timeStamp, double value)
		{
			// prepare table first time the method is used
			if(GV.gvTable.Columns.Count == 0)
			{
				GV.gvTable.Columns.Add("ID", typeof(string));
				GV.gvTable.Columns.Add("Time", typeof(DateTime));
				GV.gvTable.Columns.Add("Price", typeof(double));
			}
			
			// clean up table in case data is already available (when refreshing chart)
			if(CurrentBar == 0)
			{
				string criteria = "ID = '" + identifier + "'";		// sql string
				DataRow[] toBeDeleted = GV.gvTable.Select(criteria);	// perform sql
				if(toBeDeleted.Length > 0)
					foreach (DataRow row in toBeDeleted)
						GV.gvTable.Rows.Remove(row);
			}	
			
			// add new values. For historical data table a row can just be added
			if(Historical)
				GV.gvTable.Rows.Add(identifier, timeStamp, value);
			else
			{
				// check if new timestamp is <> from what is held in dictionary -> new bar
				// ==> add row to gvTable. store current value in dictionary.
				DateTime oldTimeStamp;
				GV.gvTime.TryGetValue(identifier, out oldTimeStamp);
				
				// if we get a new timeStamp, then real time time stamp has changed. Send to table
				if(timeStamp != oldTimeStamp)
				{
					GV.gvTable.Rows.Add(identifier, timeStamp, value);
				}
				
				// cache updated global variable
				GV.gvTime[identifier] = timeStamp;
				GV.gvPrice[identifier] = value;
			}	
		}
		
		public double GetGlobalVariable(string identifier, DateTime timeStamp)
		{
			double toBeReturned = -1;
			
			if(!Historical)
				// check if timeStamp is cached in dictionary. If yes, then return value
				GV.gvPrice.TryGetValue(identifier, out toBeReturned);
			else
			{
				// select specified global variable data from table
				string criteria = "ID = '" + identifier + "'"; 		// sql string
				DataRow[] valuesForID = GV.gvTable.Select(criteria);	// perform sql
				
				// walk through from oldest until time stamp in table is younger than what we are looking for
				foreach(DataRow row in valuesForID)
				{
					if((DateTime)row[1] <= timeStamp)
						toBeReturned = (double)row[2];
					else
						break;
				}
			}
			return toBeReturned;
		}
	}	
}

GlobalVariableSend Indicator

 
Code
#region Using declarations
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Xml.Serialization;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
using System.Windows.Forms;
#endregion

namespace NinjaTrader.Indicator
{
	/// <summary>
	/// GlobalVariableSend
	/// https://futures.io/ninjatrader-programming/18967-global-variables-ninjatrader.html
	/// </summary>
	[Description("GlobalVariableSend")]
	public class GlobalVariableSend : Indicator
	{
		//-> Variables
		//<- Variables

		//-> Properties
		private string identifier;
        [Description("Global variable identifier")]
        [GridCategory("Parameters")]
        public string Identifier
        {
            get { return identifier; }
            set { identifier = value; }
        }		
		
        [Browsable(false)]	// this line prevents the data series from being displayed in the indicator properties dialog, do not remove
        [XmlIgnore()]		// this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
        public DataSeries GVsend
        {
            get { return Values[0]; }
        }
        //<- Properties
		
		protected override void Initialize()
		{
           	Add(new Plot(new Pen(Color.OrangeRed, 2), PlotStyle.Line,  "GVsend"));
			Overlay = false;
				
			identifier = Instrument.FullName + " " + BarsPeriod.Value + " " + BarsPeriod.BasePeriodType + " " + "[UniqueID?]";
			
			BarsRequired = 0;
		}

		protected override void OnStartUp()
		{
			if (identifier == Instrument.FullName + " " + BarsPeriod.Value + " " + BarsPeriod.BasePeriodType + "[UniqueID?]")
			{
				MessageBox.Show("It appears you are using the default identifier.\n\nThe intention is to replace 'UniqueID?' with something of your choosing. . .", "Global Variable Send Unique Identifier", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button1);
			}
		}

		protected override void OnBarUpdate()
		{
			GVsend.Set(Input[0]);
			SetGlobalVariable(identifier, Bars.GetTime(CurrentBar), GVsend[0]);
		}
	}
}

GlobalVariableReceive Indicator

 
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.Gui.Chart;
using System.Windows.Forms;
#endregion

// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    /// <summary>
    /// GlobalVariableReceive
	/// https://futures.io/ninjatrader-programming/18967-global-variables-ninjatrader.html
    /// </summary>
    [Description("GlobalVariableReceive")]
    public class GlobalVariableReceive : Indicator
    {
		//-> Variables
		private bool isError = false;
		//<- Variables

        //-> Properties
		private string identifier;
        [Description("Global variable identifier")]
        [GridCategory("Parameters")]
        public string Identifier
        {
            get { return identifier; }
            set { identifier = value; }
        }
		
        [Browsable(false)]	// this line prevents the data series from being displayed in the indicator properties dialog, do not remove
        [XmlIgnore()]		// this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
        public DataSeries GVreceive
        {
            get { return Values[0]; }
        }
        //<- Properties
		
        protected override void Initialize()
        {
            Add(new Plot(new Pen(Color.OrangeRed, 2), PlotStyle.Line,  "GVreceive"));
			Overlay	= false;
		
			identifier = "???";
        }
		
		protected override void OnStartUp()
		{
			if (identifier == "???")
			{
				MessageBox.Show("It appears you are using the default identifier.\n\nEnsure this identifier matches that of the sending chart.", "Global Variable Receive Unique Identifier", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button1);
			}
		}
		
        protected override void OnBarUpdate()
        {
			if (isError) return;
			
			try
			{
				GVreceive.Set(GetGlobalVariable(identifier, Time[0]));
			}
			catch (Exception e)
			{
				isError = true;
				MessageBox.Show(e.ToString(), "Global Variable Receive Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button1);
			}
        }
    }
}

Reply With Quote
The following 3 users say Thank You to drmartell for this post:
 
  #10 (permalink)
 Vendor: www.probabletrades.com 
OC, California, USA
 
Futures Experience: Advanced
Platform: IB/TWS, NinjaTrader, thinkorswim
Favorite Futures: stocks, options, futures, VIX
 
shodson's Avatar
 
Posts: 1,859 since Jun 2009
Thanks: 480 given, 3,254 received


I would avoid accessing public static data sets directly in order to be more thread-safe. First, I would make the data private

 
Code
private static Dictionary<string, double> gvHist = new Dictionary<string, double>();
Then, in any methods that read or write the global data I would place locking mechanisms to avoid multi-threading problems. To do this I would first create a lock

 
Code
private static object lockObject = new object();
Then create a critical section around reading/reading of the Dictionary

 
Code
public bool SetGlobalVariable(string identifier, DateTime timeStamp, double value)
{
	lock(lockObject)
	{
		gvHist[identifier] = value;
	}
	return true;
}

public double GetGlobalVariable(string identifier, DateTime timeStamp)
{
	if(Historical)
		return 0;
	double value;
	
	lock(lockObject)
	{
		gvHist.TryGetValue(identifier, out value);
	}
	return value;
}
You can learn more about locks here - lock Statement (C# Reference)

Reply With Quote
The following 8 users say Thank You to shodson for this post:

Reply



futures io > > > > > Global variables in NT

Thread Tools Search this Thread
Search this Thread:

Advanced Search



Upcoming Webinars and Events (4:30PM ET unless noted)

Linda Bradford Raschke: Reading The Tape

Elite only

Adam Grimes: TBA

Elite only

NinjaTrader: TBA

January

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
Global Variables In TS c12345 EasyLanguage Programming 7 October 14th, 2017 10:52 AM
Global Variables - does this beast exist in Ninja trendisyourfriend NinjaTrader Programming 13 May 29th, 2013 07:15 PM
Global variables for sharing data between Charts ECI Ed NinjaTrader Programming 5 March 6th, 2012 10:02 AM
global variables: anyone got a complete NT7 example? elbone NinjaTrader Programming 2 July 19th, 2011 10:13 AM
Global Variables and Strategies in Ninja 6.5 TonyA NinjaTrader Programming 3 November 6th, 2010 08:50 AM


All times are GMT -4. The time now is 12:26 PM.

Copyright © 2017 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
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.
no new posts
Page generated 2017-12-12 in 0.15 seconds with 20 queries on phoenix via your IP 54.145.16.43