Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Strategy profit target and stop loss not working as expected

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

    Strategy profit target and stop loss not working as expected

    Hi NT support,

    I have created a simple strategy for debugging purposes. All it does is enter a long position when a 50 EMA crosses a 100 EMA. Profit target is set to 4 ticks and stop loss is set to 4 ticks. When I enable the strategy on the chart, my take profits and stop losses are all over the place. I have included screenshots of my strategy settings and some examples where take profit and stop loss does not behave as expected. The distance between horizontal lines on my chart is 1 tick. Tick replay is enabled on my chart. The instrument is ES. The strategy was generated using the strategy builder.

    Code:
    namespace NinjaTrader.NinjaScript.Strategies
    {
    	public class EMACrossDebug : Strategy
    	{
    		private EMA EMA1;
    		private EMA EMA2;
    
    		protected override void OnStateChange()
    		{
    			if (State == State.SetDefaults)
    			{
    				Description									= @"Enter the description for your new custom Strategy here.";
    				Name										= "EMACrossDebug";
    				Calculate									= Calculate.OnBarClose;
    				EntriesPerDirection							= 1;
    				EntryHandling								= EntryHandling.UniqueEntries;
    				IsExitOnSessionCloseStrategy				= true;
    				ExitOnSessionCloseSeconds					= 30;
    				IsFillLimitOnTouch							= true;
    				MaximumBarsLookBack							= MaximumBarsLookBack.TwoHundredFiftySix;
    				OrderFillResolution							= OrderFillResolution.High;
    				OrderFillResolutionType						= BarsPeriodType.Tick;
    				OrderFillResolutionValue					= 1;
    				Slippage									= 0;
    				StartBehavior								= StartBehavior.WaitUntilFlat;
    				TimeInForce									= TimeInForce.Day;
    				TraceOrders									= false;
    				RealtimeErrorHandling						= RealtimeErrorHandling.StopCancelClose;
    				StopTargetHandling							= StopTargetHandling.PerEntryExecution;
    				BarsRequiredToTrade							= 201;
    				// Disable this property for performance gains in Strategy Analyzer optimizations
    				// See the Help Guide for additional information
    				IsInstantiatedOnEachOptimizationIteration	= true;
    			}
    			else if (State == State.Configure)
    			{
    			}
    			else if (State == State.DataLoaded)
    			{				
    				EMA1				= EMA(Close, 50);
    				EMA2				= EMA(Close, 100);
    				EMA1.Plots[0].Brush = Brushes.Goldenrod;
    				EMA2.Plots[0].Brush = Brushes.OldLace;
    				AddChartIndicator(EMA1);
    				AddChartIndicator(EMA2);
    				SetProfitTarget(@"l", CalculationMode.Ticks, 4);
    				SetStopLoss(@"l", CalculationMode.Ticks, 4, false);
    			}
    		}
    
    		protected override void OnBarUpdate()
    		{
    			if (BarsInProgress != 0) 
    				return;
    
    			if (CurrentBars[0] < 1)
    				return;
    
    			 // Set 1
    			if (CrossAbove(EMA1, EMA2, 1))
    			{
    				EnterLong(Convert.ToInt32(DefaultQuantity), @"l");
    			}
    
    		}
    	}
    }
    Update:
    Take profit and stop loss seem to be working perfectly on 2 and 3 minute charts. It is just the one minute chart that does not seems to work. The screenshots are from the 1 minute chart.
    Last edited by BruceBrasseur; 08-30-2021, 09:24 PM.

    #2
    Originally posted by BruceBrasseur View Post
    I have created a simple strategy for debugging purposes. All it does is enter a long position when a 50 EMA crosses a 100 EMA. Profit target is set to 4 ticks and stop loss is set to 4 ticks. When I enable the strategy on the chart, my take profits and stop losses are all over the place. I have included screenshots of my strategy settings and some examples where take profit and stop loss does not behave as expected. The distance between horizontal lines on my chart is 1 tick. Tick replay is enabled on my chart. The instrument is ES.
    Why not use the @SampleMACrossOver.cs supplied by NinjaTrader?

    Seems like you just reinvented the wheel, but something went wrong.

    Can you upload your strategy?
    (Hard to know what may be wrong without looking at your code.)

    Comment


      #3
      Why not use the @SampleMACrossOver.cs supplied by NinjaTrader?

      Seems like you just reinvented the wheel, but something went wrong.

      Can you upload your strategy?
      (Hard to know what may be wrong without looking at your code.)
      If I wanted to actually use the strategy for trading I would of course use the built in MA crossover one, but as previously stated, I made the strategy for debugging purposes. I have a more complicated strategy that had a similar problem and wanted to see if I could recreate the problem with a simpler one. I have edited my original post to include the code for my strategy.

      Comment


        #4
        Hello BruceBrasseur,

        Thank you for your post.

        First, I just want to mention that the built in Sample strategies are for reference/educational purposes and are not intended for live trading.

        Next, Tick Replay will not add intrabar granularity for more accurate order fills, rather, it allows indicators to calculate intrabar. High order fill resolution (which I note your provided strategy is set to use) would assist in fill prices.

        That being said, the first of your screenshots shows an Exit on Session Close order. Here I'm showing the same trade with Execution text turned on:



        Unchecking Exit on Session Close would keep this from showing up.

        For the second, mine turns out a bit different in a backtest over historical data, likely from slightly different data (I am using a Kinetick data connection for testing):

        Click image for larger version

