Calculate spread of two symbols, set it as double for use as input for indicator - NinjaTrader Programming | futures io social day trading
futures io futures trading


Calculate spread of two symbols, set it as double for use as input for indicator
Updated: Views / Replies:3,620 / 5
Created: by Alex91320 Attachments:0

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
 
Thread Tools Search this Thread
 

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

  #1 (permalink)
Elite Member
Los Angeles, CA
 
Futures Experience: Advanced
Platform: TOS, NT
Broker/Data: AMp Futures/CQG
Favorite Futures: Options, Futures
 
Posts: 16 since Sep 2010
Thanks: 15 given, 9 received

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

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!

Reply With Quote
The following user says Thank You to Alex91320 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)
Elite Member
Fort Collins, Colorado
 
Futures Experience: Intermediate
Platform: NT7
Favorite Futures: ES
 
Posts: 57 since Feb 2011
Thanks: 48 given, 43 received


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
    }
}

Reply With Quote
The following 4 users say Thank You to fctrader for this post:
 
  #4 (permalink)
Elite Member
Fort Collins, Colorado
 
Futures Experience: Intermediate
Platform: NT7
Favorite Futures: ES
 
Posts: 57 since Feb 2011
Thanks: 48 given, 43 received

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

Reply With Quote
The following user says Thank You to fctrader for this post:
 
  #5 (permalink)
Elite Member
Los Angeles, CA
 
Futures Experience: Advanced
Platform: TOS, NT
Broker/Data: AMp Futures/CQG
Favorite Futures: Options, Futures
 
Posts: 16 since Sep 2010
Thanks: 15 given, 9 received

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


Last edited by Alex91320; March 9th, 2012 at 09:54 PM.
Reply With Quote
 
  #6 (permalink)
Elite Member
Fort Collins, Colorado
 
Futures Experience: Intermediate
Platform: NT7
Favorite Futures: ES
 
Posts: 57 since Feb 2011
Thanks: 48 given, 43 received

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.

Reply With Quote
The following user says Thank You to fctrader for this post:

Reply



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

Thread Tools Search this Thread
Search this Thread:

Advanced Search



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

Jigsaw Trading: TBA

Elite only

FuturesTrader71: TBA

Elite only

NinjaTrader: TBA

Jan 18

RandBots: TBA

Jan 23

GFF Brokers & CME Group: Futures & Bitcoin

Elite only

Adam Grimes: TBA

Elite only

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
Spread measure indicator marotom Beginners and Introductions 4 November 20th, 2016 05:21 AM
Double Top / Double Bottom indicator for Multicharts / Tradestation, one available? PositiveDeviant MultiCharts 12 February 15th, 2012 02:10 AM
Bars Object as input to Indicator NJAMC NinjaTrader Programming 3 May 21st, 2011 10:48 PM
Spread indicator for MBT on Multicharts DT 7 beta 3 koni MultiCharts 4 May 20th, 2011 07:40 AM
Indicator for double-bar? siewen NinjaTrader 6 September 12th, 2010 10:49 AM


All times are GMT -4. The time now is 04:38 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-13 in 0.11 seconds with 19 queries on phoenix via your IP 54.90.92.204