#region Using declarations using System; using NinjaTrader.Cbi; using NinjaTrader.Gui.Tools; using NinjaTrader.NinjaScript; using NinjaTrader.NinjaScript.StrategyAnalyzer; using NinjaTrader.Data; using NinjaTrader.NinjaScript.Strategies; using System.Windows.Media; #endregion namespace NinjaTrader.NinjaScript.Indicators { public class PositionLimitIndicator : Indicator { private double maxPositionSize = 0.2; // 20 micro lots private TimeSpan lockStartTime; private TimeSpan lockEndTime; protected override void OnStateChange() { if (State.SetDefaults) { Description = @"Indicator that prevents adding to a position beyond a specified limit."; Name = "PositionLimitIndicator"; Calculate = Calculate.OnEachTick; IsOverlay = true; AddPlot(Brushes.Orange, "LimitReached"); } else if (State.Configure) { // Set lock time window (e.g., 09:30 to 16:00) lockStartTime = new TimeSpan(9, 30, 0); lockEndTime = new TimeSpan(16, 0, 0); } } protected override void OnBarUpdate() { if (CurrentBars[0] < 1) return; // Check if the current time is within the lock window TimeSpan currentTime = Time[0].TimeOfDay; if (currentTime >= lockStartTime && currentTime <= lockEndTime) { double currentPositionSize = Position.MarketPosition != MarketPosition.Flat ? Position.Quantity : 0; double pendingOrdersSize = GetPendingOrdersSize(); double totalSize = currentPositionSize + pendingOrdersSize; // Prevent adding to position if limit is reached if (totalSize > maxPositionSize) { // Plot indicator or take some action Values[0][0] = maxPositionSize; // Additional logic to handle prevention can be added here } else { Values[0][0] = 0; } } } private double GetPendingOrdersSize() { double size = 0; foreach (Order order in Account.Orders) { if (order.OrderState == OrderState.Working && order.Name != Name) { size += order.Quantity; } } return size; } } }