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

Stop Loss Strategy Calculation Problem

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

    Stop Loss Strategy Calculation Problem

    I am newbie on coding.

    I am trying to code a strategy after doing the most with the Builder.
    I want to set a Stop Loss on the Highest High of 4 bars before the entry.
    The entry is good, but on the Stop calculation, I calculate:

    1. The Bar Position with the Highest High in the last 4 bars <HighestBarPosition = HighestBar(High, 4>
    2. The High Price of that bar <MyStopPrice = High[HighestBarPosition>
    3. I put that Price in the Stop Set <SetStopLoss(@"", CalculationMode.Price, MyStopPrice, false)>.

    It looks like the Stop is Located the number of ticks away (In the direction of the trade, not even in the direction against the trade) from the entry place that is Calculated by the HighestBarPosition but not in the pricing calculated.

    Any idea?
    Thanks in advance.

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class Keltner : Strategy
    {
    private double MyExitPrice;
    private double MyStopPrice;
    private int HighestBarPosition;

    private KeltnerChannel KeltnerChannel1;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "Keltner";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    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;
    KeltnerRatio = 2.5;
    KeltnerPeriod = 20;
    MyExitPrice = 1;
    MyStopPrice = 1;
    HighestBarPosition = 1;
    }
    else if (State == State.Configure)
    {
    SetStopLoss(@"", CalculationMode.Price, MyStopPrice, false);
    SetProfitTarget("", CalculationMode.Ticks, 20);
    }
    else if (State == State.DataLoaded)
    {
    KeltnerChannel1 = KeltnerChannel(Close, KeltnerRatio, Convert.ToInt32(KeltnerPeriod));
    KeltnerChannel1.Plots[0].Brush = Brushes.DarkGray;
    KeltnerChannel1.Plots[1].Brush = Brushes.Red;
    KeltnerChannel1.Plots[2].Brush = Brushes.ForestGreen;
    AddChartIndicator(KeltnerChannel1);
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 3)
    return;

    // Set 1
    if ((Close[0] < (Close[1] + (-3 * TickSize)) )
    && (Close[1] > Close[2])
    && (Close[2] > Close[3])
    && (Close[3] > KeltnerChannel1.Upper[3]))
    {
    EnterShortLimit(Convert.ToInt32(DefaultQuantity), (Close[0] + (-1 * TickSize)) , "");
    HighestBarPosition = HighestBar(High, 4);
    MyStopPrice = High[HighestBarPosition];

    #2
    Welcome to the forums Gorion!

    What you are trying to do qualifies as a "dynamic stop loss" where the stop loss will have a different value for each entry. There are some notes to consider when setting a dynamic stop loss.

    SetStopLoss() will "prep" NinjaTrader so the stop loss order is submitted after the entry order has returned as filled. When we call SetStopLoss() when we are in position, we will update the stop loss to a new level. To set an initial stop loss for an entry, it is recommended to call SetStopLoss() before the entry method is submitted, or when Position.MarketPosition is MarketPosition.Flat.

    For example, you can set your stop loss dynamically by using SetStopLoss() in OnBarUpdate() instead of within State.Configure.

    Code:
    HighestBarPosition = HighestBar(High, 4);
    MyStopPrice = High[HighestBarPosition];
    SetStopLoss(@"MyEntry", CalculationMode.Price, MyStopPrice, false);
    EnterShortLimit(Convert.ToInt32(DefaultQuantity), (Close[0] + (-1 * TickSize)) , "MyEntry");
    Keep in mind, this will set the stop loss to a level when the entry order is submitted, To have that value more current for when the order gets filled it would be advised to call SetSopLoss() for every bar where the position is still flat.

    The documentation on SetStopLoss() discusses various usage tips and warnings. I'll include a link below. This information is publicly available.

    SetStopLoss - https://ninjatrader.com/support/help...etstoploss.htm

    I may also suggest to use prints and the NinjaScript output window to view the values that are being used in your logic so you can check your implementations and make sure the stop loss is being submitted to the proper level.

    Debugging - https://ninjatrader.com/support/foru...ead.php?t=3418

    Please let us know if we can be of further assistance.
    JimNinjaTrader Customer Service

    Comment


      #3
      Jim,

      I did what you said. The problem still is that to calculate the Stop, instead of giving me back the price on the Highest High per "MyStopPrice = High[HighestBar(High, 4)]" I think is giving me the Bar Position because the stops is only between 0-5 ticks depending on the entry as you can see in the image attached.
      It is weird because when I use the "High[HighestBar(High, 4)]" as a signal to place the order is placed right (just on the top of the Higher High) but does not work for the Stop.

      Thanks.

      Code:
      namespace NinjaTrader.NinjaScript.Strategies
      {
      	public class Keltner1 : Strategy
      	{
      		private double MyExitPrice;
      		private double MyStopPrice;
      		private double MyEntryPrice;
      
      		private KeltnerChannel KeltnerChannel1;
      
      		protected override void OnStateChange()
      		{
      			if (State == State.SetDefaults)
      			{
      				Description									= @"Enter the description for your new custom Strategy here.";
      				Name										= "Keltner1";
      				Calculate									= Calculate.OnBarClose;
      				EntriesPerDirection							= 1;
      				EntryHandling								= EntryHandling.AllEntries;
      				IsExitOnSessionCloseStrategy				= true;
      				ExitOnSessionCloseSeconds					= 30;
      				IsFillLimitOnTouch							= false;
      				MaximumBarsLookBack							= MaximumBarsLookBack.TwoHundredFiftySix;
      				OrderFillResolution							= OrderFillResolution.Standard;
      				Slippage									= 0;
      				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;
      				KeltnerRatio					= 2.5;
      				KeltnerPeriod					= 20;
      			}
      			
      			else if (State == State.DataLoaded)
      			{				
      				KeltnerChannel1				= KeltnerChannel(Close, KeltnerRatio, Convert.ToInt32(KeltnerPeriod));
      				KeltnerChannel1.Plots[0].Brush = Brushes.DarkGray;
      				KeltnerChannel1.Plots[1].Brush = Brushes.Red;
      				KeltnerChannel1.Plots[2].Brush = Brushes.ForestGreen;
      				AddChartIndicator(KeltnerChannel1);
      			}
      		}
      
      		protected override void OnBarUpdate()
      		{
      			SetStopLoss(@"", CalculationMode.Price, MyStopPrice, false);
      			//Target to be Debug after Stop
      			SetProfitTarget("", CalculationMode.Ticks, 20);
      			
      			if (BarsInProgress != 0) 
      				return;
      
      			if (CurrentBars[0] < 3)
      			return;
      
      			 // Set 1
      			if ((Close[0] < (Close[1] + (-3 * TickSize)) )
      				 && (Close[1] > Close[2])
      				 && (Close[2] > Close[3])
      				 && (Close[3] > Close[4])
      				 && (Close[4] > KeltnerChannel1.Upper[4]))
      			{
      				//This Should Place the Entry 1 tick below (Works)
      				MyEntryPrice = (Close[0] + (-1 * TickSize));
      				//This should plsce the Stop @ the Highest High of 4 bars ago.
      				MyStopPrice = High[HighestBar(High, 4)];
      				//This should place the Target @ 2xStop Distance from the Entry Level.
      				MyExitPrice = (3 * MyEntryPrice) - ( 2 * MyStopPrice);
      				
      				EnterShortLimit(Convert.ToInt32(DefaultQuantity), MyEntryPrice , "");
      Attached Files

      Comment


        #4
        Hello Gorion,

        I have set up a video where I have calculated the price level for the stop loss in the same way as you have, and I am printing out the price level that is sent to SetStopLoss(). The order marker matches my print.

        Demo: https://www.screencast.com/t/5B9Y2OWK

        I'd like you to take similar steps setting up your strategy and placing prints so you may see the price level that your stop loss is to be set at.

        Please let me know if you have questions.
        JimNinjaTrader Customer Service

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by Kaledus, Today, 01:29 PM
        0 responses
        3 views
        0 likes
        Last Post Kaledus
        by Kaledus
         
        Started by PaulMohn, Today, 12:36 PM
        1 response
        16 views
        0 likes
        Last Post NinjaTrader_Gaby  
        Started by yertle, Yesterday, 08:38 AM
        8 responses
        37 views
        0 likes
        Last Post ryjoga
        by ryjoga
         
        Started by rdtdale, Today, 01:02 PM
        1 response
        6 views
        0 likes
        Last Post NinjaTrader_LuisH  
        Started by alifarahani, Today, 09:40 AM
        3 responses
        19 views
        0 likes
        Last Post NinjaTrader_Jesse  
        Working...
        X