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

Min/Max of OptimizationFitness

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

    Min/Max of OptimizationFitness

    hello,

    I'm looking to maximize/minimize a particular OptimizationFitness function I created. The confusing part I am having is how to do I explicitaly tell the optimizer to max/min a value. So I was looking at the functions where NT8 minimizes/maximizes a variable to see how you guys did. For example:

    NT8 OptimizationFitness function, "MaxAvgProfitShort"

    Code:
    namespace NinjaTrader.NinjaScript.OptimizationFitnesses
    {
    	public class MaxAvgProfitShort : OptimizationFitness
    	{
    		protected override void OnCalculatePerformanceValue(StrategyBase strategy)
    		{
    			Value = strategy.SystemPerformance.ShortTrades.TradesPerformance.Percent.AverageProfit;
    		}
    
    		protected override void OnStateChange()
    		{               
    			if (State == State.SetDefaults)
    				Name = NinjaTrader.Custom.Resource.NinjaScriptOptimizationFitnessNameMaxAvgProfitShort;
    		}
    	}
    }
    But the above code doesn't really have any code where it says, "maximize average profit." How does the optimizer "know" that you want to minimize or maximize something? Is that aspect just happening in the background somewhere? If so, I guess I should just always start with a function that you guys already created that is "maximizing" and amend the code for the performance metric if I want to maximize... vise versa for minimizing.

    #2
    Hello staycool3_a,

    This is based on the Value being set.

    The higher the Value the higher the result is in the rankings.

    If you to reverse this, you would need to do so with math and make the largest numbers the smallest numbers and the smallest numbers the largest numbers.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by staycool3_a View Post
      hello,

      I'm looking to maximize/minimize a particular OptimizationFitness function I created. The confusing part I am having is how to do I explicitaly tell the optimizer to max/min a value. So I was looking at the functions where NT8 minimizes/maximizes a variable to see how you guys did. For example:

      NT8 OptimizationFitness function, "MaxAvgProfitShort"

      Code:
      namespace NinjaTrader.NinjaScript.OptimizationFitnesses
      {
      	public class MaxAvgProfitShort : OptimizationFitness
      	{
      		protected override void OnCalculatePerformanceValue(StrategyBase strategy)
      		{
      			Value = strategy.SystemPerformance.ShortTrades.TradesPerformance.Percent.AverageProfit;
      		}
      
      		protected override void OnStateChange()
      		{               
      			if (State == State.SetDefaults)
      				Name = NinjaTrader.Custom.Resource.NinjaScriptOptimizationFitnessNameMaxAvgProfitShort;
      		}
      	}
      }
      But the above code doesn't really have any code where it says, "maximize average profit." How does the optimizer "know" that you want to minimize or maximize something? Is that aspect just happening in the background somewhere? If so, I guess I should just always start with a function that you guys already created that is "maximizing" and amend the code for the performance metric if I want to maximize... vise versa for minimizing.
      Thank you, Chelsea.

      My question is: where in the code is the Value being explicitly being “set” to max/min? The max XYZ optimization functions that you have are not setting any values that I can see. I hope my questions is making sense lol. I’m basically trying to find a function that I can use as a starting point, amend the function with my criteria, and then it will maximize the value of my criteria. I’m just confused bc none of your min/max codes explicitly have any codes that is max/min a value.

      Or, are you saying that the optimizer inherently is always seeking to maximize the value and you just have to make sure that the value your maximizing is correct. So for example, if I amended the maxavgprofit formula I posted in my OP, and multiplied the value by -1... then the optimizer would maximize that value and find the minavgprofit?

      Also, do you have any idea how to access position.unrealized at close[0] within a optimization fitness function? Is that possible?
      Last edited by staycool3_a; 09-10-2018, 11:43 AM.

      Comment


        #4
        Hello staycool3_a,

        Value is being set with the line:
        Code:
        Value = strategy.SystemPerformance.ShortTrades.TradesPerformance.Percent.AverageProfit;
        The AverageProfit will be the value assigned to value. The higher this value is, the higher the result will be in the rankings.

        You could get the Position object from the strategy object parameter in OnCalculatePerformanceValue().
        Code:
        Print(strategy.Position.ToString());
        Print(strategy.Close[0]);
        However, this does not trigger for every bar close..
        Last edited by NinjaTrader_ChelseaB; 09-10-2018, 11:45 AM.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Originally posted by NinjaTrader_ChelseaB View Post
          Hello staycool3_a,

          Value is being set with the line:
          Code:
          Value = strategy.SystemPerformance.ShortTrades.TradesPerformance.Percent.AverageProfit;
          The AverageProfit will be the value assigned to value. The higher this value is, the higher the result will be in the rankings.

          You could get the Position object from the strategy object parameter in OnCalculatePerformanceValue().
          Code:
          Print(strategy.Position.ToString());
          However, this does not trigger for every bar close..
          Right, I understand this part. But how does the optimizater know that I want to maximize this value? This value is just the avg.profit trade performance variable. How does it know that I want to maximize it? Maybe I want to minimize it...

          Are you saying that the optimizer inherently is always seeking to maximize the value and you just have to make sure that the value your maximizing is correct. So for example, if I amended the maxavgprofit formula I posted in my OP, and multiplied the value by -1... then the optimizer would maximize that value and find the minavgprofit?

          Comment


            #6
            Hello staycool3_a,

            It only works one way. The larger the value is the higher it is in rankings. If you want the smallest values ranked at the top, you would need to do this with logic. Make the largest numbers the smallest and the smallest numbers the largest.

            For example, multiply by negative 1.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_ChelseaB View Post
              Hello staycool3_a,

              It only works one way. The larger the value is the higher it is in rankings. If you want the smallest values ranked at the top, you would need to do this with logic. Make the largest numbers the smallest and the smallest numbers the largest.

              For example, multiply by negative 1.
              Thank you, Chelsea.

              Good to know that it only works one way. That was the confusing part for me. Thanks!

              -p.s; you're on the ball today!

              Comment


                #8
                Just follow up this topic. So, I have a OptimizationFitness coded in NT 7, and I want to translate it into NT 8. While I can nowhere find a custom example of NT 8 OptimizationFitness. So, I guess the calculation logic should be put in the following part:

                Code:
                protected override void OnCalculatePerformanceValue(StrategyBase strategy)
                        {
                
                        }
                And I guess I do not have to do anything in the ...?

                Code:
                if (State == State.SetDefaults)
                            {
                                Description                                    = @"Van Sharp's System Quality Number ";
                                Name                                        = "SQN";
                            }
                And maybe, I also do not have to do anything in the ... ?

                Code:
                else if (State == State.Configure)
                            {
                
                            }
                So the NT 7 code is like this:
                Code:
                #region Using declarations
                using System;
                using System.ComponentModel;
                using System.Drawing;
                using NinjaTrader.Cbi;
                using NinjaTrader.Data;
                using NinjaTrader.Indicator;
                using NinjaTrader.Strategy;
                #endregion
                
                // This namespace holds all strategies and is required. Do not change it.
                namespace NinjaTrader.Strategy
                {
                    /// <summary>
                    /// System Quality Number
                    /// </summary>
                    [Gui.Design.DisplayName("my system quality number")]
                    public class SQN : OptimizationType
                    {
                        public static double sLastSQN;
                        public static int sMinTrades = 0;
                
                        /// <summary>
                        /// Return the performance value of a backtesting result.
                        /// </summary>
                        /// <param name="systemPerformance"></param>
                        /// <returns></returns>
                        public override double GetPerformanceValue(SystemPerformance systemPerformance)
                        {
                            // Allow override of minimum number of trades to return a value
                            // Parameter is SQNMinTrades
                            int minTrades = 30;
                            if (sMinTrades > 0)
                            {
                                minTrades = sMinTrades;
                            }
                            else
                            {
                                int n;
                                for (n = 0; n < Strategy.Parameters.Count; n++)
                                {
                                    if ("SQNMinTrades".CompareTo(Strategy.Parameters[n].Name) == 0)
                                    {
                                        minTrades = (int)Strategy.Parameters[n].Value;
                                        break;
                                    }
                                }
                            }
                
                            double numTrades = systemPerformance.AllTrades.Count;
                
                            if (numTrades < minTrades)
                                return 0;
                
                            // This calc comes from NT standard net profit opt type
                            double avgProfit = (systemPerformance.AllTrades.TradesPerformance.GrossProfit +
                                systemPerformance.AllTrades.TradesPerformance.GrossLoss) / numTrades;
                
                            double stddev = 0;
                            double tradeProf;
                
                            // Now figure std dev of profit
                            // Note: I forget my statistics & pulled this algorithm from the internet,
                            // corrections welcomed.
                            foreach (Trade t in systemPerformance.AllTrades)
                            {
                                tradeProf = (t.ProfitPoints * t.Quantity * t.Entry.Instrument.MasterInstrument.PointValue);
                
                                // Uncomment this section for debug output to NT's output window
                                /*
                                Strategy.Print(t.Entry.Time + "," + t.Quantity + "," + t.Entry.Price + "," + t.Exit.Price + "," +
                                    t.ProfitPoints.ToString("N2") + "," + t.Quantity + "," +
                                    t.Entry.Instrument.MasterInstrument.PointValue + "," + tradeProf);
                                */
                
                                stddev += Math.Pow(tradeProf - avgProfit, 2);
                            }
                
                            stddev /= numTrades;
                            stddev = Math.Sqrt(stddev);
                
                            double sqn = (Math.Sqrt(numTrades) * avgProfit) / stddev;
                
                            // Uncomment this section for debug output to NT's output window
                            /*
                            Strategy.Print("numTrades: " + numTrades.ToString("N2") + "  avgProfit: " + avgProfit.ToString("N2") +
                                "  stddev: " + stddev.ToString("N2") + "  sqn: " + sqn.ToString("N2"));
                            */
                
                            // Hoping to access this from my optimizer (note: it works.)
                            sLastSQN = sqn;
                            return sqn;
                        }
                    }
                
                }

                And how do I find the corresponding functions in NT 8? For example,
                Code:
                avgProfit = (systemPerformance.AllTrades.TradesPerformance.GrossProfit +
                                systemPerformance.AllTrades.TradesPerformance.GrossLoss) / numTrades;
                Thanks !

                Comment


                  #9
                  Hello wolfcuring,

                  A basic example would be the MaxNetProfit that is included with NinjaTrader.

                  The OnStateChange() State.SetDefaults should be used for all NinjaScripts that are not pure custom addons (at least to set the Name).

                  The State.Configure is not necessary for this script.

                  Below is a link to the help guide on SystemPerformance.AllTrades and TradesPerformance.



                  These will be available from the strategy object supplied to OnCalculatePerformanceValue. (Use the MaxNetProfit as an example)
                  Chelsea B.NinjaTrader Customer Service

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by cls71, Today, 04:45 AM
                  0 responses
                  1 view
                  0 likes
                  Last Post cls71
                  by cls71
                   
                  Started by mjairg, 07-20-2023, 11:57 PM
                  3 responses
                  213 views
                  1 like
                  Last Post PaulMohn  
                  Started by TheWhiteDragon, 01-21-2019, 12:44 PM
                  4 responses
                  544 views
                  0 likes
                  Last Post PaulMohn  
                  Started by GLFX005, Today, 03:23 AM
                  0 responses
                  3 views
                  0 likes
                  Last Post GLFX005
                  by GLFX005
                   
                  Started by XXtrader, Yesterday, 11:30 PM
                  2 responses
                  12 views
                  0 likes
                  Last Post XXtrader  
                  Working...
                  X