Announcement
Collapse
No announcement yet.
Partner 728x90
Collapse
NinjaTrader
Exit all positions at Loss or Profit
Collapse
X
-
Originally 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:
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
-
Originally 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:
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
-
Originally 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 mlarocco, 06-20-2025, 11:12 AM
|
1 response
46 views
0 likes
|
Last Post
|
||
Started by futurenow, 12-06-2021, 05:49 PM
|
19 responses
1,025 views
0 likes
|
Last Post
![]()
by Redders
06-16-2025, 06:02 AM
|
||
Started by mathfrick2023, 05-08-2025, 12:51 PM
|
8 responses
139 views
0 likes
|
Last Post
![]()
by Yogaman
06-14-2025, 06:01 PM
|
||
Started by several, 04-22-2025, 05:21 AM
|
1 response
296 views
0 likes
|
Last Post
![]()
by Lukasxgtx
06-13-2025, 06:00 AM
|
||
Started by NTEducationTeam, 06-12-2025, 02:30 PM
|
0 responses
54 views
0 likes
|
Last Post
![]() |
Comment