Announcement

Collapse
No announcement yet.

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)

        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.

            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.

                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

                    Comment


                      #25
                      Hi, I tried running this strategy on Market replay data . Basically I need a strategy that should flatten out position if my profit reaches $ 100 or loss reaches $20 whichever becomes first. I manually ran a trade but account reached $200 gain but did not flatten and continued the trade. Any idea why it is not flattening.

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by mlarocco, 06-20-2025, 11:12 AM
                      1 response
                      46 views
                      0 likes
                      Last Post NinjaTrader_ChelseaB  
                      Started by futurenow, 12-06-2021, 05:49 PM
                      19 responses
                      1,025 views
                      0 likes
                      Last Post Redders
                      by Redders
                       
                      Started by mathfrick2023, 05-08-2025, 12:51 PM
                      8 responses
                      139 views
                      0 likes
                      Last Post Yogaman
                      by Yogaman
                       
                      Started by several, 04-22-2025, 05:21 AM
                      1 response
                      296 views
                      0 likes
                      Last Post Lukasxgtx  
                      Started by NTEducationTeam, 06-12-2025, 02:30 PM
                      0 responses
                      54 views
                      0 likes
                      Last Post NTEducationTeam  
                      Working...
                      X