NexusFi: Find Your Edge


Home Menu

 





Calculate spread of two symbols, set it as double for use as input for indicator


Discussion in NinjaTrader

Updated
    1. trending_up 6,149 views
    2. thumb_up 9 thanks given
    3. group 4 followers
    1. forum 5 posts
    2. attach_file 0 attachments




 
Search this Thread

Calculate spread of two symbols, set it as double for use as input for indicator

  #1 (permalink)
 Alex91320 
Los Angeles, CA
 
Experience: Advanced
Platform: TOS, NT
Broker: AMp Futures/CQG
Trading: Options, Futures
Posts: 16 since Sep 2010
Thanks Given: 15
Thanks Received: 10

Hi
I use spread (difference) of two symbols as input for another indicator.
Based on testing and a number of posts in this and other forums, it seems there are a couple of indicators (Spread, Pairs) that will do this, but both have programming errors (according to ppl who unlike myself can tell when there is one).

I've compared readings from "Spread3" indicator and "Pairs" indicator, and majority of the time they align, but at times return different result, despite being designed to perform seemingly identical function.

My second issue, is I want to use the spread calculation in Micro Trends easy trader (order management add-on for Ninjatrader), but since Easy trader was compiled WITHOUT the spread indicator present, Easy Trader cant access the return value of the spread (IF its even accurate to begin with).

Could someone advise me on:
1. Can I just declare a "double" which is (symbol1-Symbol2) and use that for input to my indicator to avoid having to access indicators that were not present when EasyTrader was compiled?
(sounds waaayy to simple, so there must be a reason its not done that way. Whats the reason?)

2. The other indicators (Spread, Pairs) seem to have much more code than a simple (symbol1-Symbol2).
I understand its for synchronization.

I'm simply trying to use spread calculation as input.
Any way to accomplish that with ACCURATE result, without calling another indie?



Any assistance will be much appreciated!

Started this thread Reply With Quote
Thanked by:

Can you help answer these questions
from other members on NexusFi?
Pivot Indicator like the old SwingTemp by Big Mike
NinjaTrader
ZombieSqueeze
Platforms and Indicators
How to apply profiles
Traders Hideout
Increase in trading performance by 75%
The Elite Circle
REcommedations for programming help
Sierra Chart
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Just another trading journal: PA, Wyckoff & Trends
34 thanks
Tao te Trade: way of the WLD
24 thanks
My NQ Trading Journal
14 thanks
Vinny E-Mini & Algobox Review TRADE ROOM
13 thanks
GFIs1 1 DAX trade per day journal
11 thanks
  #3 (permalink)
 fctrader 
Fort Collins, Colorado
 
Experience: Intermediate
Platform: NT7
Trading: ES
Posts: 57 since Feb 2011
Thanks Given: 48
Thanks Received: 45


You can get the spread between two symbols, but it will be different in real time than with historic data due to the difference in ticks coming into your PC. For example, I coded an indicator to show the real time difference between the S&P and the Dow. If you are looking at it on a daily or even hourly chart, the two numbers are the same, but when you look shorter term, you see variations because the way the exchange sends the data along with latency, etc. will not give an accurate spread on a time based scale.

The following code plots the ratio between two symbols. You could easily edit it to plot the difference instead. (The SD part is not operating, and can be removed. I just put this out to give an example of how you can make an indicator that plots the difference or ratio of two symbols.)

 
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 the Differences between the percent change in the Dow vs the SP500
    /// </summary>
    [Description("Plots the Differences between the percent change in the Dow vs the SP500")]
    public class DOWvsSP500 : Indicator
    {
        #region Variables
        // Wizard generated variables
            private string symbol = @"^DJIA"; // Default setting for Symbol
            private string symbol2 = @"^SP500"; // Default setting for Symbol2
        // User defined variables (add any user defined variables below)
        #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(symbol,BarsPeriod.Id,BarsPeriod.Value);
			Add(symbol2,BarsPeriod.Id,BarsPeriod.Value);
			Add(new Plot(Color.FromKnownColor(KnownColor.MidnightBlue), PlotStyle.Line, "PercentDif"));
            Add(new Plot(Color.FromKnownColor(KnownColor.DarkViolet), PlotStyle.HLine, "Plus1SD"));
            Add(new Plot(Color.FromKnownColor(KnownColor.DarkViolet), PlotStyle.HLine, "Minus1SD"));
            Overlay				= false;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            
            if (CurrentBars[0]<2)
				return;
			if (BarsInProgress == 0) 
			{
			double data=100*((Closes[1][0]-Closes[1][1])/Closes[1][1]-(Closes[2][0]-Closes[2][1])/Closes[2][1]);
			PercentDif.Set(data);
            Plus1SD.Set(0);
            Minus1SD.Set(0);
			Print(data);
			}
        }

        #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 PercentDif
        {
            get { return Values[0]; }
        }

        [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 Plus1SD
        {
            get { return Values[1]; }
        }

        [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 Minus1SD
        {
            get { return Values[2]; }
        }

        [Description("First symbol")]
        [GridCategory("Parameters")]
        public string Symbol
        {
            get { return symbol; }
            set { symbol = value; }
        }

        [Description("Second symbol")]
        [GridCategory("Parameters")]
        public string Symbol2
        {
            get { return symbol2; }
            set { symbol2 = value; }
        }
        #endregion
    }
}

