Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Problem with my code ... SimpleEMACrossover : Strategy

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

    Problem with my code ... SimpleEMACrossover : Strategy

    Hi, I'm trying to program a simple trading indicator/strategy. I want to take a position when the EMA 9 and the EMA 14 cross. everything seems to work fine except when my price reaches the SL or the TP, the trade doesn't CLOSE ... could you please help me?

    Here is my code:​


    Code:
    // Simple EMA 9/14 Crossover Strategy: 2 contract, $250 SL, $400 TP, BUY/SELL label only
    using System;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.NinjaScript.Strategies;
    using NinjaTrader.NinjaScript.DrawingTools;
    using System.Windows.Media;
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class SimpleEMACrossover : Strategy
        {
            private EMA ema9;
            private EMA ema14;
            private int contractQty = 2;
            private double stopLossUSD = 150;
            private double takeProfitUSD = 250;
            
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Name = "Simple EMA 9/14 Crossover";
                    Calculate = Calculate.OnBarClose;
                    IncludeCommission = true;
                }
                else if (State == State.DataLoaded)
                {
                    ema9 = EMA(9);
                    ema14 = EMA(14);
                }
            }
            
            protected override void OnBarUpdate()
            {
                if (CurrentBar < 14)
                    return;
                
                if (Position.MarketPosition == MarketPosition.Flat)
                {
                    if (CrossAbove(ema9, ema14, 1))
                    {
                        Draw.Text(this, "Buy" + CurrentBar, "BuyName", 0, Low[0] - 2 * TickSize, Brushes.Green);
                        SetStopLoss("BuyName", CalculationMode.Currency, stopLossUSD, false);
                        SetProfitTarget("BuyName", CalculationMode.Currency, takeProfitUSD, false);
                        Print("Enter Long at: " + Time[0] + " Price: " + Close[0]);
                        EnterLong(contractQty, "BuyName");
                    }
                    else if (CrossBelow(ema9, ema14, 1))
                    {
                        Draw.Text(this, "Sell" + CurrentBar, "SellName", 0, High[0] + 2 * TickSize, Brushes.Red);
                        SetStopLoss("SellName", CalculationMode.Currency, stopLossUSD, false);
                        SetProfitTarget("SellName", CalculationMode.Currency, takeProfitUSD, false);
                        Print("Enter Short at: " + Time[0] + " Price: " + Close[0]);
                        EnterShort(contractQty, "SellName");
                    }
                }
            }
        }
    }
    
    ​

    #2
    Here's some screenshot.

    Click image for larger version

Name:	image.png
Views:	243
Size:	21.4 KB
ID:	1342626
    Click image for larger version

Name:	image.png
Views:	234
Size:	5.5 KB
ID:	1342627
    Click image for larger version

