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

strategy to monitor one instrument but send entry and exit orders to another.

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

    strategy to monitor one instrument but send entry and exit orders to another.



    good day to everyone,



    i have been able to develop some very interesting strategies and i still have some important considerations to study to determine if i would indeed trade them automated with nt. i have found that nt support is consistently excellent and with the power and flexibility of the nt platform i would think it must be possible to have strategies that analyze data for one instrument but send orders to others and i would just have to learn how.



    i have two cases in mind:


    - first i think about the numerous futures instruments which share one same underlying. for example, for the eu euro currency there are at least 3 major futures contracts; 6e, e7 and m6e, and there are other similar cases for other currencies, fossil fuels and other classes. normally the most expensive contract is the most liquid and informative while the cheapest is the one that implies the least risk.

    ¿i'd like to know if it is possible to create an automated strategy on nt that would determine entries and exits based on the activity of the most expensive contract (6e) but send the entry and exit orders to the cheapest (m6e)? for example, if price (6e) crosses above sma (6e) enter long m6e.


    - also, it would be crucially important for me to be able to have a strategy that monitored price action, let's say, on the cl contract but instead of opening a long position buying futures when an uptrend began, purchased a long call options position for this instrument (the ticker would be something like LO 190214C55, where the strike price 55 would be the current price for cl plus 1 point). if price (cl) crosses above sma (cl) enter long LO 190214C55 limit. when a downtrend began, the strategy would perform similarly but would purchase long puts instead (for example, LO 190214P53).



    at the moment i have been trying to translate my strategies to some other open source trading platforms that can execute c# and python but i have been having a hard time making progress and receiving assistance. on the other hand, my strategies are already completed and ready on ninjatrader and i would prefer to trade them with the nt brokerage if it was possible to structure them as i described above. i performed some searches on these fora but didn't find anything useful.


    very well, i'll wait for the reply from the people with nt support, thanks, regards.
    Last edited by rtwave; 01-22-2019, 12:53 PM.

    #2
    Hello rtwave,

    Thank you for the post.

    Please see this publicly available link to the help guide section on multi time frame an instrument scripts:



    The most important concepts are listed on that page, please make sure to understand how each of these items work:
    That page also shows you how to enter and exit a specific instrument under the header titled "Entering, Exiting and Retrieving Position Information"

    Below is a relevant reference sample. Although the strategy does not trade multiple instruments, it demonstrates how to access and manage the various data series that you add to your script:



    Please let me know if you have any questions on this material.
    Chris L.NinjaTrader Customer Service

    Comment


      #3




      mr. Chris,




      thanks.



      i went over the links you suggested and the information was helpful. however, all the examples in the links you provided dealt exclusively with stocks and further clarification would be in order.



      - in the case of futures contracts, which expire several times per year, ¿how would the code to add additional bars objects work? ¿would this fragment of code below work correctly?


      elseif(State==State.Configure)
      {
      AddDataSeries("6E ##-##",BarsPeriodType.Minute,5);
      AddDataSeries("M6E ##-##",BarsPeriodType.Minute,5);
      }


      ¿could it be possible to use nt's version of continuous contract nomenclature on an automated strategy, or is it necessary to explicitly include the desired expirations (which would require periodical modifications to the code)?


      also, in the example above, if i want the [2] bars object (m6e) contract to be traded following the signals from the [1] bars object (6e), ¿does it matter if the interval in minutes for [2] is larger, equal or smaller than that of [1]?



      - in the case of trading calls and puts long positions as the underlying futures contract goes on uptrends and downtrends, there is a lot still to be solved.


      first of all, i assume it would be necessary to ask the people at nt brokerage for the list of futures contracts that nt makes options available on, ¿what is the nomenclature nt uses for said options and whether it could be possible to send automated orders to buy options? ¿is there any way i could reach the people at nt who could know the answers to these questions?


      even more importantly, maybe my earlier post was not clear enough. in the case of options, there are tens of different contracts and also multiple expiration dates. maybe i didn't make myself clear before but i want the strike prices and the days to expiration to be selected adaptively or dynamically, according to the current price of the underlying futures contract. for example, if cl just started an uptrend and the current price is 54, i would want a call with a strike price of 55 to be bought. if cl began a downtrend and price was 54, i would want a put with a strike price of 53 to be bought. uptrend and current price at 45 would mean the strategy should buy a call with strike price of 46, while downtrend and price at 45 would generate a buy order for a put with strike price of 44.


      while that would be the logic for the strategy i don't think that adding one additional bars object for each instrument would work. in the image i include one of the closest to expiration options chain for cl is depicted. there are more than 30 instruments in that fragment of the options chain between calls and puts and it is not even depicted in its entirety. i think it should be immediately apparent that adding tens of additional bars objects to a strategy would not be feasible nor generate the desired results. ¿are there any other ways for nt to send entry and exit orders? ¿is it possible for nt to create a "placeholder variable" with the current value for price, add a fixed number of points to it, determine the desired date for the options to be bought based on the days to expiration and then send an order for the resulting instrument? something like i initially wrote; ¿ if price (cl) crosses above sma (cl) enter long LO 190214C55 limit?



      very well, thanks, regards.

      Comment


        #4
        Hello rtwave,

        Thank you for the reply.

        If your data provider/broker supports continuous contracts, then that code snippet is OK.

        The period of each instrument series does not matter. You do not need to rely on OnBarUpdate being called to place an order to a specific instrument. You can use the special order entry methods that take a BarsInProgress index. With that, you can place an order to any one of the added data series from any OnBarUpdate call.

        EX: EnterLong(int barsInProgressIndex, int quantity, string signalName)

        All of the order entry methods have this method overload.

        While the NinjaTrader brokerage does offer options, you currently can not trade options in the NT platform, you must use a different platform to trade options for the moment.

        There is no other way to place an order to a non-primary instrument unless you add additional series to your script.

        NinjaScript is C# code, so you can make any data structure you want within your scripts. NT already provides price data arrays, more on that here.

        You can use the CrossAbove method and pass in two series to detect crossovers.

        If the price crosses the SMA in the last bar would look like this:

        if (CrossAbove(Close, SMA(14), 1))
        {
        //price crossed 14 period SMA.
        }

        Please let me know if you have any additional questions.
        Chris L.NinjaTrader Customer Service

        Comment


          #5




          mr. Chris,




          thanks again.



          i have been doing further research trying to determine the best method to trade options automated.



          i want to make sure i'm understanding everything you posted correctly.


          - nt brokerage does make options on futures available but it is impossible to trade them on the nt platform.


          - i understand there is no limit to the number of additional bars objects that can be added to a strategy on nt, and having tens of additional series should not be a problem either.


          - the most important question i have right now, is, if i made interactive brokers my broker, ¿could i create strategies with tens of additional bars objects, one for each options contract (for example, having nvda as the series to determine all entries and exits and then adding nvda 190125c155, nvda 190125p155, etc, as these are perfectly valid instruments with interactive brokers brokerage), and use nt to trade options automated?


          i think i could use a structure like the one in the code box below. i would just need to create a grid where if utc changed to true and price was between two predetermined values the strategy should open a position in the corresponding additional series that i previously determined for that interval. this would mean that every one of my strategies would have tens of different cases for entries, all based on the price on close.


          if ( (Utc == true) && ( Close is inside the lowest interval defined) )
          {
          EnterLongLimit([additional series that corresponds to lowest interval], Convert.ToInt32(Ps), GetCurrentAsk(0), @"lp01");
          }


          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 tesamplemultipleconditionentrysingleconditionexitstructuremod : Strategy
              {
                  private double Smav;
                  private double Momv;
                  private double Adxv;
                  private bool Utc;
                  private bool Dtc;
          
                  private SMA SMA1;
          
                  private Momentum Momentum1;
                  private ADX ADX1;
          
                  protected override void OnStateChange()
                  {
                      if (State == State.SetDefaults)
                      {
                          Description                                    = @"te sample multiple condition entry single condition exit structure to modify.";
                          Name                                        = "tesamplemultipleconditionentrysingleconditionexitstructuremod";
                          Calculate                                    = Calculate.OnBarClose;
                          EntriesPerDirection                            = 1;
                          EntryHandling                                = EntryHandling.UniqueEntries;
                          IsExitOnSessionCloseStrategy                = false;
                          ExitOnSessionCloseSeconds                    = 30;
                          IsFillLimitOnTouch                            = false;
                          MaximumBarsLookBack                            = MaximumBarsLookBack.Infinite;
                          OrderFillResolution                            = OrderFillResolution.Standard;
                          Slippage                                    = 0;
                          StartBehavior                                = StartBehavior.WaitUntilFlatSynchronizeAccount;
                          TimeInForce                                    = TimeInForce.Gtc;
                          TraceOrders                                    = false;
                          RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelCloseIgnoreRejects;
                          StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                          BarsRequiredToTrade                            = 600;
                          // Disable this property for performance gains in Strategy Analyzer optimizations
                          // See the Help Guide for additional information
                          IsInstantiatedOnEachOptimizationIteration    = true;
                          Smap                    = 10;
                          Momp                    = 10;
                          Momtl                    = 2;
                          Momts                    = -2;
                          Adxp                    = 10;
                          Adxt                    = 5;
                          Ps                    = 1;
                          Smav                    = 0;
                          Momv                    = 0;
                          Adxv                    = 0;
                          Utc                    = false;
                          Dtc                    = false;
                      }
                      else if (State == State.Configure)
                      {
                          AddDataSeries("NVDA", Data.BarsPeriodType.Minute, 10, Data.MarketDataType.Last);
                      }
                      else if (State == State.DataLoaded)
                      {                
                          SMA1                = SMA(Closes[1], Convert.ToInt32(Smap));
                          Momentum1                = Momentum(Closes[1], Convert.ToInt32(Momp));
                          ADX1                = ADX(Closes[1], Convert.ToInt32(Adxp));
                      }
                  }
          
                  protected override void OnBarUpdate()
                  {
                      if (BarsInProgress != 0)
                          return;
          
                      if (CurrentBars[0] < 1
                      || CurrentBars[1] < 1)
                      return;
          
                       // Set 1
                      if ((SMA1[0] > SMA1[1])
                           && (Momentum1[0] > Momtl)
                           && (ADX1[0] > Adxt))
                      {
                          Utc = true;
                      }
          
                       // Set 2
                      if (SMA1[0] < SMA1[1])
                      {
                          Utc = false;
                      }
          
                       // Set 3
                      if (Utc == true)
                      {
                          EnterLongLimit(Convert.ToInt32(Ps), GetCurrentAsk(0), @"lp01");
                      }
          
                       // Set 4
                      if (Utc == false)
                      {
                          ExitLongLimit(Convert.ToInt32(Ps), GetCurrentBid(0), @"xlp01", @"lp01");
                      }
          
                       // Set 5
                      if ((SMA1[0] < SMA1[1])
                           && (Momentum1[0] < Momts)
                           && (ADX1[0] > Adxt))
                      {
                          Dtc = true;
                      }
          
                       // Set 6
                      if (SMA1[0] > SMA1[1])
                      {
                          Dtc = false;
                      }
          
                       // Set 7
                      if (Dtc == true)
                      {
                          EnterShortLimit(Convert.ToInt32(Ps), GetCurrentAsk(0), @"sp01");
                      }
          
                       // Set 8
                      if (Dtc == false)
                      {
                          ExitShortLimit(Convert.ToInt32(Ps), GetCurrentBid(0), @"xsp01", @"sp01");
                      }
          
                  }
          
                  #region Properties
                  [NinjaScriptProperty]
                  [Range(1, int.MaxValue)]
                  [Display(Name="Smap", Description="smap.", Order=1, GroupName="Parameters")]
                  public int Smap
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(1, int.MaxValue)]
                  [Display(Name="Momp", Description="momp.", Order=2, GroupName="Parameters")]
                  public int Momp
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(-100, int.MaxValue)]
                  [Display(Name="Momtl", Description="momtl.", Order=3, GroupName="Parameters")]
                  public int Momtl
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(-100, int.MaxValue)]
                  [Display(Name="Momts", Description="momts.", Order=4, GroupName="Parameters")]
                  public int Momts
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(1, int.MaxValue)]
                  [Display(Name="Adxp", Description="adxp.", Order=5, GroupName="Parameters")]
                  public int Adxp
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(1, int.MaxValue)]
                  [Display(Name="Adxt", Description="adxt.", Order=6, GroupName="Parameters")]
                  public int Adxt
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(1, int.MaxValue)]
                  [Display(Name="Ps", Description="ps.", Order=7, GroupName="Parameters")]
                  public int Ps
                  { get; set; }
                  #endregion
          
              }
          }

          i have some further questions regarding the additional series and how i could make sure my strategy chose the appropriate positions when utc or dtc stopped being true, but it would only make sense to continue refining these strategies if i have first confirmed that nt can indeed be used to trade options automated.


          very well, thanks, regards.

          Comment


            #6
            Hello rtwave,

            Thank you for your reply.

            nt brokerage does make options on futures available but it is impossible to trade them on the nt platform.
            Yes, that is correct.

            I understand there is no limit to the number of additional bars objects that can be added to a strategy on nt, and having tens of additional series should not be a problem either.
            Yes adding tens of additional instruments is OK as long as your data conneciton will provide it.

            the most important question i have right now, is, if i made interactive brokers my broker, ¿could i create strategies with tens of additional bars objects, one for each options contract (for example, having nvda as the series to determine all entries and exits and then adding nvda 190125c155, nvda 190125p155, etc, as these are perfectly valid instruments with interactive brokers brokerage), and use nt to trade options automated?
            There are no instrument definitions for options, so it is not supported to trade options in NinjaTrader 8 currently. Futures, stocks, forex, and CFD's can currently be traded in the platform. For your question about your code, you can use the special entry/exit method overloads that take a BarsInProgress index. For example:

            //EnterLong(int barsInProgressIndex, int quantity, string signalName)
            EnterLong(1, 100, "NVDABUY");

            This will enter 100 long on the NVDA instrument you added no matter what BarsInProgress OnBarUpdate is running for. This overload exists for all entry/exit methods.

            Please let me know if I can clarify anything further.


            Chris L.NinjaTrader Customer Service

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by Waxavi, Today, 02:10 AM
            0 responses
            3 views
            0 likes
            Last Post Waxavi
            by Waxavi
             
            Started by TradeForge, Today, 02:09 AM
            0 responses
            9 views
            0 likes
            Last Post TradeForge  
            Started by Waxavi, Today, 02:00 AM
            0 responses
            2 views
            0 likes
            Last Post Waxavi
            by Waxavi
             
            Started by elirion, Today, 01:36 AM
            0 responses
            4 views
            0 likes
            Last Post elirion
            by elirion
             
            Started by gentlebenthebear, Today, 01:30 AM
            0 responses
            4 views
            0 likes
            Last Post gentlebenthebear  
            Working...
            X