Name:	2021-08-31_08-10-37.png
Views:	654
Size:	16.2 KB
ID:	1169680

        You'll notice that while the exit calculated for mine is on the same bar as the entry and yours is on the next bar, both exit at 4 ticks. Likely what occurred in your case is that the simulator calculated that the limit order being used for the profit target would have been unable to fill at that price on the entry bar and filled it when the price came back to that level on the next bar.

        Other than that, I'm seeing the profit targets and stops being executed at levels I'd expect in a backtest. I added a bit of code to draw some lines where the profit target and stop get set to double check:

        Code:
         protected override void OnBarUpdate()
        {
        if (BarsInProgress != 0)
        return;
        
        if (CurrentBars[0] < 1)
        return;
        
        // Set 1
        if (CrossAbove(EMA1, EMA2, 1))
        {
        EnterLong(Convert.ToInt32(DefaultQuantity), @"l");
        }
        
        if(Position.MarketPosition == MarketPosition.Long)
        {
        Draw.Line(this, "ProfitTargetLine" + (CurrentBar - 1), 2, Position.AveragePrice + (4 * TickSize), 0, Position.AveragePrice + (4 * TickSize), Brushes.Green);
        Draw.Line(this, "StopLossLine" + (CurrentBar - 1), 2, Position.AveragePrice - (4 * TickSize), 0, Position.AveragePrice - (4 * TickSize), Brushes.Red);
        }
        
        }
        Note this will only draw the lines if the trade is still active on the next bar, but it's rather helpful to double check.

        If you add this do you see trades that are exited not at the levels the lines are drawn?

        Thanks in advance; I look forward to assisting you further.
        Kate W.NinjaTrader Customer Service

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by frslvr, 04-11-2024, 07:26 AM
        5 responses
        96 views
        1 like
        Last Post caryc123  
        Started by algospoke, 04-17-2024, 06:40 PM
        6 responses
        49 views
        0 likes
        Last Post algospoke  
        Started by arvidvanstaey, Today, 02:19 PM
        4 responses
        11 views
        0 likes
        Last Post arvidvanstaey  
        Started by samish18, 04-17-2024, 08:57 AM
        16 responses
        61 views
        0 likes
        Last Post samish18  
        Started by jordanq2, Today, 03:10 PM
        2 responses
        11 views
        0 likes
        Last Post jordanq2  
        Working...
        X