Name:	image.png
Views:	237
Size:	15.8 KB
ID:	1342628​​​

    Comment


      #3
      Hello mathfrick2023,

      Thank you for your post.

      From the code, it seems like you want your stop/target to stay static. If you're simply trying to use static stop/targets, it's recommended to just call these from OnStateChange when State == State.Configure. This is noted in the Help Guide:

      "Tips (also see Overview):
      It is suggested to call this method from within the strategy OnStateChange() method if your stop loss price/offset is static"





      It's only recommended to call SetStopLoss() and SetProfitTarget() from OnBarUpdate if you're going to dynamically update their values.


      Debugging is also recommended to understand a strategy's behavior. 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


        #4
        Hello, Thank you very much for your help, I've been reading to get even more information!

        The only problem I have now is that when the price reaches the TP or SL, I trade does not close and I have a POPUP to tell me to close the trade manually ...

        I want the script to work by itself, it detects a cross, takes position and reaches the TP or SL. Then it does it again...

        Here's my new code:



        Code:
        using System;
        using NinjaTrader.Cbi;
        using NinjaTrader.Gui.Tools;
        using NinjaTrader.Data;
        using NinjaTrader.NinjaScript;
        using NinjaTrader.NinjaScript.Indicators;
        using NinjaTrader.NinjaScript.Strategies;
        using NinjaTrader.NinjaScript.DrawingTools;
        using System.Windows.Media;
        
        namespace NinjaTrader.NinjaScript.Strategies
        {
            public class SimpleEMACrossover : Strategy
            {
                private EMA ema9;
                private EMA ema14;
                
                // Paramètres configurables
                [NinjaScriptProperty]
                public int ContractQty { get; set; }
                
                [NinjaScriptProperty]
                public double StopLossUSD { get; set; }
                
                [NinjaScriptProperty]
                public double TakeProfitUSD { get; set; }
                
                [NinjaScriptProperty]
                public bool ShowLabels { get; set; }
                
                [NinjaScriptProperty]
                public bool LogCrossovers { get; set; }
        
                protected override void OnStateChange()
                {
                    if (State == State.SetDefaults)
                    {
                        Name = "Simple EMA 9/14 Crossover";
                        Description = "Stratégie de trading basée sur le croisement des EMA 9 et 14";
                        
                        // Configuration par défaut
                        Calculate = Calculate.OnEachTick;
                        IncludeCommission = true;
                        TraceOrders = true;
                        
                        // Paramètres par défaut
                        ContractQty = 2;
                        StopLossUSD = 150;
                        TakeProfitUSD = 250;
                        ShowLabels = true;
                        LogCrossovers = true;
                    }
                    else if (State == State.Configure)
                    {
                        // Ajouter les EMAs au graphique
                        AddChartIndicator(EMA(9));
                        AddChartIndicator(EMA(14));
                    }
                    else if (State == State.DataLoaded)
                    {
                        ema9 = EMA(9);
                        ema14 = EMA(14);
                    }
                }
        
                protected override void OnBarUpdate()
                {
                    try
                    {
                        // Attendre que suffisamment de données soient disponibles
                        if (CurrentBar < 14)
                            return;
        
                        // Journaliser les informations de croisement
                        if (LogCrossovers)
                        {
                            Print(string.Format("Bar #{0} | Time: {1} | EMA9: {2:F2} | EMA14: {3:F2} | CrossAbove: {4} | CrossBelow: {5}",
                                CurrentBar,
                                Time[0],
                                ema9[0],
                                ema14[0],
                                CrossAbove(ema9, ema14, 1),
                                CrossBelow(ema9, ema14, 1)));
                        }
        
                        // Gérer l'entrée en position uniquement si nous sommes à plat
                        if (Position.MarketPosition == MarketPosition.Flat)
                        {
                            // Signal d'achat: EMA9 croise au-dessus de EMA14
                            if (CrossAbove(ema9, ema14, 1))
                            {
                                // Afficher l'étiquette BUY sur le graphique
                                if (ShowLabels)
                                {
                                    Draw.Text(this, "Buy" + CurrentBar, "BUY", 0, Low[0] - 3 * TickSize, Brushes.Green);
                                }
                                
                                // Journaliser l'entrée
                                Print(string.Format("SIGNAL LONG | Bar #{0} | Time: {1} | Price: {2:F2}",
                                    CurrentBar, Time[0], Close[0]));
                                
                                // Entrer en position LONG avec SL et TP
                                EnterLong(ContractQty, "Buy");
                                SetStopLoss("Buy", CalculationMode.Currency, StopLossUSD, false);
                                SetProfitTarget("Buy", CalculationMode.Currency, TakeProfitUSD, false);
                            }
                            // Signal de vente: EMA9 croise en-dessous de EMA14
                            else if (CrossBelow(ema9, ema14, 1))
                            {
                                // Afficher l'étiquette SELL sur le graphique
                                if (ShowLabels)
                                {
                                    Draw.Text(this, "Sell" + CurrentBar, "SELL", 0, High[0] + 3 * TickSize, Brushes.Red);
                                }
                                
                                // Journaliser l'entrée
                                Print(string.Format("SIGNAL SHORT | Bar #{0} | Time: {1} | Price: {2:F2}",
                                    CurrentBar, Time[0], Close[0]));
                                
                                // Entrer en position SHORT avec SL et TP
                                EnterShort(ContractQty, "Sell");
                                SetStopLoss("Sell", CalculationMode.Currency, StopLossUSD, false);
                                SetProfitTarget("Sell", CalculationMode.Currency, TakeProfitUSD, false);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // Capturer et journaliser toute erreur
                        Print("ERREUR: " + ex.Message);
                        if (ShowLabels)
                        {
                            Draw.Text(this, "Error" + CurrentBar, "ERREUR", 0, Close[0], Brushes.Yellow);
                        }
                    }
                }
            }
        }

        Comment


          #5
          What is the error you are seeing? If possible provide a screenshot.

          Additionally I do not see that you have moved SetStopLoss() and SetProfitTarget() to State.Configure.​

          Comment


            #6
            Why SetStopLoss causes an error but SetProfitTarget doesn't

            and the 2 when they are reached, their line disappears but does not close the Trade...

            I tried with a SIM account and my other account which is connected to Tradovate​


            Code:
            using System;
            using NinjaTrader.Cbi;
            using NinjaTrader.Gui.Tools;
            using NinjaTrader.Data;
            using NinjaTrader.NinjaScript;
            using NinjaTrader.NinjaScript.Indicators;
            using NinjaTrader.NinjaScript.Strategies;
            using NinjaTrader.NinjaScript.DrawingTools;
            using System.Windows.Media;
            
            namespace NinjaTrader.NinjaScript.Strategies
            {
                public class SimpleEMACrossover : Strategy
                {
                    private EMA ema9;
                    private EMA ema14;
                    
                    [NinjaScriptProperty]
                    public int ContractQty { get; set; }
                    
                    [NinjaScriptProperty]
                    public double StopLossUSD { get; set; }
                    
                    [NinjaScriptProperty]
                    public double TakeProfitUSD { get; set; }
                    
                    [NinjaScriptProperty]
                    public bool ShowLabels { get; set; }
                    
                    [NinjaScriptProperty]
                    public bool LogCrossovers { get; set; }
            
                    protected override void OnStateChange()
                    {
                        if (State == State.SetDefaults)
                        {
                            Name = "Simple EMA 9/14 Crossover";
                            Description = "Stratégie de trading basée sur le croisement des EMA 9 et 14";
            
                            Calculate = Calculate.OnEachTick;
                            IncludeCommission = true;
                            //TraceOrders = true;
                            ContractQty = 2;
                            StopLossUSD = 100;
                            TakeProfitUSD = 150;
                            ShowLabels = true;
                            LogCrossovers = true;
                        }
                        else if (State == State.Configure)
                        {
                            SetStopLoss(CalculationMode.Currency, StopLossUSD);
                            SetProfitTarget(CalculationMode.Currency, TakeProfitUSD);
                        }
                        else if (State == State.DataLoaded)
                        {
                            ema9 = EMA(9);
                            ema14 = EMA(14);
                        }
                    }
            
                    protected override void OnBarUpdate()
                    {
                        if (Position.MarketPosition == MarketPosition.Flat)
                        {
                            if (CrossAbove(ema9, ema14, 1))
                            {
                                EnterLong(ContractQty);
                            }
                            else if (CrossBelow(ema9, ema14, 1))
                            {
                                EnterShort(ContractQty);
                            }
                        }
                    }
                }
            }​
            Last edited by mathfrick2023; 05-09-2025, 06:29 AM.

            Comment


              #7
              If you want a dynamic stop loss/profit target with Set() methods then you need to call the Set method with CalculationMode.Ticks when the strategy is flat.

              Below is a sample script that demonstrates how to dynamically modify the price of stops and targets using Set() methods.



              Comment


                #8
                Thanks for your code unfortunately it doesn't work anymore ... the SL or TP doesn't CLOSE my current trade ... really weird ...

                Is it because I text the strategy with a Sim101 account? How can we FLATTERN all trade ?
                Last edited by mathfrick2023; 05-11-2025, 06:09 PM.

                Comment


                  #9
                  Hi, I am trying to get the stock NT 8/20 crossover to work, but its not executing trades and I would like some help getting it to work. The strategy performance analyzer is calculating performance and illustrating statistics so something is working. Whom might I communicate with to figure it out?

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by aligator, 07-14-2025, 05:09 PM
                  0 responses
                  34 views
                  1 like
                  Last Post aligator  
                  Started by NTEducationTeam, 07-14-2025, 01:49 PM
                  0 responses
                  65 views
                  0 likes
                  Last Post NTEducationTeam  
                  Started by NTEducationTeam, 07-14-2025, 01:24 PM
                  0 responses
                  50 views
                  0 likes
                  Last Post NTEducationTeam  
                  Started by saltminer, 07-07-2025, 01:43 PM
                  1 response
                  154 views
                  0 likes
                  Last Post NinjaTrader_ChelseaB  
                  Started by idude, 07-08-2025, 05:06 AM
                  0 responses
                  64 views
                  0 likes
                  Last Post idude
                  by idude
                   
                  Working...
                  X