Any help would be greatly appreciated.
//This namespace holds Strategies in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies
{
public class SampleMACrossoverWithATRstops : Strategy
{
private SMA smaFast;
private SMA smaSlow;
private ATR atr;
private double atrStopValueLong;
private double atrStopValueShort;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = "MA Crossover with ATR Trailing Stops";
Name = "SampleMACrossoverWithATRstops";
Fast = 9;
Slow = 21;
AtrPeriod = 14;
AtrMultiplier = 2;
IsInstantiatedOnEachOptimizationIteration = false;
// Adding session close exit properties
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30; // Exits 30 seconds before session close
}
else if (State == State.DataLoaded)
{
smaFast = SMA(Fast);
smaSlow = SMA(Slow);
atr = ATR(AtrPeriod);
smaFast.Plots[0].Brush = Brushes.Snow;
smaSlow.Plots[0].Brush = Brushes.Yellow;
AddChartIndicator(smaFast);
AddChartIndicator(smaSlow);
}
}
protected override void OnBarUpdate()
{
if (CurrentBars[0] < Slow) return;
double atrValue = atr[0] * AtrMultiplier;
if (CrossAbove(smaFast, smaSlow, 1))
{
EnterLong();
atrStopValueLong = Close[0] - atrValue;
Draw.Line(this, "AtrTrailLong" + CurrentBar, CurrentBar, atrStopValueLong, CurrentBar - 1, atrStopValueLong, Brushes.Green);
Draw.ArrowUp(this, "EnterLongArrow" + CurrentBar, false, 0, Low[0] - 2 * TickSize, Brushes.Green);
}
else if (CrossBelow(smaFast, smaSlow, 1))
{
EnterShort();
atrStopValueShort = Close[0] + atrValue;
Draw.Line(this, "AtrTrailShort" + CurrentBar, CurrentBar, atrStopValueShort, CurrentBar - 1, atrStopValueShort, Brushes.Red);
Draw.ArrowDown(this, "EnterShortArrow" + CurrentBar, false, 0, High[0] + 2 * TickSize, Brushes.Red);
}
// Update the trailing stop for LONG positions
if (Position.MarketPosition == MarketPosition.Long)
{
if (Close[0] - atrValue > atrStopValueLong)
{
atrStopValueLong = Close[0] - atrValue;
ExitLongStopMarket(atrStopValueLong, "ATR Trailing Stop Long");
Draw.ArrowDown(this, "ExitLongArrow" + CurrentBar, false, 0, High[0] + TickSize, Brushes.Red);
}
}
// Update the trailing stop for SHORT positions
if (Position.MarketPosition == MarketPosition.Short)
{
if (Close[0] + atrValue < atrStopValueShort)
{
atrStopValueShort = Close[0] + atrValue;
ExitShortStopMarket(atrStopValueShort, "ATR Trailing Stop Short");
Draw.ArrowUp(this, "ExitShortArrow" + CurrentBar, false, 0, Low[0] - TickSize, Brushes.Green);
}
}
}

Comment