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

Martingale Strategy

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

    #16
    Hello ossamaelouadih,

    Thanks for your note.

    We would not be able to say for certain why the logic you created in your script is not functioning as you expect it to. If Size is a user-defined variable, you would simply call something like Print("Size: " + Size); to print out that variable.

    If the NextSize variable is an int, you could print out the NextSize variable using something like Print("NextSize: " + NextSize);.

    It would be up to you to continue debugging the logic you created in your script to find out why it is not behaving as you are expecting it to. I suggest adding debugging prints throughout your entire strategy to print out all the variables and conditions in the script so you can see exactly how all the logic is evaluating.

    If you need assistance creating a debugging print, please let me know what you want to print out and I will be happy to assist.

    Let me know if you have other questions.
    Brandon H.NinjaTrader Customer Service

    Comment


      #17
      I did all of this steps I printed all of the conditions Size and Next and Lastprofit and LastTrade.Quantity and i figued out that the problem is getting The right LastTrade.Qyantity
      As you know "LastTrade.Quatity" is refrence in ninjascript

      Comment


        #18
        Hello ossamawlouadih,

        Thanks for your note.

        That would be the correct way to get the quantity of the last trade from the SystemPerformance.RealTimeTrades TradeCollection. See the sample code below.

        Note that when using the SystemPerformance collection, a trade is considered a buy and a sell.

        Code:
        if (SystemPerformance.RealTimeTrades.Count >= 1)
        {
             Trade lastTrade = SystemPerformance.RealTimeTrades[SystemPerformance.RealTimeTrades.Count - 1];
             Print("lastTrade: " + lastTrade);
             double lastTradeQty = lastTrade.Quantity;
             Print("The last trade quantity is: " + lastTradeQty);
        }​​​
        The prints in the Output window would look something like this.

        lastTrade: instrument='ES 12-22' entryPrice=3849 exitPrice=3846.75 quantity=1 marketPosition=Short entryTime='10/26/2022 11:46:00 AM' exitTime='10/26/2022 11:47:54 AM' profitCurrency=107.02

        The last trade quantity is:
        1

        Let me know if I may assist further.​
        Brandon H.NinjaTrader Customer Service

        Comment


          #19
          Thank you for this reply i used exactly this code as you see in my first post . This refrence is not geving me the last actual trade quantity it returns only the last execution .
          For exemple entered in a position with 4contracts but in the exit i haven't executed all 4 contracts at the same time it exits 3 then 1 so it's gonna return just 1 but the actual trade was 4contacts
          I hope i explained well
          So the question is how can i get the whole last trade while it returning just the last execution of that trade ??
          Attached Files

          Comment


            #20
            Hello ossamaelouadih,

            Thanks for your note.

            It seems like you might be wanting to get the quantity of the current position. If you want to get the quantity of the current position placed by the strategy you could consider using Position.Quantity in your script.

            See this help guide page for more information and sample code: https://ninjatrader.com/support/help...n_quantity.htm

            Let me know if I may assist further.
            Brandon H.NinjaTrader Customer Service

            Comment


              #21
              Thank you Soo much Mr Brandon H , Problem has been solved
              I really appreciate your help , and ninjatrader for having such a great support

              Comment


                #22
                I would like help adding logic to double position size upon experiencing a losing a trade, and then drop back to the strategy default quantity upon experiencing a winning trade. I made this using strategy builder and dont have any coding experience so I am hoping there is a tutorial or instructions to add the elements as I am lost.

                Best regards


                region Using declarations
                using System;
                using System.Collections.Generic;
                using System.ComponentModel;
                using System.ComponentModel.DataAnnotations;
                using System.Linq;
                using System.Text;
                using System.Threading.Tasks;
                using System.Windows;
                using System.Windows.Input;
                using System.Windows.Media;
                using System.Xml.Serialization;
                using NinjaTrader.Cbi;
                using NinjaTrader.Gui;
                using NinjaTrader.Gui.Chart;
                using NinjaTrader.Gui.SuperDom;
                using NinjaTrader.Gui.Tools;
                using NinjaTrader.Data;
                using NinjaTrader.NinjaScript;
                using NinjaTrader.Core.FloatingPoint;
                using NinjaTrader.NinjaScript.Indicators;
                using NinjaTrader.NinjaScript.DrawingTools;
                #endregion

                //This namespace holds Strategies in this folder and is required. Do not change it.
                namespace NinjaTrader.NinjaScript.Strategies
                {
                public class ESMG : Strategy
                {
                private EMA EMA1;
                private EMA EMA2;

                protected override void OnStateChange()
                {
                if (State == State.SetDefaults)
                {
                Description = @"Enter the description for your new custom Strategy here.";
                Name = "ES10to11WEDandTHURSonlyMG";
                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 = true;
                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;
                Tp = 100;
                Sl = 25;
                Start = DateTime.Parse("00:00", System.Globalization.CultureInfo.InvariantCulture) ;
                Stop = DateTime.Parse("00:00", System.Globalization.CultureInfo.InvariantCulture) ;
                FASTema = 10;
                SLOWema = 200;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {
                EMA1 = EMA(Close, Convert.ToInt32(FASTema));
                EMA2 = EMA(Median, Convert.ToInt32(SLOWema));
                SetProfitTarget("", CalculationMode.Ticks, Tp);
                SetStopLoss("", CalculationMode.Ticks, Sl, false);
                }
                }

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

                if (CurrentBars[0] < 10)
                return;

                // Set 1
                if ((EMA1[0] > EMA2[0])
                && (Times[0][0].TimeOfDay < Stop.TimeOfDay)
                && (Times[0][0].TimeOfDay >= Start.TimeOfDay)
                && (Times[0][0].DayOfWeek != DayOfWeek.Monday)
                && (Times[0][0].DayOfWeek != DayOfWeek.Tuesday)
                && (Times[0][0].DayOfWeek != DayOfWeek.Thursday))
                {
                EnterLong(1, @"LONG");
                }

                // Set 2
                if ((EMA1[0] < EMA2[0])
                && (Times[0][0].TimeOfDay < Stop.TimeOfDay)
                && (Times[0][0].TimeOfDay >= Start.TimeOfDay)
                && (Times[0][0].DayOfWeek != DayOfWeek.Monday)
                && (Times[0][0].DayOfWeek != DayOfWeek.Tuesday)
                && (Times[0][0].DayOfWeek != DayOfWeek.Thursday))
                {
                EnterShort(1, @"SHORT");
                }

                }

                region Properties
                [NinjaScriptProperty]
                [Range(1, int.MaxValue)]
                [Display(Name="Tp", Description="take profit", Order=1, GroupName="Parameters")]
                public int Tp
                { get; set; }

                [NinjaScriptProperty]
                [Range(1, int.MaxValue)]
                [Display(Name="Sl", Description="stop loss", Order=2, GroupName="Parameters")]
                public int Sl
                { get; set; }

                [NinjaScriptProperty]
                [PropertyEditor("NinjaTrader.Gui.Tools.TimeEditorKe y")]
                [Display(Name="Start", Order=3, GroupName="Parameters")]
                public DateTime Start
                { get; set; }

                [NinjaScriptProperty]
                [PropertyEditor("NinjaTrader.Gui.Tools.TimeEditorKe y")]
                [Display(Name="Stop", Order=4, GroupName="Parameters")]
                public DateTime Stop
                { get; set; }

                [NinjaScriptProperty]
                [Range(1, int.MaxValue)]
                [Display(Name="FASTema", Order=5, GroupName="Parameters")]
                public int FASTema
                { get; set; }

                [NinjaScriptProperty]
                [Range(1, int.MaxValue)]
                [Display(Name="SLOWema", Order=6, GroupName="Parameters")]
                public int SLOWema
                { get; set; }
                #endregion

                }
                }

                Comment


                  #23
                  Hello rolledchange,

                  Thanks for your note.

                  This would not be possible to accomplish using the Strategy Builder.

                  You would need to manually program the logic in an unlocked strategy in the NinjaScript Editor to accomplish this.

                  The SystemPerformance collection could be used to get information about the last trade that was made and then you could add logic to your script that doubles your position's quantity if the last Trade's ProfitCurrency value is positive or negative.

                  See the help guide documentation below for more information and sample code.
                  SystemPerformance: https://ninjatrader.com/support/help...erformance.htm
                  AllTrades: https://ninjatrader.com/support/help.../alltrades.htm
                  TradeCollection: https://ninjatrader.com/support/help...collection.htm
                  Trade: https://ninjatrader.com/support/help.../nt8/trade.htm

                  Let me know if I may further assist.
                  Brandon H.NinjaTrader Customer Service

                  Comment


                    #24
                    Originally posted by NinjaTrader_BrandonH View Post
                    Hello rolledchange,

                    Thanks for your note.

                    This would not be possible to accomplish using the Strategy Builder.

                    You would need to manually program the logic in an unlocked strategy in the NinjaScript Editor to accomplish this.

                    The SystemPerformance collection could be used to get information about the last trade that was made and then you could add logic to your script that doubles your position's quantity if the last Trade's ProfitCurrency value is positive or negative.

                    See the help guide documentation below for more information and sample code.
                    SystemPerformance: https://ninjatrader.com/support/help...erformance.htm
                    AllTrades: https://ninjatrader.com/support/help.../alltrades.htm
                    TradeCollection: https://ninjatrader.com/support/help...collection.htm
                    Trade: https://ninjatrader.com/support/help.../nt8/trade.htm

                    Let me know if I may further assist.
                    Thank you very much for the prompt response, I have my homework cutout for me!

                    Best regards

                    Comment


                      #25
                      I have worked towards finally developing a very good working strategy. I use the NinjaTrader alert sometimes to submit my trades, but, there are sometime bad days for trading that I would like to clean up by using the martingale while trading with the NT alert system activated. Can someone point me to a starting place on how to add code to NinjaTrader and does anyone have a working martingale code/program from start to finish? Occasionally, I manually use the martingale for up to 1 to 2 trades, only and return back to the original trading unit.

                      Comment


                        #26
                        Hello ReginaldS8,

                        Thanks for your post.

                        I am not aware of an existing 'Martingale' script that is available for NinjaTrader.

                        This forum thread will be open for community members to share their insights on a possible existing solution or share a script that they created themselves.

                        That said, I see you asked 'how to add code to NinjaTrader'. You could find educational material about learning NinjaScript below to help get you started. This will allow you to gain a foundation and understanding of how to create custom NinjaScripts.

                        NinjaTrader utilizes the C# programming language for developing indicators and strategies.

                        The best way to begin learning NinjaScript is to use the Strategy Builder. With the Strategy Builder, you can set up conditions and variables and then see the generated code in the NinjaScript Editor by clicking the View Code button.

                        Here is a link to our publicly available training videos, 'Strategy Builder 301' and 'NinjaScript Editor 401', for you to view at your own convenience.

                        Strategy Builder 301 — https://www.youtube.com/watch?v=_KQF2Sv27oE&t=13s

                        NinjaScript Editor 401 - https://youtu.be/H7aDpWoWUQs?list=PL...We0Nf&index=14

                        I am also linking you to the Educational Resources section of the Help Guide to help you get started with NinjaScript:
                        https://ninjatrader.com/support/help..._resources.htm

                        If you are new to C#, to get a basic foundation for the concepts and syntax used in NinjaScript I would recommend this section of articles in our help guide first:
                        https://ninjatrader.com/support/help...g_concepts.htm

                        And the MSDN (Microsft Developers Network) C# Language Reference.
                        https://ninjatrader.com/support/help...erence_wip.htm


                        Please let us know if we may further assist.​
                        Brandon H.NinjaTrader Customer Service

                        Comment


                          #27
                          Thanks Brandon H.

                          I will begin reviewing the videos and reading up on the information you've sent me.

                          Comment


                            #28
                            I received this martingale strategy from someone. But, seems like we could not get rid of the Error Code, CS0234. [The type or namespace name "Strategy" does not exist in the namespace "NinjaTrader" (are you missing an assembly reference?)] Line 15 column 19. Line 15 is "using NinjaTrader.Strategy;".


                            Can someone help me get rid of this code so that I can test it. Or, is something missing?
                            region Using declarations
                            using System;
                            using System.ComponentModel;
                            using System.ComponentModel.DataAnnotations;
                            using System.Collections.Generic;
                            using System.Linq;
                            using System.Text;
                            using System.Threading.Tasks;
                            using System.Windows;
                            using System.Windows.Input;
                            using System.Windows.Media;
                            using System.Xml.Serialization;
                            using NinjaTrader.Cbi;
                            using NinjaTrader.Data;
                            using NinjaTrader.Strategy;
                            using NinjaTrader.NinjaScript;
                            using NinjaTrader.NinjaScript.Indicators;
                            #endregion

                            namespace NinjaTrader.NinjaScript.Strategies
                            {
                            public class Martingale : Strategy
                            {
                            private int buyCount = 0;
                            private int sellCount = 0;
                            private double entryPrice = 0.0;
                            private double currentPrice = 0.0;

                            protected override void OnStateChange()
                            {
                            if (State == State.SetDefaults)
                            {
                            Description = @"Enter the description for your new custom Strategy here.";
                            Name = "Martingale";
                            Calculate = Calculate.OnBarClose;
                            EntriesPerDirection = 2;
                            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;
                            }
                            else if (State == State.Configure)
                            {
                            ClearOutputWindow();
                            }
                            }

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

                            if (CurrentBars[0] < BarsRequiredToTrade)
                            return;

                            if (Position.MarketPosition == MarketPosition.Flat)
                            {
                            if (buyCount < EntriesPerDirection && currentPrice < entryPrice)
                            {
                            buyCount++;
                            entryPrice = currentPrice;
                            EnterLong(DefaultQuantity, "Buy1");
                            }
                            else if (sellCount < EntriesPerDirection && currentPrice > entryPrice)
                            {
                            sellCount++;
                            entryPrice = currentPrice;
                            EnterShort(DefaultQuantity, "Sell1");
                            }
                            }
                            else if (Position.MarketPosition == MarketPosition.Long)
                            {
                            if (buyCount < EntriesPerDirection && currentPrice < entryPrice)
                            {
                            buyCount++;
                            entryPrice = currentPrice;
                            EnterLong(DefaultQuantity, "Buy2");
                            }
                            else
                            {
                            ExitLong(DefaultQuantity, "ExitBuy");
                            sellCount = 0;
                            entryPrice = 0.0;
                            buyCount = 0;
                            }
                            }
                            else if (Position.MarketPosition == MarketPosition.Short)
                            {
                            if (sellCount < EntriesPerDirection && currentPrice > entryPrice)
                            {
                            sellCount++;
                            entryPrice = currentPrice;
                            EnterShort(DefaultQuantity, "Sell2");
                            }
                            else
                            {
                            ExitShort(DefaultQuantity, "ExitSell");
                            buyCount = 0;
                            entryPrice = 0.0;
                            sellCount = 0;
                            }
                            }
                            }

                            protected override void OnMarketData(MarketDataEventArgs marketDataUpdate)
                            {
                            if (marketDataUpdate.MarketDataType == MarketDataType.Last)
                            {
                            currentPrice = marketDataUpdate.Price;
                            }
                            }
                            }
                            }

                            Comment


                              #29
                              Hello ReginaldS8,

                              Thanks for your note.

                              The Using statement you mentioned does not need to be added in the script.

                              You may remove 'using NinjaTrader.Strategy' from the script and then run a compile.

                              Please let me know if I may assist further.
                              Brandon H.NinjaTrader Customer Service

                              Comment


                                #30
                                I tried that earlier and ended up with more codes CS1502 and CS1503 stating the "NinjaTrader.NinjaScript.StrategyBase.ExitLong(str ing, string)" has some invalid Argument 1: cannot convert from "int" to "string" . It's the same for short except the word long is short

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by geotrades1, Today, 10:02 AM
                                1 response
                                5 views
                                0 likes
                                Last Post NinjaTrader_BrandonH  
                                Started by ender_wiggum, Today, 09:50 AM
                                1 response
                                5 views
                                0 likes
                                Last Post NinjaTrader_Gaby  
                                Started by rajendrasubedi2023, Today, 09:50 AM
                                1 response
                                12 views
                                0 likes
                                Last Post NinjaTrader_BrandonH  
                                Started by bmartz, Today, 09:30 AM
                                1 response
                                10 views
                                0 likes
                                Last Post NinjaTrader_Erick  
                                Started by geddyisodin, Today, 05:20 AM
                                3 responses
                                26 views
                                0 likes
                                Last Post NinjaTrader_Gaby  
                                Working...
                                X