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

Write custom optimize on

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

    Write custom optimize on

    I've searched but cannot find a guide to creating my own "optimize on".

    I want the optimizer to optimize on fewest trades.

    I loaded MaxNetProfit from optimizationfitnesses into the editor but cannot decipher it to write my own.

    #2
    Hello Chippy,

    Thank you for your post.

    It'd be pretty simple, really all you need is a single line of code that checks the TradesCount of AllTrades:

    Code:
    namespace NinjaTrader.NinjaScript.OptimizationFitnesses
    {
    public class FewestTrades : OptimizationFitness
    {
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Optimization Fitness here.";
    Name = "FewestTrades";
    }
    else if (State == State.Configure)
    {
    }
    }
    
    protected override void OnCalculatePerformanceValue(StrategyBase strategy)
    {
    [B]Value = strategy.SystemPerformance.AllTrades.TradesCount * -1;[/B]
    }
    
    }
    }
    If you want to optimize on the most number of trades, you would simply modify this so you don't multiply strategy.SystemPerformance.AllTrades.TradesCount by -1.

    Please let us know if we may be of further assistance to you.
    Kate W.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_Kate View Post
      Hello Chippy,

      Thank you for your post.

      It'd be pretty simple, really all you need is a single line of code that checks the TradesCount of AllTrades:

      Code:
      namespace NinjaTrader.NinjaScript.OptimizationFitnesses
      {
      public class FewestTrades : OptimizationFitness
      {
      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"Enter the description for your new custom Optimization Fitness here.";
      Name = "FewestTrades";
      }
      else if (State == State.Configure)
      {
      }
      }
      
      protected override void OnCalculatePerformanceValue(StrategyBase strategy)
      {
      [B]Value = strategy.SystemPerformance.AllTrades.TradesCount * -1;[/B]
      }
      
      }
      }
      If you want to optimize on the most number of trades, you would simply modify this so you don't multiply strategy.SystemPerformance.AllTrades.TradesCount by -1.

      Please let us know if we may be of further assistance to you.
      So "Value" is the variable we need to set? Is there a comprehensive guide explaining what properties are available? I have to say that multiplying by -1 isn't very intuitive for me. I would like to read more on how to write these generally. Do you have a link?

      Comment


        #4
        Hello Chippy,

        Thank you for your note.

        Yes, you would set Value to the value you want the script to be optimized on.

        We really don't have a lot of documentation on optimization fitnesses - it's fairly rare people make their own and also they've got a very simple structure. What we do have is available in our help guide here:

        https://ninjatrader.com/support/help...on_fitness.htm

        Please let us know if we may be of further assistance to you.
        Kate W.NinjaTrader Customer Service

        Comment


          #5
          Revisiting this thread.

          I'm trying to create a custom optimize on for Unrealized Drawdown. NT8 doesn't take into account unrealized drawdowns of positions, which is the actual drawdown..., so I'm trying to create my own. I've created a new file, I can select it but the system doesn't seem to be optimizing on anything. All results for performance are 0. I'm also not sure how to tell it to optimize for max or min. I've looked at the other files and it doesn't really seem to say there either. Please advise.

          Code:
          #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;
          #endregion
          //This namespace holds Optimization fitnesses in this folder and is required. Do not change it.
          namespace NinjaTrader.NinjaScript.OptimizationFitnesses
          {
          public class MinUnrealizedDrawdown : OptimizationFitness
          {
          protected override void OnStateChange()
          {
          if (State == State.SetDefaults)
          {
          Description = @"Minimum Unrealized Drawdown by bar.";
          Name = "MinUnrealizedDrawdown";
          }
          else if (State == State.Configure)
          {
          }
          }
          protected override void OnCalculatePerformanceValue(StrategyBase strategy)
          {
          Value = strategy.Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency);
          Print(Value);
          }
          }
          }

          Comment


            #6
            Hi chasebank, This question has been discussed here:
            https://ninjatrader.com/support/foru...izationfitness

            In short, the optimizer is always looking for the Maximum value, so to get the minimum, you would make the minimum values the highest ones in the OptimizationFitness script.
            Chris L.NinjaTrader Customer Service

            Comment


              #7
              That makes sense, however, the unrealized profit/loss method is returning 0 for everything. I cannot get it to return a positive number whatsoever. It always returns 0.

              Edit: It looks as if all the Position methods are returning 0. I tried quantity and averageprice too.
              Last edited by chasebank; 01-25-2023, 01:21 PM.

              Comment


                #8
                Hi, I will test it out and let you know if I get the same thing.

                Thanks in advance.
                Chris L.NinjaTrader Customer Service

                Comment


                  #9
                  Hi, this is expected because Optimization Fitness gets the "OnCalculatePerformanceValue()" method called once after every optimization iteration, you will notice that all of the default optimization fitness scripts iterate through the strategy.SystemPerformance.AllTrades collection and not run time variables such as the strategy.Position object.
                  Chris L.NinjaTrader Customer Service

                  Comment


                    #10
                    Understood.

                    So, given that the drawdown metrics on the strategy analyzer aren't accurate, can you think of another way to get optimize on metrics outside of the AllTrades collection?

                    For instance, here is an equity curve of a strategy by day in the strategy analyzer. The 2nd image is the real equity curve by taking the unrealized profit/loss each day + realized gains and putting it in excel. As you can see, NT8 looks like you've found a madoff curve and in reality, we've blown up the account multiple times over. I suppose this is more an issue with how the AllTrades collection works then just the optimizer. Anyway we can edit the AllTrades collection to consider open positions unrealized profit/loss?

                    Click image for larger version

