Rate this code 1-100 and explain why
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
#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.DrawingTools;
using NinjaTrader.NinjaScript.Indicators; // Standard indicators namespace
using NinjaTrader.NinjaScript.Indicators.Institutional; // Assuming custom VWAP approx might be here
using NinjaTrader.NinjaScript.Indicators.OrderFlow; // For built-in VWAP if license allows
using NinjaTrader.NinjaScript.Strategies.Institutional; // Custom namespace for organization [1]
#endregion
//Define the custom namespace for organization
namespace NinjaTrader.NinjaScript.Strategies.Institutional
{
///
/// Represents an institutional-grade intraday trading strategy for ES/MES futures.
/// Incorporates Multi-Timeframe Analysis, Volume Profile Approximation, Price Action Patterns (FVG, Divergence),
/// Indicator Confluence (EMA, RSI, ATR, VWAP), Dynamic Position Sizing, Partial Profits, Trailing Stops,
/// and comprehensive Risk/Session Management.
///
public class InstitutionalESBot : Strategy
{
#region Strategy Parameters (User Inputs - Step 1 & III)
// Contract Selection (Strategy runs on the chart instrument)
// Timeframes
public int PrimaryTimeFrameMinutes { get; set; }
public int SecondaryTimeFrame1Minutes { get; set; }
public int SecondaryTimeFrame2Minutes { get; set; }
// Session Timing
public DateTime SessionStartTime { get; set; }
public DateTime SessionEndTime { get; set; }
// Risk Management
public double RiskPerTradePercent { get; set; }
public double MaxDailyLossCurrency { get; set; }
public int MinPositionSize { get; set; }
public int MaxPositionSize { get; set; }
// Entry Logic Parameters
public int FVGLookbackPeriod { get; set; }
// Note: FVG Mitigation Method enum would be defined below or in a separate file
[Display(Name = "FVG Mitigation Method", Description = "How FVG is considered mitigated (for re-entry logic if applicable).", Order = 41, GroupName = "Entry Logic")]
public FVGMitigation FVGMitigationMethod { get; set; }
[Display(Name = "Divergence Lookback", Description = "Period for divergence detection.", Order = 42, GroupName = "Entry Logic")]
public int DivergenceLookbackPeriod { get; set; }
// Note: DivergenceSource enum would be defined below or in a separate file
[Display(Name = "Divergence Indicator", Description = "Oscillator to use for divergence.", Order = 43, GroupName = "Entry Logic")]
public DivergenceSource DivergenceIndicator { get; set; }
public int DivergenceStrength { get; set; }
// Indicator Parameters
[Display(Name = "Fast EMA Period", Description = "Period for the fast Exponential Moving Average.", Order = 50, GroupName = "Indicators")]
public int FastEmaPeriod { get; set; }
public int SlowEmaPeriod { get; set; }
public int RsiPeriod { get; set; }
public int RsiSmoothPeriod { get; set; }
public int RsiLevelBullish { get; set; }
public int RsiLevelBearish { get; set; }
public int AtrPeriod { get; set; }
// VWAP Parameters - Placeholder for Approximation if OrderFlow+ is unavailable
// If using built-in OrderFlowVWAP, parameters would be different [2]
// Assuming a simple daily VWAP approximation for now
public bool UseOrderFlowVWAP { get; set; }
// MACD Parameters [3]
[Display(Name = "MACD Fast", Description = "Fast EMA period for MACD.", Order = 60, GroupName = "Indicators")]
public int MacdFast { get; set; }
public int MacdSlow { get; set; }
public int MacdSmooth { get; set; }
// Volume Profile Parameters
// Note: VPApproximation enum would be defined below or in a separate file
public VPApproximation VPApproximationMethod { get; set; }
public int VPTickAggregation { get; set; }
[Display(Name = "VP Value Area %", Description = "Percentage of volume to include in the Value Area.", Order = 72, GroupName = "Volume Profile")]
public double VPValueAreaPercent { get; set; }
// Stop Loss Parameters
// Note: StopLossMethod enum would be defined below or in a separate file
public StopLossMethod StopLossMethod { get; set; }
public double StopLossAtrMultiplier { get; set; }
public int StopLossStructureLookback { get; set; }
// Take Profit Parameters
// Note: TakeProfitMethod enum would be defined below or in a separate file
public TakeProfitMethod TakeProfitMethod { get; set; }
public double TakeProfitAtrMultiplier { get; set; }
public double TakeProfitRiskRewardRatio { get; set; }
// Partial Profit Parameters
[Display(Name = "Enable Partial Profit 1", Description = "Enable first partial profit target.", Order = 100, GroupName = "Partial Profits")]
public bool EnablePartialProfit1 { get; set; }
[Display(Name = "Partial Profit 1 %", Description = "Percentage of position to exit at PP1.", Order = 101, GroupName = "Partial Profits")]
public double PartialProfit1Percent { get; set; }
public double PartialProfit1RRRatio { get; set; }
[Display(Name = "Enable Partial Profit 2", Description = "Enable second partial profit target.", Order = 103, GroupName = "Partial Profits")]
public bool EnablePartialProfit2 { get; set; }
[Display(Name = "Partial Profit 2 %", Description = "Percentage of position to exit at PP2.", Order = 104, GroupName = "Partial Profits")]
public double PartialProfit2Percent { get; set; }
public double PartialProfit2RRRatio { get; set; }
// Trailing Stop Parameters
public bool EnableTrailingStop { get; set; }
public double TrailingStopTriggerRRRatio { get; set; }
// Note: TrailingStopMethod enum would be defined below or in a separate file
public TrailingStopMethod TrailingStopMethod { get; set; }
public double TrailingStopAtrMultiplier { get; set; }
public int TrailingStopStructureLookback { get; set; }
public bool MoveStopToBreakEven { get; set; }
public double BreakEvenTriggerRRRatio { get; set; }
public int BreakEvenPlusTicks { get; set; }
#endregion
#region Class Level Variables (Step 1 & IV)
// Indicator Instances (Primary Timeframe - BarsArray)
private EMA emaFastPrimary;
private EMA emaSlowPrimary;
private RSI rsiPrimary;
private ATR atrPrimary;
private MACD macdPrimary;
private OrderFlowVWAP vwapBuiltInPrimary; // If using OrderFlow+ [2]
private VWAPDaily vwapApproxPrimary; // Example approximation if OrderFlow+ is not used
// Indicator Instances (Secondary Timeframe 1 - BarsArray[1])
private EMA emaFastSecondary1;
private EMA emaSlowSecondary1;
private RSI rsiSecondary1;
private ATR atrSecondary1;
private MACD macdSecondary1;
private OrderFlowVWAP vwapBuiltInSecondary1;
private VWAPDaily vwapApproxSecondary1;
// Indicator Instances (Secondary Timeframe 2 - BarsArray[2])
private EMA emaFastSecondary2;
private EMA emaSlowSecondary2;
private RSI rsiSecondary2;
private ATR atrSecondary2;
private MACD macdSecondary2;
private OrderFlowVWAP vwapBuiltInSecondary2;
private VWAPDaily vwapApproxSecondary2;
// Volume Profile Data Structures [4]
private Dictionary<double, long> sessionVolumeProfile;
private double pocPrice;
private double vahPrice;
private double valPrice;
private bool isVpLevelsCalculated;
private long totalSessionVolume; // Needed for VA calculation
// State Management Variables
private bool isTradingWindowActive;
private bool isDailyLossLimitReached;
private double startOfDayCumProfit;
private DateTime currentTradingDay = DateTime.MinValue; // Initialize to a value that won't match first bar's date
private bool breakEvenActivated;
private bool trailingStopActivated;
private double activeStopPrice; // Tracks the current price of the active stop loss order
private IOrder stopLossOrder; // Holds the reference to the active stop loss order for modification [5, 6]
private Dictionary<string, IOrder> partialProfitOrders; // Tracks active partial profit limit orders
private int filledEntryQuantity; // Tracks the quantity filled for the current entry signal
private double entryPrice; // Stores the average entry price of the current position
private string lastEntrySignalName = string.Empty; // Stores the unique signal name of the last entry order
// Instrument Details (Fetched in DataLoaded) [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
private double tickSize;
private double pointValue;
// Constants
private const int BARS_REQUIRED_LOOKBACK = 200; // Default lookback, adjust based on longest period needed
#endregion
#region OnStateChange Implementation (Step 1, 2, 5 & V)
/// <summary>
/// Handles state changes of the strategy (SetDefaults, Configure, DataLoaded, etc.).
/// Crucial for initializing parameters, adding data series, and setting up indicators correctly. [19, 20]
/// </summary>
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
// --- Strategy Behavior Configuration (II.C) ---
Description = @"Institutional Grade Intraday ES/MES Futures Bot V1.0";
Name = "InstitutionalESBot";
// Calculate OnBarClose is generally less resource-intensive. Use OnEachTick only if VP or other logic absolutely requires it AND Tick Replay is enabled. [21, 22, 23]
Calculate = Calculate.OnBarClose;
EntriesPerDirection = 1; // Allow only one entry per direction until flat
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true; // Ensure flat position at session end
ExitOnSessionCloseSeconds = 30; // Exit 30 seconds before session close
IsFillLimitOnTouch = false;
// Set a reasonable lookback; adjust if indicators/logic need more data. Balance performance. [21, 23]
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
OrderFillResolution = OrderFillResolution.Standard;
Slippage = 2; // Default slippage in ticks (user can override)
StartBehavior = StartBehavior.WaitUntilFlat;
TimeInForce = TimeInForce.Gtc; // Good Till Cancelled
TraceOrders = false; // Set to true ONLY for debugging
// More robust error handling for production [20]
RealtimeErrorHandling = RealtimeErrorHandling.StopStrategyCancelOrdersAndClosePosition;
// Crucial for managing stops/targets associated with specific entry fills, especially with partials [24, 25, 26]
StopTargetHandling = StopTargetHandling.PerEntryExecution;
IsInstantiatedOnEachOptimizationIteration = true; // Ensures clean state for optimization [19]
IsAdoptAccountPositionAware = false; // Strategy manages its own position tracking
// --- Default User Input Parameter Values (III) ---
PrimaryTimeFrameMinutes = 1;
SecondaryTimeFrame1Minutes = 5;
SecondaryTimeFrame2Minutes = 15;
SessionStartTime = DateTime.Parse("08:30", System.Globalization.CultureInfo.InvariantCulture); // Default 8:30 AM (Chart TimeZone)
SessionEndTime = DateTime.Parse("15:00", System.Globalization.CultureInfo.InvariantCulture); // Default 3:00 PM (Chart TimeZone)
RiskPerTradePercent = 0.5; // 0.5% risk
MaxDailyLossCurrency = 1000; // $1000 max daily loss
MinPositionSize = 1;
MaxPositionSize = 10;
FVGLookbackPeriod = 3;
FVGMitigationMethod = FVGMitigation.Wick; // Default mitigation check
DivergenceLookbackPeriod = 14;
DivergenceIndicator = DivergenceSource.RSI; // Default to RSI
DivergenceStrength = 10; // Lookback for swing points
FastEmaPeriod = 9;
SlowEmaPeriod = 21;
RsiPeriod = 14;
RsiSmoothPeriod = 3;
RsiLevelBullish = 55; // Slightly adjusted default
RsiLevelBearish = 45; // Slightly adjusted default
AtrPeriod = 14;
UseOrderFlowVWAP = false; // Default to approximation, user must enable if licensed
MacdFast = 12;
MacdSlow = 26;
MacdSmooth = 9;
VPApproximationMethod = VPApproximation.DValueAreaStyle; // Default VP method
VPTickAggregation = 1;
VPValueAreaPercent = 70.0; // User requested 70%
StopLossMethod = StopLossMethod.ATR; // Default SL method
StopLossAtrMultiplier = 1.5;
StopLossStructureLookback = 10;
TakeProfitMethod = TakeProfitMethod.FixedRatio; // Default TP method
TakeProfitAtrMultiplier = 2.0;
TakeProfitRiskRewardRatio = 2.0; // Default R:R
EnablePartialProfit1 = true;
PartialProfit1Percent = 50.0;
PartialProfit1RRRatio = 1.0; // 1:1 R:R for first partial
EnablePartialProfit2 = false;
PartialProfit2Percent = 25.0;
PartialProfit2RRRatio = 1.5;
EnableTrailingStop = true;
TrailingStopTriggerRRRatio = 1.0; // Activate trailing at 1:1 R:R
TrailingStopMethod = TrailingStopMethod.ATR; // Default trailing method
TrailingStopAtrMultiplier = 1.5;
TrailingStopStructureLookback = 10;
MoveStopToBreakEven = true;
BreakEvenTriggerRRRatio = 0.75; // Activate BE at 0.75 R
BreakEvenPlusTicks = 2; // Move stop BE + 2 ticks
// Set BarsRequiredToTrade based on longest lookback needed by any indicator/logic
// Example: Max(SlowEmaPeriod, RsiPeriod, AtrPeriod, MacdSlow, DivergenceLookbackPeriod, StopLossStructureLookback, TrailingStopStructureLookback) + buffer
BarsRequiredToTrade = BARS_REQUIRED_LOOKBACK; // Use a constant or calculate dynamically based on params
}
else if (State == State.Configure)
{
// --- Add Secondary Data Series (Step 2) ---
// AddDataSeries MUST be called in State.Configure [20, 27]
// Parameters should ideally be hardcoded or from user inputs, not runtime variables [27, 28]
if (SecondaryTimeFrame1Minutes > 0)
AddDataSeries(BarsPeriodType.Minute, SecondaryTimeFrame1Minutes); // BarsArray[1]
if (SecondaryTimeFrame2Minutes > 0 && SecondaryTimeFrame2Minutes!= SecondaryTimeFrame1Minutes)
AddDataSeries(BarsPeriodType.Minute, SecondaryTimeFrame2Minutes); // BarsArray[2]
// Add any custom series if needed (e.g., for complex calculations)
// Reset class variables here if they are not reset in DataLoaded and might persist across optimization runs [20]
}
else if (State == State.DataLoaded)
{
// --- Initialize Indicators (Step 5) ---
// Best practice: Initialize all data-dependent objects here [19, 20]
// Ensure indicators are initialized for all Bars objects in BarsArray
// Primary Timeframe (BarsArray)
emaFastPrimary = EMA(FastEmaPeriod);
emaSlowPrimary = EMA(SlowEmaPeriod);
rsiPrimary = RSI(RsiPeriod, RsiSmoothPeriod);
atrPrimary = ATR(AtrPeriod);
macdPrimary = MACD(MacdFast, MacdSlow, MacdSmooth);
if (UseOrderFlowVWAP)
{
// Requires OrderFlow+ license [2, 29]
try { vwapBuiltInPrimary = OrderFlowVWAP(VWAPResolution.Standard, TradingHours.UseDataSeriesSettingsInstance, VWAPStandardDeviations.None, 1, 1, 1); }
catch (Exception ex) { Print($"Error initializing built-in VWAP on Primary TF: {ex.Message}. Ensure OrderFlow+ license is active. Falling back to approximation."); UseOrderFlowVWAP = false; /* Fallback handled below */ }
}
if (!UseOrderFlowVWAP) { vwapApproxPrimary = VWAPDaily(this); } // Use 'this' to pass strategy reference if needed by indicator
// Secondary Timeframe 1 (BarsArray[1]) - Check if added
if (BarsArray.Length > 1 && BarsArray![1]= null)
{
emaFastSecondary1 = EMA(BarsArray[1], FastEmaPeriod);
emaSlowSecondary1 = EMA(BarsArray[1], SlowEmaPeriod);
rsiSecondary1 = RSI(BarsArray[1], RsiPeriod, RsiSmoothPeriod);
atrSecondary1 = ATR(BarsArray[1], AtrPeriod);
macdSecondary1 = MACD(BarsArray[1], MacdFast, MacdSlow, MacdSmooth);
if (UseOrderFlowVWAP)
{
try { vwapBuiltInSecondary1 = OrderFlowVWAP(BarsArray[1], VWAPResolution.Standard, TradingHours.UseDataSeriesSettingsInstance, VWAPStandardDeviations.None, 1, 1, 1); }
catch (Exception ex) { Print($"Error initializing built-in VWAP on Secondary TF1: {ex.Message}."); /* Handle error or ignore */ }
}
else { vwapApproxSecondary1 = VWAPDaily(BarsArray[1]); }
}
// Secondary Timeframe 2 (BarsArray[2]) - Check if added
if (BarsArray.Length > 2 && BarsArray![2]= null)
{
emaFastSecondary2 = EMA(BarsArray[2], FastEmaPeriod);
emaSlowSecondary2 = EMA(BarsArray[2], SlowEmaPeriod);
rsiSecondary2 = RSI(BarsArray[2], RsiPeriod, RsiSmoothPeriod);
atrSecondary2 = ATR(BarsArray[2], AtrPeriod);
macdSecondary2 = MACD(BarsArray[2], MacdFast, MacdSlow, MacdSmooth);
if (UseOrderFlowVWAP)
{
try { vwapBuiltInSecondary2 = OrderFlowVWAP(BarsArray[2], VWAPResolution.Standard, TradingHours.UseDataSeriesSettingsInstance, VWAPStandardDeviations.None, 1, 1, 1); }
catch (Exception ex) { Print($"Error initializing built-in VWAP on Secondary TF2: {ex.Message}."); /* Handle error or ignore */ }
}
else { vwapApproxSecondary2 = VWAPDaily(BarsArray[2]); }
}
// --- Initialize Volume Profile Structures (Step 4) ---
sessionVolumeProfile = new Dictionary<double, long>();
pocPrice = 0;
vahPrice = 0;
valPrice = 0;
isVpLevelsCalculated = false;
totalSessionVolume = 0;
// --- Initialize State Variables ---
isTradingWindowActive = false;
isDailyLossLimitReached = false;
startOfDayCumProfit = 0; // Will be set on the first bar of the day in OnBarUpdate
currentTradingDay = DateTime.MinValue; // Ensure it gets set on the first bar
breakEvenActivated = false;
trailingStopActivated = false;
activeStopPrice = 0;
stopLossOrder = null;
partialProfitOrders = new Dictionary<string, IOrder>();
filledEntryQuantity = 0;
entryPrice = 0;
lastEntrySignalName = string.Empty;
// --- Fetch Instrument Details ---
// Accessing Instrument properties is safe in DataLoaded [19, 20]
if (Instrument!= null && Instrument.MasterInstrument!= null)
{
tickSize = Instrument.MasterInstrument.TickSize;
pointValue = Instrument.MasterInstrument.PointValue;
}
else
{
Print("Error: Could not access Instrument details in State.DataLoaded.");
// Potentially stop the strategy or use default values?
tickSize = 0.25; // Default for ES/MES
pointValue = Instrument.MasterInstrument.Name.Contains("MES")? 5 : 50; // Guess based on name
}
// Check if Tick Replay is needed but not enabled
if (VPApproximationMethod == VPApproximation.DValueAreaStyle &&!Bars.IsTickReplay)
{
Print("Warning: VP Approximation Method 'DValueAreaStyle' may be inaccurate without Tick Replay enabled in Data Series settings. [22]");
}
}
else if (State == State.Terminated)
{
// Clean up any resources if necessary (e.g., dispose custom drawing objects)
if (sessionVolumeProfile!= null)
sessionVolumeProfile.Clear();
if (partialProfitOrders!= null)
partialProfitOrders.Clear();
}
}
#endregion
#region Helper Functions (Steps 3, 4, 7 & VI)
/// <summary>
/// Detects a Fair Value Gap (FVG) pattern based on the 3-candle definition. [30]
/// An FVG occurs when the wicks of the candles surrounding a central candle do not overlap.
/// </summary>
/// <param name="barsInProgressIndex">The index of the BarsArray (timeframe) to check.</param>
/// <param name="lookback">How many bars back to check for the FVG pattern (e.g., 1 means check bars 1, 2, 3 ago).</param>
/// <param name="fvgHigh">Output: The high price of the detected FVG.</param>
/// <param name="fvgLow">Output: The low price of the detected FVG.</param>
/// <returns>1 for Bullish FVG, -1 for Bearish FVG, 0 for No FVG.</returns>
private int DetectFVG(int barsInProgressIndex, int lookback, out double fvgHigh, out double fvgLow)
{
fvgHigh = 0;
fvgLow = 0;
// Ensure we have enough bars and the Bars object is valid
if (CurrentBars[barsInProgressIndex] <= lookback + 2 |
| BarsArray[barsInProgressIndex] == null)
return 0;
// Access price data using the specified BarsArray index and lookback
// Example: lookback = 1 checks bars 1, 2, 3 ago relative to the current bar (index 0)
double high_bar1 = Highs[barsInProgressIndex][lookback + 2]; // Bar 3 ago
double low_bar1 = Lows[barsInProgressIndex][lookback + 2]; // Bar 3 ago
double high_bar2 = Highs[barsInProgressIndex][lookback + 1]; // Bar 2 ago (Middle Candle)
double low_bar2 = Lows[barsInProgressIndex][lookback + 1]; // Bar 2 ago (Middle Candle)
double high_bar3 = Highs[barsInProgressIndex][lookback]; // Bar 1 ago
double low_bar3 = Lows[barsInProgressIndex][lookback]; // Bar 1 ago
// Check for Bullish FVG (Low of middle candle > High of first candle)
bool bullishGapExists = low_bar2 > high_bar1;
if (bullishGapExists)
{
// Check if the gap is still open (Low of 3rd candle > High of 1st candle)
// This simple check assumes the gap is defined between low_bar2 and high_bar1
// A more robust check might consider mitigation based on FVGMitigationMethod
if (low_bar3 > high_bar1)
{
fvgLow = high_bar1; // Bottom of the gap
fvgHigh = low_bar2; // Top of the gap
// Optional: Add Min Gap check using tickSize
// if ((fvgHigh - fvgLow) >= MinFVGGapTicks * tickSize)
return 1; // Bullish FVG
}
}
// Check for Bearish FVG (High of middle candle < Low of first candle)
bool bearishGapExists = high_bar2 < low_bar1;
if (bearishGapExists)
{
// Check if the gap is still open (High of 3rd candle < Low of 1st candle)
if (high_bar3 < low_bar1)
{
fvgLow = high_bar2; // Bottom of the gap
fvgHigh = low_bar1; // Top of the gap
// Optional: Add Min Gap check
// if ((fvgHigh - fvgLow) >= MinFVGGapTicks * tickSize)
return -1; // Bearish FVG
}
}
return 0; // No FVG detected
}
/// <summary>
/// Detects Regular and Hidden Momentum Divergence between price and a selected oscillator (RSI or MACD). [31, 32]
/// </summary>
/// <param name="barsInProgressIndex">The index of the BarsArray (timeframe) to check.</param>
/// <returns>2 Bullish Hidden, 1 Bullish Regular, 0 None, -1 Bearish Regular, -2 Bearish Hidden.</returns>
private int DetectDivergence(int barsInProgressIndex)
{
// Ensure indicators are initialized and we have enough bars
if ((DivergenceIndicator == DivergenceSource.RSI && rsiPrimary == null) ||
(DivergenceIndicator == DivergenceSource.MACD && macdPrimary == null) ||
CurrentBars[barsInProgressIndex] < DivergenceLookbackPeriod + DivergenceStrength + 5) // Need buffer for swings
{
return 0;
}
// Use Swing indicator to identify price pivots
Swing swingIndicator = Swing(BarsArray[barsInProgressIndex], DivergenceStrength);
// Find the last two swing lows and their corresponding oscillator values
double low1 = swingIndicator.SwingLow;
int low1Idx = swingIndicator.BarsAgoLow;
double low2 = swingIndicator.SwingLow; // Look further back for the previous swing
int low2Idx = swingIndicator.BarsAgoLow;
// Find the last two swing highs and their corresponding oscillator values
double high1 = swingIndicator.SwingHigh;
int high1Idx = swingIndicator.BarsAgoHigh;
double high2 = swingIndicator.SwingHigh;
int high2Idx = swingIndicator.BarsAgoHigh;
// Check if valid swing points were found (indices should be within lookback)
if (low1Idx < 0 |
| low2Idx < 0 |
| low1Idx >= DivergenceLookbackPeriod |
| low2Idx >= DivergenceLookbackPeriod ||
high1Idx < 0 |
| high2Idx < 0 |
| high1Idx >= DivergenceLookbackPeriod |
| high2Idx >= DivergenceLookbackPeriod ||
low1Idx == low2Idx |
| high1Idx == high2Idx) // Ensure distinct points
{
return 0;
}
// Get oscillator values at the swing points
double oscLow1, oscLow2, oscHigh1, oscHigh2;
if (DivergenceIndicator == DivergenceSource.RSI)
{
oscLow1 = rsiPrimary[low1Idx];
oscLow2 = rsiPrimary[low2Idx];
oscHigh1 = rsiPrimary[high1Idx];
oscHigh2 = rsiPrimary[high2Idx];
}
else // MACD
{
oscLow1 = macdPrimary.Default[low1Idx]; // Use MACD line
oscLow2 = macdPrimary.Default[low2Idx];
oscHigh1 = macdPrimary.Default[high1Idx];
oscHigh2 = macdPrimary.Default[high2Idx];
}
// --- Check for Divergences ---
// Regular Bullish: Price Lower Low, Oscillator Higher Low
if (low1 < low2 && oscLow1 > oscLow2) return 1;
// Hidden Bullish: Price Higher Low, Oscillator Lower Low
if (low1 > low2 && oscLow1 < oscLow2) return 2;
// Regular Bearish: Price Higher High, Oscillator Lower High
if (high1 > high2 && oscHigh1 < oscHigh2) return -1;
// Hidden Bearish: Price Lower High, Oscillator Higher High
if (high1 < high2 && oscHigh1 > oscHigh2) return -2;
return 0; // No divergence detected
}
/// <summary>
/// Updates the session's volume profile data structure based on the current bar's data.
/// Uses the selected approximation method. [4, 22]
/// </summary>
private void UpdateVolumeProfile()
{
// Ensure we have valid data
if (CurrentBar < 1 |
| BarsArray == null |
| sessionVolumeProfile == null) return;
// Get current bar data
double high = Highs;
double low = Lows;
long volume = Volumes;
if (volume <= 0 |
| high <= low) return; // Skip bars with no volume or range
// Mark VP as needing recalculation
isVpLevelsCalculated = false;
if (VPApproximationMethod == VPApproximation.BarDataApproximation)
{
// Simple Approximation: Assign total bar volume to the typical price
double typicalPrice = Instrument.MasterInstrument.RoundToTickSize((high + low + Closes) / 3.0);
if (sessionVolumeProfile.ContainsKey(typicalPrice))
sessionVolumeProfile[typicalPrice] += volume;
else
sessionVolumeProfile.Add(typicalPrice, volume);
totalSessionVolume += volume;
}
else // DValueAreaStyle Approximation
{
// Distribute volume evenly across the price range of the bar
// This is an approximation, especially without Tick Replay.
// For higher accuracy with this method, enable Tick Replay in Data Series settings. [22]
int ticksInRange = (int)Math.Round((high - low) / tickSize) + 1;
if (ticksInRange <= 0) ticksInRange = 1;
long volumePerTick = volume / ticksInRange;
if (volumePerTick == 0 && volume > 0) volumePerTick = 1; // Ensure at least 1 contract per tick if volume exists
long remainderVolume = volume % ticksInRange; // Volume that doesn't divide evenly
for (double price = low; price <= high; price += tickSize)
{
price = Instrument.MasterInstrument.RoundToTickSize(price); // Ensure price aligns with tick size
long volToAdd = volumePerTick;
if (sessionVolumeProfile.ContainsKey(price))
sessionVolumeProfile[price] += volToAdd;
else
sessionVolumeProfile.Add(price, volToAdd);
totalSessionVolume += volToAdd;
}
// Distribute any remainder volume (can add to POC or typical price for simplicity)
if (remainderVolume > 0)
{
double typicalPrice = Instrument.MasterInstrument.RoundToTickSize((high + low + Closes) / 3.0);
if (sessionVolumeProfile.ContainsKey(typicalPrice))
sessionVolumeProfile[typicalPrice] += remainderVolume;
else if (sessionVolumeProfile.Count > 0) // Add to first price level if typical doesn't exist
sessionVolumeProfile[sessionVolumeProfile.Keys.First()] += remainderVolume;
totalSessionVolume += remainderVolume;
}
}
}
/// <summary>
/// Calculates the Point of Control (POC) from the session volume profile data. [4]
/// </summary>
/// <returns>The price level with the highest volume.</returns>
private double CalculatePOC()
{
if (sessionVolumeProfile == null |
| sessionVolumeProfile.Count == 0)
return 0;
long maxVolume = 0;
double calculatedPoc = 0;
// Find price level with maximum volume
foreach (KeyValuePair<double, long> kvp in sessionVolumeProfile)
{
if (kvp.Value > maxVolume)
{
maxVolume = kvp.Value;
calculatedPoc = kvp.Key;
}
// Simple tie-breaker: keep the first one found or could implement middle-range logic
}
return calculatedPoc;
}
/// <summary>
/// Calculates the Value Area High (VAH) and Value Area Low (VAL) from the session volume profile. [4]
/// Uses the DValueArea approach: Find POC, then expand outwards adding volume until target % is reached.
/// </summary>
private void CalculateValueArea()
{
if (sessionVolumeProfile == null |
| sessionVolumeProfile.Count == 0 |
| pocPrice == 0 |
| totalSessionVolume == 0)
{
vahPrice = 0;
valPrice = 0;
isVpLevelsCalculated = true; // Mark as calculated even if empty
return;
}
double targetVolume = totalSessionVolume * (VPValueAreaPercent / 100.0);
long currentVolumeInVA = sessionVolumeProfile.ContainsKey(pocPrice)? sessionVolumeProfile[pocPrice] : 0;
double currentVAH = pocPrice;
double currentVAL = pocPrice;
// Get sorted list of prices above and below POC
List<double> pricesAbovePoc = sessionVolumeProfile.Keys.Where(p => p > pocPrice).OrderBy(p => p).ToList();
List<double> pricesBelowPoc = sessionVolumeProfile.Keys.Where(p => p < pocPrice).OrderByDescending(p => p).ToList();
int indexAbove = 0;
int indexBelow = 0;
// Expand outwards from POC, adding the next highest volume level (above or below)
while (currentVolumeInVA < targetVolume && (indexAbove < pricesAbovePoc.Count |
| indexBelow < pricesBelowPoc.Count))
{
long volumeAbove = (indexAbove < pricesAbovePoc.Count && sessionVolumeProfile.ContainsKey(pricesAbovePoc[indexAbove]))? sessionVolumeProfile[pricesAbovePoc[indexAbove]] : -1;
long volumeBelow = (indexBelow < pricesBelowPoc.Count && sessionVolumeProfile.ContainsKey(pricesBelowPoc))? sessionVolumeProfile] : -1;
// If both sides have prices left, choose the side with higher volume
if (volumeAbove >= 0 && volumeBelow >= 0)
{
if (volumeAbove > volumeBelow)
{
currentVolumeInVA += volumeAbove;
currentVAH = pricesAbovePoc[indexAbove];
indexAbove++;
}
else
{
currentVolumeInVA += volumeBelow;
currentVAL = pricesBelowPoc;
indexBelow++;
}
}
// If only prices above are left
else if (volumeAbove >= 0)
{
currentVolumeInVA += volumeAbove;
currentVAH = pricesAbovePoc[indexAbove];
indexAbove++;
}
// If only prices below are left
else if (volumeBelow >= 0)
{
currentVolumeInVA += volumeBelow;
currentVAL = pricesBelowPoc;
indexBelow++;
}
else
{
// Should not happen if loop condition is correct
break;
}
}
vahPrice = Instrument.MasterInstrument.RoundToTickSize(currentVAH);
valPrice = Instrument.MasterInstrument.RoundToTickSize(currentVAL);
isVpLevelsCalculated = true;
}
/// <summary>
/// Calculates the position size based on account equity, risk percentage, and stop distance. [33]
/// </summary>
/// <param name="entryPrice">The intended entry price.</param>
/// <param name="stopLossPrice">The calculated stop loss price.</param>
/// <returns>The calculated position size (number of contracts), respecting Min/Max constraints.</returns>
private int CalculatePositionSize(double entryPrice, double stopLossPrice)
{
if (tickSize.ApproxCompare(0) == 0 |
| pointValue.ApproxCompare(0) == 0 |
| RiskPerTradePercent <= 0)
{
Print("Error in CalculatePositionSize: Invalid instrument details or risk percent.");
return 0;
}
double stopDistancePoints = Math.Abs(entryPrice - stopLossPrice);
if (stopDistancePoints.ApproxCompare(0) == 0)
{
Print("Warning in CalculatePositionSize: Stop distance is zero. Cannot calculate size.");
return 0; // Avoid division by zero
}
// Calculate risk per contract in account currency
double riskPerContract = stopDistancePoints / tickSize * pointValue;
if (riskPerContract.ApproxCompare(0) == 0)
{
Print("Warning in CalculatePositionSize: Risk per contract is zero. Cannot calculate size.");
return 0;
}
// Get current account equity [33]
double accountEquity = Account.Get(AccountItem.NetLiquidation, Currency.Usd);
if (accountEquity <= 0)
{
Print("Warning in CalculatePositionSize: Account equity is zero or negative.");
return 0;
}
// Calculate risk amount in currency
double riskAmount = accountEquity * (RiskPerTradePercent / 100.0);
// Calculate raw position size
int positionSize = (int)Math.Floor(riskAmount / riskPerContract);
// Apply Min/Max constraints
positionSize = Math.Max(MinPositionSize, positionSize);
positionSize = Math.Min(MaxPositionSize, positionSize);
// Final check: Ensure size is at least 1 if constraints allow
if (positionSize <= 0)
{
// If constraints forced size to 0, but MinPositionSize is > 0, maybe default to MinPositionSize if affordable?
// For now, return 0 if calculation results in <= 0 after constraints.
// Print($"Warning: Calculated position size ({positionSize}) is not valid after applying constraints (Min: {MinPositionSize}, Max: {MaxPositionSize}). Risk Amount: {riskAmount:C}, Risk Per Contract: {riskPerContract:C}");
return 0;
}
return positionSize;
}
/// <summary>
/// Calculates the stop loss price based on the selected method (ATR or Structure). [5, 34]
/// </summary>
/// <param name="isLong">True if calculating for a long position, false for short.</param>
/// <param name="referencePrice">The price to base the calculation on (e.g., entry price, current price).</param>
/// <param name="barsAgoReference">How many bars ago the reference price/ATR/structure applies (0 for current/entry bar).</param>
/// <returns>The calculated stop loss price, rounded to the nearest tick.</returns>
private double CalculateStopLossPrice(bool isLong, double referencePrice, int barsAgoReference = 0)
{
if (atrPrimary == null |
| CurrentBar < Math.Max(StopLossStructureLookback, AtrPeriod) + barsAgoReference + 2) // Ensure enough data
{
Print("Warning: Not enough data or ATR not initialized for CalculateStopLossPrice.");
// Fallback: Use a fixed stop distance? Or return 0?
return isLong? referencePrice - 10 * tickSize : referencePrice + 10 * tickSize; // Example fallback
}
double stopPrice = 0;
if (StopLossMethod == StopLossMethod.ATR)
{
double atrValue = atrPrimary; // Use ATR from the reference bar [35]
double atrOffset = atrValue * StopLossAtrMultiplier;
stopPrice = isLong? referencePrice - atrOffset : referencePrice + atrOffset;
}
else // Structure
{
double structureLevel;
int lookback = StopLossStructureLookback;
if (isLong)
{
// Find lowest low over the lookback period ending 'barsAgoReference' bars ago [5, 36]
int lowestBarIndex = LowestBar(Lows, lookback + barsAgoReference) - barsAgoReference; // Adjust index relative to current bar
if (lowestBarIndex < 0 |
| lowestBarIndex >= lookback) // Check if LowestBar returned a valid index within the intended range
lowestBarIndex = lookback -1; // Fallback to oldest bar in lookback if invalid index
structureLevel = Lows; // Get the low price at that index
stopPrice = structureLevel - (1 * tickSize); // Place stop 1 tick below the low
}
else
{
// Find highest high over the lookback period ending 'barsAgoReference' bars ago [5, 36]
int highestBarIndex = HighestBar(Highs, lookback + barsAgoReference) - barsAgoReference;
if (highestBarIndex < 0 |
| highestBarIndex >= lookback)
highestBarIndex = lookback -1;
structureLevel = Highs;
stopPrice = structureLevel + (1 * tickSize); // Place stop 1 tick above the high
}
}
// Ensure stop is rounded to tick size
return Instrument.MasterInstrument.RoundToTickSize(stopPrice);
}
/// <summary>
/// Calculates the final take profit price based on the selected method (ATR Multiple or Fixed Ratio).
/// </summary>
/// <param name="isLong">True if calculating for a long position.</param>
/// <param name="entryPrice">The position's entry price.</param>
/// <param name="stopLossPrice">The position's initial stop loss price.</param>
/// <returns>The calculated take profit price, rounded to the nearest tick.</returns>
private double CalculateTakeProfitPrice(bool isLong, double entryPrice, double stopLossPrice)
{
if (atrPrimary == null |
| CurrentBar < AtrPeriod + 2) // Ensure enough data for ATR
{
Print("Warning: Not enough data or ATR not initialized for CalculateTakeProfitPrice.");
// Fallback: Use fixed R:R?
double riskPoints = Math.Abs(entryPrice - stopLossPrice);
return isLong? entryPrice + riskPoints * TakeProfitRiskRewardRatio : entryPrice - riskPoints * TakeProfitRiskRewardRatio; // Example fallback
}
double takeProfitPrice = 0;
double riskPoints = Math.Abs(entryPrice - stopLossPrice);
if (TakeProfitMethod == TakeProfitMethod.ATRMultiple)
{
double atrValue = atrPrimary; // Use current ATR
double atrOffset = atrValue * TakeProfitAtrMultiplier;
takeProfitPrice = isLong? entryPrice + atrOffset : entryPrice - atrOffset;
}
else // FixedRatio
{
if (riskPoints.ApproxCompare(0) > 0) // Ensure risk is not zero
{
takeProfitPrice = isLong? entryPrice + riskPoints * TakeProfitRiskRewardRatio : entryPrice - riskPoints * TakeProfitRiskRewardRatio;
}
else
{
// Handle zero risk case - maybe use ATR multiple as fallback?
Print("Warning: Risk is zero, cannot calculate Fixed Ratio TP. Using ATR fallback.");
double atrValue = atrPrimary;
double atrOffset = atrValue * TakeProfitAtrMultiplier;
takeProfitPrice = isLong? entryPrice + atrOffset : entryPrice - atrOffset;
}
}
return Instrument.MasterInstrument.RoundToTickSize(takeProfitPrice);
}
/// <summary>
/// Calculates the price for a partial take profit target based on a Risk/Reward ratio.
/// </summary>
/// <param name="isLong">True if calculating for a long position.</param>
/// <param name="entryPrice">The position's entry price.</param>
/// <param name="stopLossPrice">The position's initial stop loss price.</param>
/// <param name="partialProfitRRRatio">The Risk/Reward ratio for this partial target.</param>
/// <returns>The calculated partial take profit price, rounded to the nearest tick.</returns>
private double CalculatePartialTakeProfitPrice(bool isLong, double entryPrice, double stopLossPrice, double partialProfitRRRatio)
{
double riskPoints = Math.Abs(entryPrice - stopLossPrice);
double takeProfitPrice = 0;
if (riskPoints.ApproxCompare(0) > 0 && partialProfitRRRatio > 0)
{
takeProfitPrice = isLong? entryPrice + riskPoints * partialProfitRRRatio : entryPrice - riskPoints * partialProfitRRRatio;
}
else
{
// Handle zero risk or invalid ratio - fallback?
Print($"Warning: Cannot calculate Partial TP Price (Risk: {riskPoints}, RR Ratio: {partialProfitRRRatio}). Returning entry price.");
return entryPrice; // Avoid placing order at invalid level
}
return Instrument.MasterInstrument.RoundToTickSize(takeProfitPrice);
}
/// <summary>
/// Calculates the potential trailing stop price based on the selected method (ATR or Structure).
/// Used within the manual trailing logic in OnBarUpdate.
/// </summary>
/// <param name="isLong">True if calculating for a long position.</param>
/// <returns>The potential new trailing stop price, rounded to the nearest tick.</returns>
private double CalculatePotentialTrailingStop(bool isLong)
{
if (atrPrimary == null |
| CurrentBar < Math.Max(TrailingStopStructureLookback, AtrPeriod) + 2) // Ensure enough data
{
Print("Warning: Not enough data or ATR not initialized for CalculatePotentialTrailingStop.");
return activeStopPrice; // Return current stop if cannot calculate
}
double potentialStop = 0;
if (TrailingStopMethod == TrailingStopMethod.ATR)
{
// Trail relative to the *current* close, using previous bar's ATR
double atrValue = atrPrimary[1]; // Use previous bar's ATR for stability
double atrOffset = atrValue * TrailingStopAtrMultiplier;
potentialStop = isLong? Closes - atrOffset : Closes + atrOffset;
}
else // Structure
{
double structureLevel;
int lookback = TrailingStopStructureLookback;
if (isLong)
{
// Trail below the lowest low of the lookback period *ending 1 bar ago* [5, 37]
int lowestBarIndex = LowestBar(Lows, lookback + 1) -1; // Index relative to bar 1 ago
if (lowestBarIndex < 0 |
| lowestBarIndex >= lookback) lowestBarIndex = lookback -1;
structureLevel = Lows; // Price from 1 bar ago's lookback
potentialStop = structureLevel - (1 * tickSize);
}
else
{
// Trail above the highest high of the lookback period ending 1 bar ago
int highestBarIndex = HighestBar(Highs, lookback + 1) -1;
if (highestBarIndex < 0 |
| highestBarIndex >= lookback) highestBarIndex = lookback -1;
structureLevel = Highs;
potentialStop = structureLevel + (1 * tickSize);
}
}
return Instrument.MasterInstrument.RoundToTickSize(potentialStop);
}
/// <summary>
/// Helper to get the current VWAP value, abstracting whether built-in or approximation is used.
/// </summary>
/// <param name="barsInProgressIndex">The BarsArray index.</param>
/// <returns>The VWAP value for the current bar on the specified timeframe.</returns>
private double GetCurrentVWAP(int barsInProgressIndex)
{
if (UseOrderFlowVWAP)
{
OrderFlowVWAP vwapInst = null;
if (barsInProgressIndex == 0) vwapInst = vwapBuiltInPrimary;
else if (barsInProgressIndex == 1) vwapInst = vwapBuiltInSecondary1;
else if (barsInProgressIndex == 2) vwapInst = vwapBuiltInSecondary2;
return (vwapInst!= null && vwapInst.VWAP.IsValidDataPoint(0))? vwapInst.VWAP : 0;
}
else
{
VWAPDaily vwapInst = null;
if (barsInProgressIndex == 0) vwapInst = vwapApproxPrimary;
else if (barsInProgressIndex == 1) vwapInst = vwapApproxSecondary1;
else if (barsInProgressIndex == 2) vwapInst = vwapApproxSecondary2;
// Assuming the approximation indicator has a plot named "VWAP" or similar
return (vwapInst!= null && vwapInst.IsValidDataPoint(0))? vwapInst : 0;
}
}
#endregion
#region OnBarUpdate Implementation (Steps 2, 5, 6, 9, 10 & VII)
/// <summary>
/// Called on each bar update. Contains the core strategy logic, including
/// session/risk management, signal generation, entry execution, and position management (trailing stops).
/// </summary>
protected override void OnBarUpdate()
{
// --- Initial Checks ---
if (CurrentBar < BarsRequiredToTrade) // Ensure enough bars for all lookbacks [27]
return;
// If using Tick Replay based VP, might need to handle historical state differently
// if (State == State.Historical && VPApproximationMethod == VPApproximation.DValueAreaStyle && Bars.IsTickReplay)
// UpdateVolumeProfile(); // Update VP on historical ticks if needed
// --- Daily PnL / Session Rollover Logic ---
// Check if it's a new trading day based on the date part of the bar time
if (Time.Date!= currentTradingDay)
{
// Capture the cumulative PnL at the *end* of the previous day (or start of the new one before any trades) [38]
startOfDayCumProfit = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit;
isDailyLossLimitReached = false; // Reset daily loss flag
currentTradingDay = Time.Date; // Update the current trading day
sessionVolumeProfile.Clear(); // Reset volume profile data
isVpLevelsCalculated = false;
totalSessionVolume = 0;
pocPrice = 0;
vahPrice = 0;
valPrice = 0;
// Reset position state flags ONLY if flat, otherwise they persist across days if position held overnight (though IsExitOnSessionCloseStrategy should prevent this)
if(Position.MarketPosition == MarketPosition.Flat)
{
ResetPositionState();
}
Print($"New Trading Day: {currentTradingDay.ToShortDateString()}. Start of Day CumProfit: {startOfDayCumProfit:C}. Daily Loss Limit Reset.");
}
// --- Daily Max Loss Check (Step 10) ---
// Calculate PnL realized *today* [38, 39, 40, 41]
double currentDailyRealizedPnL = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - startOfDayCumProfit;
// Include unrealized PnL for the check? Optional, depends on requirements. Let's include it for stricter control.
double currentDailyTotalPnL = currentDailyRealizedPnL + Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Closes);
if (!isDailyLossLimitReached && MaxDailyLossCurrency > 0 && currentDailyTotalPnL <= -MaxDailyLossCurrency)
{
isDailyLossLimitReached = true;
Print($"{Time}: Daily Max Loss Limit Reached! Daily PnL: {currentDailyTotalPnL:C} <= -{MaxDailyLossCurrency:C}. Halting trading for the day and flattening position.");
if (Position.MarketPosition!= MarketPosition.Flat)
{
if (Position.MarketPosition == MarketPosition.Long) ExitLong("Daily Loss Exit", lastEntrySignalName);
else ExitShort("Daily Loss Exit", lastEntrySignalName);
}
// Optional: Cancel working orders? Managed approach might handle this via StopTargetHandling.
// CancelAllOrders(); // Use with caution if managing orders manually
}
// --- Session Time Filter (Step 10) ---
// Convert current bar time and session parameters to integer format (HHMMSS) for comparison
int currentTimeInt = ToTime(Time);
int sessionStartTimeInt = ToTime(SessionStartTime);
int sessionEndTimeInt = ToTime(SessionEndTime);
isTradingWindowActive = (currentTimeInt >= sessionStartTimeInt && currentTimeInt < sessionEndTimeInt); // Use < EndTime to avoid trading on the exact end bar
// --- Process Only Primary Bar Updates for Core Logic ---
// Use BarsInProgress to ensure core logic runs only once per primary bar update [27, 42, 43, 44]
if (BarsInProgress!= 0)
return;
// --- Update Volume Profile (Step 4) ---
// Update VP only during the active trading window to represent the session profile
if (isTradingWindowActive)
{
UpdateVolumeProfile();
}
// --- Entry Logic Gate ---
// Check conditions for potential new entries
bool canEnterTrade = Position.MarketPosition == MarketPosition.Flat && isTradingWindowActive &&!isDailyLossLimitReached;
if (canEnterTrade)
{
// --- Calculate VP Levels (lazily, only if needed for entry) ---
if (!isVpLevelsCalculated && sessionVolumeProfile.Count > 0)
{
pocPrice = CalculatePOC();
CalculateValueArea(); // Calculates VAH/VAL
//Print($"VP Calculated: POC={pocPrice}, VAH={vahPrice}, VAL={valPrice}");
}
// --- Indicator Confluence Checks (Step 5) ---
bool isPriceAboveVwap = GetCurrentVWAP(0) > 0 && Closes > GetCurrentVWAP(0); // Check VWAP > 0 to avoid issues before calculation
bool isFastAboveSlowPrimary = emaFastPrimary > emaSlowPrimary;
bool isRsiBullish = rsiPrimary > RsiLevelBullish;
bool isRsiBearish = rsiPrimary < RsiLevelBearish;
// Higher Timeframe Context Checks
bool isHTF1Bullish = BarsArray.Length > 1 && emaFastSecondary1!= null && emaSlowSecondary1!= null && emaFastSecondary1 > emaSlowSecondary1;
bool isHTF2Bullish = BarsArray.Length > 2 && emaFastSecondary2!= null && emaSlowSecondary2!= null && emaFastSecondary2 > emaSlowSecondary2;
bool isHTF1Bearish = BarsArray.Length > 1 && emaFastSecondary1!= null && emaSlowSecondary1!= null && emaFastSecondary1 < emaSlowSecondary1;
bool isHTF2Bearish = BarsArray.Length > 2 && emaFastSecondary2!= null && emaSlowSecondary2!= null && emaFastSecondary2 < emaSlowSecondary2;
// --- Price Action Signal Checks (Step 3) ---
double fvgHigh, fvgLow;
int fvgSignal = DetectFVG(0, 1, out fvgHigh, out fvgLow); // Check 1 bar ago for FVG pattern
bool fvgBullishRetest = (fvgSignal == 1 && Lows <= fvgHigh && Closes > fvgLow); // Price dipped into bullish FVG and closed above bottom
bool fvgBearishRetest = (fvgSignal == -1 && Highs >= fvgLow && Closes < fvgHigh); // Price touched into bearish FVG and closed below top
int divergenceSignal = DetectDivergence(0);
bool bullishDivergence = divergenceSignal > 0; // Regular or Hidden Bullish
bool bearishDivergence = divergenceSignal < 0; // Regular or Hidden Bearish
// --- Volume Profile Context Checks (Step 4) ---
bool isAboveVAL = valPrice > 0 && Closes > valPrice;
bool isBelowVAH = vahPrice > 0 && Closes < vahPrice;
bool isAbovePOC = pocPrice > 0 && Closes > pocPrice;
bool isBelowPOC = pocPrice > 0 && Closes < pocPrice;
// --- Core Entry Logic (Step 6) ---
bool longSetup = false;
bool shortSetup = false;
// Define Long Setup Conditions (Example Combination - refine based on specific strategy rules)
if (isHTF1Bullish && isHTF2Bullish) // Higher timeframe trend alignment
{
if (fvgBullishRetest |
| bullishDivergence) // Price action signal
{
if (isAboveVAL && isAbovePOC) // Volume profile context (e.g., above value, above POC)
{
if (isPriceAboveVwap && isFastAboveSlowPrimary && isRsiBullish) // Indicator confluence
{
longSetup = true;
}
}
}
}
// Define Short Setup Conditions (Example Combination - mirrored logic)
if (isHTF1Bearish && isHTF2Bearish) // Higher timeframe trend alignment
{
if (fvgBearishRetest |
| bearishDivergence) // Price action signal
{
if (isBelowVAH && isBelowPOC) // Volume profile context (e.g., below value, below POC)
{
if (!isPriceAboveVwap &&!isFastAboveSlowPrimary && isRsiBearish) // Indicator confluence
{
shortSetup = true;
}
}
}
}
// --- Execute Entry ---
if (longSetup |
| shortSetup)
{
// Calculate Initial Stop Loss Price (Step 8, part 1)
double initialStopPrice = CalculateStopLossPrice(longSetup, Closes, 0);
// Calculate Position Size (Step 7)
int size = CalculatePositionSize(Closes, initialStopPrice);
if (size > 0)
{
// Generate unique signal name for this entry [26]
lastEntrySignalName = (longSetup? "LongEntry_" : "ShortEntry_") + CurrentBar + "_" + Time.ToString("HHmmss");
if (longSetup)
{
Print($"{Time}: Long Setup Confirmed. Conditions: HTF Bullish, PA Signal, VP Context, Indicator Confluence. Size: {size}, Entry: ~{Closes}, Initial SL: {initialStopPrice}");
EnterLong(size, lastEntrySignalName);
}
else // shortSetup
{
Print($"{Time}: Short Setup Confirmed. Conditions: HTF Bearish, PA Signal, VP Context, Indicator Confluence. Size: {size}, Entry: ~{Closes}, Initial SL: {initialStopPrice}");
EnterShort(size, lastEntrySignalName);
}
// Stop/Target/Partials will be placed in OnExecutionUpdate once fill is confirmed
}
else
{
Print($"{Time}: {(longSetup? "Long" : "Short")} Setup Confirmed, but calculated position size is 0. No trade entered. Risk%: {RiskPerTradePercent}, StopDist: {Math.Abs(Closes-initialStopPrice):F2}");
}
}
}
// --- Position Management Logic (Step 9) ---
else if (Position.MarketPosition!= MarketPosition.Flat && stopLossOrder!= null &&!isDailyLossLimitReached) // Only manage if in position, stop exists, and not halted
{
bool isLong = Position.MarketPosition == MarketPosition.Long;
// --- Break-Even Logic ---
if (MoveStopToBreakEven &&!breakEvenActivated)
{
double riskPoints = Math.Abs(entryPrice - activeStopPrice); // Use the *active* stop price
if (riskPoints > 0)
{
double triggerPrice = isLong? entryPrice + riskPoints * BreakEvenTriggerRRRatio
: entryPrice - riskPoints * BreakEvenTriggerRRRatio;
triggerPrice = Instrument.MasterInstrument.RoundToTickSize(triggerPrice);
bool triggerMet = (isLong && Closes >= triggerPrice) |
| (!isLong && Closes <= triggerPrice);
if (triggerMet)
{
double bePrice = entryPrice + (isLong? 1 : -1) * BreakEvenPlusTicks * tickSize;
bePrice = Instrument.MasterInstrument.RoundToTickSize(bePrice);
// Check if BE price is actually better than current active stop
bool isBEBetter = (isLong && bePrice > activeStopPrice) |
| (!isLong && bePrice < activeStopPrice);
if (isBEBetter)
{
Print($"{Time}: BreakEven Trigger Met (Close: {Closes}, Trigger: {triggerPrice}). Moving stop to {bePrice}");
// Modify the existing stop loss order using SetStopLoss [25, 45, 46]
// Use the unique entry signal name the stop is associated with
SetStopLoss(lastEntrySignalName, CalculationMode.Price, bePrice, false);
activeStopPrice = bePrice; // Update tracked stop price
breakEvenActivated = true;
}
}
}
}
// --- Trailing Stop Logic ---
if (EnableTrailingStop)
{
// Determine if trailing should be active (e.g., after BE or at specific R:R)
bool canTrail = breakEvenActivated; // Simple: Trail after BE
// OR: Check R:R Trigger
if (!canTrail && TrailingStopTriggerRRRatio > 0)
{
double riskPoints = Math.Abs(entryPrice - activeStopPrice);
if(riskPoints > 0)
{
double trailTriggerPrice = isLong? entryPrice + riskPoints * TrailingStopTriggerRRRatio
: entryPrice - riskPoints * TrailingStopTriggerRRRatio;
trailTriggerPrice = Instrument.MasterInstrument.RoundToTickSize(trailTriggerPrice);
canTrail = (isLong && Closes >= trailTriggerPrice) |
| (!isLong && Closes <= trailTriggerPrice);
}
}
if (canTrail)
{
if (!trailingStopActivated)
{
Print($"{Time}: Trailing Stop Activated.");
trailingStopActivated = true; // Activate flag only once
}
// Calculate potential new stop based on chosen method (ATR or Structure)
double potentialTrailStop = CalculatePotentialTrailingStop(isLong);
// Check if the potential new stop is more favorable than the active stop
bool isTrailBetter = (isLong && potentialTrailStop > activeStopPrice) |
| (!isLong && potentialTrailStop < activeStopPrice);
if (isTrailBetter)
{
Print($"{Time}: Trailing Stop Update. Moving stop from {activeStopPrice} to {potentialTrailStop}");
// Modify the existing stop loss order using SetStopLoss
SetStopLoss(lastEntrySignalName, CalculationMode.Price, potentialTrailStop, false);
activeStopPrice = potentialTrailStop; // Update tracked stop price
}
}
}
}
}
#endregion
#region OnExecutionUpdate Implementation (Steps 8, 9 & VIII)
/// <summary>
/// Called on every execution update (fill or partial fill).
/// Used here to place initial stop loss, take profit, and partial profit orders
/// once an entry order is filled. Also handles resetting state on exit fills. [26]
/// </summary>
protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
{
// Ignore executions not related to this strategy instance or non-fills
if (execution.Order == null |
| execution.Order.IsInternal |
| execution.Order.OrderState!= OrderState.Filled) // Only process fully filled orders for simplicity here
{
// Note: Handling OrderState.PartFilled requires more complex logic to manage exits for partially filled entries.
// The current approach assumes the entry order signal ('lastEntrySignalName') represents the intended full size,
// and exits are placed once that signal leads to a fill (even if it was technically a partial fill of a larger requested size).
// For true partial profit scaling based on partial entry fills, splitting the entry into multiple orders is more robust. [26]
return;
}
// --- Entry Fill Handling (Place Initial Exits - Step 8) ---
if (execution.Order.Name == lastEntrySignalName && filledEntryQuantity == 0) // Check if it's the first fill for our tracked entry signal
{
entryPrice = execution.AverageFillPrice;
filledEntryQuantity = execution.Order.Filled; // Total filled quantity for this order object
bool isLong = execution.Order.OrderAction == OrderAction.Buy |
| execution.Order.OrderAction == OrderAction.BuyToCover;
Print($"{time}: Entry Order '{execution.Order.Name}' Filled. Qty: {filledEntryQuantity}, AvgPrice: {entryPrice:F2}");
// Calculate and Set Initial Stop Loss [25, 47]
activeStopPrice = CalculateStopLossPrice(isLong, entryPrice, 0); // Use entry bar for initial calculation
stopLossOrder = SetStopLoss(lastEntrySignalName, CalculationMode.Price, activeStopPrice, false);
if (stopLossOrder!= null)
Print($" Initial Stop Loss set at {activeStopPrice:F2} for signal {lastEntrySignalName}");
else
Print($" Error: Failed to set initial Stop Loss for signal {lastEntrySignalName}");
// Calculate and Set Final Take Profit [24, 47]
double finalTakeProfitPrice = CalculateTakeProfitPrice(isLong, entryPrice, activeStopPrice);
SetProfitTarget(lastEntrySignalName, CalculationMode.Price, finalTakeProfitPrice, false);
Print($" Final Take Profit set at {finalTakeProfitPrice:F2} for signal {lastEntrySignalName}");
// --- Place Partial Profit Orders (Step 9) ---
int remainingQuantity = filledEntryQuantity;
partialProfitOrders.Clear(); // Clear any previous partial order tracking
if (EnablePartialProfit1 && remainingQuantity > 0)
{
int pp1Quantity = (int)Math.Floor(filledEntryQuantity * (PartialProfit1Percent / 100.0));
pp1Quantity = Math.Min(pp1Quantity, remainingQuantity); // Ensure we don't exit more than available
if (pp1Quantity > 0)
{
double pp1Price = CalculatePartialTakeProfitPrice(isLong, entryPrice, activeStopPrice, PartialProfit1RRRatio);
string pp1Signal = "PP1_" + lastEntrySignalName;
IOrder pp1Order = null;
if (isLong)
pp1Order = ExitLongLimit(pp1Quantity, pp1Price, pp1Signal, lastEntrySignalName);
else
pp1Order = ExitShortLimit(pp1Quantity, pp1Price, pp1Signal, lastEntrySignalName);
if (pp1Order!= null)
{
partialProfitOrders = pp1Order;
remainingQuantity -= pp1Quantity;
Print($" Partial Profit 1 set: Qty={pp1Quantity}, Price={pp1Price:F2}, Signal={pp1Signal}");
}
else Print($" Error: Failed to set Partial Profit 1 for signal {lastEntrySignalName}");
}
}
if (EnablePartialProfit2 && remainingQuantity > 0)
{
// Calculate PP2 quantity based on *original* filled size, but ensure it doesn't exceed remaining
int pp2BaseQuantity = (int)Math.Floor(filledEntryQuantity * (PartialProfit2Percent / 100.0));
int pp2Quantity = Math.Min(pp2BaseQuantity, remainingQuantity);
if (pp2Quantity > 0)
{
double pp2Price = CalculatePartialTakeProfitPrice(isLong, entryPrice, activeStopPrice, PartialProfit2RRRatio);
string pp2Signal = "PP2_" + lastEntrySignalName;
IOrder pp2Order = null;
if (isLong)
pp2Order = ExitLongLimit(pp2Quantity, pp2Price, pp2Signal, lastEntrySignalName);
else
pp2Order = ExitShortLimit(pp2Quantity, pp2Price, pp2Signal, lastEntrySignalName);
if (pp2Order!= null)
{
partialProfitOrders = pp2Order;
remainingQuantity -= pp2Quantity;
Print($" Partial Profit 2 set: Qty={pp2Quantity}, Price={pp2Price:F2}, Signal={pp2Signal}");
}
else Print($" Error: Failed to set Partial Profit 2 for signal {lastEntrySignalName}");
}
}
// Reset state flags for the new position
breakEvenActivated = false;
trailingStopActivated = false;
}
// --- Partial Profit Fill Handling ---
else if (partialProfitOrders.ContainsKey(execution.Order.Name))
{
Print($"{time}: Partial Profit Order '{execution.Order.Name}' Filled. Qty: {execution.Quantity}, Price: {execution.Price:F2}");
partialProfitOrders.Remove(execution.Order.Name); // Remove from active tracking
// Optional: Check if break-even should be triggered now if not already active
if (MoveStopToBreakEven &&!breakEvenActivated && stopLossOrder!= null)
{
bool isLongPos = Position.MarketPosition == MarketPosition.Long;
double bePrice = entryPrice + (isLongPos? 1 : -1) * BreakEvenPlusTicks * tickSize;
bePrice = Instrument.MasterInstrument.RoundToTickSize(bePrice);
bool isBEBetter = (isLongPos && bePrice > activeStopPrice) |
| (!isLongPos && bePrice < activeStopPrice);
if(isBEBetter)
{
Print(" Moving stop to BreakEven+ ({bePrice:F2}) after partial profit taken.");
SetStopLoss(lastEntrySignalName, CalculationMode.Price, bePrice, false);
activeStopPrice = bePrice;
breakEvenActivated = true;
}
}
}
// --- Stop Loss / Final Target Fill Handling ---
// Check if the execution corresponds to our tracked stop loss order OR the internally named final profit target
else if ((stopLossOrder!= null && execution.Order.OrderId == stopLossOrder.OrderId) |
| execution.Order.Name == "Profit target") // Default name for SetProfitTarget exit [24]
{
Print("{time}: Position Closed by '{execution.Order.Name}'. Qty: {execution.Quantity}, Price: {execution.Price:F2}");
// Reset all position-related state variables
ResetPositionState();
}
// --- Daily Loss Limit Exit Handling ---
else if (execution.Order.Name == "Daily Loss Exit")
{
Print("{time}: Position Flattened due to Daily Loss Limit by '{execution.Order.Name}'. Qty: {execution.Quantity}, Price: {execution.Price:F2}");
ResetPositionState();
// isDailyLossLimitReached remains true until next day rollover
}
// --- Session Close Exit Handling ---
else if (execution.Order.Name == "Exit on session close") // Default name for IsExitOnSessionCloseStrategy
{
Print("{time}: Position Flattened by Exit On Session Close. Qty: {execution.Quantity}, Price: {execution.Price:F2}");
ResetPositionState();
}
}
/// <summary>
/// Helper method to reset position-specific state variables.
/// Called when a position is fully closed (by stop, target, or flatten).
/// </summary>
private void ResetPositionState()
{
stopLossOrder = null;
partialProfitOrders.Clear();
filledEntryQuantity = 0;
entryPrice = 0;
activeStopPrice = 0;
breakEvenActivated = false;
trailingStopActivated = false;
lastEntrySignalName = string.Empty;
// Do NOT reset daily PnL variables here, only position state
}
#endregion
#region OnOrderUpdate Implementation (Optional - Step IX)
/// <summary>
/// Called on order status changes (Submitted, Accepted, Cancelled, etc.).
/// Can be used for detailed order tracking, logging, or advanced unmanaged order handling.
/// For this managed strategy, it's primarily for logging/debugging if needed. [6, 48]
/// </summary>
protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
{
// Log state changes for debugging if TraceOrders is enabled
if (TraceOrders)
Print($"{time}: OrderUpdate: {order.Name} ({order.OrderId}) - State: {orderState}, Filled: {filled}/{order.Quantity} @ {averageFillPrice:F2}, Error: {error}");
// Update our reference to the stop loss order if it changes state (e.g., gets accepted)
if (stopLossOrder!= null && order.OrderId == stopLossOrder.OrderId)
{
stopLossOrder = order; // Keep the reference updated
}
// Update references to partial profit orders
if (partialProfitOrders.ContainsKey(order.Name) && partialProfitOrders[order.Name].OrderId == order.OrderId)
{
if (order.IsTerminalState()) // If filled or cancelled, remove from tracking [6]
partialProfitOrders.Remove(order.Name);
else
partialProfitOrders[order.Name] = order; // Update reference
}
// Handle potential errors
if (orderState == OrderState.Rejected |
| orderState == OrderState.Cancelled)
{
if (error!= ErrorCode.NoError && error!= ErrorCode.Unknown) // Ignore simple cancels
Print($"Error/Rejection: Order {order.Name} ({order.OrderId}) failed. State: {orderState}, Error: {error}, Native: {nativeError}");
// If an essential order (like SL) fails, consider flattening?
if (stopLossOrder!= null && order.OrderId == stopLossOrder.OrderId && order.IsTerminalState())
{
Print($"Warning: Active Stop Loss order ({order.Name}) reached terminal state ({orderState}) unexpectedly. Error: {error}. Consider manual intervention or flattening logic.");
// Potentially flatten position if stop order fails critically
// if(Position.MarketPosition!= MarketPosition.Flat) FlattenStrategy("Stop Loss Order Failed");
stopLossOrder = null; // Clear the reference
}
// If an entry order fails, clear the signal name
if(order.Name == lastEntrySignalName && order.IsTerminalState())
{
lastEntrySignalName = string.Empty;
}
}
}
#endregion
#region Helper Enums
/// <summary>
/// Defines methods for calculating stop loss.
/// </summary>
public enum StopLossMethod
{
ATR,
Structure
}
/// <summary>
/// Defines methods for calculating take profit.
/// </summary>
public enum TakeProfitMethod
{
ATRMultiple,
FixedRatio
}
/// <summary>
/// Defines methods for calculating trailing stop loss.
/// </summary>
public enum TrailingStopMethod
{
ATR,
Structure
}
/// <summary>
/// Defines oscillators available for divergence detection.
/// </summary>
public enum DivergenceSource
{
RSI,
MACD
}
/// <summary>
/// Defines methods for approximating Volume Profile.
/// </summary>
public enum VPApproximation
{
DValueAreaStyle, // Distributes bar volume across price range (more accurate with Tick Replay)
BarDataApproximation // Simpler, assigns volume to typical price
}
/// <summary>
/// Defines how an FVG is considered mitigated.
/// </summary>
public enum FVGMitigation
{
Close, // Bar closes within the FVG
Wick, // Bar wick touches or penetrates the FVG
Touch // Bar high/low touches the FVG boundary
}
#endregion
} // End of Class InstitutionalESBot
#region VWAP Approximation Indicator Placeholder
// This is a placeholder for a simple daily VWAP approximation.
// Replace with a more robust indicator if needed, especially if not using OrderFlow+.
// Ensure the indicator resets daily.
namespace NinjaTrader.NinjaScript.Indicators.Institutional
{
public class VWAPDaily : Indicator
{
private double cumulativeTypicalPriceVolume = 0;
private long cumulativeVolume = 0;
private DateTime currentTradingDay = DateTime.MinValue;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Simple Daily VWAP Approximation";
Name = "VWAPDaily";
IsOverlay = true;
IsAutoScale = false;
DrawOnPricePanel = true;
DrawHorizontalGridLines = true;
DrawVerticalGridLines = true;
PaintPriceMarkers = true;
ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
IsSuspendedWhileInactive = true; // Performance optimization
AddPlot(Brushes.DodgerBlue, "VWAP");
}
else if (State == State.DataLoaded)
{
// Reset on DataLoaded
cumulativeTypicalPriceVolume = 0;
cumulativeVolume = 0;
currentTradingDay = DateTime.MinValue;
}
else if (State == State.Historical)
{
// Potentially pre-calculate historical VWAP if needed, handle daily resets carefully
}
}
protected override void OnBarUpdate()
{
if (CurrentBar < 1) return;
// Reset VWAP calculation at the start of a new trading day
if (Time.Date!= currentTradingDay)
{
cumulativeTypicalPriceVolume = 0;
cumulativeVolume = 0;
currentTradingDay = Time.Date;
}
// Calculate Typical Price: (High + Low + Close) / 3
double typicalPrice = (High + Low + Close) / 3.0;
long volume = Volume;
if (volume > 0)
{
cumulativeTypicalPriceVolume += typicalPrice * volume;
cumulativeVolume += volume;
}
// Calculate VWAP
if (cumulativeVolume > 0)
{
Value = cumulativeTypicalPriceVolume / cumulativeVolume;
}
else
{
Value = Close; // Default to close if no volume yet
}
}
}
}
#endregion
} // End of Namespace