Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Multi Time Frame Stop Loss Issue

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

    Multi Time Frame Stop Loss Issue

    I am having an issue with a Multi Time Frame Strategy.

    Mostly the strategy works ok until I try and define fixed stop loss values in the Initialize section.

    If I use CalculationMode.Ticks and enter a value it works fine, but as soon as I try to set a calculated price value, it compiles ok but the strategy tester does not like it and gives me no options at all.

    I have tried a number of solutions to get around it using BarsArray etc. but I dont think it likes these sorts of calulations in the Initialize section.

    Would someone mind passing comment on my Initialize section?


    protected override void Initialize()
    {

    TraceOrders = true;
    QuantityType = QuantityType.Strategy;
    TimeInForce = Cbi.TimeInForce.Gtc;
    ExitOnClose = false;
    CalculateOnBarClose = false;

    Add(PeriodType.Minute, 5);
    Add(PeriodType.Minute, 240);

    spread = GetCurrentAsk()- GetCurrentBid();

    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.UniqueEntries;

    if (BarsInProgress !=0)
    return;

    longstop = MIN(Low,12)[0];
    shortstop = MAX(High,12)[0];

    SetStopLoss("Long 1a", CalculationMode.Price, longstop, false);
    SetStopLoss("Long 1b", CalculationMode.Price, longstop, false);
    SetStopLoss("Long 1c", CalculationMode.Price, longstop, false);

    SetStopLoss("Short 1a", CalculationMode.Price, shortstop, false);
    SetStopLoss("Short 1b", CalculationMode.Price, shortstop, false);
    SetStopLoss("Short 1c", CalculationMode.Price, shortstop, false);

    }

    #2
    Hi yimbot, please move the stoploss code into your OnBarUpdate() as they are not static and keep changing with long/shortstop values. Please also see this link - http://www.ninjatrader-support.com/H...tStopLoss.html

    Comment


      #3
      Thanks Bertrand,

      I want these stops to be fixed stops though, called only when entering a position and not to move.

      Comment


        #4
        Any ideas why this would not work as a fixed stop loss??

        Comment


          #5
          Hi yimbot, thanks for your patience - what do you mean by 'the strategy tester does not like it and gives me no options at all' ? Can you post the complete strategy code? You could also add Print() statements to your Stop values and verify that they 'sit' at the price levels you want to them to be. Please also see this tip here - http://www.ninjatrader-support2.com/...ead.php?t=3418

          Comment


            #6
            Basically, the code compiles fine, but when I open it in the Strategy tester and try to backtest against a symbol, it is a completely blank window and I cannot choose any backtesting settings at all. If I comment out the 6 stop loss lines, all is ok...


            using System;
            using System.ComponentModel;
            using System.Drawing;
            using NinjaTrader.Cbi;
            using NinjaTrader.Data;
            using NinjaTrader.Indicator;

            // This namespace holds all market analyzer column definitions and is required. Do not change it.
            namespace NinjaTrader.Strategy
            {
            /// <summary>
            /// </summary>
            [Gui.Design.DisplayName("TLFX4ST")]
            public class TLFX4ST : Strategy
            {


            private double spread;
            private double RealizedProfitLoss;
            private int direction = 0;
            private int position = 0;

            private double risk = 1;

            [Description("Risk %")]
            [Category("Parameters")]
            [Gui.Design.DisplayName("Risk %")]
            public double Risk
            {
            get { return risk; }
            set { risk = value; }
            }


            protected override void Initialize()
            {

            TraceOrders = true;
            QuantityType = QuantityType.Strategy;
            TimeInForce = Cbi.TimeInForce.Gtc;
            ExitOnClose = false;
            CalculateOnBarClose = false;

            Add(PeriodType.Minute, 5);
            Add(PeriodType.Minute, 240);

            spread = GetCurrentAsk()- GetCurrentBid();

            EntriesPerDirection = 1;
            EntryHandling = EntryHandling.UniqueEntries;

            if (BarsInProgress !=0)
            return;

            SetStopLoss("Long 1a", CalculationMode.Price, MIN(Low,12)[0], false);
            SetStopLoss("Long 1b", CalculationMode.Price, MIN(Low,12)[0], false);
            SetStopLoss("Long 1c", CalculationMode.Price, MIN(Low,12)[0], false);

            SetStopLoss("Short 1a", CalculationMode.Price, MAX(High,12)[0], false);
            SetStopLoss("Short 1b", CalculationMode.Price, MAX(High,12)[0], false);
            SetStopLoss("Short 1c", CalculationMode.Price, MAX(High,12)[0], false);

            }
            protected override void OnBarUpdate()
            {
            //if (Historical)
            //{
            // return;
            //}

            if (BarsInProgress !=0)
            return;

            if(BearTrend(BarsArray[2],false,1,1).Trend==false)
            direction=1; //Indicates Bull trend on 60min chart

            if(BullTrend(BarsArray[2],false,1,1).Trend==false)
            direction=2; //Indicates Bear trend on 60min chart

            {
            int qnt;

            double accountSize = 0;
            #if !TESTBED
            accountSize = 100000; //this.Account.GetAccountItem(AccountItemType.CashVa lue, Currency.Unknown).Value;

            #endif

            if (direction==1)
            {

            qnt = (int)Math.Round(accountSize * Risk / (100 * (GetCurrentAsk() - MIN(Low,12)[0]) * Instrument.MasterInstrument.PointValue))*10000;
            if (
            qnt > 0
            && BearTrend(false,1,2).Signal==1
            && MIN(Low,6)[0] < (HurstEnvelope(2.5,30).Lower[0] )
            )
            {
            EnterLong(qnt, "Long 1a");
            EnterLong(qnt, "Long 1b");
            EnterLong(qnt, "Long 1c");
            position = 1;

            Print("Long" + qnt + ", Gap is :" + (GetCurrentBid()-MIN(Low,12)[0]) + ", Account Size is :" + accountSize + ", Risk is :" + Risk + "%" + "Spread is:" + spread + "Buy Price is:" + GetCurrentAsk());
            }
            }
            if (direction==2)
            {

            qnt = (int)Math.Round(accountSize * Risk / (100 * ((MAX(High,12)[0] + spread) - GetCurrentBid()) * Instrument.MasterInstrument.PointValue))*10000;
            if (
            qnt > 0
            && BullTrend(false,1,2).Signal==1
            && MAX(High,6)[0] > (HurstEnvelope(2.5,30).Upper[0] )
            )
            {
            EnterShort(qnt, "Short 1a");
            EnterShort(qnt, "Short 1b");
            EnterShort(qnt, "Short 1c");
            position =2;

            Print("Short" + qnt + ", Gap is :" + (MAX(High,12)[0] + spread - GetCurrentAsk()) + ", Account Size is :" + accountSize + ", Risk is :" + Risk + "%" + "Spread is:" + spread + "Sell Price is:" + GetCurrentBid());
            }
            }

            if (position ==1 && BullTrend(false,1,1).Signal==1)
            ExitLong("","Long 1a");

            if (position ==2 && BearTrend(false,1,1).Signal==1)
            ExitShort("","Short 1a");

            if (position ==1 && BullTrend(false,1,2).Signal==1)
            ExitLong("","Long 1b");

            if (position ==2 && BearTrend(false,1,2).Signal==1)
            ExitShort("","Short 1b");

            if (position ==1 && BullTrend(false,1,3).Signal==1)
            ExitLong("","Long 1c");

            if (position ==2 && BearTrend(false,1,3).Signal==1)
            ExitShort("","Short 1c");


            }


            }
            }
            }

            Comment


              #7
              Thanks yimbot, does it work when applied to a chart or from the strategies tab? I would still suggest moving them out of the Initialize() and make sure the MAX() and MIN() calculations are only run for example every morning at the session start (you will have to test which makes the most sense for your stoploss values). Do you get any errors in the log tab if you run the Strategy Analyzer with your script?

              Comment


                #8
                Hi Bertrand,

                If I run the strategy from the chart, I see no trades at all. (although if I remove the stop loss there are plenty)
                I cannot run it from the Strategy tab either as I get the same blank options window.

                As it is designed as a real-time Forex strategy which may get into 3 trades a day per symbol, it is not really an option to start the stop loss at the beginning of the session.

                Cheers.

                Comment


                  #9
                  The log gives a clue when applying the strategy to a chart.

                  Initially it said:

                  3/01/2009 9:23:40 AM Strategy Failed to call method 'Initialize' for strategy 'TLFX4ST': 'BarsInProgress' property can not be accessed from within 'Initialize' method

                  So I removed the BarsInProgress line and got this:

                  3/01/2009 9:29:05 AM Strategy Failed to call method 'Initialize' for strategy 'TLFX4ST': MIN[barsAgo]: barsAgo out of valid range 0 through -2, was 0.

                  So I set the barsAgo to -1 to try and make it happy and got this:

                  3/01/2009 9:30:45 AM Strategy Failed to call method 'Initialize' for strategy 'TLFX4ST': MIN[barsAgo]: barsAgo must be greater/equal 0 but was -1

                  ???????

                  Comment


                    #10
                    yimbot, you have to consider that functionality like CurrentBar, Time[], etc are runtime specific. Initialize() is invoked before the simulator starts processing the first tick of the first bar, they are simply not known at that moment of time. If you would like to initialize runtime specific items you could implement something like:
                    Code:
                    [FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff]protected [/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff]override [/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff]void[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2][FONT=Courier New][SIZE=2] OnBarUpdate()[/SIZE][/FONT]
                    [SIZE=2][FONT=Courier New]{[/FONT][/SIZE]
                    [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff]  if[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2][FONT=Courier New][SIZE=2] (FirstTickOfBar)[/SIZE][/FONT]
                    [SIZE=2][FONT=Courier New]  {[/FONT][/SIZE]
                    [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff]    if[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2][FONT=Courier New][SIZE=2] (runTimeInit == [/SIZE][/FONT][/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff]false[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2][FONT=Courier New][SIZE=2])[/SIZE][/FONT][/SIZE][/FONT]
                    [FONT=Courier New][SIZE=2][FONT=Courier New][SIZE=2]    {[/SIZE][/FONT][/SIZE][/FONT]
                    [FONT=Courier New]      myInitialisationCode ...[/FONT]
                    [FONT=Courier New]      [SIZE=2][SIZE=2]runTimeInit = [/SIZE][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]true[/COLOR][/SIZE][/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][SIZE=2];[/SIZE][/SIZE][/FONT][SIZE=2]
                    [SIZE=2][FONT=Courier New]    }[/FONT][/SIZE]
                    [FONT=Courier New]  }[/FONT]
                    [SIZE=2][FONT=Courier New]}[/FONT][/SIZE]
                    [/SIZE]
                    Regards
                    Ralph
                    Last edited by Ralph; 01-02-2009, 06:02 PM.

                    Comment


                      #11
                      Thanks for that Ralph,

                      That gives me something to play with.

                      Interesting though... It means you cant really make any calculation in the Initialization area. e.g. you could not have a fixed stop at a level of 3*ATR from entry. Which would be a fairly common request.

                      Comment


                        #12
                        Thanks for everybody's help with this issue.

                        I am still having a little bit of trouble after playing around with Ralphs suggestion and experimenting using BarsSinceEntry for time calculations etc. I am still not getting the expected results (although no errors in the log now).

                        I would like to ask anybody with coding experience if they could code the following basic strategy as an example for anyone who is struggling with a similar issue.

                        ENTRY/EXIT

                        SMA crossover on 5min timeframe

                        FILTER

                        SMA Above/Below longer SMA on 60min time frame

                        STOP LOSS

                        3*ATR away from entry point FIXED(static) for the duration of the trade


                        sounds simple enough...

                        Comment


                          #13
                          Originally posted by yimbot View Post
                          ...It means you cant really make any calculation in the Initialization area. e.g. you could not have a fixed stop at a level of 3*ATR from entry. Which would be a fairly common request.
                          This is a runtime request too, yimbot. You can't calculate that in Initialize(). You rather calculate and initialise your fixed ATR stop loss at the moment, when firing the entry order. It is because the ATR is moving with the progress in time, you can't calculate it pre-runtime.

                          Regards
                          Ralph

                          Comment


                            #14
                            Originally posted by yimbot View Post
                            I would like to ask anybody with coding experience if they could code the following basic strategy as an example for anyone who is struggling with a similar issue ... sounds simple enough...
                            Yes, it's very simple because Josh provided the examples already. Have a look at the Reference Sample section. Guess your issues are covered by the following code samples:

                            Strategy: Entering on one time frame and exiting on another
                            Strategy: Modifying the price of stop loss and profit target orders

                            Regards
                            Ralph

                            Comment


                              #15
                              Thanks for your input Ralph - here's a link to our reference samples section - http://www.ninjatrader-support2.com/...splay.php?f=30

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              639 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              366 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              107 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              569 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              572 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X