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

Exit all positions at Loss or Profit

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

    #16
    Originally posted by NinjaTrader_ChrisL View Post
    Hi Steve, Could you export and post the code you are using so I can test it?

    Kind regards.
    You bet, thanks!
    Attached Files

    Comment


      #17
      Originally posted by Steve4616 View Post
      You bet, thanks!
      #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;
      using System.Collections.ObjectModel;
      #endregion

      //This namespace holds Strategies in this folder and is required. Do not change it.
      namespace NinjaTrader.NinjaScript.Strategies
      {
      public class CumProfitPlusAccountUnrealizedPnLFlatten : Strategy
      {
      private Account myAccount;
      private double CurrentPNL;

      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"Enter the description for your new custom Strategy here.";
      Name = "CumProfitPlusAccountUnrealizedPnLFlatten";
      Calculate = Calculate.OnEachTick;
      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 = false;
      RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
      StopTargetHandling = StopTargetHandling.PerEntryExecution;
      BarsRequiredToTrade = 1;
      // Disable this property for performance gains in Strategy Analyzer optimizations
      // See the Help Guide for additional information
      IsInstantiatedOnEachOptimizationIteration = true;
      MyDailyStopLevel = -10;
      MyDailyProfitLevel = 10;
      // Find our Sim101 account
      lock (Account.All)
      myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");
      }
      else if (State == State.Configure)
      {
      }
      }

      protected override void OnBarUpdate()
      {
      // Evaluates to see if the account has more than Profit targt/stop loss

      // Set 1
      if (Account.Get(AccountItem.CashValue, Currency.UsDollar) > MyDailyProfitLevel)
      {
      Account.Flatten(new [] { Instrument.GetInstrument("NQ 09-22")});
      }

      // Set 2
      if (Account.Get(AccountItem.CashValue, Currency.UsDollar) < MyDailyStopLevel)
      {
      Account.Flatten(new [] { Instrument.GetInstrument("NQ 09-22") });
      }
      }

      #region Properties
      [NinjaScriptProperty]
      [Range(-999999, int.MaxValue)]
      [Display(Name="MyDailyStopLevel", Order=1, GroupName="Parameters")]
      public int MyDailyStopLevel
      { get; set; }

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

      }
      }

      Comment


        #18
        Hi Steve, thanks for posting that. First, you should ignore the historical data since you are running this code in OnBarUpdate, it will run on every historical bar on the chart:

        Code:
        if(State == State.Historical) 
           return;
        It's not disabling for me when I run it. But the condition is triggering on every tick, check your code to make sure its doing what you want it to do by printing out the values you are using. This is the best way to debug a strategy that is not acting the way you want:

        Code:
        Print(Account.Get(AccountItem.CashValue, Currency.UsDollar));
        Print(MyDailyProfitLevel);
        Print(""); //for spacing. 
        if (Account.Get(AccountItem.CashValue, Currency.UsDollar) > MyDailyProfitLevel)
        Chris L.NinjaTrader Customer Service

        Comment


          #19
          Originally posted by NinjaTrader_ChrisL View Post
          Hi Steve, thanks for posting that. First, you should ignore the historical data since you are running this code in OnBarUpdate, it will run on every historical bar on the chart:

          Code:
          if(State == State.Historical)
          return;
          It's not disabling for me when I run it. But the condition is triggering on every tick, check your code to make sure its doing what you want it to do by printing out the values you are using. This is the best way to debug a strategy that is not acting the way you want:

          Code:
          Print(Account.Get(AccountItem.CashValue, Currency.UsDollar));
          Print(MyDailyProfitLevel);
          Print(""); //for spacing.
          if (Account.Get(AccountItem.CashValue, Currency.UsDollar) > MyDailyProfitLevel)
          Thanks Chris. I added the print code, but I'm not sure what I should do with the "State.Historical" code. Do i input it? I don't see it in the strategy to remove it. Sorry, I'm a strategy builder guy and not much for this coding stuff lol

          Comment


            #20
            Hi Steve, the OnBarUpdate method is processed from top to bottom, so place the Historical return at the very top of OnBarUpdate.
            Chris L.NinjaTrader Customer Service

            Comment


              #21
              Originally posted by NinjaTrader_ChrisL View Post
              Hi Steve, the OnBarUpdate method is processed from top to bottom, so place the Historical return at the very top of OnBarUpdate.
              Thanks Chris. I tired that but still same issue. So i thought maybe it was the "CashValue" part, so I changed "if(Account.Get(AccountItem.CashValue, Currency.UsDollar) > MyDailyProfitLevel)" to  

              CurrentPNL = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit;

              if (CurrentPNL + PositionAccount.GetUnrealizedProfitLoss(Performanc eUnit.Currency, Close[0]) < MyDailyStopLevel)

              But then I got these 2 errors and I tried everything to get rid of them but no luck. I'm not really sure what to callout for the Account.Get for TotalPNL(Realized + Unrealized), maybe thats what the "CashValue" represents? I noticed that I could callout "NetLiquidation" but my real account shows that as $0.00 always, no matter what. I have 3 PA accounts from APEX and a couple trial accounts and they show "NetLiquidation" as the totalPNL with fees included. Not sure why my real Ironbeam account won't show it like that though.

              Sorry fro so many questions, but I really need to figure this out, and it's been a struggle so far, thanks again
              Attached Files

              Comment


                #22
                Hi Steve, You will need to practice writing C# code and learning the syntax. There are missing parentheses at the end of your statement. If you are just beginning writing scripts, I would recommend getting familiar with the managed approach strategy code before going into unmanaged Account based submissions. We will not be able to spend too much time debugging or fixing code through forum tickets. All of our tools and educational resources are documented here:
                https://ninjatrader.com/support/help...injascript.htm

                There is a grid here showing data providers that we support and what account data they send to the platform:


                Kind regards,
                -ChrisL
                Last edited by NinjaTrader_ChrisL; 07-20-2022, 10:04 AM.
                Chris L.NinjaTrader Customer Service

                Comment


                  #23
                  Thanks Chris. So i did a bunch of reading from the links you posted. Basically, because I don't use NinjaTrader Brokerage(Not available to Canadians) there's no way for me to call out the Total PnL or the Realized + Unrealized of a single account to make a simple Account profit target and account stop loss. Maybe that explains why I can't even find a third party that sells it or anything. It seems like such a simple and i would think sought after function, yet it's impossible from what I read

                  Comment


                    #24
                    Hello Steve4616,

                    Unrealized PnL could be calculated from the current market price, the position's average entry price.

                    We also offer Position.GetUnrealizedProfitLoss and PositionAccount.GetUnrealizedProfitLoss.





                    You could also consider looping through each open position in Account.Positions to check the unrealized PnL from each open position on the account.

                    Account.Positions - https://ninjatrader.com/support/help...ns_account.htm
                    JimNinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by DJ888, 04-16-2024, 06:09 PM
                    4 responses
                    11 views
                    0 likes
                    Last Post DJ888
                    by DJ888
                     
                    Started by terofs, Today, 04:18 PM
                    0 responses
                    5 views
                    0 likes
                    Last Post terofs
                    by terofs
                     
                    Started by nandhumca, Today, 03:41 PM
                    0 responses
                    5 views
                    0 likes
                    Last Post nandhumca  
                    Started by The_Sec, Today, 03:37 PM
                    0 responses
                    3 views
                    0 likes
                    Last Post The_Sec
                    by The_Sec
                     
                    Started by GwFutures1988, Today, 02:48 PM
                    1 response
                    9 views
                    0 likes
                    Last Post NinjaTrader_Clayton  
                    Working...
                    X