Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Strange "if" statement behavior

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

    Strange "if" statement behavior

    Hello I am new to Ninjascript and I have a problem when I run my code.

    I would like to enter only once but as soon as I initialize it, the “OkToTrade” variable is already set to “false” when it should be equal to “true” before entering the position for the first time.

    I don't understand why, but thanks in advance for your answers

    Code:
    namespace NinjaTrader.NinjaScript.Strategies
        {
            public class MyCustomStrategy : Strategy
            {    
                private double buyPrice;
                private double sellPrice;
                private bool OkToTrade = true;
    
                protected override void OnStateChange()
                {
                    if (State == State.SetDefaults)
                    {
                        Description    = "";
                        Name        = "My Strategy";
                        TakeProfit    = 40;
                        StopLoss    = 20;
                        Distance    = 30;
                        
                        AddPlot(Brushes.Green, "BuyPlot");
                        AddPlot(Brushes.Red, "SellPlot");
                    }
                    else if (State == State.Configure)
                    {
                        SetProfitTarget(CalculationMode.Ticks, TakeProfit);
                        SetStopLoss(CalculationMode.Ticks, StopLoss);
                    }
                }
    
                protected override void OnBarUpdate()
                {    
                    if (CurrentBar < BarsRequiredToTrade)
                        return;
                    
                    BuyPlot[0] = buyPrice;
                    SellPlot[0] = sellPrice;
                    
                    double currentAsk = GetCurrentAsk();
                    
                    // Update of entry prices
                    if (ToTime(Time[0]) <= 93000)
                    {
                        buyPrice = GetCurrentBid() + TickSize * Distance;
                        sellPrice = GetCurrentAsk() - TickSize * Distance;
                    }
                    
                    // Entry
                    if (OkToTrade)
                    {
                        if (currentAsk >= buyPrice)
                        {
                            EnterLong(1);
                            OkToTrade = false;
                        }
                        else if (currentAsk <= sellPrice)
                        {
                            EnterShort(1);
                            OkToTrade = false;
                        }
                    }
                }
                
                #region Properties
                
                [Browsable(false)]
                [XmlIgnore]
                public Series<double> BuyPlot
                {
                    get { return Values[0]; }
                }
                
                [Browsable(false)]
                [XmlIgnore]
                public Series<double> SellPlot
                {
                  get { return Values[1]; }
                }
                
                [Range(1, int.MaxValue), NinjaScriptProperty]
                [Display(ResourceType = typeof(Custom.Resource), Name = "Take Profit", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
                public int TakeProfit
                { get; set; }
    
                [Range(1, int.MaxValue), NinjaScriptProperty]
                [Display(ResourceType = typeof(Custom.Resource), Name = "Stop Loss", GroupName = "NinjaScriptStrategyParameters", Order = 1)]
                public int StopLoss
                { get; set; }
                
                [Range(1, int.MaxValue), NinjaScriptProperty]
                [Display(ResourceType = typeof(Custom.Resource), Name = "Distance", GroupName = "NinjaScriptStrategyParameters", Order = 2)]
                public int Distance
                { get; set; }
                #endregion
            }
    }

    #2
    Hello Zadomani,

    Thank you for your post.

    To understand why the script is behaving as it is, such as placing orders or not placing orders when expected, it is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.

    In the strategy add prints (outside of any conditions) that print the date time of the bar and all values compared in every condition that places an order.

    The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.

    The debugging print output should clearly show what the condition is, what time the conditions are being compared, all values being compared, and how they are being compared.

    Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

    Further, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

    After enabling TraceOrders remove the instance of the strategy from the Configured list in the Strategies window and add a new instance of the strategy from the Available list.

    I am happy to assist you with analyzing the output from the output window.

    Run or backtest the script and when the output from the output window appears save this by right-clicking the output window and selecting Save As... -> give the output file a name and save -> then attach the output text file to your reply.

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

    https://support.ninjatrader.com/s/ar...nd-TraceOrders

    Comment


      #3
      Thank you for your reply.

      I enabled TraceOrders and noticed that orders were being sent the day before at the futures opening (6PM). My condition for updating my entry prices was therefore true because 6 PM is equal to 180000 and this is greater than 92955. I therefore added a second condition to check whether the time was greater than 180000 with an “or”.

      My current problem is that the strategy takes an order at the right time but the day before. I'd like it to start acting only when I add it to my chart. In a way, I'd like it not to look into the “past”. I'm not familiar with how ninjascript works, but I hope it's possible to do this.

      Here is the output (I added the first four prints when the programm starts a trading operation) :

      Time : 134924
      Current Ask : 18674.75
      Buy price : 18685.5
      Sell price : 18675.5
      9/9/2024 1:49:24 PM Strategy 'My Strategy/332151536': Entered internal SetStopTarget() method: Type=Target FromEntrySignal='' Mode=Ticks Value=115 IsSimulatedStop=False IsMarketIfTouched=False
      9/9/2024 1:49:24 PM Strategy 'My Strategy/332151536': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='' Mode=Ticks Value=500 IsSimulatedStop=False IsMarketIfTouched=False
      9/9/2024 1:49:24 PM Strategy 'My Strategy/332151536': Entered internal SubmitOrderManaged() method at 9/9/2024 1:49:24 PM: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='Sell' FromEntrySignal=''
      orderId='NT-00000-349' account='Sim101' name='Sell' orderState=Submitted instrument='NQ SEP24' orderAction=SellShort orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00000-349' account='Sim101' name='Sell' orderState=Accepted instrument='NQ SEP24' orderAction=SellShort orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00000-349' account='Sim101' name='Sell' orderState=Working instrument='NQ SEP24' orderAction=SellShort orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00001-349' account='Sim101' name='Stop loss' orderState=Submitted instrument='NQ SEP24' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=18799.5 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00001-349' account='Sim101' name='Stop loss' orderState=Accepted instrument='NQ SEP24' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=18799.5 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00001-349' account='Sim101' name='Stop loss' orderState=Working instrument='NQ SEP24' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=18799.5 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00002-349' account='Sim101' name='Profit target' orderState=Submitted instrument='NQ SEP24' orderAction=BuyToCover orderType='Limit' limitPrice=18645.75 stopPrice=0 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00002-349' account='Sim101' name='Profit target' orderState=Accepted instrument='NQ SEP24' orderAction=BuyToCover orderType='Limit' limitPrice=18645.75 stopPrice=0 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00002-349' account='Sim101' name='Profit target' orderState=Working instrument='NQ SEP24' orderAction=BuyToCover orderType='Limit' limitPrice=18645.75 stopPrice=0 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00000-349' account='Sim101' name='Sell' orderState=Filled instrument='NQ SEP24' orderAction=SellShort orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=18674.5 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      9/9/2024 1:58:08 PM Strategy 'My Strategy/332151536: Cancelled pending exit order, since associated position is closed, orderId='NT-00001-349' account='Sim101' name='Stop loss' orderState=Working instrument='NQ SEP24' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=18799.5 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00001-349' account='Sim101' name='Stop loss' orderState=CancelPending instrument='NQ SEP24' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=18799.5 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00001-349' account='Sim101' name='Stop loss' orderState=CancelSubmitted instrument='NQ SEP24' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=18799.5 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00001-349' account='Sim101' name='Stop loss' orderState=Cancelled instrument='NQ SEP24' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=18799.5 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      orderId='NT-00002-349' account='Sim101' name='Profit target' orderState=Filled instrument='NQ SEP24' orderAction=BuyToCover orderType='Limit' limitPrice=18645.75 stopPrice=0 quantity=1 tif=Gtc oco='NT-00000-349' filled=1 averageFillPrice=18645.75 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      9/9/2024 1:58:08 PM Strategy 'My Strategy/332151536': Cancelled OCO paired order: BarsInProgress=0, orderId='NT-00001-349' account='Sim101' name='Stop loss' orderState=Cancelled instrument='NQ SEP24' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=18799.5 quantity=1 tif=Gtc oco='NT-00000-349' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2024-09-09 13:49:24' gtd='2099-12-01' statementDate='2024-09-10'
      Enabling NinjaScript strategy 'MyCustomStrategy/332151536' : On starting a real-time strategy - StartBehavior=WaitUntilFlat 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
      Disabling NinjaScript strategy 'MyCustomStrategy/332151536'
      Enabling NinjaScript strategy 'MyCustomStrategy/332151537' : On starting a real-time strategy - StartBehavior=WaitUntilFlat 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
      9/11/2024 1:31:30 AM CancelAllOrders: BarsInProgress=0​

      Comment


        #4
        Hello,

        Unfortunately these prints aren't descriptive enough to understand why the condition to place an order is becoming true before you expect it to.

        In the strategy add prints (outside of any conditions) that print the date time of the bar and all values compared in every condition that places an order.

        The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.

        The debugging print output should clearly show what the condition is, what time the conditions are being compared, all values being compared, and how they are being compared.

        For example,

        Code:
        Print(Times[0][0] + ", OkToTrade: " + OkToTrade);
        if (OkToTrade)
        {
        Print(Times[0][0] + ", currentAsk: " + currentAsk + " >= buyPrice: " + buyPrice);
        if (currentAsk >= buyPrice)
        ...​
        All conditions in your script should have similar prints. ​

        Comment


          #5
          The entire output exceeds 1 MB so here is the link to the wetransfer containing the file : https://we.tl/t-bhhrT9V4ol

          I noticed that the code is executed on the day before, causing the variable okToTrade to swith to false.

          Thanks in advance for your reply

          Comment


            #6
            Hello,

            We're still missing the descriptive prints for all conditions in the strategy. It looks like you only added the example print I made for two of your conditions. You need to create print statements for all conditions in your strategy, including your time condition.

            You could also contact a professional NinjaScript Consultant who would be eager to debug 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.

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by NullPointStrategies, 03-13-2026, 05:17 AM
            0 responses
            87 views
            0 likes
            Last Post NullPointStrategies  
            Started by argusthome, 03-08-2026, 10:06 AM
            0 responses
            151 views
            0 likes
            Last Post argusthome  
            Started by NabilKhattabi, 03-06-2026, 11:18 AM
            0 responses
            80 views
            0 likes
            Last Post NabilKhattabi  
            Started by Deep42, 03-06-2026, 12:28 AM
            0 responses
            53 views
            0 likes
            Last Post Deep42
            by Deep42
             
            Started by TheRealMorford, 03-05-2026, 06:15 PM
            0 responses
            62 views
            0 likes
            Last Post TheRealMorford  
            Working...
            X