I am trying to write a strategy that monitors my unrealized P/L and closes out all positions when it reaches a certain threshold.
For example, if I set the profit threshold to 10 and the loss threshold to 5, when my unrealized P/L hits +$10 it closes all positions and similarly, if the unrealized P/L reaches -$5, it will close all positions.
Here is the code I have:
It compiles correctly and I can load it on the chart, but it never closes when the profit or loss threshold is hit in the unrealized P/L...
region Using declarations
using System;
using NinjaTrader.Cbi;
using NinjaTrader.NinjaScript;
#endregion
namespace NinjaTrader.NinjaScript.Strategies
{
public class AutoCloseOnPL : Strategy
{
// User-defined parameters for profit and loss thresholds
public double ProfitThreshold { get; set; } = 5.0; // Default to 5
public double LossThreshold { get; set; } = 10.0; // Default to 10
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = "Automatically closes all positions when P/L threshold is met.";
Name = "AutoCloseOnPL";
Calculate = Calculate.OnEachTick;
}
}
protected override void OnBarUpdate()
{
// Check if there's an open position
if (Position.MarketPosition == MarketPosition.Flat)
return;
// Get the current unrealized profit/loss
double unrealizedPL = Position.GetUnrealizedProfitLoss(PerformanceUnit.C urrency, Close[0]);
// Print unrealized P/L for debugging purposes
Print("Current Unrealized P/L: " + unrealizedPL);
// Check if unrealized P/L meets the threshold criteria for auto-closing positions
if (unrealizedPL >= ProfitThreshold || unrealizedPL <= -LossThreshold)
{
Print("P/L threshold met. Closing all positions.");
CloseAllPositions();
}
}
private void CloseAllPositions()
{
// Close any active positions based on their type
if (Position.MarketPosition == MarketPosition.Long)
{
Print("Closing long position.");
ExitLong();
}
else if (Position.MarketPosition == MarketPosition.Short)
{
Print("Closing short position.");
ExitShort();
}
}
}
}
Any help would be appreciated!

Comment