Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Candle close execute order and stop loss

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

    Candle close execute order and stop loss

    Hello my strategy enters a long after a bullish candle close. The part that doesn't work is when i set a dynamic stop loss which is basically based on the lowest price of the last three candles. Please have a look at my code its so frustrating been on it for hours for such a simple functionality...

    Code:
    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class bullishexecution : Strategy
        {
            private double StopLong;
    
            private MIN MIN1;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "bullishexecution";
                    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;
                    StopLong                    = 1;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {                
                    MIN1                = MIN(Low, 3);
                }
            }
    
            protected override void OnBarUpdate()
            {
                if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 1)
                    return;
    
                 // Set 1
                if ((Position.MarketPosition == MarketPosition.Flat)
                     && (Close[0] > Open[0]))
                {
                    EnterLong(Convert.ToInt32(DefaultQuantity), @"entry");
                    StopLong = MIN1[0];
                }
                
                 // Set 2
                if (Position.MarketPosition == MarketPosition.Long)
                {
                    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity), StopLong, @"stoplol", @"entry");
                    ExitLongLimit(Convert.ToInt32(DefaultQuantity), (Position.AveragePrice + (10 * TickSize)) , @"tp", @"entry");
                }
                
            }
        }
    }​
    Starts
    04-22-2024
    Ends
    04-23-2024

    #2
    Hello traderqz,

    Thank you for your post.

    How exactly is the stop loss not working? Is it not behaving as expected, or is the order not being submitted at all?

    Are there errors appearing on the Log tab of the Control Center?


    In order to better understand how the code is working, it will be necessary to use Print to see how the conditions are evaluating and enable TraceOrders to see if orders are being submitted, ignored, rejected, or cancelled.

    Below is a link to a forum post that demonstrates using prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.


    Enable TraceOrders, print the time of the bar and all values used in the conditions that submit entry orders. Include labels for all values and comparison operators.

    Let me know if you need any assistance creating a print or enabling TraceOrders.

    Save the output from the output window to a text file and provide this with your reply.

    I'll be happy to assist with analyzing the output.​
    Gaby V.NinjaTrader Customer Service

    Comment


      #3
      Hey Gaby thanks for the reply.
      I’ve used prints yeah, and they all pointed the problem to the stop loss im trying to set…

      the error i get is “an order placed at 04-18 has been ignored since the order before the strategy property bars requiredToTrade had been met”

      when i remove my dynamic stop loss and use a fix one with setStopLoss it works well but when i go in Conditions and put an exitStopLong, it gives me this error no idea why , the logic should be good no?

      simple version of logic is :

      if current market position is long —> setLongStop at low of current candle

      Comment


        #4
        Hello traderqz,

        This message is more of a warning than an error, it that states that an order was ignored because the strategy tried to place a trade before there were enough bars loaded on the chart.

        Code:
        if (CurrentBar < BarsRequiredToTrade)
        {
        return;
        }
        The code above would be used to avoid this warning message. That said, you would not be able to add this condition to your strategy using the Strategy Builder. To incorporate this condition in your script, you would have to unlock the code of your strategy from the Strategy Wizard using the 'Unlock code' button and add this code to the top of OnBarUpdate(). ​​

        Please let us know if you have any further questions.
        Gaby V.NinjaTrader Customer Service

        Comment


          #5
          Hey Gaby, i've added that line of code you gave me and it still gave me the same error, also i forgot to mention that error and this one are the two errors that always appear
          4/23/2024 1:12:49 PM Default Enabling NinjaScript strategy 'test/325227607' : On starting a real-time strategy - StartBehavior=WaitUntilFlat Position=NQ 06-24 1L AccountPosition=NQ 06-24 1L EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes

          please help me if you could go look it from your side as to why its not working its pretty frustrating not being able to make such a simple feature work. Please try the file i've sent you
          Attached Files

          Comment


            #6
            Hello traderqz,

            Did you compile the script after editing it? And then reload the script from the chart?

            What errors are appearing specifically? That message from the log is just a message that your strategy is being enabled, not an error message. You can see it says 'Enabling NinajScript strategy'. There is no error listed there.

            Additionally, the "an order placed at 04-18 has been ignored since the order before the strategy property bars requiredToTrade had been met” is not an error message either, it's just a warning.

            Can you please provide more detail on what errors you think are occurring? What are the actual error messages?
            Last edited by NinjaTrader_Gaby; 04-23-2024, 11:56 AM.
            Gaby V.NinjaTrader Customer Service

            Comment


              #7
              Hey Gaby, it’d be easier if you download the file and open it with ninjatrader, i did everything you mentionned above yes, the error seems to come from stop loss part of the strategy but the logic is good

              Comment


                #8
                Hello traderqz,

                I am seeing the strategy is getting the following error when enabled:

                An order has been ignored since the stop price ‘'5064’ near the bar stamped ‘04/17/2024 17:270:00 PM’ is invalid based on the price range of the bar. This is an invalid order and subsequent orders may also be ignored.

                The message is letting you know that a stop order was ignored because the strategy submitted the order to an invalid price level. Buy stop orders must be placed above the current ask price. Sell stop orders must be placed below the current ask price.

                When the order is submitted, is the stop price parameter greater than the GetCurrentAsk() for a buy stop order? Or, is the stop price parameter less than the GetCurrentAsk() for a sell stop order?

                I would recommend you add prints to the strategy to determine why the stop order is being ignored. One line above where the stop order is placed, print the GetCurrentAsk() and print the price being submitted to the order method.

                Below is a link to a support article that demonstrates using prints to understand behavior.


                Enable TraceOrders, print the time of the bar and all values used in the conditions that submit entry orders. Include labels for all values and comparison operators.

                Please see the help guide documentation below for more information about GetCurrentAsk().
                https://ninjatrader.com/support/help...currentask.htm
                Gaby V.NinjaTrader Customer Service

                Comment


                  #9
                  Hey Gaby, thanks for helping me out and running my script i did do the traces but they didnt find anything helpful from them
                  As for my stop loss, its supposed to be place under the low of current candle close since it’s a buy entry. I dont quite understand because the entry of the long is already higher than the price of the stop loss since they’re the same candle ( long executed at close price and stop loss put a low price) so its obviously higher than the ask price…. any idea ? im really stuck, thanks!

                  Comment


                    #10
                    Hello traderqz,

                    Thanks for your response.

                    To truly know what is causing the issue it would be necessary to use prints and debug by looking at all of the information the script is using for decisions.

                    Debugging using prints is necessary to determine why the stop order is being ignored. Printing the ask and the price the order is being submitted to will help clear up how the order is being submitted to an invalid price.

                    Adding prints and getting output is known as debugging and is a process that all programmers use to understand the behavior of their code and what steps to take to correct it. You can learn to do this too and become an advanced programmer that is able to work out the barriers preventing the code from behaving as you have intended.

                    With TraceOrders we can see when orders are being submitted, when orders are being filled, ignored, and cancelled. This lets us know the logic is good, but something is happening with the orders and fill processing. With that information we know which way to address the issue.

                    If you need assistance creating a print, enabling TraceOrders, or analyzing the output please let me know and I'm happy to help.


                    You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services.

                    Please let me know if you would like a list of affiliate consultants who would be happy to create this script or any others at your request or provide one on one educational services.​​​
                    Gaby V.NinjaTrader Customer Service

                    Comment


                      #11
                      Hey Gaby, i understand but i’ve been adding the prints and in the output section when i execute strategy it just displays the string ive typed in the print, its not helpful… any way you can check it yourself ? been hours on this for such a seemingly simpel task…

                      Comment


                        #12
                        Hello,

                        Unfortunately, in the support department at NinjaTrader it is against our policy to create, debug, or modify, code or logic for our clients. Further, we do not provide C# programming education services or one on one educational support in our NinjaScript Support department. This is so that we can maintain a high level of service for all of our clients as well as our associates.


                        That said, through email or on the forum we are happy to answer any questions you may have about NinjaScript if you decide to code this yourself. We are also happy to assist with finding resources in our help guide as well as simple examples, and we are happy to assist with guiding you through the debugging process to assist you with understanding unexpected behavior.


                        You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services.


                        Please let me know if you would like a list of affiliate consultants who would be happy to create this script or any others at your request or provide one on one educational services.​
                        Gaby V.NinjaTrader Customer Service

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by pjsmith, 10-01-2019, 08:59 AM
                        26 responses
                        1,989 views
                        0 likes
                        Last Post nephew94  
                        Started by Str8boominit, 04-14-2025, 06:03 PM
                        6 responses
                        74 views
                        0 likes
                        Last Post Str8boominit  
                        Started by TAJTrades, Today, 09:01 AM
                        5 responses
                        29 views
                        0 likes
                        Last Post NinjaTrader_ChelseaB  
                        Started by quantyse_ntforum, 03-10-2025, 09:05 AM
                        14 responses
                        244 views
                        0 likes
                        Last Post dakensei  
                        Started by ntwong, 10-08-2024, 08:22 PM
                        10 responses
                        228 views
                        0 likes
                        Last Post akvevo
                        by akvevo
                         
                        Working...
                        X