Here is what it wrote, can you rate this code/strategy 1-100 and explain why ?
#region Using declarations
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.IO; // Required for file logging
#endregion
//This namespace holds Strategies in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies.Futures
{
[Gui.StrategyEditor.Option("Description", "Intraday ES/MES Morning Rush Strategy (9:30-11:30 EST) using Multi-Timeframe Analysis and Dynamic Risk Management.")]
[Gui.StrategyEditor.Option("Name", "MorningRushMTF_ES")]
[Gui.StrategyEditor.Option("Calculate", Calculate.OnBarClose)] // Or OnEachTick/OnPriceChange depending on needs
[Gui.StrategyEditor.Option("EntriesPerDirection", 1)]
[Gui.StrategyEditor.Option("EntryHandling", EntryHandling.AllEntries)]
[Gui.StrategyEditor.Option("IsExitOnSessionCloseStrategy", true)] // Ensures flattening at session end
[Gui.StrategyEditor.Option("ExitOnSessionCloseSeconds", 30)]
[Gui.StrategyEditor.Option("IsFillLimitOnTouch", false)]
[Gui.StrategyEditor.Option("MaximumBarsLookBack", MaximumBarsLookBack.Infinite)] // Adjust if memory becomes an issue
[Gui.StrategyEditor.Option("OrderFillResolution", OrderFillResolution.Standard)]
[Gui.StrategyEditor.Option("Slippage", 2)] // Slippage in ticks (adjust based on instrument/market)
[Gui.StrategyEditor.Option("StartBehavior", StartBehavior.WaitUntilFlat)]
[Gui.StrategyEditor.Option("TimeInForce", TimeInForce.Gtc)]
[Gui.StrategyEditor.Option("TraceOrders", true)] // Enable detailed order tracing
[Gui.StrategyEditor.Option("RealtimeErrorHandling", RealtimeErrorHandling.StopCancelClose)] // Robust error handling
[Gui.StrategyEditor.Option("StopTargetHandling", StopTargetHandling.PerEntryExecution)]
[Gui.StrategyEditor.Option("BarsRequiredToTrade", 100)] // Ensure enough data loaded
// Disable this property for performance gains in production but enable it for debugging development
[Gui.StrategyEditor.Option("IsInstantiatedOnEachOptimizationIteration", false)] // Crucial for Walk-Forward
public class MorningRushMTF_ES : Strategy
{
#region Strategy Variables & Parameters
// --- User Configurable Parameters ---
private double accountCapital = 10000;
private double maxRiskPercent = 1.0; // Max % of account capital to risk per trade
private int atrPeriod = 14; // ATR period for volatility calculation
private double atrStopMultiplier = 2.0; // Multiplier for ATR based Stop Loss
private double atrProfitMultiplier = 3.0; // Multiplier for ATR based Profit Target
private bool useTrailingStop = true;
private double trailingStopMultiplier = 1.5; // Multiplier for ATR based Trailing Stop activation
private bool enablePartialProfits = true;
private int partialProfitContracts = 1; // Number of contracts to take partial profit on
private double partialProfitMultiplier = 1.5; // ATR Multiplier for first partial profit target
private TimeSpan startTime = new TimeSpan(9, 30, 0); // 9:30 AM EST
private TimeSpan endTime = new TimeSpan(11, 30, 0); // 11:30 AM EST
private TimeZoneInfo exchangeTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); // Ensure this matches NT chart setting
private int consecutiveLossCooldownThreshold = 3; // Cooldown after N consecutive losses
private int consecutiveWinCooldownThreshold = 5; // Cooldown after N consecutive wins (optional)
private int cooldownMinutes = 15; // Duration of cooldown period
private bool enableTrading = true; // Master switch to enable/disable trading logic
private string logFileName = "MorningRushMTF_ES_TradeLog.csv"; // Log file name
// --- Multi-Timeframe Periods ---
// Primary chart timeframe is assumed to be the fastest (e.g., 1-min)
private int tf1Period = 5; // e.g., 5 minutes
private int tf2Period = 15; // e.g., 15 minutes
private int tf3Period = 60; // e.g., 60 minutes
// --- Internal Strategy State Variables ---
private bool isTradingWindowActive = false;
private double currentAtr = 0;
private double stopLossPrice = 0;
private double profitTargetPrice = 0;
private double partialTargetPrice = 0;
private string currentEntrySignalName = ""; // Track entry for logging/management
private int consecutiveLosses = 0;
private int consecutiveWins = 0;
private bool isCoolingDown = false;
private DateTime coolDownEndTime = DateTime.MinValue;
private double lastTradeProfit = 0; // Track profit of the last closed trade
private int lastTradeSize = 0; // Track size of the last trade
private StreamWriter logWriter = null; // For logging trades to CSV
private object logLock = new object(); // Thread safety for logging
// --- Multi-Timeframe Indicator Instances ---
// Primary Timeframe (BarsArray[0]) - Assuming 1 Min for this example
private SMA smaFastPrimary;
private SMA smaSlowPrimary;
private RSI rsiPrimary;
private ATR atrPrimary; // Used for primary timeframe volatility & stops
// Timeframe 1 (BarsArray[1]) - e.g., 5 Min
private SMA smaTf1;
private RSI rsiTf1;
private ATR atrTf1;
// Add other TF1 indicators as needed
// Timeframe 2 (BarsArray[2]) - e.g., 15 Min
private SMA smaTf2;
private ADX adxTf2; // Example: ADX for trend strength
// Add other TF2 indicators as needed
// Timeframe 3 (BarsArray[3]) - e.g., 60 Min
private SMA smaTf3;
// Add other TF3 indicators as needed
#endregion
#region OnStateChange() - Initialization & Cleanup
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Intraday ES/MES Morning Rush Strategy (9:30-11:30 EST) using Multi-Timeframe Analysis and Dynamic Risk Management.";
Name = "MorningRushMTF_ES";
Calculate = Calculate.OnBarClose; // Or OnEachTick if higher resolution needed
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = false;
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix; // Or Infinite, adjust based on indicator needs
OrderFillResolution = OrderFillResolution.Standard;
Slippage = 2; // In Ticks - Adjust for ES/MES
StartBehavior = StartBehavior.WaitUntilFlat;
TimeInForce = TimeInForce.Gtc;
TraceOrders = true;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose; // Important for live trading
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 100; // Minimum bars needed on primary series
IsInstantiatedOnEachOptimizationIteration = false; // Enable for WFO, disable for normal backtest/live
}
else if (State == State.Configure)
{
// --- Add Secondary Data Series for Multi-Timeframe Analysis ---
// IMPORTANT: Ensure the primary chart timeframe is the *lowest* timeframe needed (e.g., 1 min)
// Add higher timeframes here. Index corresponds to BarsArray[index].
AddDataSeries(BarsPeriodType.Minute, tf1Period); // BarsArray[1] = 5 min
AddDataSeries(BarsPeriodType.Minute, tf2Period); // BarsArray[2] = 15 min
AddDataSeries(BarsPeriodType.Minute, tf3Period); // BarsArray[3] = 60 min
// Set default order properties
SetStopLoss(CalculationMode.Price, 0); // Initialize stop loss (price will be set dynamically)
SetProfitTarget(CalculationMode.Price, 0); // Initialize profit target (price will be set dynamically)
if (UseTrailingStop)
SetTrailStop(CalculationMode.Price, 0); // Initialize trail stop (price will be set dynamically)
// --- Setup Logging ---
// Initialize log file only once, typically in Configure or Historical state change
if (logWriter == null && !string.IsNullOrEmpty(LogFileName))
{
try
{
string filePath = Path.Combine(NinjaTrader.Core.Globals.UserDataDir, LogFileName);
// Use append mode if file exists, otherwise create new
logWriter = new StreamWriter(filePath, true);
// Write header if file is newly created or empty
if (new FileInfo(filePath).Length == 0)
{
logWriter.WriteLine("Timestamp,TradeIndex,Action,Type,SignalName,Quantity,EntryPrice,ExitPrice,StopPrice,TargetPrice,ProfitLoss,CumulativeProfit,ConsecutiveLosses,ConsecutiveWins,ATR,PositionSizeReason");
}
logWriter.AutoFlush = true; // Ensure data is written promptly
}
catch (Exception e)
{
Print($"Error initializing log file '{LogFileName}': {e.Message}");
logWriter = null; // Prevent further attempts if initialization fails
}
}
}
else if (State == State.DataLoaded)
{
// --- Initialize Indicators for ALL Timeframes ---
// Ensure indicator periods are sensible for their timeframes
// Primary Timeframe (e.g., 1 Min) - BarsArray[0]
smaFastPrimary = SMA(5); // Fast MA for crossover
smaSlowPrimary = SMA(20); // Slow MA for trend context
rsiPrimary = RSI(14, 3);
atrPrimary = ATR(AtrPeriod); // ATR on primary for stops/targets
// Timeframe 1 (e.g., 5 Min) - BarsArray[1]
smaTf1 = SMA(BarsArray[1], 20); // Example: 20-period SMA on 5-min chart
rsiTf1 = RSI(BarsArray[1], 14, 3);
atrTf1 = ATR(BarsArray[1], AtrPeriod);
// Add other TF1 indicators: Add(BarsArray[1], Indicator(...));
// Timeframe 2 (e.g., 15 Min) - BarsArray[2]
smaTf2 = SMA(BarsArray[2], 50); // Example: Longer term trend on 15-min
adxTf2 = ADX(BarsArray[2], 14); // Example: Trend strength on 15-min
// Add other TF2 indicators: Add(BarsArray[2], Indicator(...));
// Timeframe 3 (e.g., 60 Min) - BarsArray[3]
smaTf3 = SMA(BarsArray[3], 20); // Example: Trend direction on 60-min
// Add other TF3 indicators: Add(BarsArray[3], Indicator(...));
// Add plots for visualization if desired (optional)
AddChartIndicator(smaFastPrimary);
AddChartIndicator(smaSlowPrimary);
AddChartIndicator(rsiPrimary);
AddChartIndicator(atrPrimary);
}
else if (State == State.Terminated)
{
// --- Cleanup ---
// Dispose of any resources like the log writer
lock (logLock)
{
if (logWriter != null)
{
try
{
logWriter.Flush();
logWriter.Close();
logWriter.Dispose();
}
catch (Exception e)
{
Print($"Error closing log file: {e.Message}");
}
finally
{
logWriter = null;
}
}
}
// Dispose indicators explicitly if necessary (rarely needed as NT manages them)
}
}
#endregion
#region OnBarUpdate() - Core Trading Logic
protected override void OnBarUpdate()
{
// --- Pre-Trade Checks ---
// Ensure enough bars loaded on all series (check CurrentBar for each BarsArray index)
if (CurrentBars[0] < BarsRequiredToTrade || CurrentBars[1] < 20 || CurrentBars[2] < 20 || CurrentBars[3] < 20)
{
//Print($"Waiting for sufficient bars: P={CurrentBars[0]}, TF1={CurrentBars[1]}, TF2={CurrentBars[2]}, TF3={CurrentBars[3]}");
return;
}
// Check if master trading switch is enabled
if (!EnableTrading)
return;
// --- Time Window Check ---
DateTime chartTime = Times[0][0]; // Time of the current primary bar
DateTime exchangeTime = TimeZoneInfo.ConvertTime(chartTime, TimeZoneInfo.Local, exchangeTimeZone); // Convert chart time to exchange time
// Check if within the allowed trading window (9:30 AM to 11:30 AM EST)
isTradingWindowActive = (exchangeTime.TimeOfDay >= StartTime && exchangeTime.TimeOfDay < EndTime);
// --- Cooldown Check ---
if (isCoolingDown)
{
if (exchangeTime >= coolDownEndTime)
{
isCoolingDown = false; // Cooldown period finished
Print($"{exchangeTime}: Cooldown period ended.");
}
else
{
return; // Still in cooldown, do nothing
}
}
// --- Flatten Position Outside Trading Window ---
// If it's past the end time and we still hold a position, flatten immediately.
if (Position.MarketPosition != MarketPosition.Flat && exchangeTime.TimeOfDay >= EndTime)
{
Print($"{exchangeTime}: Outside trading window ({StartTime} - {EndTime} EST). Flattening position.");
if (Position.MarketPosition == MarketPosition.Long) ExitLong("Window End Exit", Position.AveragePrice);
if (Position.MarketPosition == MarketPosition.Short) ExitShort("Window End Exit", Position.AveragePrice);
ResetTradeState(); // Reset counters after flattening
return; // Exit after flattening
}
// --- Main Logic - Only Run During Trading Window ---
if (isTradingWindowActive)
{
// Calculate current volatility (ATR) on the primary timeframe
currentAtr = atrPrimary[0];
if (currentAtr <= 0) currentAtr = Instrument.MasterInstrument.TickSize; // Avoid zero ATR
// --- Position Management ---
if (Position.MarketPosition != MarketPosition.Flat)
{
// Dynamic Stop Loss Adjustment (Example: simple trail based on ATR)
ManageStopLoss();
// Trailing Stop Logic
ManageTrailingStop();
// Partial Profit Target Management
ManagePartialProfits();
// Check for Exit Signals (e.g., counter-trend signals on lower timeframes, target hit already handled by NT)
CheckExitSignal();
}
// --- Entry Logic ---
else // Only look for new entries if flat
{
// Calculate position size BEFORE checking for entry signals
int calculatedPositionSize = CalculatePositionSize();
if (calculatedPositionSize <= 0)
{
// Log reason if size is zero (e.g., insufficient capital, high vol)
// Print($"{exchangeTime}: Position size calculated as 0. Cannot trade.");
return;
}
// Apply post-trade adjustments (optional, can be refined)
if (lastTradeProfit < 0 && consecutiveLosses > 0) // After a loss
{
// Reduce size or wait for better signal (example: simple size reduction)
// calculatedPositionSize = Math.Max(1, calculatedPositionSize / 2); // Reduce by half, min 1
// Print($"{exchangeTime}: Reducing size after loss. New size: {calculatedPositionSize}");
}
else if (lastTradeProfit > 0 && consecutiveWins > 0) // After a win
{
// Consider scaling in slightly (be cautious) or maintain size
// Example: Maintain size calculated by risk %
// Print($"{exchangeTime}: Maintaining size after win. Size: {calculatedPositionSize}");
}
// Check for Entry Signals (using multi-timeframe data)
string longSignal = CheckLongEntrySignal();
if (!string.IsNullOrEmpty(longSignal))
{
currentEntrySignalName = longSignal; // Store signal name for logging/management
SetTradeTargets(true, calculatedPositionSize); // Set SL/TP before entry
EnterLong(calculatedPositionSize, "Long Entry");
Print($"{exchangeTime}: ENTER LONG Signal: {longSignal}, Size: {calculatedPositionSize}, Entry: {GetCurrentAsk()}, SL: {stopLossPrice}, TP: {profitTargetPrice}");
LogTrade("Enter", "Long", currentEntrySignalName, calculatedPositionSize, GetCurrentAsk(), 0, stopLossPrice, profitTargetPrice, ""); // Log entry attempt
}
else
{
string shortSignal = CheckShortEntrySignal();
if (!string.IsNullOrEmpty(shortSignal))
{
currentEntrySignalName = shortSignal;
SetTradeTargets(false, calculatedPositionSize);
EnterShort(calculatedPositionSize, "Short Entry");
Print($"{exchangeTime}: ENTER SHORT Signal: {shortSignal}, Size: {calculatedPositionSize}, Entry: {GetCurrentBid()}, SL: {stopLossPrice}, TP: {profitTargetPrice}");
LogTrade("Enter", "Short", currentEntrySignalName, calculatedPositionSize, GetCurrentBid(), 0, stopLossPrice, profitTargetPrice, ""); // Log entry attempt
}
}
}
}
else
{
// Optional: Add logic for outside the main trading window if needed,
// but typically we just wait or flatten as handled above.
}
}
#endregion
#region Entry/Exit Signal Logic (Placeholders - *** REPLACE WITH YOUR LOGIC ***)
// Returns the name of the signal if conditions met, otherwise empty string
private string CheckLongEntrySignal()
{
// --- THIS IS A PLACEHOLDER - REPLACE WITH YOUR DETAILED MULTI-TIMEFRAME LOGIC ---
// Example: Basic Trend Following with Pullback Confirmation
bool tf3TrendUp = Close[0] > smaTf3[0]; // 60min Trend (Price > SMA)
bool tf2TrendStrong = adxTf2[0] > 25; // 15min Trend Strength (ADX > 25)
bool tf1Pullback = Close[0] > smaTf1[0] && Low[0] <= smaTf1[0]; // 5min pullback to SMA
bool primaryEntry = CrossAbove(smaFastPrimary, smaSlowPrimary, 1); // 1min fast MA crosses above slow MA
bool primaryMomentum = rsiPrimary[0] > 55; // 1min RSI confirmation
// Combine conditions (adjust logic as needed)
if (tf3TrendUp && tf2TrendStrong && primaryEntry && primaryMomentum) // Removed tf1Pullback for simpler example
{
// Add Volume checks, Price Action Patterns (e.g., Engulfing, Pin Bar), S/R checks here
// Example: Check if volume on primary is above average
// bool volumeSpike = Volume[0] > SMA(Volume, 20)[0] * 1.5;
// if (volumeSpike) return "TrendFollow_VolConf";
return "TrendFollow_MACross_RSI"; // Signal Name
}
return string.Empty; // No signal
}
// Returns the name of the signal if conditions met, otherwise empty string
private string CheckShortEntrySignal()
{
// --- THIS IS A PLACEHOLDER - REPLACE WITH YOUR DETAILED MULTI-TIMEFRAME LOGIC ---
// Example: Basic Trend Following with Pullback Confirmation
bool tf3TrendDown = Close[0] < smaTf3[0]; // 60min Trend (Price < SMA)
bool tf2TrendStrong = adxTf2[0] > 25; // 15min Trend Strength (ADX > 25)
bool tf1Pullback = Close[0] < smaTf1[0] && High[0] >= smaTf1[0]; // 5min pullback to SMA
bool primaryEntry = CrossBelow(smaFastPrimary, smaSlowPrimary, 1); // 1min fast MA crosses below slow MA
bool primaryMomentum = rsiPrimary[0] < 45; // 1min RSI confirmation
// Combine conditions (adjust logic as needed)
if (tf3TrendDown && tf2TrendStrong && primaryEntry && primaryMomentum) // Removed tf1Pullback for simpler example
{
// Add Volume checks, Price Action Patterns (e.g., Engulfing, Pin Bar), S/R checks here
return "TrendFollow_MACross_RSI"; // Signal Name
}
return string.Empty; // No signal
}
private void CheckExitSignal()
{
// --- PLACEHOLDER FOR DISCRETIONARY EXIT LOGIC ---
// Example: Exit if RSI crosses back overbought/oversold against the trend,
// or if a significant counter-trend bar forms on a higher timeframe.
// Note: Basic Stop Loss / Profit Target / Trailing Stop are handled by NT or Manage methods.
if (Position.MarketPosition == MarketPosition.Long)
{
// Example: Exit long if 15min closes below its SMA
// if (Close[0] < smaTf2[0]) // Check using primary series price against TF2 SMA
// {
// ExitLong("TF2 Trend Break", Position.AveragePrice);
// LogTrade("Exit", "Long", "TF2 Trend Break", Position.Quantity, GetCurrentBid(), 0, stopLossPrice, profitTargetPrice, "");
// ResetTradeState();
// }
}
else if (Position.MarketPosition == MarketPosition.Short)
{
// Example: Exit short if 15min closes above its SMA
// if (Close[0] > smaTf2[0])
// {
// ExitShort("TF2 Trend Break", Position.AveragePrice);
// LogTrade("Exit", "Short", "TF2 Trend Break", Position.Quantity, GetCurrentAsk(), 0, stopLossPrice, profitTargetPrice, "");
// ResetTradeState();
// }
}
}
#endregion
#region Risk & Position Sizing
private int CalculatePositionSize()
{
if (AccountCapital <= 0 || MaxRiskPercent <= 0 || currentAtr <= 0)
{
Print($"Position sizing skipped: Capital={AccountCapital}, Risk%={MaxRiskPercent}, ATR={currentAtr}");
LogTrade("Info", "System", "PositionSizeCalc", 0, 0, 0, 0, 0, "Invalid input for size calc (Capital/Risk/ATR)");
return 0; // Cannot calculate size with invalid inputs
}
// 1. Calculate Risk Amount in Account Currency
double riskAmount = AccountCapital * (MaxRiskPercent / 100.0);
// 2. Calculate Initial Stop Loss Distance in Points (based on ATR)
double stopDistancePoints = currentAtr * AtrStopMultiplier;
if (stopDistancePoints < Instrument.MasterInstrument.TickSize * 2) // Ensure minimum stop distance (e.g., 2 ticks)
{
stopDistancePoints = Instrument.MasterInstrument.TickSize * 2;
// Print($"ATR stop distance too small ({currentAtr * AtrStopMultiplier}), using minimum {stopDistancePoints}");
}
// 3. Calculate Risk Per Contract (Point Value * Stop Distance)
double pointValue = Instrument.MasterInstrument.PointValue;
double riskPerContract = stopDistancePoints * pointValue;
if (riskPerContract <= 0)
{
Print($"Position sizing skipped: Risk per contract is zero or negative ({riskPerContract}). PointValue={pointValue}, StopDist={stopDistancePoints}");
LogTrade("Info", "System", "PositionSizeCalc", 0, 0, 0, 0, 0, "Risk per contract is zero or negative");
return 0;
}
// 4. Calculate Position Size (Risk Amount / Risk Per Contract)
// Use Floor to ensure we don't exceed max risk percentage
int positionSize = (int)Math.Floor(riskAmount / riskPerContract);
// 5. Minimum Position Size Check
if (positionSize < 1)
{
// Print($"Calculated position size ({positionSize}) is less than 1. Cannot trade. RiskAmount={riskAmount:C}, RiskPerContract={riskPerContract:C}");
LogTrade("Info", "System", "PositionSizeCalc", 0, 0, 0, 0, 0, $"Calculated size {positionSize} < 1 (RiskAmt={riskAmount:F2}, RiskPerContr={riskPerContract:F2})");
positionSize = 0; // Ensure it's 0 if less than 1
}
// Optional: Add margin checks here if needed, though risk-based sizing often suffices.
// double requiredMargin = positionSize * Instrument.MasterInstrument.Margin;
// double availableFunds = Account.Get(AccountItem.BuyingPower, Currency.Usd); // Check buying power in real-time/backtest approximation
// if (requiredMargin > availableFunds) { ... reduce size ... }
string reason = $"Size={positionSize} (Cap={AccountCapital:F0}, Risk%={MaxRiskPercent}, RiskAmt={riskAmount:F2}, ATR={currentAtr:F2}, StopPts={stopDistancePoints:F2}, PtVal={pointValue}, Risk/Contr={riskPerContract:F2})";
// Print(reason); // Log detailed calculation if needed
// LogTrade("Info", "System", "PositionSizeCalc", positionSize, 0, 0, 0, 0, reason); // Log the detailed reason
return positionSize;
}
private void SetTradeTargets(bool isLong, int quantity)
{
if (quantity <= 0 || currentAtr <= 0) return;
double entryPrice = isLong ? GetCurrentAsk() : GetCurrentBid(); // Approximate entry for calc
if (entryPrice <= 0) entryPrice = Close[0]; // Fallback if market data not ready
double stopDistancePoints = currentAtr * AtrStopMultiplier;
stopDistancePoints = Math.Max(stopDistancePoints, Instrument.MasterInstrument.TickSize * 2); // Min stop distance
double profitDistancePoints = currentAtr * AtrProfitMultiplier;
profitDistancePoints = Math.Max(profitDistancePoints, Instrument.MasterInstrument.TickSize * 2); // Min target distance
double partialProfitDistancePoints = 0;
if (EnablePartialProfits && quantity > PartialProfitContracts)
{
partialProfitDistancePoints = currentAtr * PartialProfitMultiplier;
partialProfitDistancePoints = Math.Max(partialProfitDistancePoints, Instrument.MasterInstrument.TickSize); // Min partial target distance
}
if (isLong)
{
stopLossPrice = entryPrice - stopDistancePoints;
profitTargetPrice = entryPrice + profitDistancePoints;
if (partialProfitDistancePoints > 0)
partialTargetPrice = entryPrice + partialProfitDistancePoints;
else
partialTargetPrice = 0; // No partial target
SetStopLoss(CalculationMode.Price, stopLossPrice);
// Set main profit target for the remaining contracts after partial exit
SetProfitTarget("Profit Target", CalculationMode.Price, profitTargetPrice, (quantity - (EnablePartialProfits ? PartialProfitContracts : 0)) > 0);
if (EnablePartialProfits && PartialProfitContracts > 0 && partialTargetPrice > entryPrice)
SetProfitTarget("Partial Target", CalculationMode.Price, partialTargetPrice, true); // Set first target
}
else // Short
{
stopLossPrice = entryPrice + stopDistancePoints;
profitTargetPrice = entryPrice - profitDistancePoints;
if (partialProfitDistancePoints > 0)
partialTargetPrice = entryPrice - partialProfitDistancePoints;
else
partialTargetPrice = 0; // No partial target
SetStopLoss(CalculationMode.Price, stopLossPrice);
// Set main profit target for the remaining contracts after partial exit
SetProfitTarget("Profit Target", CalculationMode.Price, profitTargetPrice, (quantity - (EnablePartialProfits ? PartialProfitContracts : 0)) > 0);
if (EnablePartialProfits && PartialProfitContracts > 0 && partialTargetPrice < entryPrice)
SetProfitTarget("Partial Target", CalculationMode.Price, partialTargetPrice, true); // Set first target
}
// Trailing stop initialization (will activate based on profit later)
if (UseTrailingStop)
{
// Initial trail stop setting - price doesn't matter much here, just sets the mode.
// Activation and trailing amount will be handled in ManageTrailingStop()
SetTrailStop(CalculationMode.Price, stopLossPrice); // Start trailing from initial SL level
}
}
#endregion
#region Trade Management
private void ManageStopLoss()
{
// Optional: Implement custom dynamic stop loss adjustments here if needed,
// beyond the standard SetStopLoss(). For example, move SL to Break Even after price moves X points/ATR.
// Example: Move to Breakeven
/*
if (Position.MarketPosition == MarketPosition.Long && GetRealizedProfitLoss(Position.AveragePrice, Close[0]) >= currentAtr * 1.0 * Instrument.MasterInstrument.PointValue * Position.Quantity)
{
if (stopLossPrice < Position.AveragePrice) // Check if stop is not already at or above breakeven
{
double breakEvenPrice = Position.AveragePrice + Instrument.MasterInstrument.TickSize; // Add a tick for buffer
SetStopLoss(CalculationMode.Price, breakEvenPrice);
stopLossPrice = breakEvenPrice; // Update internal variable
Print($"{Times[0][0]}: Moved Stop Loss to Breakeven ({breakEvenPrice})");
LogTrade("Modify", "StopLoss", "MoveToBE", Position.Quantity, 0, 0, breakEvenPrice, profitTargetPrice, "");
}
}
else if (Position.MarketPosition == MarketPosition.Short && GetRealizedProfitLoss(Position.AveragePrice, Close[0]) >= currentAtr * 1.0 * Instrument.MasterInstrument.PointValue * Position.Quantity)
{
if (stopLossPrice > Position.AveragePrice) // Check if stop is not already at or below breakeven
{
double breakEvenPrice = Position.AveragePrice - Instrument.MasterInstrument.TickSize; // Subtract a tick for buffer
SetStopLoss(CalculationMode.Price, breakEvenPrice);
stopLossPrice = breakEvenPrice; // Update internal variable
Print($"{Times[0][0]}: Moved Stop Loss to Breakeven ({breakEvenPrice})");
LogTrade("Modify", "StopLoss", "MoveToBE", Position.Quantity, 0, 0, breakEvenPrice, profitTargetPrice, "");
}
}
*/
}
private void ManageTrailingStop()
{
if (!UseTrailingStop || Position.MarketPosition == MarketPosition.Flat || currentAtr <= 0)
return;
double trailActivationThresholdPoints = currentAtr * TrailingStopMultiplier; // Profit needed to activate trailing
double trailAmountPoints = currentAtr * TrailingStopMultiplier; // How far behind price to trail
if (trailActivationThresholdPoints <= 0 || trailAmountPoints <= 0) return; // Safety check
// Check if profit exceeds activation threshold
double unrealizedPnlPoints = 0;
if (Position.MarketPosition == MarketPosition.Long)
unrealizedPnlPoints = Close[0] - Position.AveragePrice;
else if (Position.MarketPosition == MarketPosition.Short)
unrealizedPnlPoints = Position.AveragePrice - Close[0];
if (unrealizedPnlPoints >= trailActivationThresholdPoints)
{
// Activate or adjust the trailing stop
double newTrailStopPrice = 0;
if (Position.MarketPosition == MarketPosition.Long)
{
newTrailStopPrice = Close[0] - trailAmountPoints;
// Ensure trail stop only moves up, not down
newTrailStopPrice = Math.Max(newTrailStopPrice, stopLossPrice); // Don't move below initial/current stop
}
else if (Position.MarketPosition == MarketPosition.Short)
{
newTrailStopPrice = Close[0] + trailAmountPoints;
// Ensure trail stop only moves down, not up
newTrailStopPrice = Math.Min(newTrailStopPrice, stopLossPrice); // Don't move above initial/current stop
}
// Only update if the new trail stop price is better than the current one
if ((Position.MarketPosition == MarketPosition.Long && newTrailStopPrice > stopLossPrice) ||
(Position.MarketPosition == MarketPosition.Short && newTrailStopPrice < stopLossPrice))
{
SetStopLoss(CalculationMode.Price, newTrailStopPrice); // Use SetStopLoss to trail
stopLossPrice = newTrailStopPrice; // Update internal variable
// Print($"{Times[0][0]}: Trailing Stop Adjusted to {newTrailStopPrice}");
LogTrade("Modify", "TrailStop", "Adjust", Position.Quantity, 0, 0, newTrailStopPrice, profitTargetPrice, $"UnrealizedPts={unrealizedPnlPoints:F2}");
}
}
}
private void ManagePartialProfits()
{
// NinjaTrader handles SetProfitTarget("Partial Target", ...) automatically.
// This section is for potential custom logic if needed, e.g., scaling out
// at different levels based on complex conditions not handled by simple targets.
// For most cases using multiple SetProfitTarget calls is sufficient.
// Example: If first partial target hit (check via OnExecutionUpdate or if price exceeds target),
// you might want to move the stop loss for the remaining position to breakeven immediately.
// This logic would typically reside in OnExecutionUpdate.
}
private void ResetTradeState()
{
// Reset variables related to the current trade after it closes
stopLossPrice = 0;
profitTargetPrice = 0;
partialTargetPrice = 0;
currentEntrySignalName = "";
}
#endregion
#region Event Handlers (OnExecutionUpdate, OnOrderUpdate)
protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time, ErrorCode error, string comment)
{
// This method is called when an order execution occurs (fill)
// --- Track P/L and Consecutive Wins/Losses ---
if (execution.Order != null && execution.Order.OrderState == OrderState.Filled)
{
// Check if the execution closes or reduces a position
if ((execution.Order.OrderAction == OrderAction.Sell && marketPosition == MarketPosition.Flat && execution.MarketPosition == MarketPosition.Long) || // Exited Long
(execution.Order.OrderAction == OrderAction.BuyToCover && marketPosition == MarketPosition.Flat && execution.MarketPosition == MarketPosition.Short) || // Exited Short
(execution.Order.IsExit)) // Covers exits reducing position size too
{
// Calculate Profit/Loss for the closed portion
// Note: Accessing Performance directly might include prior trades if not careful.
// It's often better to track P/L per trade based on entry/exit executions.
Trade lastTrade = Performance.AllTrades.LastOrDefault(); // Get the most recent completed trade
if (lastTrade != null && lastTrade.ExitExecution != null && lastTrade.ExitExecution.ExecutionId == executionId) // Ensure this execution closed the trade
{
lastTradeProfit = lastTrade.ProfitCurrency; // P/L in account currency
lastTradeSize = lastTrade.Quantity;
if (lastTradeProfit > 0)
{
consecutiveWins++;
consecutiveLosses = 0;
// Check for win streak cooldown
if (ConsecutiveWinCooldownThreshold > 0 && consecutiveWins >= ConsecutiveWinCooldownThreshold)
{
StartCooldown($"Win streak ({consecutiveWins} wins)");
}
}
else
{
consecutiveLosses++;
consecutiveWins = 0;
// Check for loss streak cooldown
if (ConsecutiveLossCooldownThreshold > 0 && consecutiveLosses >= ConsecutiveLossCooldownThreshold)
{
StartCooldown($"Loss streak ({consecutiveLosses} losses)");
}
}
// Log the exit details
string exitReason = comment; // Use the comment from the exit order if available
if (string.IsNullOrEmpty(exitReason)) exitReason = execution.Order.Name; // Fallback to order name
LogTrade("Exit", execution.MarketPosition == MarketPosition.Long ? "Long" : "Short", exitReason, execution.Quantity, execution.Price, lastTrade.ProfitLoss, stopLossPrice, profitTargetPrice, $"ConsecWins={consecutiveWins}, ConsecLoss={consecutiveLosses}, Cum P/L={Performance.AllTrades.TradesPerformance.Currency.CumProfit:F2}");
// Reset state after trade closes
ResetTradeState();
// Update Account Capital simulation (important for backtesting accurate position sizing)
// Note: This is a basic simulation. Real account updates are handled by NT broker connection.
// Only adjust if running purely simulation/backtest where AccountCapital parameter is used.
AccountCapital += lastTradeProfit;
// Print($"Trade Closed. P/L: {lastTradeProfit:C}. New Simulated Capital: {AccountCapital:C}");
}
}
else if (execution.Order.IsEntry)
{
// Optional: Log entry fill details if needed beyond the initial EnterLong/Short log
// LogTrade("Fill", execution.Order.OrderAction == OrderAction.Buy ? "Long" : "Short", "Entry Filled", execution.Quantity, execution.Price, 0, stopLossPrice, profitTargetPrice, "");
}
else if (EnablePartialProfits && execution.Order.Name == "Partial Target" && execution.Order.OrderState == OrderState.Filled)
{
// Handle partial profit fill
// Example: Move stop to breakeven for remaining contracts
double realizedPartial = execution.Price - Position.AveragePrice; // For long
if (execution.MarketPosition == MarketPosition.Short) realizedPartial = Position.AveragePrice - execution.Price;
LogTrade("PartialExit", execution.MarketPosition == MarketPosition.Long ? "Long" : "Short", "Partial Target Hit", execution.Quantity, execution.Price, realizedPartial * execution.Quantity * Instrument.MasterInstrument.PointValue, stopLossPrice, profitTargetPrice, $"Remaining Contracts: {Position.Quantity}");
// Optional: Move stop to breakeven immediately after partial fill
/*
if (Position.Quantity > 0) // If contracts remain
{
double breakEvenPrice = Position.AveragePrice;
if (Position.MarketPosition == MarketPosition.Long) breakEvenPrice += Instrument.MasterInstrument.TickSize;
else if (Position.MarketPosition == MarketPosition.Short) breakEvenPrice -= Instrument.MasterInstrument.TickSize;
if ((Position.MarketPosition == MarketPosition.Long && stopLossPrice < breakEvenPrice) || (Position.MarketPosition == MarketPosition.Short && stopLossPrice > breakEvenPrice))
{
SetStopLoss(CalculationMode.Price, breakEvenPrice);
stopLossPrice = breakEvenPrice;
Print($"{Times[0][0]}: Moved Stop to Breakeven ({breakEvenPrice}) after Partial Profit.");
LogTrade("Modify", "StopLoss", "MoveToBE_Partial", Position.Quantity, 0, 0, breakEvenPrice, profitTargetPrice, "");
}
} */
}
}
}
protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string comment)
{
// This method is called when an order's state changes (Submitted, Accepted, Cancelled, Filled, etc.)
// --- Handle Order Errors/Rejections ---
if (orderState == OrderState.Rejected || orderState == OrderState.Cancelled)
{
// Log the rejection/cancellation
Print($"Order {order.Name} ({order.OrderAction}, {order.Quantity} @ {order.LimitPrice}/{order.StopPrice}) {orderState} - Error: {error} - Comment: {comment}");
LogTrade("OrderUpdate", order.IsEntry ? "Entry" : "Exit", $"{orderState}", order.Quantity, order.IsMarket ? 0 : order.LimitPrice, 0, order.StopPrice, 0, $"Error: {error}, Comment: {comment}");
// If an entry order failed, ensure we are flat and reset any related state.
if (order.IsEntry && Position.MarketPosition == MarketPosition.Flat)
{
ResetTradeState();
}
// If an exit order failed, we might need emergency flattening logic (though RealtimeErrorHandling.StopCancelClose helps)
if (order.IsExit && Position.MarketPosition != MarketPosition.Flat)
{
// Consider emergency flatten if exit keeps failing
// Print($"WARNING: Exit order {order.Name} failed ({orderState}). Position remains {Position.MarketPosition}.");
}
}
// Optional: Track modification confirmations
if (orderState == OrderState.Accepted && (order.IsChange || comment.Contains("Change")))
{
//LogTrade("Modify", order.IsStop ? "StopLoss" : (order.IsLimit ? "Target" : "Other"), "Accepted", order.Quantity, order.LimitPrice, 0, order.StopPrice, 0, "");
}
}
#endregion
#region Helper Methods & Logging
private void StartCooldown(string reason)
{
isCoolingDown = true;
coolDownEndTime = TimeZoneInfo.ConvertTime(Times[0][0], TimeZoneInfo.Local, exchangeTimeZone).AddMinutes(CooldownMinutes);
Print($"{TimeZoneInfo.ConvertTime(Times[0][0], TimeZoneInfo.Local, exchangeTimeZone)}: Starting {CooldownMinutes} min cooldown. Reason: {reason}. Ends approx: {coolDownEndTime}");
// Log cooldown event
LogTrade("Info", "System", "CooldownStart", 0, 0, 0, 0, 0, $"Reason: {reason}, Duration: {CooldownMinutes} min");
// Optional: Flatten any open position when cooldown starts
// if (Position.MarketPosition != MarketPosition.Flat)
// {
// Print("Flattening position due to cooldown start.");
// if (Position.MarketPosition == MarketPosition.Long) ExitLong("Cooldown Flatten", Position.AveragePrice);
// if (Position.MarketPosition == MarketPosition.Short) ExitShort("Cooldown Flatten", Position.AveragePrice);
// }
}
// Log trade details to a CSV file
private void LogTrade(string action, string type, string signalName, int quantity, double price, double pnl, double stopPrice, double targetPrice, string reason)
{
if (logWriter == null || State == State.Historical) return; // Don't log during optimization phase directly, or if file init failed
lock (logLock) // Ensure thread-safe access to the file
{
try
{
// Get timestamp in a consistent format (e.g., ISO 8601)
string timestamp = Times[0][0].ToString("yyyy-MM-dd HH:mm:ss");
int tradeIndex = Performance.AllTrades.Count; // Current trade number (or count + 1 for entries)
double cumulativeProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit;
// Format the log entry as CSV
string logEntry = string.Join(",",
timestamp,
tradeIndex,
action, // e.g., Enter, Exit, Modify, PartialExit, Info
type, // e.g., Long, Short, System, StopLoss
signalName, // e.g., TrendFollow_MACross, MoveToBE, CooldownStart
quantity,
price.ToString("F2"), // Format price
(action == "Exit" || action == "PartialExit") ? price.ToString("F2") : "0.00", // Exit price only on exits
stopPrice.ToString("F2"),
targetPrice.ToString("F2"),
pnl.ToString("F2"), // Profit/Loss for this specific event (if applicable)
cumulativeProfit.ToString("F2"), // Overall strategy P/L
consecutiveLosses,
consecutiveWins,
currentAtr.ToString("F4"), // Current ATR at time of event
$"\"{reason.Replace("\"", "\"\"")}\"" // Enclose reason in quotes, escape internal quotes
);
logWriter.WriteLine(logEntry);
// logWriter.Flush(); // Optionally flush immediately, but AutoFlush=true handles this
}
catch (Exception e)
{
Print($"Error writing to log file: {e.Message}");
// Consider disabling further logging attempts if errors persist
// logWriter = null;
}
}
}
#endregion
#region User Configurable Properties ([NinjaScriptProperty])
[NinjaScriptProperty]
[Display(Name = "01. Account Capital", Order = 1, GroupName = "Parameters")]
public double AccountCapital
{ get { return accountCapital; } set { accountCapital = Math.Max(1, value); } }
[NinjaScriptProperty]
[Range(0.1, 5.0)] // Sensible range for risk %
[Display(Name = "02. Max Risk % Per Trade", Order = 2, GroupName = "Parameters")]
public double MaxRiskPercent
{ get { return maxRiskPercent; } set { maxRiskPercent = Math.Max(0.1, value); } }
[NinjaScriptProperty]
[Range(5, 50)] // ATR Period Range
[Display(Name = "03. ATR Period", Order = 3, GroupName = "Parameters")]
public int AtrPeriod
{ get { return atrPeriod; } set { atrPeriod = Math.Max(1, value); } }
[NinjaScriptProperty]
[Range(0.5, 5.0)] // ATR Stop Multiplier Range
[Display(Name = "04. ATR Stop Multiplier", Order = 4, GroupName = "Parameters")]
public double AtrStopMultiplier
{ get { return atrStopMultiplier; } set { atrStopMultiplier = Math.Max(0.1, value); } }
[NinjaScriptProperty]
[Range(0.5, 10.0)] // ATR Profit Multiplier Range
[Display(Name = "05. ATR Profit Multiplier", Order = 5, GroupName = "Parameters")]
public double AtrProfitMultiplier
{ get { return atrProfitMultiplier; } set { atrProfitMultiplier = Math.Max(0.1, value); } }
[NinjaScriptProperty]
[Display(Name = "06. Use Trailing Stop", Order = 6, GroupName = "Parameters")]
public bool UseTrailingStop
{ get { return useTrailingStop; } set { useTrailingStop = value; } }
[NinjaScriptProperty]
[Range(0.5, 5.0)]
[Display(Name = "07. Trailing Stop ATR Multiplier", Order = 7, GroupName = "Parameters")]
public double TrailingStopMultiplier
{ get { return trailingStopMultiplier; } set { trailingStopMultiplier = Math.Max(0.1, value); } }
[NinjaScriptProperty]
[Display(Name="08. Enable Partial Profits", Order=8, GroupName="Parameters")]
public bool EnablePartialProfits
{ get { return enablePartialProfits; } set { enablePartialProfits = value; } }
[NinjaScriptProperty]
[Range(1, 10)]
[Display(Name="09. Partial Profit Contracts", Order=9, GroupName="Parameters")]
public int PartialProfitContracts
{ get { return partialProfitContracts; } set { partialProfitContracts = Math.Max(1, value); } }
[NinjaScriptProperty]
[Range(0.5, 5.0)]
[Display(Name="10. Partial Profit ATR Multiplier", Order=10, GroupName="Parameters")]
public double PartialProfitMultiplier
{ get { return partialProfitMultiplier; } set { partialProfitMultiplier = Math.Max(0.1, value); } }
[NinjaScriptProperty]
[PropertyEditor("NinjaTrader.Gui.Tools.TimeEditor")]
[Display(Name = "11. Start Time (EST)", Order = 11, GroupName = "Parameters")]
public TimeSpan StartTime
{ get { return startTime; } set { startTime = value; } }
[NinjaScriptProperty]
[PropertyEditor("NinjaTrader.Gui.Tools.TimeEditor")]
[Display(Name = "12. End Time (EST)", Order = 12, GroupName = "Parameters")]
public TimeSpan EndTime
{ get { return endTime; } set { endTime = value; } }
[NinjaScriptProperty]
[Range(1, 10)]
[Display(Name = "13. Consecutive Loss Cooldown Threshold", Order = 13, GroupName = "Parameters")]
public int ConsecutiveLossCooldownThreshold
{ get { return consecutiveLossCooldownThreshold; } set { consecutiveLossCooldownThreshold = Math.Max(0, value); } } // 0 disables
[NinjaScriptProperty]
[Range(1, 10)]
[Display(Name = "14. Consecutive Win Cooldown Threshold", Order = 14, GroupName = "Parameters")]
public int ConsecutiveWinCooldownThreshold
{ get { return consecutiveWinCooldownThreshold; } set { consecutiveWinCooldownThreshold = Math.Max(0, value); } } // 0 disables
[NinjaScriptProperty]
[Range(5, 120)]
[Display(Name = "15. Cooldown Period (Minutes)", Order = 15, GroupName = "Parameters")]
public int CooldownMinutes
{ get { return cooldownMinutes; } set { cooldownMinutes = Math.Max(1, value); } }
[NinjaScriptProperty]
[Display(Name = "16. MASTER TRADING SWITCH", Order = 16, GroupName = "Parameters")]
public bool EnableTrading
{ get { return enableTrading; } set { enableTrading = value; } }
[NinjaScriptProperty]
[Range(1, 60)]
[Display(Name = "TF1 Period (e.g., 5 min)", Order = 1, GroupName = "Multi-Timeframe")]
public int Tf1Period
{ get { return tf1Period; } set { tf1Period = Math.Max(1, value); } }
[NinjaScriptProperty]
[Range(5, 120)]
[Display(Name = "TF2 Period (e.g., 15 min)", Order = 2, GroupName = "Multi-Timeframe")]
public int Tf2Period
{ get { return tf2Period; } set { tf2Period = Math.Max(1, value); } }
[NinjaScriptProperty]
[Range(15, 240)]
[Display(Name = "TF3 Period (e.g., 60 min)", Order = 3, GroupName = "Multi-Timeframe")]
public int Tf3Period
{ get { return tf3Period; } set { tf3Period = Math.Max(1, value); } }
[NinjaScriptProperty]
[Display(Name="Log File Name", Order=1, GroupName="Logging")]
public string LogFileName
{ get { return logFileName; } set { logFileName = value; } }
// Hidden properties for internal state tracking if needed (usually not necessary for user)
//[Browsable(false)]
//[XmlIgnore]
//public double CurrentAtrValue { get { return currentAtr; } set { currentAtr = value; } }
#endregion
}
}