Announcement
Collapse
No announcement yet.
Partner 728x90
Collapse
NinjaTrader
Exit all positions at Loss or Profit
Collapse
X
-
#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
}
}
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
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)
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
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.
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
Comment
-
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
-
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 NullPointStrategies, Today, 05:17 AM
|
0 responses
46 views
0 likes
|
Last Post
|
||
|
Started by argusthome, 03-08-2026, 10:06 AM
|
0 responses
126 views
0 likes
|
Last Post
by argusthome
03-08-2026, 10:06 AM
|
||
|
Started by NabilKhattabi, 03-06-2026, 11:18 AM
|
0 responses
66 views
0 likes
|
Last Post
|
||
|
Started by Deep42, 03-06-2026, 12:28 AM
|
0 responses
42 views
0 likes
|
Last Post
by Deep42
03-06-2026, 12:28 AM
|
||
|
Started by TheRealMorford, 03-05-2026, 06:15 PM
|
0 responses
46 views
0 likes
|
Last Post
|

Comment