Visit my NexusFi Trade Journal Reply With Quote
  #4 (permalink)
 fctrader 
Fort Collins, Colorado
 
Experience: Intermediate
Platform: NT7
Trading: ES
Posts: 57 since Feb 2011
Thanks Given: 48
Thanks Received: 45

To fix it, you could simply change the body of the code to read:

 
Code
{
            
            if (CurrentBars[0]<2)
				return;
			if (BarsInProgress == 0) 
			{
			double data=(Closes[1][0]-Closes[2][0]);
			PercentDif.Set(data);
            
           
			Print(data);
			}
        }
That should give you the difference between any two symbols at the current Close. (Closes[1][1]-Closes[2][1]) would give you the difference at the last bar. You can edit the symbols in the Indicator panel, and you can set your code to buy or sell when the difference reaches a predetermined value.

Good luck

FC

Visit my NexusFi Trade Journal Reply With Quote
Thanked by:
  #5 (permalink)
 Alex91320 
Los Angeles, CA
 
Experience: Advanced
Platform: TOS, NT
Broker: AMp Futures/CQG
Trading: Options, Futures
Posts: 16 since Sep 2010
Thanks Given: 15
Thanks Received: 10

Fc, Thank you for taking the time to code this.

Im not so much after percent difference, as much as the actual spread value.
Its used on a short term 3, 5 and 10 min charts, so intraday accuracy is essential.
In your second post you said "to fix this", was that directed towards your initial tip on inaccuracy of short term data?

I currently get the spread value via Spread and Pairs indicators (which align MOST of the time, which IS the core of my problem as I dont know which I should use).

And as I mentioned, calling for outside indicator is not an option when it comes to integrating it with MicroTrends, so
I'm looking for code I'd need to add to my strategy that will do the calculation of the spread (we can use XXXX and YYYY as symbols for now), and output the result in such way (double or Int?) so it can be used as input for another indicator.

Example: (Please forgive my coding, I'm watching C# tutorials and getting better at this)


Public Int (or double?)
spreadCalc = "xxxx"-"yyyy"

if EMA(spreadCalc)20 [0]<EMA(spreadCalc)20 [1]

Do something

Also,

I'd like to access same data on other timeframes

if EMA(spreadCalc)20 [0]<EMA(spreadCalc)20 [1] periodType.Minute (5)
&& EMA(spreadCalc)20 [0]<EMA(spreadCalc)20 [1] periodType.Minute (3)

Do something..

Thank you

Started this thread Reply With Quote
  #6 (permalink)
 fctrader 
Fort Collins, Colorado
 
Experience: Intermediate
Platform: NT7
Trading: ES
Posts: 57 since Feb 2011
Thanks Given: 48
Thanks Received: 45

Sorry I wasn't clear what I meant when I said "To fix this." What I meant was to make it give the difference instead of the ratio. By doing Close(XXXX)-Close(YYYY) instead of "100*((Closes[1][0]-Closes[1][1])/Closes[1][1]-(Closes[2][0]-Closes[2][1])/Closes[2][1]);"

I am not familiar with the limitations of MicroTrends, but I think I understand that you are saying it can't call an outside indicator, but you can write your own ninjascript into a Strategy that it executes.

If that's the case, you need to add the extra symbols into the initialization of the strategy with the code
 
Code
Add("XXXX",BarsPeriod.Id,BarsPeriod.Value);
Add("YYYY",BarsPeriod.Id,BarsPeriod.Value);
Once you have added those two lines, you can access them by using the "Closes" format as opposed to "Close"

For example, the method to access the XXXX symbol for the present bar would be Closes[1][0], whereas to access the YYYY symbol, you would use Closes[2][0]. Likewise, you can access one bar prior with Closes[1][1] and Closes[2][2], etc. You can also do this with Opens, Highs, Lows, Medians, etc.

Thus, you can write the spread directly into a strategy in the same way that you would write it into an indicator.

Closes[1][0]-Closes[2][0] will give you the "spread" between the two symbols on the present bar if you have COBC set to false, though I would caution you that it is subject to the last reported trade in each symbol, and therefore can be quite off if volume is low and there is significant time between trades.

I hope that helps.

Visit my NexusFi Trade Journal Reply With Quote
Thanked by:




Last Updated on March 9, 2012


© 2024 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 - Privacy Policy - Downloads - Top
no new posts