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

Breakeven logic

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

    Breakeven logic

    I am trying to add a breakeven strategy to my existing script. I thought I should provide some background on where I’m up to before asking about the specific code I have tried.

    I am still in the development phase so I’m just working on the buy side to keep it simple. I only have one condition set (for the buy side), however the nature of the conditions I’ve created means that I can potentially have multiple consecutive signals on consecutive candles. I do NOT use market orders, I always use limit orders set above the high of the setup bar which reduces the chances of having multiple trades open at once, but never the less I do find I get multiple trades at a time.

    The multiple trades issue caused me problems setting the initial stop and profit target but I fixed that by adding a counter to signal names. What I want to do is adjust the stop after the first bar (of the open trade) has closed. If the current price is greater than or equal to the entry price, bring the stop up to breakeven. If the current price is less than the entry price, set the profit target to the entry price. So I have:

    Code:
    private int LongCount = 0; // I create a variable that counts trades
    protected override void OnBarUpdate()
    //condition set
    if ( //long conditions)
    {
    LongCount++  //increment the trade counter first
    double InitialRisk = (High[0] + 2*TickSize) - (Low[0]-2*TickSize) // I also create a variable here for initial risk so I can print the value and pass it into the profit target
    EnterLongLimit(DefaultQuantity, High[0] + 2*TickSize, “LongEntry:”+LongCount);
    SetStopLoss(“LongEntry:”+LongCount, CalculationMode.Price, Low[0]-2*TickSize,false);
    SetProfitTarget(“LongEntry:”+LongCount,CalculationMode.Price,High[0]+2*TickSize+(InitialRisk*2));
    }
    if (BarsSinceEntry(“LongEntry:”+LongCount)==1 && Close[0]>=Position.AvgPrice)
    { 
    SetStopLoss(“LongEntry:”+LongCount, CalculationMode.Price, Position.AvgPrice, false);
    }
    else if (BarsSinceEntry(“LongEntry:”+LongCount)==1 && Close[0]<Position.AvgPrice)
    { 
    SetProfitTarget(“LongEntry:”+LongCount, CalculationMode.Price, Position.AvgPrice);
    }
    So far as I can tell the entry order and initial stop/profit logic all works fine and as intended, but the trade management code below it does not appear to make any difference to my outcomes.

    #2
    Hello newuser,

    Thank you for your post.

    Are you referring to the results of the trades not being affected or do you mean that the Profit Target and Stop Loss are not adjusting as you wish?

    Can you detail further what you are seeing and what you wish to see in the behavior of the strategy and it's orders?

    I look forward to your response.

    Comment


      #3
      Hi,

      Thanks for writing back.

      Are you referring to the results of the trades not being affected or do you mean that the Profit Target and Stop Loss are not adjusting as you wish?


      So I guess a bit of both. The Stop Loss and Profit Target are not updating and consequently the trade results are not being affected.

      Can you detail further what you are seeing and what you wish to see in the behavior of the strategy and it's orders?

      Take for example the AUDUSD pair, looking at the 60 minute chart on 27/9/16 there is an entry after 16:00 Australian Eastern Standard Time (the setup bar is 15:00). The entry price is at 0.7670, the initial stop set to 0.7656 and the 16:00 bar (the first bar of the trade) closes as 0.7677. The stop loss should be adjusted to the entry price at the close of this bar as it is greater than the entry price (and the trade should close out for breakeven as the market action unfolds), but the strategy analyzer records the trade as hitting the stop loss several bars later at 22:00.

      Comment


        #4
        Hello newuser,

        The issue looks to be related to your SetStopLoss/SetProfitTarget functions calling entry signal name “LongEntry:”+LongCount, however LongCount is going to have 1 added to it by the time BarsSinceEntry condition is true, thus you’re referring to an EntrySignal name which may not exist.

        You should add print statements to confirm the value of LongCount is the same when its assigned in the entry signal name as it is when the BarsSinceEntry is true.

        Please let us know if you need further assistance.
        Alan P.NinjaTrader Customer Service

        Comment


          #5
          I tried removing all references in the code to the entry signal name ("LongEntry"+LongCount) but alas the breakeven logic still doesn't work as intended.
          I looked through the trade results and I noticed that the breakeven logic worked for a small handful of trades, but it didn't work in other instances (when I confirmed manually that it should). For example the trade described in my previous post - AUDUSD on 27/9/16 - still does not change (the stop loss remains at the initial point and the trade is recorded as a loss).

          For the record I changed the code on this attempt to the following:
          Code:
          protected override void OnBarUpdate()
          //condition set
          if ( //long conditions)
          {
          double InitialRisk = (High[0] + 2*TickSize) - (Low[0]-2*TickSize) //variable for initial risk 
          EnterLongLimit(DefaultQuantity, High[0] + 2*TickSize, "");
          }
          if BarsSinceEntry()==0)
          {
          SetStopLoss(CalculationMode.Price, Low[0]-2*TickSize,false);
          SetProfitTarget(CalculationMode.Price,High[0]+2*TickSize+(InitialRisk*2));
          }
          if (BarsSinceEntry()==1 && Close[0]>=Position.AvgPrice)
          { 
          SetStopLoss(CalculationMode.Price, Position.AvgPrice, false);
          }
          else if (BarsSinceEntry()==1 && Close[0]<Position.AvgPrice)
          { 
          SetProfitTarget(CalculationMode.Price, Position.AvgPrice);
          }
          Note that in this code I set the initial stop and profit target simply by using BarsSinceEntry()==0. I have confirmed through traceorders = true; that stops and targets are being set correctly using this approach.

          I was wondering if using Position.AvgPrice is the problem? I added a print for Position.AvgPrice and I couldn't understand the values it was returning in the output. It made me wonder if the simultaneous open trades was causing an issue with Position.AvgPrice?

          Comment


            #6
            Hello Newuser,

            If you’re Position.AvgPrice prints are not matching what you’d expect, then it would be expected to have issues with your breakeven logic as the modification of your stop/target rely on this calculation.

            Are you running this strategy with CalculateOnBarClose set to true or false?

            I look forward to your reply.
            Alan P.NinjaTrader Customer Service

            Comment


              #7
              Hi,

              Thanks for replying.

              In response to your question I have always set COBC = true;

              I ran another backtest from 20 Sep 2016 to 3 October 2016 using the code described in my previous post (all references to entry name removed, stop/profit set using BarsSinceEntry only) to try debug the breakeven logic. I notice that the print of the Average Entry Price value does not return anything until after the 5th trade has been placed (21/9/16 20:00), so it seems that whatever is happening the Position.AvgPrice is not behaving as expected.

              I also noticed a rather unusual bug. While I was looking through the output [for the test simulation over the date range of 20 Sep 2016 to 3 October 2016] I noticed that there was an error when trying to set the stop on 21 Sep 16 at 9am. The error was: **NT** Calculated stop order price for strategy 'Buynoentryname' was smaller/equal 0. No stop order placed.

              I couldn’t see why this might be the case so I did another test run, this time for the date range 1 Jan 2016 to 3 October 2016. When I looked through the output of the longer backtest the error no longer appeared on 21 Sep, but did appear on 11 Jan 16 at 10pm. It seems as though there is some sort of bug causing an error early in the iteration of my code?

              In both cases the error pertains to a setup that never actually triggers an order so it hasn’t affected the outcome, but never the less I spotted it so thought I’d mention it.

              I have attached the output of both simulations and the trade list for the shorter simulation. For reference both simulations were on the AUDUSD 60 minute chart and the timezone I operate in is Australian Eastern Time (GMT +10).
              Attached Files

              Comment


                #8
                Hello Newuser,

                The issue may be that at your BarsSinceEntry conditions, NinjaTrader hasn’t received confirmation that your order has been filled just yet. Try adding a position check.

                Try your breakeven logic under,

                if (Position.MarketPosition == MarketPosition.Long)
                {
                }


                Please let us know if you need further assistance.
                Alan P.NinjaTrader Customer Service

                Comment


                  #9
                  I tried adding the check for the market position == long as you suggested but that made no difference. A handful of trades get adjusted to breakeven but for example the setup previously identified in my earlier post still records a loss when it should be a breakeven.

                  I'm getting a bit frustrated with this - I thought setting a stop to breakeven after a number of bars would be a fairly common thing and thus easy to script.

                  Comment


                    #10
                    Hello Newuser,

                    If the issue is that Position.Avg is coming up with a value of zero, then BarsSinceEntry probably isn’t running. When Position.Avg does update, bars since entry may be greater than just 1 bar so perhaps the condition isn’t ever being true.

                    Rather than using bars since entry, simplify by setting a variable to the current bar, then after 1 bar submit Stop/Target then a bar after that check if close[0] is above or below Position.AvgPrice.
                    I modified this section of your earlier code, see below.

                    Please let us know if backtest results are as expected.
                    Attached Files
                    Alan P.NinjaTrader Customer Service

                    Comment


                      #11
                      Hi,

                      Thanks for writing back so quickly. Before I respond to your post I just want to revisit your earlier reply (and mine).

                      I had another think about the market position == long code and I think I got it to work (sorry I'm guessing I made a mistake when I first tried it and posted a reply in haste). The previously cited trade of 27 Sep 16 @ 17:00 now works for example as it gets closed out for breakeven. That said, I've encountered another problem(!) which I think I can attritube to the Position.AvgPrice by a process of elimination .

                      I was looking through the rest of the results of the backtest and I noticed just a handful of trades that ended by taking a loss but were actually closed out by the profit target. One trade for example on the AUDUSD 6/9/16 @ 1400 was closed out by the profit target for a loss of approximately 28 ticks. The irony is that this was greater than the initial risk of 19 ticks(!!)

                      I inserted print commands for the time, high, low and Postion.AvgPrice to help debug. The average price at the time of this trade is returned at 0.7602, while the high and low (for the setup bar) are 0.7632 and 0.7617 respectively. The trace shows that the initial stop and target are being set correctly so it seems safe to say that the breakeven logic is coming unstuck on the Position.AvgPrice.

                      As far as I can tell there are no other open trades at the time of this particular trade, but there have definitely been previous long trades in the execution. Could it be that Position.AvgPrice is then averaging the value of all trades placed to date? If so, is there a way I could reset the value of Position.AvgPrice after every trade?

                      Given the above it seems to like BarsSinceEntry is working as intended and I don't need to set a variable, but I will give that a go if you still think it will work?

                      Comment


                        #12
                        Hello Newuser,

                        Position.Avg price returns to zero when you’re flat so there is no need to reset the value after each trade. If you’re Position.Avg at the time your profit target was modified beneath your (expected) breakeven, was printing a value you weren’t expecting, I might suggest adding a print to check your market position at that time.

                        For Example,
                        Print(Position.MarketPosition.ToString() + " " + Position.Quantity.ToString());

                        See Quantity Section of our helpguide:


                        Please let us know if you need further assistance.
                        Alan P.NinjaTrader Customer Service

                        Comment


                          #13
                          I added a print command as per your suggestion

                          Code:
                          Print(Position.MarketPosition.ToString() + " " + Position.Quantity.ToString());
                          and started looking through the output. I could see that the average entry price would return to zero when I was flat and would update once I had a trade open. I also figured out by looking at the output that the Position.AvgPrice is indeed averaging the value of any and all open positions (if more than 1 trade is open at a time, which sometimes happens under the entry conditions I have set).

                          With regards to the trade that I mentioned in my previous post - the AUDUSD on 6/09/16 @ 1400 - I am puzzled as to why it got closed out by a profit target at 0.7606 (which is lower than the initial stop as I said). At the time of the trade the print of Position.MarketPosition returns a ‘Flat 0’ value for some reason. The only thing I can see in the trace is that the previous trade (which was from 20:00 on the previous day) closed negative after the first bar and consequently the code set the profit target to the Postion.AvgPrice value (as it should)…..but that value just so happens to be 0.7606. That earlier trade gets closed out by its stop loss and the trace does report that the profit target is cancelled at that time. However unlikely it seems that the code has picked up the now changed value for the previous profit target (0.7606) and applied it to the next trade?? I can’t see anything else going on to explain why the next trade at 14:00 on the following day would get closed out for a loss by a profit target?

                          Comment


                            #14
                            Hello Newuser,

                            Regarding the AUDUSD trade on 6-9-16 at 1400 getting closed out by the profit target, could you please send an email to platformsupport[at]ninjatrader[dot]com with Attn: Alan P in the Subject line. Also within the email please include a link to this thread, and attach the log and trace files for the day in subject which you can find in My Documents>NinjaTrader7>Log and My Documents>NinjaTrader7/Trace folders.

                            I look forward to your email.
                            Alan P.NinjaTrader Customer Service

                            Comment


                              #15
                              So as per my post (#13 in the thread) my breakeven code doesn’t work with Position.AvgPrice. The problem I discovered is that Position.AvgPrice will return the average entry price of all open strategy positions – and occasionally my strategy will have more than one trade open at a time.

                              I am trying to find a better solution but not having much luck. What can I use instead of Position.AvgPrice? The code I currently have under OnBarUpdate() is as follows:


                              Code:
                              if (Position.MarketPosition == MarketPosition.Long)
                              {
                              	if (BarsSinceEntry()==1 && Close[0]>=Position.AvgPrice)
                              	{
                              				SetStopLoss(CalculationMode.Price,Position.AvgPrice);		
                              	}
                              	else if (BarsSinceEntry()==1 && Close[0]<Position.AvgPrice)
                              	{		
                              				SetProfitTarget(CalculationMode.Price,Position.AvgPrice);	
                              	}
                              }
                              So basically what I need is something that will check the position after the first bar of the trade has closed. If the trade is profitable set the stop loss to the entry price; if the trade is not profitable then set the profit target to the entry price.

                              I thought I should use OnExecution() but when I put the following code in:

                              Code:
                              protected override void OnExecution(IExecution execution)
                                 {
                                    if (entryOrder != null && entryOrder == execution.Order)
                                    Print("Execution Price=" + execution.Price);
                              Print("Execution="+execution.ToString());
                                 }
                              I find that ‘Execution’ in the code above printed values in the output but ‘Execution Price’ did not (and I have no idea why).

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Waxavi, Today, 02:10 AM
                              0 responses
                              3 views
                              0 likes
                              Last Post Waxavi
                              by Waxavi
                               
                              Started by TradeForge, Today, 02:09 AM
                              0 responses
                              9 views
                              0 likes
                              Last Post TradeForge  
                              Started by Waxavi, Today, 02:00 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post Waxavi
                              by Waxavi
                               
                              Started by elirion, Today, 01:36 AM
                              0 responses
                              4 views
                              0 likes
                              Last Post elirion
                              by elirion
                               
                              Started by gentlebenthebear, Today, 01:30 AM
                              0 responses
                              4 views
                              0 likes
                              Last Post gentlebenthebear  
                              Working...
                              X