Name:	Screen Shot 2023-01-25 at 1.18.54 PM.png
Views:	37
Size:	874.8 KB
ID:	1232713
                    Click image for larger version

Name:	Screen Shot 2023-01-25 at 1.20.19 PM.png
Views:	20
Size:	121.8 KB
ID:	1232714

                    Comment


                      #11
                      Hello, thanks for the follow up. Only the StrategyPerformance.AllTrades collection is available at the time OnCalculatePerformanceValue() is called so it's not possible to get run time values from the strategy. It may be possible to create your own data structure (list, dictionary, etc) within the strategy that holds information necessary to calculate your custom performance metric. This would need to be tested though, Im not positive it would be available from the StrategyBase object after the optimization iteration.

                      Kind regards,
                      -ChrisL
                      Chris L.NinjaTrader Customer Service

                      Comment


                        #12
                        Yea, I've already created my own dictionaries that hold the data, however, I'd was trying to optimize on that data. You should let your dev team know that ALL drawdown figures are not correct and this needs to be corrected for your customers. It's borderline dangerous to suggest drawdown is only applicable to closed trades.

                        Comment


                          #13
                          Hi, can you please give me a reproducible scenario that I can test on my end? Please provide exact steps and describe exactly what you think is wrong with the Max/Min drawdown.
                          Chris L.NinjaTrader Customer Service

                          Comment


                            #14
                            Buy /ES on Feb 20, 2022, Sell it on Aug 12, 2020. You'll see the strategy analyzer will say 0 drawdown, when, in fact, your account would blow up if you held a futures contract through the pandemic crash. Now, imagine this on any set of time series. If the position is never closed, no drawdown is ever recorded. Drawdown, realized or unrealized, is a drawdown, non the less. In particular, for futures contracts held overnight, it's standard to cash sweep the account and realize the drawdown at end of day.

                            Comment


                              #15
                              Hi, The strategy analyzer has no concept of account status while the backtest is running. Currently, we have a feature request open that is asking for portfolio-level backtesting: SFT-137 I'll add a vote to this for you. Your strategy script would need to keep track of a mock Account that would represent the real-world account and prevent trading or exit trades based on the PnL of the account.
                              Chris L.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Don22Trader1, Yesterday, 04:54 PM
                              2 responses
                              31 views
                              0 likes
                              Last Post Don22Trader1  
                              Started by Taras, Yesterday, 03:44 AM
                              7 responses
                              133 views
                              0 likes
                              Last Post jeronymite  
                              Started by anton_tymoshchuk, Yesterday, 01:43 AM
                              4 responses
                              74 views
                              0 likes
                              Last Post jeronymite  
                              Started by trader24211341, 03-09-2023, 12:30 PM
                              2 responses
                              38 views
                              0 likes
                              Last Post trader24211341  
                              Started by ct, Today, 04:56 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post ct
                              by ct
                               
                              Working...
                              X