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

Risk Aversion Switch

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

    Risk Aversion Switch

    I am creating a NT8 strategy that utilizes Strategy Performance Metrics to determine if a strategy can trade or not to get into a position. I have heard of TradePerformanceValues. Does TradePerformanceValues track Realtime and Historical performance per instense of the strategy? Side Note, will I be allowed to switch between accounts? Side Side Note, will I need to build a sim101 account reset, if sim account runs out of funds? Side Side Side Note, I will probabily have to create an AddOn that tracks Acount information, or download one from somewhere?
    Post Scipt; Sorry, for getting off topic on the Side Side Side Note.
    Last edited by GTBrooks; 09-10-2017, 10:30 AM. Reason: Make the hummer dryer / clarification

    #2
    Hello GTBrooks,

    Yes, trade performance is available for both real-time and historical.
    If you are using trade performance within the strategy, then whichever account you enable the strategy on will be the trade performance values you see. In order to switch accounts you’d have to disable then re-enable the strategy on the desired account.

    If you’re running the strategy on the sim account and you run out of funds, yes you would need to reset the account for the strategy to keep running.

    Below is a link for to a strategy which uses TradePerformance.



    If you were looking to track account information via an Addon you should see the example at the following link to get you started with addons,


    And the information on Account class in the helpguide,


    Please let us know if you need further assistance.
    Alan P.NinjaTrader Customer Service

    Comment


      #3
      Communications From Strategy to AddOn?

      Thank you for your earlier excellent response.

      I would like your help clarifying something for me. I want to set up a stream of communication between the AddOn and Strategy this is necessary for running a risk counter measure. The strategy would track its own performance compile into a couple of variables transmitted to the AddOn that then groups all the Strategy its rank them and assess funds in the account then bounce back to the strategy how much it is authorized to trade of the accounts funds.

      This would require a send of performance metrics's coded through (Account.Instrument.Strategy) UI system too the AddOn. I am sure it can work the other way round (pulling data the AddOn generated).

      If this is possible what can be done on the strategy side to create data for the AddOn to reference?

      Comment


        #4
        Hello GTBrooks,

        You could create a public variable inside the strategy, for example,

        Code:
        public double lastPrice;
        Then save a value to the variable, for example,

        Code:
        lastPrice=Close[0];
        You can now access this variable from within an Addon.

        Please let us know if you need further assistance.
        Alan P.NinjaTrader Customer Service

        Comment


          #5
          Thank you for your help so far,

          Is there a way for the Strategy to display its (Account / Instrument / Strategy)?
          I will be using them as a UI (A/I/S) to save off data for the AddOn to work with. In conjunction with the Strategy out-putting a variable, the AddOn will be out-putting a Variable. They both will use the UI (A/I/S) as a base. Hopefully this will generate way 2 way communication.
          Are there any more efficient means of 2 way communication between Strategy and AddOn?

          Comment


            #6
            Hello GTBrooks,

            Mr Dooms has a good sample of strategies/indicators/addons passing information between each other, please see the following sample,


            Please let us know if you need further assistance.
            Alan P.NinjaTrader Customer Service

            Comment


              #7
              Thank you, Alan_P!!!
              Mr. Dooms does have good samples.

              I put together this bit of code: ... I do not recommend the use of this code, due to factors I will specify later

              The goal is with the code is to; Base amount in on any given trade is only 1/50 of total account value, Bool arg determining if there is enough money in the account to trade (preventing an entry trade from occurring), finally a Performance check based off of (Historical and Real-Time trade history) (divided into Long / Short) if a minimum performance metric has not occurred (ProfitFactor>=1). The Plan is the incorporation of this code into code into Strategies. These Strategies; I already back-tested, I have already Paper-Traded with success.

              Code:
              Code:
              ///Code to be Used
              
              //This namespace holds Strategies in this folder and is required. Do not change it. 
              namespace NinjaTrader.NinjaScript.Strategies.AlanStrategies
              {
                  public class Risk_MoneyManagment_StopLoss : Strategy
                  {
              
                      private Account account;
              
                      protected override void OnStateChange()
                      {
              
                          if (State == State.SetDefaults)
                          {
              
                              IsInstantiatedOnEachOptimizationIteration    = true;
                              ProfitTargetPips                = 1;
                              TrailingStopLossPips                = 1;
                              StopLossPips                    = 1;
                              LongOnOffSwitch                 = true;
                              ShortOnOffSwitch                 = true;
              
                          }
                          else if (State == State.Configure)
                          {
              
                          }
                          else if (State == State.DataLoaded)
                          {
              
                              SetProfitTarget("", CalculationMode.Pips, (ProfitTargetPips + TrailingStopLossPips + StopLossPips));
                              SetTrailStop("", CalculationMode.Pips, (TrailingStopLossPips + StopLossPips), false);
                              SetStopLoss("", CalculationMode.Pips, StopLossPips, false);
              
                      }
              
                      protected override void OnBarUpdate()
                      {
              
                          if(CurrentBar < 10) return;
              
                          //Divides account by 18 ( # of Forex Currency Pairs being traded on the account )
                          double splitRisk; 
              
                          splitRisk = Account.Get(AccountItem.CashValue, Currency.UsDollar) / 18;
              
                          //Initial Margin of the Instrument Traded by Strategy
                          double StratInstrumentInitialMargin;
              
                          StratInstrumentInitialMargin = Risk.Get("NinjaTrader Brokerage Lifetime").ByMasterInstrument[Instrument.MasterInstrument].InitialMargin;
              
                          //Authorised ammount to Trade on the Account, divided by the Forex Initial Margin, & rounds down.
                          int sharesToBuy; 
              
                          sharesToBuy = Math.Max( (int) Math.Floor( splitRisk / StratInstrumentInitialMargin ), 1 ) * DefaultQuantity;
              
                          //Buying Power of the Account "Cash on Hand"
                          double gtbBuyingPower;
              
                          gtbBuyingPower = Account.Get(AccountItem.CashValue, Currency.UsDollar) - Account.Get(AccountItem.InitialMargin, Currency.UsDollar);
              
                          if (Close[0] > Close[1])
                          && gtbBuyingPower >= Math.Max( (int) Math.Floor(( splitRisk / StratInstrumentInitialMargin )), 1 ) * StratInstrumentInitialMargin
                          && LongOnOffSwitch )    
                          {
                              EnterLong(sharesToBuy, "");
                          }
              
                          if (Close[0] < Close[1])
                          && gtbBuyingPower >= Math.Max( (int) Math.Floor(( splitRisk / StratInstrumentInitialMargin )), 1 ) * StratInstrumentInitialMargin
                          && ShortOnOffSwitch )    
                          {            
                              EnterShort(sharesToBuy, "");
                          }
              
                      }
              
                  }
              
                      }
              
              
                      protected override void OnPositionUpdate(Cbi.Position position, double averagePrice, int quantity, Cbi.MarketPosition marketPosition)
                      {
              
                          if(Position.MarketPosition == MarketPosition.Flat)
                          {
                          // Check to make sure there is at least one trade in the collection
                              if ( SystemPerformance.AllTrades.Count > 0 )
                              {
              
                                  // Risk Long On Off Switch
                                  if ( SystemPerformance.LongTrades.TradesPerformance.ProfitFactor >= 1 )    
                                  {            
                                      LongOnOffSwitch = true;
                                  }
                                  else
                                  {
                                      LongOnOffSwitch = false;
                                  }
              
                                  // Risk Short On Off Switch
                                  if ( SystemPerformance.ShortTrades.TradesPerformance.ProfitFactor >= 1 )    
                                  {
                                      ShortOnOffSwitch = true;
                                  }
                                  else
                                  {
                                      ShortOnOffSwitch = false;
                                  }
                              }
                          }
                      }
                      #region Properties
              
                      [NinjaScriptProperty]
                      [Range(1, int.MaxValue)]
                      [Display(Name="ProfitTargetPips", Description="ProfitTarget set in Pips", Order=1, GroupName="Parameters")]
                      public int ProfitTargetPips
                      { get; set; }
              
                      [NinjaScriptProperty]
                      [Range(1, int.MaxValue)]
                      [Display(Name="TrailingStopLossPips", Description="TrailingStopLoss set in Pips", Order=2, GroupName="Parameters")]
                      public int TrailingStopLossPips
                      { get; set; }
              
                      [NinjaScriptProperty]
                      [Range(1, int.MaxValue)]
                      [Display(Name="StopLossPips", Description="StopLoss set in Pips", Order=3, GroupName="Parameters")]
                      public int StopLossPips
                      { get; set; }
              
                      [NinjaScriptProperty]
                      [Display(ResourceType = typeof(Custom.Resource), Name = "Long On Off Switch", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
                      public bool LongOnOffSwitch
                      { get; set; }
              
                      [NinjaScriptProperty]
                      [Display(ResourceType = typeof(Custom.Resource), Name = "Short On Off Switch", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
                      public bool ShortOnOffSwitch
                      { get; set; }
              
                      #endregion
              
                  }
              }
              The reason I would not use the code is I integrated this code into my Strategies. The same NinjaTrader 8 Strategy Builder built Strategies, that tested successful when asked to trade with this code stops the Strategy from trading after initiation, on their own accord. Simply, I take a successful strategy put this code in it set it up just like the successful runs before and click the Box off to the right of the Strategies Tab to activate the Strategy. the Standard warning comes on and I select OK. The Strategy Connects to Forex.com and then disconnects it self and shuts down.

              Any Tips or Tricks would be helpful. Is my grammor off? am I using incorect Syntaxx. Are the performance Metric Logic being handled under the correct Event? did I just Tell Ninja Trader to light it self on fire and jump off a cliff? again any Help would be appriciated.

              Thank you & best regards
              Last edited by GTBrooks; 02-05-2019, 01:44 PM.

              Comment


                #8
                Hello GTBrooks,

                As a tip when posting code, you can use [CODE] blocks and the forum post will retain the proper formatting and will be easier to read.

                There are some extra nested curly braces that would not be needed, but the rest of the syntax looks correct. Checking StrategyPerformance in OnPositionUpdate would be fine, but you could also place this in OnBarUpdate before your other trading logic is processed.

                If the issue is that the strategy disables itself and shuts down, I may suggest the following to debug the strategy and identify why it is disabling.
                1. Check the log tab of the Control Center. Are there any errors? Does the message mention where the error was thrown?
                2. Checking any method mentioned that is throwing errors, if you add prints to the strategy, which line of code is throwing the error?
                3. Does the context of the error give any clues to what's wrong?
                Also when testing the logic, I would suggest printing out the values that you are calculating so you can verify that the code is working exactly as expected. Prints can also be used to check the values used to evaluate your conditions, so you can see why some logic is or is not happening.

                Debugging tips - https://ninjatrader.com/support/help...script_cod.htm

                Please let us know if we can be of further assistance.
                JimNinjaTrader Customer Service

                Comment


                  #9
                  Hello,

                  Thanks again for your help, as you can see I applied your [CODE] tip.

                  Code:
                  Risk.Get("NinjaTrader Brokerage Lifetime").ByMasterInstrument[Instrument.MasterInstrument].InitialMargin;
                  for back-testing & paper-trading this bit of code is fine, BUT I will be using this code in a LIVE Account. What segment of code do I need to reference the Initial Margin of an Instrument that a Strategy is being applied?



                  On another totally different issue; I did check the Log and it says "Error on calling 'OnBarUpdate' method on bar 1: Object reference not set to an instance of an object." I fixed the issue.
                  Last edited by GTBrooks; 02-05-2019, 03:00 PM.

                  Comment


                    #10
                    Hello GTBrooks,

                    The code used to access the Risk template is not documented/supported, but it looks like you are making use of it. Remember that this code will access the risk templates that are saved on the platform and not real margins for the account that are determined by the broker. If you have a risk template configured with margins that match that of your broker's, accessing the risk template would give that margin. Your usage looks to be correct to reference the instrument that the strategy is applied to, but I would suggest printing the value so you can verify your expectations since the code is not documented/supported.

                    Runtime errors like "Object reference not set to an instance of an object." are general C# runtime errors. Googling these errors can point to other developer's posting about similar issues and can describe better how these errors are encountered and can be avoided.

                    Particularly, the error means that an object that is being referenced is null. You may add debugging prints to identify which line the error is coming from.

                    More information on these errors is also outlined here - https://ninjatrader.com/support/help...references.htm

                    Let us know if there is anything else we can do to help.
                    JimNinjaTrader Customer Service

                    Comment


                      #11
                      one last thing.

                      I need a line of code that gets the Instrument Initial Margin from a LIVE account

                      Comment


                        #12
                        Hello GTBrooks,

                        When you print the value returned by Risk.Get("NinjaTrader Brokerage Lifetime").ByMasterInstrument[Instrument.MasterInstrument].InitialMargin, do you get the Initial Margin for that instrument as configured in the Risk template?

                        There is not any NinjaScript that we could offer to fetch another value. (This code is also unsupported.) You would have to configure a custom Risk template and use that template to get different values.

                        Using the Risk Window - https://ninjatrader.com/support/help...isk_window.htm

                        Please let us know if you have any questions.
                        JimNinjaTrader Customer Service

                        Comment


                          #13
                          Hello JIM,

                          Yes, it does grab the Risk Template named "NinjaTrader Brokerage Lifetime" and returns the Initial Margin for the Instrument in the Risk Template.

                          I am interested in a line of code that does NOT grab "NinjaTrader Brokerage Lifetime" Initial Margin.

                          I am interested in a bit of code that would grab the Live Account Initial Margin. Can you provide a supported code for obtaining the Live Account Initial Margin of the Instrument the Strategy is trading?

                          Best Regards,
                          G.T.Brooks

                          Comment


                            #14
                            Hello GTBrooks,

                            There is no NinjaScript method that can fetch instrument margin settings from your broker. My recommendation would be to create your own Risk template that includes the values that you have confirmed with your broker, and then use that template instead of the "NinjaTrader Brokerage Lifetime" template in your script.
                            JimNinjaTrader Customer Service

                            Comment


                              #15
                              So you are telling me, there is no way to get the cost of the trade, until after I submit the trade?!? Insane!!!

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Waxavi, Today, 02:10 AM
                              0 responses
                              3 views
                              0 likes
                              Last Post Waxavi
                              by Waxavi
                               
                              Started by TradeForge, Today, 02:09 AM
                              0 responses
                              9 views
                              0 likes
                              Last Post TradeForge  
                              Started by Waxavi, Today, 02:00 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post Waxavi
                              by Waxavi
                               
                              Started by elirion, Today, 01:36 AM
                              0 responses
                              4 views
                              0 likes
                              Last Post elirion
                              by elirion
                               
                              Started by gentlebenthebear, Today, 01:30 AM
                              0 responses
                              4 views
                              0 likes
                              Last Post gentlebenthebear  
                              Working...
                              X