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

Multi instrument strategy question

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

    Multi instrument strategy question

    Hi,

    I am new to Ninjatrader and trying to program a strategy.
    It is a multi instrument that needs 2 instruments which are stocks- SPY and SSO and works on daily bars.
    The buy and sell signals for both the instruments will be based on SMA crossover of primary instrument(SPY) only.

    The logic is as follows:-

    1) If primary instrument(SPY) SMA20 crosses above primary instrument(SPY) SMA50, then Exit short position of 2nd instrument(SSO)(if market position of 2nd instrument is short) and Enter long position of primary instrument(SPY).
    2) If primary instrument(SPY) SMA20 crosses above primary instrument(SPY) SMA200,then Exit long position of primary instrumen(SPY)(if market position of primary instrument is long) and Enter long position of 2nd instrument(SSO).
    3) If primary instrument(SPY) SMA20 crosses below primary instrument(SPY) SMA50, then Exit long position of 2nd instrument(SSO)(if market position of 2nd instrument is long) and Enter Short primary instrument(SPY).
    4) If primary instrument(SPY) SMA20 crosses below primary instrument(SPY) SMA200,then Exit short position of primary instrument(SPY)(if market position of primary instrument is short) and Enter short position of 2nd instrument(SSO).

    Below is the code:-

    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.Strategy
    {
    /// <summary>
    /// Spy and SSO strategy
    /// </summary>
    [Description("Spy and SSO strategy")]
    public class SPYSSO : Strategy
    {
    #region Variables
    // Wizard generated variables
    private int myInput0 = 1; // Default setting for MyInput0
    // User defined variables (add any user defined variables below)
    private int Fast = 20;
    private int Medium = 50;
    private int Slow = 200;
    #endregion


    /// <summary>
    /// This method is used to configure the strategy and is called once before any strategy method is called.
    /// </summary>
    protected override void Initialize()
    {
    // Add SSO 1 day Bars object to the strategy

    Add("SSO", PeriodType.Day, 1);

    SMA(Fast).Plots[0].Pen.Color = Color.Orange;
    SMA(Medium).Plots[0].Pen.Color = Color.Green;
    SMA(Slow).Plots[0].Pen.Color = Color.Red;

    Add(SMA(Fast));
    Add(SMA(Medium));
    Add(SMA(Slow));
    CalculateOnBarClose = true;

    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    // OnBarUpdate() will be called on incoming tick events on all Bars objects added to the strategy
    // We only want to process events on our primary Bars object (main instrument) (index = 0) which
    // is set when adding the strategy to a chart
    //
    if (BarsInProgress == 1)
    return;

    // If SPY SMA20 crosses above SMA50, then go long SPY and exit short position of SSO.
    if (Positions[1].MarketPosition == MarketPosition.Short
    && CrossAbove(SMA(Fast), SMA(Medium), 1))
    {
    ExitShort(1);
    EnterLong();
    }

    // If SPY SMA20 crosses above SMA200,and long position of SPY exists then exit long position of SPY
    // and go long SSO.
    if (Positions[0].MarketPosition == MarketPosition.Long
    && CrossAbove(SMA(Fast), SMA(Slow), 1))
    {
    ExitLong();
    EnterLong(1,100,"buy sso");
    }

    // If long SSO and SPY SMA20 crosses below SMA50, then exit long SSO and go short SPY
    if (Positions[1].MarketPosition == MarketPosition.Long
    && CrossBelow(SMA(Fast), SMA(Medium), 1))
    {
    ExitLong(1);
    EnterShort();
    }

    // If SPY SMA20 crosses below SMA200,and a short position of SPY exists then exit short position of SPY and
    // go short SSO.
    if (CrossBelow(SMA(Fast), SMA(Slow), 1))
    {
    if (Positions[0].MarketPosition == MarketPosition.Short)
    ExitShort();
    EnterShort(1,100,"short sso");
    }


    }

    #region Properties
    [Description("")]
    [GridCategory("Parameters")]
    public int MyInput0
    {
    get { return myInput0; }
    set { myInput0 = Math.Max(1, value); }
    }
    #endregion
    }
    }



    I have 2 questions.
    1) How do i place buy/sell and short/buy-to-cover orders on the 2nd instrument(SSO) correctly when the context is of the primary instrument(SPY)(BarsInProgress==0)? Do i have to use an IOrder or is there another way?
    Do i have to use something like this:- "ExitLong(int barsInProgressIndex, int quantity, string signalName, string fromEntrySignal)". I have tried to do "ExitLong(1);" where 1 is barsInProgressIndex for the 2nd instrument, but i dont think thats correct.

    2) When i run backtest with the strategy, i only see entry and exit signals on the chart of primary instrument(SPY). How can i see the chart of 2nd instrument after backtesting?

    Thanks,
    Subrat

    #2
    subrat,

    1) How do i place buy/sell and short/buy-to-cover orders on the 2nd instrument(SSO) correctly when the context is of the primary instrument(SPY)(BarsInProgress==0)? Do i have to use an IOrder or is there another way?
    Do i have to use something like this:- "ExitLong(int barsInProgressIndex, int quantity, string signalName, string fromEntrySignal)". I have tried to do "ExitLong(1);" where 1 is barsInProgressIndex for the 2nd instrument, but i dont think thats correct.
    Here is a reference sample on how to do this : http://www.ninjatrader.com/support/f...ead.php?t=5787

    2) When i run backtest with the strategy, i only see entry and exit signals on the chart of primary instrument(SPY). How can i see the chart of 2nd instrument after backtesting?
    Unfortunately this isn't currently possible. You could try to make an indicator that plots the close values perhaps then add it to your strategy as an indicator perhaps.

    Please let me know if I may assist further.
    Adam P.NinjaTrader Customer Service

    Comment


      #3
      Multi Instrument Strategy

      I have a 50 stock multiple instrument strategy that fires at the open of the market each day. I want to keep the overall risk (2 %) the same no matter how many of these stocks have fired.

      For example on day 1:

      5 of 50 fired so 0.4 % risk per position


      For example on day 2:

      10 of 50 fired so 0.2 % risk per position


      What I am trying to do is count how many stocks in the array fit the conditions, store this information and then execute the trades on those stocks with the correct adjusted size Any ideas how to approach this what must be a common problem for multi-instrument strategy users?
      Last edited by elliot5; 05-12-2015, 01:41 AM. Reason: update

      Comment


        #4
        Hello,

        Thank you for the question.

        In the future please post any new question as a new thread.

        For this, there are multiple ways to go about this depending on what you already have coded.

        Based on your message, it sounds like you have an array for the list of stocks.

        You may need to loop through the array and preform your calculation(not submitting anything at this point) and create a second array of the stocks that you detected could trade. You would then have a count of the items and also the names and could loop through the second array of pre qualified stocks.

        There are other ways but if you are already using an array. this may be the easiest without changing too much code that is already there.

        I look forward to being of further assistance.
        JesseNinjaTrader Customer Service

        Comment


          #5
          Yes I have used the Add function to create an array of the 50 stocks. I have now created the dataseries for storing the qualifying stocks.. but how do you populate that array with their names once the condition is met during the initial loop?

          Regards and thx

          Comment


            #6
            Hello,

            Based on your last message I am unsure if you are referring to the type array or just loosely using the term "array" saying that you have the stocks added using Add().

            Can you clarify are you saying that you have an actual array of stocks or have declared an array variable like the following?

            Code:
            string[] array = new string[50];
            or is this that you have used Add() for all 50 stocks so you have 50 Add statements in Initialize?

            I look forward to being of further assistance.
            JesseNinjaTrader Customer Service

            Comment


              #7
              Multi Instrument strategy not firing

              I use the following code to check for enough loaded bars in the array... the strategy is still not firing although I can see that I have more than the minimum number of bars loaded for each member (25) in the array. What am I missing here?

              Regards





              if (BarsInProgress != 0)
              return;

              if (CurrentBars[0] <= BarsRequired || CurrentBars[1] <= BarsRequired || CurrentBars[2] <= BarsRequired ||
              CurrentBars[3]<= BarsRequired || CurrentBars[4] <= BarsRequired || CurrentBars[5] <= BarsRequired
              || CurrentBars[6] <= BarsRequired || CurrentBars[7] <= BarsRequired ||
              CurrentBars[8]<= BarsRequired || CurrentBars[9] <= BarsRequired || CurrentBars[10] <= BarsRequired ||
              CurrentBars[11] <= BarsRequired || CurrentBars[12] <= BarsRequired || CurrentBars[13] <= BarsRequired
              || CurrentBars[14] <= BarsRequired || CurrentBars[15] <= BarsRequired ||
              CurrentBars[16]<= BarsRequired || CurrentBars[17] <= BarsRequired || CurrentBars[18] <= BarsRequired ||
              CurrentBars[19]<= BarsRequired || CurrentBars[20] <= BarsRequired || CurrentBars[21] <= BarsRequired

              )


              Print ("Data Error");
              Print (BarsRequired);

              Print (CurrentBars[0]);
              Print (CurrentBars[1]);
              Print (CurrentBars[2]);
              Print (CurrentBars[3]);
              Print (CurrentBars[4]);
              Print (CurrentBars[5]);
              Print (CurrentBars[6]);
              Print (CurrentBars[7]);
              Print (CurrentBars[8]);
              Print (CurrentBars[9]);
              Print (CurrentBars[10]);
              Print (CurrentBars[11]);
              Print (CurrentBars[12]);
              Print (CurrentBars[13]);
              Print (CurrentBars[14]);
              Print (CurrentBars[15]);
              Print (CurrentBars[16]);
              Print (CurrentBars[17]);
              Print (CurrentBars[18]);
              Print (CurrentBars[19]);
              Print (CurrentBars[20]);
              Print (CurrentBars[21]);
              Print (CurrentBars[22]);
              Print (CurrentBars[23]);
              Print (CurrentBars[24]);

              Comment


                #8
                Hello,

                Thank you for the question.

                You said that you can see there is enough data, are you confirming this by the prints or on the chart?

                if by the strategy is not firing, you mean the prints are not happening, this would mean that one of the statements is returning and not allowing the print to be reached.

                For this, have you opened a chart for each instrument on the timeframe that will be used to ensure there is historical data for each instrument?

                If your prints are being hit, and you are referring to a different portion of the strategy not firing, please post that section of logic and I would be happy to look at it.

                I look forward to being of further assistance.
                JesseNinjaTrader Customer Service

                Comment


                  #9
                  I see this on the charts... I have 25 open charts.

                  No trades have happened yet.... but in the output window I see stops and target data flowing through for the primary bar series (JPM).

                  Should the output window also show activity for the other Add() array instruments?

                  Also this condition is in the strategy... Will that be referenced for each in individual member of the array as it is written?

                  && WilliamsR(10)[1]>-50

                  Regards and thx

                  Comment


                    #10
                    Hello,

                    The output window will really only show Errors, TraceOrders, or things you Print, the Add() statement would not show anything in the output by its self.

                    Have you added any Print() statements inside of the conditions where you are submitting orders to verify the condition is happening? This would be a first step in debugging what is wrong.

                    If there are no Errors in the Output Window and you have historical data loaded and also you are seeing the prints for: Print (CurrentBars[0]); etc.. then the strategy should be running and able to trade if the conditions you set become true. If this is the case, the next step would be to determine why your conditions are not becoming true, this would be a good use for a Print inside the condition.

                    If the condition is not happening, I would recommend moving the print outside of the condition and then Print the values of what you are checking in the condition as they may not be as you had expected.

                    The condition you have listed, or the part would be only referring to the main series as you have not specified the series for this to calculate on.

                    This would be for a Primary series for 1 bar ago
                    Code:
                    WilliamsR(10)[1]
                    This would be for a secondary series for 1 bar ago
                    Code:
                    WilliamsR(Closes[1], 10)[1]
                    I look forward to being of further assistance.
                    JesseNinjaTrader Customer Service

                    Comment


                      #11
                      Multi Instrument Strategy

                      Ok well I have tested it at the open today and the primary instrument JPM worked fine.... the other 25 stocks via the ADD () function however .... not a single one fired.... I do see the list of the stocks on the strategy tab on the control center.. with columns Instr / Position / Avg Price / Unrealised / Realised.



                      protected override void Initialize()
                      {
                        

                      {

                      Add("XOM", PeriodType.Minute,390); // none of this list fired...
                      Add("MSFT", PeriodType.Minute,390);
                      Add("IBM", PeriodType.Minute,390);
                      Add("GE", PeriodType.Minute,390);
                      Add("CVX", PeriodType.Minute,390);
                      Add("WMT", PeriodType.Minute,390);
                      Add("T", PeriodType.Minute,390);
                      Add("PG", PeriodType.Minute,390);
                      Add("JNJ", PeriodType.Minute,390);
                      Add("WFC", PeriodType.Minute,390);
                      Add("PFE", PeriodType.Minute,390);
                      Add("KO", PeriodType.Minute,390);
                      Add("GOOG", PeriodType.Minute,390);
                      Add("PM", PeriodType.Minute,390);
                      Add("ORCL", PeriodType.Minute,390);
                      Add("MRK", PeriodType.Minute,390);
                      Add("QCOM", PeriodType.Minute,390);
                      Add("C", PeriodType.Minute,390);
                      Add("PEP", PeriodType.Minute,390);
                      Add("BAC", PeriodType.Minute,390);
                      Add("MCD", PeriodType.Minute,390);
                      Add("COP", PeriodType.Minute,390);
                      Add("ABT", PeriodType.Minute,390);
                      Add("SLB", PeriodType.Minute,390);
                      Add("AMZN", PeriodType.Minute,390);

                      }





                      EntryHandling = EntryHandling.UniqueEntries;
                      EntriesPerDirection = 1;
                      CalculateOnBarClose = false;
                      TraceOrders = true;
                      ExitOnClose = true;
                      TimeInForce = Cbi.TimeInForce.Gtc;
                      DefaultQuantity=100;
                      Last edited by elliot5; 05-27-2015, 08:12 AM. Reason: update

                      Comment


                        #12
                        Hello,

                        Thank you for the reply.

                        It seems the strategy is on and working but only the primary submitted an order.

                        This may be due to the entry statements you are using, can you please provide a post or a copy of the script to see the logic being used?

                        If you are not using the overload set that includes a BarsInProgress for the Entry statements, this would still be trying the orders on the primary instead of the other instruments.

                        With more information on your entry logic we will know more on what is happening.

                        I look forward to being of further assistance.
                        JesseNinjaTrader Customer Service

                        Comment


                          #13
                          protected override void Initialize()
                          {
                            

                          {

                          Add("XOM", PeriodType.Minute,390);
                          Add("MSFT", PeriodType.Minute,390);
                          Add("IBM", PeriodType.Minute,390);
                          Add("GE", PeriodType.Minute,390);
                          Add("CVX", PeriodType.Minute,390);
                          Add("WMT", PeriodType.Minute,390);
                          Add("T", PeriodType.Minute,390);
                          Add("PG", PeriodType.Minute,390);
                          Add("JNJ", PeriodType.Minute,390);
                          Add("WFC", PeriodType.Minute,390);
                          Add("PFE", PeriodType.Minute,390);
                          Add("KO", PeriodType.Minute,390);
                          Add("GOOG", PeriodType.Minute,390);
                          Add("PM", PeriodType.Minute,390);
                          Add("ORCL", PeriodType.Minute,390);
                          Add("MRK", PeriodType.Minute,390);
                          Add("QCOM", PeriodType.Minute,390);
                          Add("C", PeriodType.Minute,390);
                          Add("PEP", PeriodType.Minute,390);
                          Add("BAC", PeriodType.Minute,390);
                          Add("MCD", PeriodType.Minute,390);
                          Add("COP", PeriodType.Minute,390);
                          Add("ABT", PeriodType.Minute,390);
                          Add("SLB", PeriodType.Minute,390);
                          Add("AMZN", PeriodType.Minute,390);
                          }





                          EntryHandling = EntryHandling.UniqueEntries;
                          EntriesPerDirection = 1;
                          CalculateOnBarClose = false;
                          TraceOrders = true;
                          ExitOnClose = true;
                          TimeInForce = Cbi.TimeInForce.Gtc;
                          DefaultQuantity=100;

                          }
                          protected override void OnBarUpdate()
                          {


                          if (BarsInProgress != 0)
                          return;

                          if (CurrentBars[0] <= BarsRequired || CurrentBars[1] <= BarsRequired || CurrentBars[2] <= BarsRequired ||
                          CurrentBars[3]<= BarsRequired || CurrentBars[4] <= BarsRequired || CurrentBars[5] <= BarsRequired
                          || CurrentBars[6] <= BarsRequired || CurrentBars[7] <= BarsRequired ||
                          CurrentBars[8]<= BarsRequired || CurrentBars[9] <= BarsRequired || CurrentBars[10] <= BarsRequired ||
                          CurrentBars[11] <= BarsRequired || CurrentBars[12] <= BarsRequired || CurrentBars[13] <= BarsRequired
                          || CurrentBars[14] <= BarsRequired || CurrentBars[15] <= BarsRequired ||
                          CurrentBars[16]<= BarsRequired || CurrentBars[17] <= BarsRequired || CurrentBars[18] <= BarsRequired ||
                          CurrentBars[19]<= BarsRequired || CurrentBars[20] <= BarsRequired || CurrentBars[21] <= BarsRequired

                          )


                          Print ("Data Error");






                          voldivide1 = (DailyATR(5)[0]*0.3);
                          adjust1 = size*0.001;
                          voladjust1 = (int)(adjust1/voldivide1);






                          if (Position.MarketPosition == MarketPosition.Flat
                          && Time[0].DayOfWeek != DayOfWeek.Tuesday
                          && PriorDayOHLC().PriorOpen[0] < PriorDayOHLC().PriorClose[0]
                          && (CurrentDayOHL().CurrentOpen[0] - PriorDayOHLC().PriorClose[0]) > (DailyATR(5)[0]*0.1)
                          && ((CurrentDayOHL().CurrentOpen[0] - PriorDayOHLC().PriorClose[0]) <= (DailyATR(5)[0]*0.3))
                          && CurrentDayOHL().CurrentOpen[0] > PriorDayOHLC().PriorHigh[0]
                          && WilliamsR(10)[1]>-50
                          && CurrentDayOHL().CurrentOpen[0] > EMA(10)[0]
                          && Bars.FirstBarOfSession
                          && Bars.TickCount <1000)

                          {
                          Print(Time[0] + " Enter Short");
                          EnterShort(voladjust1, "SP STOCKS U-H Short");
                          }
                           

                          Comment


                            #14
                            Hello,

                            Thank you for that,

                            Yes it looks like you only have a Entry for the primary series or:

                            EnterShort(voladjust1, "SP STOCKS U-H Short");


                            Instead you would need to choose which instrument you are submitting the order to by using the following overload set:

                            EnterShort(int barsInProgressIndex, int quantity, string signalName)

                            If you look in the help guide for any of the Entry or Exit methods, it lists the overloads as the one above, this uses a BarsInProgress so this would be used in Multi Series scripts.



                            I look forward to being of further assistance.
                            JesseNinjaTrader Customer Service

                            Comment


                              #15
                              can you give me an example of this as applied to my strategy entry?


                              EnterShort(1,voladjust1, "SP STOCK 1 U-H Short");
                              EnterShort(2,voladjust1, "SP STOCK 2 U-H Short");
                              EnterShort(3,voladjust1, "SP STOCK 3 U-H Short");
                              EnterShort(4,voladjust1, "SP STOCK 4 U-H Short");
                              EnterShort(5,voladjust1, "SP STOCK 5 U-H Short");
                              EnterShort(6,voladjust1, "SP STOCK 6 U-H Short");
                              EnterShort(7,voladjust1, "SP STOCK 7 U-H Short");
                              EnterShort(25,voladjust1, "SP STOCK 25 U-H Short");


                              Is that what you mean? I would have to put in 25 different entry lines?
                              Last edited by elliot5; 05-27-2015, 09:46 AM. Reason: update

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by ETFVoyageur, 05-07-2024, 07:05 PM
                              6 responses
                              50 views
                              0 likes
                              Last Post ETFVoyageur  
                              Started by Klaus Hengher, Yesterday, 03:13 AM
                              2 responses
                              15 views
                              0 likes
                              Last Post Klaus Hengher  
                              Started by Sebastian - TwinPeaks, Yesterday, 01:31 PM
                              2 responses
                              13 views
                              0 likes
                              Last Post Sebastian - TwinPeaks  
                              Started by wbennettjr, 07-15-2017, 05:07 PM
                              16 responses
                              2,533 views
                              1 like
                              Last Post eladlevi  
                              Started by Human#102, Yesterday, 09:54 AM
                              2 responses
                              8 views
                              0 likes
                              Last Post Human#102  
                              Working...
                              X