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

Custom Trail Stop Is being updated a bar late in Market Replay

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

    Custom Trail Stop Is being updated a bar late in Market Replay

    I've finally made my own decent "Trail Stop" that is just an updating SetStopLoss call (im doing this as I enter the position with a StopLoss and then want to switch to a trailstop). The only issue is when I try to backtest this strategy, the trail stop seems to update only when the bar closes which is causing my strategy to miss a significant amount of exits. I've created the script to have some print logs for debugging.

    Output "
    Setting initial short stop loss: 17281.5 (Bid: 17274)
    Average Position 17274.25
    New best price for short position: 17274

    New best price for short position: 17268
    Activating trail stop for short position: 17280.5 (Bid: 17268)
    Updating trailing stop for short position: 17269 (Bid: 17268)
    "
    These first three (Bolded) occurred within the entry bar, however the next 3 update AFTER the bar has already closed causing us to get worse exit and in many other instances causing us to lose on a trade when we should've exited for profit. Is this just a market replay thing or something wrong with my code? Thanks!!!

    Code Snippets: (Code is set with Calculate.OnTickUpdate)

    Entry and Initial Stop Loss Logic:

    if (shortCondition && Position.MarketPosition == MarketPosition.Flat)
    {
    EnterShort("Short");
    currentStopLoss = Open[1] + InitialSL * TickSize;
    if (currentStopLoss > GetCurrentBid())
    {
    Print($"Setting initial short stop loss: {currentStopLoss} (Bid: {GetCurrentBid()})");
    SetStopLoss("Short", CalculationMode.Ticks, InitialSL, false);
    }
    trailStopActivated = false;
    bestPriceInFavor = Position.AveragePrice;
    Print($"Average Position {bestPriceInFavor}");
    shortOpened = true;
    longOpened = false;
    lastEntryBar = CurrentBar;
    }​

    Trail Stop Logic:

    if (Position.MarketPosition == MarketPosition.Short)
    {
    double currentPrice = GetCurrentBid(0);
    if (currentPrice < bestPriceInFavor)
    {
    bestPriceInFavor = currentPrice;
    Print($"New best price for short position: {bestPriceInFavor}");
    }

    double unrealizedProfit = Position.GetUnrealizedProfitLoss(PerformanceUnit.C urrency, Close[0]);
    if (!trailStopActivated && unrealizedProfit >= TpPoints * TickSize * 20)
    {
    currentStopLoss = bestPriceInFavor + InitialSL * TickSize;
    Print($"Activating trail stop for short position: {currentStopLoss} (Bid: {GetCurrentBid()})");
    SetStopLoss("Short", CalculationMode.Price, currentStopLoss, false);
    trailStopActivated = true;
    }

    if (trailStopActivated)
    {
    double newStopLoss = bestPriceInFavor + TrailOffset * TickSize;
    if (newStopLoss < currentStopLoss && newStopLoss > GetCurrentBid(0) && newStopLoss != lastUpdateStopLoss)
    {
    Print($"Updating trailing stop for short position: {newStopLoss} (Bid: {GetCurrentBid()})");
    currentStopLoss = newStopLoss;
    SetStopLoss("Short", CalculationMode.Price, currentStopLoss, false);
    lastUpdateStopLoss = newStopLoss;​
    Last edited by Graeham9; 05-23-2024, 02:02 PM.

    #2
    Hello Graeham9,

    Are you running the strategy with Calculate OnBarClose? If so that would explain the stoploss being updated after the bar closes, to update the stop intrabar would require using OnEachTick. Your logic is executed based on the Calculate setting.
    JesseNinjaTrader Customer Service

    Comment


      #3
      Hi Jesse! Yes I just realized I forgot to include that! My code has the calculate = calculate.OnEachTick set as shown below, however the rest of my strategy occurs within OnBarUpdate()

      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      calculate = calculate.OnEachTick;
      //Rest of code
      }​

      Comment


        #4
        Hello Graeham9,

        In that case you would have to use prints to see when your condition that calls SetStopLoss is becoming true. Are you seeing the print you added when the bar closes or for every tick where your condition is true?
        JesseNinjaTrader Customer Service

        Comment


          #5
          Its strange, if you look at the print log I provided in the original post, the first 3 prints are put out almost immediately after the trade is entered, all other prints occur after the bar has closed. So really all prints are coming either at the opening or closing of a trade OR at the close of a bar

          Comment


            #6
            Hello Graeham9,

            That doesn't really help me to know what is happening because I did not test the script to see when specifically those prints happened. If you are using OnEachTick your condition to update the stop could happen at any point as soon as your condition is true. That may be within the same bar as the entry bar or not, it would depend on your condition. To know why the condition is happening when it is you would have to use a Print to output the values for every tick so you can see the ticks between when it is true and not. That will let you debug the condition and also see why the condition was true when it was.

            JesseNinjaTrader Customer Service

            Comment


              #7
              Got it! I'll make some new prints now!

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by Pole123, Today, 06:02 PM
              0 responses
              8 views
              0 likes
              Last Post Pole123
              by Pole123
               
              Started by samish18, Today, 05:27 PM
              0 responses
              5 views
              0 likes
              Last Post samish18  
              Started by Tonkingrf1551, Today, 03:59 PM
              0 responses
              10 views
              0 likes
              Last Post Tonkingrf1551  
              Started by rocker84, Today, 03:10 PM
              0 responses
              12 views
              0 likes
              Last Post rocker84  
              Started by Oracletrades, 02-21-2020, 01:37 PM
              17 responses
              2,066 views
              0 likes
              Last Post Ttrade12  
              Working...
              X