Announcement
Collapse
No announcement yet.
Partner 728x90
Collapse
NinjaTrader
Exit all positions at Loss or Profit
Collapse
X
-
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.
-
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
Leave a comment:
-
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
Leave a comment:
-
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,
-ChrisLLast edited by NinjaTrader_ChrisL; 07-20-2022, 10:04 AM.
Leave a comment:
-
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)" toOriginally posted by NinjaTrader_ChrisL View PostHi Steve, the OnBarUpdate method is processed from top to bottom, so place the Historical return at the very top of OnBarUpdate.
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
Leave a comment:
-
Hi Steve, the OnBarUpdate method is processed from top to bottom, so place the Historical return at the very top of OnBarUpdate.
Leave a comment:
-
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 lolOriginally posted by NinjaTrader_ChrisL View PostHi 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:
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:if(State == State.Historical) return;
Code:Print(Account.Get(AccountItem.CashValue, Currency.UsDollar)); Print(MyDailyProfitLevel); Print(""); //for spacing. if (Account.Get(AccountItem.CashValue, Currency.UsDollar) > MyDailyProfitLevel)
Leave a comment:
-
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:
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:if(State == State.Historical) return;
Code:Print(Account.Get(AccountItem.CashValue, Currency.UsDollar)); Print(MyDailyProfitLevel); Print(""); //for spacing. if (Account.Get(AccountItem.CashValue, Currency.UsDollar) > MyDailyProfitLevel)
- Likes 1
Leave a comment:
-
#region Using declarationsOriginally posted by Steve4616 View PostYou bet, thanks!
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
}
}
Leave a comment:
-
You bet, thanks!Originally posted by NinjaTrader_ChrisL View PostHi Steve, Could you export and post the code you are using so I can test it?
Kind regards.
Leave a comment:
-
Hi Steve, Could you export and post the code you are using so I can test it?
Kind regards.
Leave a comment:
-
Thanks Chris,Originally posted by NinjaTrader_ChrisL View PostHi, thanks for the follow up. If a strategy is disabled immediately, check the Log tab of the Control Center for any errors. There is likely an exception being thrown.
Kind regards,
-ChrisL
It only shows this, no errors. Also there were no trades open and not trades in the Sim101 account today so the PL is 0, thanks
Leave a comment:
-
Hi, thanks for the follow up. If a strategy is disabled immediately, check the Log tab of the Control Center for any errors. There is likely an exception being thrown.
Kind regards,
-ChrisL
Leave a comment:
-
Hi Chris,Originally posted by NinjaTrader_ChrisL View PostHi Steve4616, thanks for posting. The SystemPerformance class will only provide the performance metrics of the single strategy it is being called from, not the entire account. Each strategy needs to check its own PnL value and close its position based on that calculation. You can get Account based metrics by using the Get method:
Kind regards,
-ChrisL
I tried it out and it compiles without errors, but immediately disables. Also, if i have any other strategies enabled on the account, it immediately flattens also. I had the profit target and stop set at 200 and -200 and the sim101 account was down $25 and no open positions and it still disabled immediately. Does anything jump out to you that would cause this? Thanks again
Leave a comment:
-
Thanks Chris, I will look into this, might be the missing link, cheersOriginally posted by NinjaTrader_ChrisL View PostHi Steve4616, thanks for posting. The SystemPerformance class will only provide the performance metrics of the single strategy it is being called from, not the entire account. Each strategy needs to check its own PnL value and close its position based on that calculation. You can get Account based metrics by using the Get method:
Kind regards,
-ChrisL
Leave a comment:
Latest Posts
Collapse
| Topics | Statistics | Last Post | ||
|---|---|---|---|---|
|
Started by Mindset, 04-21-2026, 06:46 AM
|
0 responses
87 views
0 likes
|
Last Post
by Mindset
04-21-2026, 06:46 AM
|
||
|
Started by M4ndoo, 04-20-2026, 05:21 PM
|
0 responses
132 views
0 likes
|
Last Post
by M4ndoo
04-20-2026, 05:21 PM
|
||
|
Started by M4ndoo, 04-19-2026, 05:54 PM
|
0 responses
65 views
0 likes
|
Last Post
by M4ndoo
04-19-2026, 05:54 PM
|
||
|
Started by cmoran13, 04-16-2026, 01:02 PM
|
0 responses
118 views
0 likes
|
Last Post
by cmoran13
04-16-2026, 01:02 PM
|
||
|
Started by PaulMohn, 04-10-2026, 11:11 AM
|
0 responses
67 views
0 likes
|
Last Post
by PaulMohn
04-10-2026, 11:11 AM
|

Leave a comment: