Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Short using Break Even Example issue

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

    Short using Break Even Example issue

    I am testing the sample break even script provided by the mods. I see the default long positions work great. When i try to reverse the code to take shorts I get short entries but the strategy does not respect /trigger stop loss and break even. Any help is appreciated to get the short condition to work. Below is my code for shorts.

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class BreakEvenBuilderExample : Strategy
    {
    private double StopPrice;
    private double TriggerPrice;
    private int TriggerState;


    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"";
    Name = "BreakEvenBuilderExample";
    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;
    BreakEvenTrigger = 5;
    InitialStopDistance = -10;
    StopPrice = 0;
    TriggerPrice = 0;
    TriggerState = 0;
    }
    else if (State == State.Configure)
    {
    }
    }

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

    // Set 1
    if ((TriggerState <= 2)
    && (Position.MarketPosition == MarketPosition.Flat))
    {
    TriggerState = 0;
    }

    if (CurrentBars[0] < 1)
    return;

    // Set 2
    if ((Position.MarketPosition == MarketPosition.Flat)
    && (CrossBelow(Close, High, 1))
    && (State == State.Realtime))
    {
    TriggerState = 1;
    EnterShort(Convert.ToInt32(DefaultQuantity), @"entry");
    }

    // Set 3
    if ((TriggerState == 1)
    && (Position.MarketPosition == MarketPosition.Short))
    {
    TriggerState = 2;
    StopPrice = (Position.AveragePrice + (InitialStopDistance * TickSize)) ;
    TriggerPrice = (Position.AveragePrice + (BreakEvenTrigger * TickSize)) ;
    }

    // Set 4
    if ((TriggerState == 2)
    && (Close[0] <= TriggerPrice))
    {
    TriggerState = 3;
    StopPrice = Position.AveragePrice;
    Draw.Diamond(this, @"BreakEvenBuilderExample Diamond_1", true, 0, (High[0] + (2 * TickSize)) , Brushes.DarkCyan);
    }

    // Set 5
    if (TriggerState >= 2)
    {
    ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), StopPrice, @"exit", @"entrty");
    }

    }​
    Last edited by Teebone21; 03-23-2023, 05:15 AM.

    #2
    Hello Teebone21,

    As a tip, to export a NinjaTrader 8 NinjaScript so this can be shared and imported by the recipient do the following:
    1. Click Tools -> Export -> NinjaScript Add-on...
    2. Click the 'add' link -> check the box(es) for the script(s) and reference(s) you want to include
    3. Click the 'Export' button
    4. Enter a unique name for the file in the value for 'File name:'
    5. Choose a save location -> click Save
    6. Click OK to clear the export location message
    By default your exported file will be in the following location:
    • (My) Documents/NinjaTrader 8/bin/Custom/ExportNinjaScript/<export_file_name.zip>
    Below is a link to the help guide on Exporting NinjaScripts.
    http://ninjatrader.com/support/helpG...-us/export.htm

    By attaching the export, others can import and test your script. Further, you would not have to post the entire code of your script into a forum posts or email.


    To understand behavior, enable TraceOrders and add prints.

    Below is a link to a forum post that demonstrates using Print() and TraceOrders to understand behavior.



    Is TraceOrders output showing your order is being submitted, or is this being ignored?
    Is the order being automatically cancelled?

    ​From the print output of the conditions, are you showing that the TriggerPrice is being set below the market price?
    Is the stopPrice above the current bid?
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_ChelseaB View Post
      Hello Teebone21,

      As a tip, to export a NinjaTrader 8 NinjaScript so this can be shared and imported by the recipient do the following:
      1. Click Tools -> Export -> NinjaScript Add-on...
      2. Click the 'add' link -> check the box(es) for the script(s) and reference(s) you want to include
      3. Click the 'Export' button
      4. Enter a unique name for the file in the value for 'File name:'
      5. Choose a save location -> click Save
      6. Click OK to clear the export location message
      By default your exported file will be in the following location:
      • (My) Documents/NinjaTrader 8/bin/Custom/ExportNinjaScript/<export_file_name.zip>
      Below is a link to the help guide on Exporting NinjaScripts.
      http://ninjatrader.com/support/helpG...-us/export.htm

      By attaching the export, others can import and test your script. Further, you would not have to post the entire code of your script into a forum posts or email.


      To understand behavior, enable TraceOrders and add prints.

      Below is a link to a forum post that demonstrates using Print() and TraceOrders to understand behavior.



      Is TraceOrders output showing your order is being submitted, or is this being ignored?
      Is the order being automatically cancelled?

      ​From the print output of the conditions, are you showing that the TriggerPrice is being set below the market price?
      Is the stopPrice above the current bid?
      Thanks for help. I finally got the logic working but need an exampled of setting the profit target using exit methods. Any advise?

      Comment


        #4
        Hello Teebone21,

        Unfortunately, the BreakEvenBuilderExample_NT8 does not demonstrate a limit, as it is more demonstrating a concept to learn from that can be applied to any exit or entry order. Once it's understood how to add ticks to a price and save this to a variable and then supply this to an order, this can be used for any order.

        I know of one example that uses "Exit long position with a limit order" (ExitLongLimit()), but this is not using an input for the distance.
        https://forum.ninjatrader.com/forum/...ns#post1225339

        I have an unlocked script that demonstrates using a limit with chase logic.
        ProfitChaseStopTrailExitOrdersExample_NT8 - https://forum.ninjatrader.com/forum/...269#post802269


        In the Strategy Builder the concept is still the same for limit orders

        Add an input for the user to set the distance.
        Add a variable to store the limitPrice of the order.
        In the long position conditions assign the limitPrice variable the entry price (Position.AveragePrice) with the offset set to the distance input variable in ticks.
        Supply the limitPrice variable to the limit order as the limit price.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Originally posted by NinjaTrader_ChelseaB View Post
          Hello Teebone21,

          Unfortunately, the BreakEvenBuilderExample_NT8 does not demonstrate a limit, as it is more demonstrating a concept to learn from that can be applied to any exit or entry order. Once it's understood how to add ticks to a price and save this to a variable and then supply this to an order, this can be used for any order.

          I know of one example that uses "Exit long position with a limit order" (ExitLongLimit()), but this is not using an input for the distance.
          https://forum.ninjatrader.com/forum/...ns#post1225339

          I have an unlocked script that demonstrates using a variable and chase logic.
          ProfitChaseStopTrailExitOrdersExample_NT8 - https://forum.ninjatrader.com/forum/...269#post802269


          In the Strategy Builder the concept is still the same for limit orders

          Add an input for the user to set the distance.
          Add a variable to store the limitPrice of the order.
          In the long position conditions assign the limitPrice variable the entry price (Position.AveragePrice) with the offset set to the distance input variable in ticks.
          Supply the limitPrice variable to the limit order as the limit price.
          Thanks i used the exit methods example and finally got orders to show in chart. Only issue I am having is my target order disappears once the break even price is met. His is my code below
          Attached Files

          Comment


            #6
            Hello Teebone21,

            Use TraceOrders and Print to understand the behavior.

            Add a blank condition set and print all values used in the condition set that submits the exit stop market and exit stop limit.

            Below is a link to a forum post on using print to understand behavior. Please watch the video 'Debugging using prints with the Strategy Builder'.


            Please provide the output text file attached to your next post and I will be happy to assist in analyzing the output.


            Note, in the BreakEvenBuilder example the stopPrice (and the limitPrice if there was a limit) would be calculated in Set 3, and the Exit orders (for the stop and limit if there is a limit) are submitted in Set 5 anytime the TriggerState is greater than 2 (meaning the order prices have been calculated and the position is still open). The break even condition is Set 4, and only changes the prices of the StopPrice variable (and LimitPrice variable if there is one).
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_ChelseaB View Post
              Hello Teebone21,

              Use TraceOrders and Print to understand the behavior.

              Add a blank condition set and print all values used in the condition set that submits the exit stop market and exit stop limit.

              Below is a link to a forum post on using print to understand behavior. Please watch the video 'Debugging using prints with the Strategy Builder'.


              Please provide the output text file attached to your next post and I will be happy to assist in analyzing the output.


              Note, in the BreakEvenBuilder example the stopPrice (and the limitPrice if there was a limit) would be calculated in Set 3, and the Exit orders (for the stop and limit if there is a limit) are submitted in Set 5 anytime the TriggerState is greater than 2 (meaning the order prices have been calculated and the position is still open). The break even condition is Set 4, and only changes the prices of the StopPrice variable (and LimitPrice variable if there is one).
              Thank you. I Will work in it tomorrow and post the result!

              Comment


                #8
                Hello Teebone21,

                To have separate stops and limits, EntryHandling should be set UniqueEntries, and each entry should have a unique signalName. The exit orders must be using the fromEntrySignals of those entries.

                The 'Automate Your Trading with NinjaTrader's Strategy Builder' training video discusses.


                Below is a link to an example.


                With the logic, you will need a variable for each stop and limit to store the stop and limit price.
                Chelsea B.NinjaTrader Customer Service

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by NullPointStrategies, Yesterday, 05:17 AM
                0 responses
                59 views
                0 likes
                Last Post NullPointStrategies  
                Started by argusthome, 03-08-2026, 10:06 AM
                0 responses
                134 views
                0 likes
                Last Post argusthome  
                Started by NabilKhattabi, 03-06-2026, 11:18 AM
                0 responses
                75 views
                0 likes
                Last Post NabilKhattabi  
                Started by Deep42, 03-06-2026, 12:28 AM
                0 responses
                45 views
                0 likes
                Last Post Deep42
                by Deep42
                 
                Started by TheRealMorford, 03-05-2026, 06:15 PM
                0 responses
                50 views
                0 likes
                Last Post TheRealMorford  
                Working...
                X