Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Instrument correlation against Close[0]

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Instrument correlation against Close[0]

    Hello,

    I had the idea to create a strategy based off of the correlation between a indicator and Close[0]. I wrote up some code

    Code:
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    //This namespace holds Strategies in this folder and is required. Do not change it. 
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class CorrelationAndCausalityGTB : Strategy
        {
    
            private WilliamsR WilliamsR1;
            private Correlation Correlation1;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"WilliamR causality cross Correlated with price. Vector William R and Correlation confirmation initiates trades.  ATR in Ticks dictates Profit Target and Stop Loss. ";
                    Name                                        = "CorrelationAndCausalityGTB";
                    Calculate                                    = Calculate.OnEachTick;
                    EntriesPerDirection                            = 1;
                    EntryHandling                                = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy                = true;
                    ExitOnSessionCloseSeconds                    = 30;
                    IsFillLimitOnTouch                            = false;
                    MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution                            = OrderFillResolution.High;
                    OrderFillResolutionType                        = BarsPeriodType.Minute;
                    OrderFillResolutionValue                    = 1;
                    Slippage                                    = 2;
                    StartBehavior                                = StartBehavior.WaitUntilFlat;
                    TimeInForce                                    = TimeInForce.Gtc;
                    TraceOrders                                    = false;
                    RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelClose;
                    StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade                            = 20;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration    = true;
    
                    SharedPeriodLength                        = 2;
                    ATRticksPeriodLength                    = 2;
                    ProfitTargetMultiplier                    = 1;
                    ProfitTargetAndStopLossMultiplier        = 1;
    
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {                
                    WilliamsR1                = WilliamsR(Close, Convert.ToInt32(SharedPeriodLength));
                    Correlation1                = Correlation(WilliamsR1, Convert.ToInt32(SharedPeriodLength), @"WilliamsRCorrelationWithInstrumentAppliedToo");
    
                    SetProfitTarget(@"EnterLongCorrelationCausalityGTB", CalculationMode.Ticks, ((20 * ProfitTargetAndStopLossMultiplier));
                    SetTrailStop(@"EnterLongCorrelationCausalityGTB", CalculationMode.Ticks, ((20 *ProfitTargetAndStopLossMultiplier), false);
                    SetProfitTarget(@"EnterShortCorrelationCausalityGTB", CalculationMode.Ticks, ((20 *ProfitTargetAndStopLossMultiplier));
                    SetTrailStop(@"EnterShortCorrelationCausalityGTB", CalculationMode.Ticks, ((20 *ProfitTargetAndStopLossMultiplier), false);
                }
            }
    
            protected override void OnBarUpdate()
            {
                if (BarsInProgress != 0) 
                    return;
    
                if (CurrentBars[0] < 1)
                    return;
    
                 // Set 1
                if ((WilliamsR1[0] > WilliamsR1[1])
                     && (Correlation1[0] > Correlation1[1]))
                {
                    EnterLong(Convert.ToInt32(1000), @"EnterLongCorrelationCausalityGTB");
                }
    
                 // Set 2
                if ((WilliamsR1[0] < WilliamsR1[1])
                     && (Correlation1[0] < Correlation1[1]))
                {
                    EnterShort(Convert.ToInt32(1000), @"EnterShortCorrelationCausalityGTB");
                }
    
            }
    
            #region Properties
            [NinjaScriptProperty]
            [Range(2, int.MaxValue)]
            [Display(Name="SharedPeriodLength", Description="Shared Period Length (Set 5 to 125)", Order=1, GroupName="Parameters")]
            public int SharedPeriodLength
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="ProfitTargetAndStopLossMultiplier", Description="Profit Target And Stop Loss Multiplier (Set 1 to 10)", Order=2, GroupName="Parameters")]
            public int ProfitTargetAndStopLossMultiplier
            { get; set; }
            #endregion
    
        }
    }
    I have had issues starting this strategy up on sim101 and have issues with backtesting.
    Is there anything I should know about Correlation that might be causing this issue?

    #2
    Hello GTBrooks,

    Thank you for your post.

    The issue is most likely that while the Correlation indicator is addding a separate DataSeries using AddDataSeries so the secondary series can be specified, you're not also adding the series in the hosting Strategy.

    Should your script be the host for other scripts that are creating indicators and series dependent resources in State.DataLoaded, please make sure that the host is doing the same AddDataSeries() calls as those hosted scripts would. For further reference, please also review the example below and the 'Adding additional Bars Objects to NinjaScript' section in Multi-Time Frame & Instruments:

    Code:
    protected override void OnStateChange()
    {
        if (State == State.Configure)
        {
            // Our hosting script needs to have the AddDataSeries call included as well, which the Pivots indicator we call in the 2nd statement below
    
             // also has per default in it's own State.Configure method. This is required since our Pivots indicator below is created in State.DataLoaded          
             // (which is happening after State.Configure and it depends on the AddDataSeries call to have the bars available to properly calculate in
    
             // daily bars mode.
            AddDataSeries(BarsPeriodType.Day, 1);
        }
    
        else if (State == State.DataLoaded)
        {
            //In this state, we pass the 1 day series to the Pivots indicator (as BarsArray[1]) and create its instance
            pivots = Pivots(BarsArray[1], PivotRange.Weekly, HLCCalculationMode.DailyBars, 0, 0, 0, 20);
        }
    }


    I would take a look at the code for the correlation indicator to see how it's adding that secondary series and copy that code over to your strategy.

    Please let us know if we may be of further assistance to you.
    Kate W.NinjaTrader Customer Service

    Comment


      #3
      I am a little confused, when I built this in the Strategy Builder it did not require a a specific State == ???. My intent when I selected Correlation of WilliamR for this Instrument. was as a confirmation for the WilliamR. In your opinion If I AddDataSeries(???, #), will this clear up the issue (not allowing sim101 realtime & Backtesting failures)?

      Is there a work-around where I force Strategy Builder to construct the majority of the Code so I can Grab it pull it over to my C# Code editing application?
      It would streamline my process if I could combine them before moving the "Fix" into the NinjaTrader Automated Strategy Coding.

      Comment


        #4
        Hello GTBrooks,

        Thank you for your reply.

        You can add additional data series in the Strategy Builder on the Additional Data Screen. This will automatically add the code to add the additional series to the proper place within the code.



        Generally I would advise using the Builder to construct at least part of your code even though you may unlock the code and then copy it to whatever editor you like or edit it in the NinjaScript Editor window. If you add an additional data series in the Builder you could then unlock the code and compare the added series to the added series the Correlation indicator uses.

        Please let us know if we may be of further assistance to you.
        Kate W.NinjaTrader Customer Service

        Comment


          #5
          I used Strategy Builder to create the code and Integrated it into the existing code.
          Good News, it fixed the previous errors.
          Bad News, New errors have arised

          It looks like I ran into 2 errors when trying to compile code.
          Error;
          1) CS1502 error code information is provided within the context of NinjaScript. The examples provided are only a subset of potential problems that this error code may reflect. In any case, the examples below provide a reference of coding flaw possibilities.
          2) CS1503 error code information is provided within the context of NinjaScript. The examples provided are only a subset of potential problems that this error code may reflect. In any case, the examples below provide a reference of coding flaw possibilities.

          here is the code
          Code:
          #region Using declarations
          using System;
          using System.Collections.Generic;
          using System.ComponentModel;
          using System.ComponentModel.DataAnnotations;
          using System.Linq;
          using System.Text;
          using System.Threading.Tasks;
          using System.Windows;
          using System.Windows.Input;
          using System.Windows.Media;
          using System.Xml.Serialization;
          using NinjaTrader.Cbi;
          using NinjaTrader.Gui;
          using NinjaTrader.Gui.Chart;
          using NinjaTrader.Gui.SuperDom;
          using NinjaTrader.Gui.Tools;
          using NinjaTrader.Data;
          using NinjaTrader.NinjaScript;
          using NinjaTrader.Core.FloatingPoint;
          using NinjaTrader.NinjaScript.Indicators;
          using NinjaTrader.NinjaScript.DrawingTools;
          #endregion
          
          //This namespace holds Strategies in this folder and is required. Do not change it. 
          namespace NinjaTrader.NinjaScript.Strategies
          {
              public class CorrelationAndCausalityGTB : Strategy
              {
                  public int LotSizeToTradeEnterLong;
                  public int LotSizeToTradeEnterShort;
                  private Series<double> CorrelationPriceAndWilliamRofPriceGTB;
          
                  private WilliamsR WilliamsR1;
                  private Correlation Correlation1;
                  private ATRtick8 ATRtick81;
          
                  protected override void OnStateChange()
                  {
                      if (State == State.SetDefaults)
                      {
                          Description                                    = @"WilliamR causality cross Correlated with price. Vector William R and Correlation confirmation iniciates trades.  ATR in Ticks dictates Profit Target and Stop Loss. ";
                          Name                                        = "CorrelationAndCausalityGTB";
                          Calculate                                    = Calculate.OnEachTick;
                          EntriesPerDirection                            = 1;
                          EntryHandling                                = EntryHandling.AllEntries;
                          IsExitOnSessionCloseStrategy                = true;
                          ExitOnSessionCloseSeconds                    = 30;
                          IsFillLimitOnTouch                            = false;
                          MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                          OrderFillResolution                            = OrderFillResolution.High;
                          OrderFillResolutionType                        = BarsPeriodType.Minute;
                          OrderFillResolutionValue                    = 1;
                          Slippage                                    = 2;
                          StartBehavior                                = StartBehavior.WaitUntilFlat;
                          TimeInForce                                    = TimeInForce.Gtc;
                          TraceOrders                                    = false;
                          RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelClose;
                          StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                          BarsRequiredToTrade                            = 20;
                          // Disable this property for performance gains in Strategy Analyzer optimizations
                          // See the Help Guide for additional information
                          IsInstantiatedOnEachOptimizationIteration    = true;
          
                          SharedPeriodLength                        = 2;
                          ATRticksPeriodLength                    = 2;
                          ProfitTargetMultiplier                    = 1;
                          ProfitTargetAndStopLossMultiplier        = 1;
          
                          LotSizeToTradeEnterLong = 1000;
                          LotSizeToTradeEnterShort= 1000;
                      }
                      else if (State == State.Configure)
                      {
                      }
                      else if (State == State.DataLoaded)
                      {                
                          WilliamsR1                = WilliamsR(Close, Convert.ToInt32(SharedPeriodLength));
                          Correlation1                = Correlation(WilliamsR1, Convert.ToInt32(SharedPeriodLength), @"WilliamsRCorrelationWithInstrumentAppliedToo");
                          ATRtick81                = ATRtick8(Close, Convert.ToInt32(ATRticksPeriodLength));
          
                          // Passing in CorrelationPriceAndWilliamRofPriceGTB Series with an identical variable Correlation1
                            CorrelationPriceAndWilliamRofPriceGTB = new Series<double>(Correlation1[0]);
          
                          SetProfitTarget(@"EnterLongCorrelationCausalityGTB", CalculationMode.Ticks, ((ATRtick81[0] / 10) * ProfitTargetMultiplier * ProfitTargetAndStopLossMultiplier));
                          SetTrailStop(@"EnterLongCorrelationCausalityGTB", CalculationMode.Ticks, ((ATRtick81[0] / 10) * ProfitTargetAndStopLossMultiplier), false);
                          SetProfitTarget(@"EnterShortCorrelationCausalityGTB", CalculationMode.Ticks, ((ATRtick81[0] / 10) * ProfitTargetMultiplier * ProfitTargetAndStopLossMultiplier));
                          SetTrailStop(@"EnterShortCorrelationCausalityGTB", CalculationMode.Ticks, ((ATRtick81[0] / 10) * ProfitTargetAndStopLossMultiplier), false);
                      }
                  }
          
                  protected override void OnBarUpdate()
                  {
                      if (BarsInProgress != 0) 
                          return;
          
                      if (CurrentBars[0] < 1)
                          return;
          
                      //Lots to trade in a Enter Long situation//
                      if ((SystemPerformance.LongTrades.Count > 0)
                          &&  (SystemPerformance.LongTrades[SystemPerformance.LongTrades.Count - 1].ProfitCurrency > 0))
                              LotSizeToTradeEnterLong = 2000;
                      else if ((SystemPerformance.LongTrades.Count > 0)
                          &&  (SystemPerformance.LongTrades[SystemPerformance.LongTrades.Count - 1].ProfitCurrency <= 0))
                              LotSizeToTradeEnterLong = 1000;
                      //Lots to trade in a Enter Short situation
                      if ((SystemPerformance.ShortTrades.Count > 0)
                          &&  (SystemPerformance.ShortTrades[SystemPerformance.ShortTrades.Count - 1].ProfitCurrency > 0))
                              LotSizeToTradeEnterShort = 2000;
                      else if ((SystemPerformance.ShortTrades.Count > 0)
                          &&  (SystemPerformance.ShortTrades[SystemPerformance.ShortTrades.Count - 1].ProfitCurrency <= 0))
                              LotSizeToTradeEnterShort = 1000;
          
                       // Set 1
                      if (Open[0] > Close[0]
                           && (WilliamsR1[0] > WilliamsR1[1])
                           && (ATRtick81[0] > ATRtick81[1])
                           && (CorrelationPriceAndWilliamRofPriceGTB[0] > CorrelationPriceAndWilliamRofPriceGTB[1]))
                      {
                          EnterLong(Convert.ToInt32(LotSizeToTradeEnterLong), @"EnterLongCorrelationCausalityGTB");
                      }
          
                       // Set 2
                      if (Open[0] < Close[0]
                           && (WilliamsR1[0] < WilliamsR1[1])
                           && (ATRtick81[0] > ATRtick81[1])
                           && (CorrelationPriceAndWilliamRofPriceGTB[0] > CorrelationPriceAndWilliamRofPriceGTB[1]))
                      {
                          EnterShort(Convert.ToInt32(LotSizeToTradeEnterShort), @"EnterShortCorrelationCausalityGTB");
                      }
          
                  }
          
                  #region Properties
                  [NinjaScriptProperty]
                  [Range(2, int.MaxValue)]
                  [Display(Name="SharedPeriodLength", Description="Shared Period Length (Set 5 to 125)", Order=1, GroupName="Parameters")]
                  public int SharedPeriodLength
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(2, int.MaxValue)]
                  [Display(Name="ATRticksPeriodLength", Description="ATRticks Period Length (Set 5 to 125)", Order=2, GroupName="Parameters")]
                  public int ATRticksPeriodLength
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(1, int.MaxValue)]
                  [Display(Name="ProfitTargetMultiplier", Description="Profit Target Multiplier (Set 1 to 10)", Order=3, GroupName="Parameters")]
                  public int ProfitTargetMultiplier
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(1, int.MaxValue)]
                  [Display(Name="ProfitTargetAndStopLossMultiplier", Description="Profit Target And Stop Loss Multiplier (Set 1 to 10)", Order=4, GroupName="Parameters")]
                  public int ProfitTargetAndStopLossMultiplier
                  { get; set; }
                  #endregion
          
              }
          }
          What suggestion do you have for me to correct Errors; CS1502 ,CS1503?

          Comment


            #6
            Hello GTBrooks,

            Thank you for your reply.

            Here's your issue:

            CorrelationPriceAndWilliamRofPriceGTB = new Series<double>(Correlation1[0]);

            This should instead be:

            CorrelationPriceAndWilliamRofPriceGTB = new Series<double>(Correlation1);

            You need to reference the whole Correlation1 series, not just the latest value.

            Please let us know if we may be of further assistance to you.
            Kate W.NinjaTrader Customer Service

            Comment


              #7
              First off thank you the Program is up and running. One question, is CorrelationPriceAndWilliamRofPriceGTB[0] 1 bar behinde Close[0}?

              After walking down this path, it got me thinking.



              could I create a reference based off of calculations that typically happening on OnBarUpdate?

              Example:
              Code:
              else if (State == State.DataLoaded)
              {
              
              // Passing in CorrelationPriceAndWilliamRofPriceGTB Series with an identical variable Correlation1
              CorrelationPriceAndWilliamRofPriceGTB = new Series<double>(SharedPeriodLength * PeriodLength);
              protected override void OnBarUpdate()
              {
              if (CurrentBars[0] < 1)
              return;
              
              Private double SharedPeriodLength
              SharedPeriodLength = 0;
              SharedPeriodLength = Open[0] - Close[0];
              
              Private double PeriodLength
              PeriodLength = 0;
              if(Open[0] > Close[0])
              PeriodLength = 1;
              else if(Open[0] == Close[0])
              PeriodLength = 0;
              else if(Open[0] < Close[0])
              PeriodLength = -1;
              
              //where I can later reference it as;
              
              CorrelationPriceAndWilliamRofPriceGTB[0]
              ???
              Last edited by GTBrooks; 07-01-2020, 09:22 PM.

              Comment


                #8
                Hello GTBrooks,

                Thank you for your reply.

                Yes, you'd want to create a Series<T> variable to store the calculations for each bar. You could then reference the calculation results for whatever bar you like.

                Here's a link to an example from our help guide that goes over how you can create and use a Series<T> variable in a script:



                Please let us know if we may be of further assistance to you.
                Kate W.NinjaTrader Customer Service

                Comment


                  #9
                  I followed the Link and used it with success. Thank you!
                  I have 1 lingering question: are Series<T> evaluated(indicator[0] == Close[0] as it relates to Bar number) the same as indicators?

                  is this true?
                  Example;
                  Bar 1 of the series has an output of Close[0]
                  and Indicator[0] referring to Bar 1

                  Comment


                    #10
                    Hello GTBrooks,

                    Thank you for your reply.

                    Yes, Series <T> variables would be referenced in the same way, where mySeriesT[0] would be the value for the most recent bar, mySeriesT[1] would refer to the previous bar to that, and so on.

                    Please let us know if we may be of further assistance to you.
                    Kate W.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by adeelshahzad, Today, 03:54 AM
                    5 responses
                    32 views
                    0 likes
                    Last Post NinjaTrader_BrandonH  
                    Started by stafe, 04-15-2024, 08:34 PM
                    7 responses
                    32 views
                    0 likes
                    Last Post NinjaTrader_ChelseaB  
                    Started by merzo, 06-25-2023, 02:19 AM
                    10 responses
                    823 views
                    1 like
                    Last Post NinjaTrader_ChristopherJ  
                    Started by frankthearm, Today, 09:08 AM
                    5 responses
                    21 views
                    0 likes
                    Last Post NinjaTrader_Clayton  
                    Started by jeronymite, 04-12-2024, 04:26 PM
                    3 responses
                    43 views
                    0 likes
                    Last Post jeronymite  
                    Working...
                    X