PnL Monitor Add-On

Hi,
here I share my PnL real-time account monitoring Add-On I have developed with the help of Perplexity and DeepSeek for monitoring my account in a user-friendly manner.

PnLMonitorROI is a NinjaTrader 8 Add-On that monitors an account’s profit and loss in real time. It opens a floating window from Control Center → Tools → PnL Monitor ROI where the user selects an account and sees live PnL, account value, and a semicircular gauge whose needle moves from red (loss) to green (profit). The user can set a Profit Target and Loss Limit; when either is reached, the add-on plays a sound and shows a popup with instructions. The window also lists all open positions (instrument, signed quantity, unrealized PnL) and offers a Close All Trades button to flatten the account. The add-on displays a custom logo (ROIPro.png) in the bottom-left corner, and this image file is required — it must be saved in the NinjaTrader templates folder (Documents\NinjaTrader 8\templates\). If the image is missing, the logo and the Close All Trades button will not be displayed, since both are rendered within the same UI block. I attach a ROIPro logo in a reply message below to save it in that location. Feel free to add another image in .png format and similar size if you want.

2 Likes
///First part of the code
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using NinjaTrader.Cbi;
using NinjaTrader.NinjaScript;
using NinjaTrader.Gui.NinjaScript;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Tools;
using NinjaTrader.NinjaScript.DrawingTools;
using System.Reflection;
using System.Text;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Linq;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Media;

namespace NinjaTrader.NinjaScript.AddOns
{
    public class PnLMonitorROI : AddOnBase, INotifyPropertyChanged
    {
        private readonly object _riskLock = new object();
        private double _profitTarget;
        private double _lossLimit;
        private bool _limitAlreadyTriggered = false;
        private bool _thresholdPopupOpen = false;
        private string _lastThresholdMessage = string.Empty;

        private Account _account;
        private PnLMonitorWindowvROI _monitorWindow;
        private DispatcherTimer _liveTimer;
        private double _currentPnL;
        private double _displayAccountValue;

        private NTMenuItem _menuItem;
        private bool _windowOpening;

        private readonly string _ninjaTraderSoundsFolder = @"C:\Program Files (x86)\NinjaTrader 8\sounds";
        private readonly string _profitSoundFile = "crossed.wav";
        private readonly string _lossSoundFile = "crossed.wav";

        [NinjaScriptProperty]
        [Display(Name = "Profit Target ($)", Description = "Objetivo de ganancia para cerrar posiciones", Order = 1, GroupName = "Parámetros")]
        public double ProfitTarget
        {
            get { lock (_riskLock) { return _profitTarget; } }
            set { lock (_riskLock) { _profitTarget = value; } }
        }

        [NinjaScriptProperty]
        [Display(Name = "Loss Limit ($)", Description = "Límite de pérdida para cerrar posiciones", Order = 2, GroupName = "Parámetros")]
        public double LossLimit
        {
            get { lock (_riskLock) { return _lossLimit; } }
            set { lock (_riskLock) { _lossLimit = value; } }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public string AccountName
        {
            get { return _account != null ? _account.Name : "No Account Selected"; }
        }

        public void ClearWindowReference()
        {
            _monitorWindow = null;
            _windowOpening = false;
        }

        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Description = "PnL Monitor Add-On: Monitorea el PnL en tiempo real y gestiona el riesgo.";
                Name = "PnLMonitorROI";
                ProfitTarget = 4000;
                LossLimit = -4000;
            }
            else if (State == State.Configure)
            {
                Core.Globals.RandomDispatcher.Invoke(new Action(delegate()
                {
                    _liveTimer = new DispatcherTimer();
                    _liveTimer.Interval = TimeSpan.FromMilliseconds(250);
                    _liveTimer.Tick += OnLiveTimerTick;
                }));
            }
            else if (State == State.Terminated)
            {
                Core.Globals.RandomDispatcher.Invoke(new Action(delegate()
                {
                    if (_liveTimer != null)
                    {
                        _liveTimer.Stop();
                        _liveTimer.Tick -= OnLiveTimerTick;
                    }
                }));

                if (_account != null)
                    _account.AccountItemUpdate -= OnAccountItemUpdate;

                System.Windows.Application.Current.Dispatcher.Invoke(new Action(delegate()
                {
                    if (_monitorWindow != null)
                    {
                        _monitorWindow.Close();
                        _monitorWindow = null;
                    }

                    _windowOpening = false;
                }));
            }
        }

        public void SetAccount(Account account)
        {
            if (_account != null)
                _account.AccountItemUpdate -= OnAccountItemUpdate;

            _account = account;

            if (_account != null)
            {
                _account.AccountItemUpdate += OnAccountItemUpdate;
                Print("PnLMonitorROI -> Monitoring cuenta: " + _account.Name);

                _displayAccountValue = GetRealtimeAccountValue();

                if (_monitorWindow != null)
                    _monitorWindow.UpdateAccountLabel(_account.Name);

                if (_liveTimer != null && !_liveTimer.IsEnabled)
                    _liveTimer.Start();

                RecalculateAndCheckPnL();
            }
        }

        public void CloseAllOpenTrades()
        {
            if (_account == null)
            {
                Print("PnLMonitorROI -> No account selected.");
                return;
            }

            try
            {
                List<Instrument> instrumentsToFlatten = _account.Positions
                    .Where(p => p.MarketPosition == MarketPosition.Long || p.MarketPosition == MarketPosition.Short)
                    .Select(p => p.Instrument)
                    .Distinct()
                    .ToList();

                if (instrumentsToFlatten.Count > 0)
                {
                    _account.Dispatcher.InvokeAsync(new Action(delegate()
                    {
                        _account.Flatten(instrumentsToFlatten);
                        Print("PnLMonitorROI -> Manual close button pressed. Flatten command sent.");
                    }));
                }
                else
                {
                    Print("PnLMonitorROI -> No open trades to close.");
                }
            }
            catch (Exception ex)
            {
                Print("PnLMonitorROI -> Error closing trades: " + ex.Message);
            }
        }

        private void PlayThresholdSound(bool isProfit)
        {
            try
            {
                string soundFileName = isProfit ? _profitSoundFile : _lossSoundFile;
                string fullSoundPath = System.IO.Path.Combine(_ninjaTraderSoundsFolder, soundFileName);

                if (!File.Exists(fullSoundPath))
                {
                    Print("PnLMonitorROI -> Sound file not found: " + fullSoundPath);
                    return;
                }

                using (SoundPlayer player = new SoundPlayer(fullSoundPath))
                {
                    player.Play();
                }

                Print("PnLMonitorROI -> Played sound: " + fullSoundPath);
            }
            catch (Exception ex)
            {
                Print("PnLMonitorROI -> Sound error: " + ex.Message);
            }
        }

        private void ShowThresholdPopup(string title, string message)
        {
            if (_thresholdPopupOpen)
                return;

            _thresholdPopupOpen = true;
            _lastThresholdMessage = message;

            try
            {
                System.Windows.Application.Current.Dispatcher.Invoke(
                    new Action(delegate()
                    {
                        System.Windows.MessageBox.Show(
                            message,
                            title,
                            MessageBoxButton.OK);
                    })
                );
            }
            catch (Exception ex)
            {
                Print("PnLMonitorROI -> Popup error: " + ex.Message);
            }
            finally
            {
                _thresholdPopupOpen = false;
            }
        }

        public void ResetThresholdAlertState()
        {
            _limitAlreadyTriggered = false;
            _lastThresholdMessage = string.Empty;
            Print("PnLMonitorROI -> Threshold alert state reset.");
        }

        private void OnAccountItemUpdate(object sender, AccountItemEventArgs e)
        {
            if (e.AccountItem == AccountItem.RealizedProfitLoss
                || e.AccountItem == AccountItem.UnrealizedProfitLoss
                || e.AccountItem == AccountItem.CashValue
                || e.AccountItem == AccountItem.NetLiquidation
                || e.AccountItem == AccountItem.GrossRealizedProfitLoss
                || e.AccountItem == AccountItem.TotalCashBalance)
            {
                RecalculateAndCheckPnL();
            }
        }

        private void OnLiveTimerTick(object sender, EventArgs e)
        {
            RecalculateAndCheckPnL();
        }

        private double GetRealtimeAccountValue()
        {
            if (_account == null)
                return 0;

            try
            {
                double netLiq = _account.Get(AccountItem.NetLiquidation, Currency.UsDollar);
                if (!double.IsNaN(netLiq) && !double.IsInfinity(netLiq) && netLiq != 0)
                    return netLiq;
            }
            catch
            {
            }

            try
            {
                double cashValue = _account.Get(AccountItem.CashValue, Currency.UsDollar);
                if (!double.IsNaN(cashValue) && !double.IsInfinity(cashValue))
                    return cashValue;
            }
            catch
            {
            }

            return 0;
        }

        private void RecalculateAndCheckPnL()
        {
            if (_account == null)
            {
                Print("PnLMonitorROI -> Recalculate skipped because no account is selected.");
                return;
            }

            try
            {
                double currentProfitTarget;
                double currentLossLimit;
                lock (_riskLock)
                {
                    currentProfitTarget = _profitTarget;
                    currentLossLimit = _lossLimit;
                }

                double realized = _account.Get(AccountItem.RealizedProfitLoss, Currency.UsDollar);
                double unrealized = _account.Get(AccountItem.UnrealizedProfitLoss, Currency.UsDollar);
                _currentPnL = realized + unrealized;

                _displayAccountValue = GetRealtimeAccountValue();

                if (_monitorWindow != null)
                {
                    double pnlToShow = _currentPnL;
                    double accountValueToShow = _displayAccountValue;

                    _monitorWindow.Dispatcher.InvokeAsync(new Action(delegate()
                    {
                        if (_monitorWindow != null && _monitorWindow.IsLoaded)
                            _monitorWindow.UpdatePnL(pnlToShow, accountValueToShow, currentProfitTarget, currentLossLimit);
                    }));
                }

                if ((_currentPnL >= currentProfitTarget || _currentPnL <= currentLossLimit) && _limitAlreadyTriggered == false)
                {
                    _limitAlreadyTriggered = true;

                    string formattedPnL = _currentPnL >= 0
                        ? _currentPnL.ToString("C2", new CultureInfo("en-US"))
                        : _currentPnL.ToString("$#,0.00;-$#,0.00", new CultureInfo("en-US"));

                    if (_currentPnL >= currentProfitTarget)
                    {
                        Print("PnLMonitorROI -> Profit target reached. PnL: " + formattedPnL);
                        PlayThresholdSound(true);

                        ShowThresholdPopup(
                            "Profit Target Reached",
                            "The profit target has been reached.\n\n" +
                            "You can now:\n" +
                            "1. Manually close all trades using the 'Close All Trades' button in the Add-On.\n" +
                            "2. Adapt/reset the Profit Target and Loss Limit values, then click 'Apply Limits'.\n\n" +
                            "After applying the new values, a new popup alert can trigger again when a target is reached.");
                    }
                    else if (_currentPnL <= currentLossLimit)
                    {
                        Print("PnLMonitorROI -> Loss limit reached. PnL: " + formattedPnL);
                        PlayThresholdSound(false);

                        ShowThresholdPopup(
                            "Loss Limit Reached",
                            "The loss limit has been reached.\n\n" +
                            "You can now:\n" +
                            "1. Manually close all trades using the 'Close All Trades' button in the Add-On.\n" +
                            "2. Adapt/reset the Profit Target and Loss Limit values, then click 'Apply Limits'.\n\n" +
                            "After applying the new values, a new popup alert can trigger again when a target is reached.");
                    }
                }
                else if (!(_currentPnL >= currentProfitTarget || _currentPnL <= currentLossLimit))
                {
                    _limitAlreadyTriggered = false;
                }
            }
            catch (Exception ex)
            {
                Print("PnLMonitorROI -> Error calculando PnL: " + ex.Message);
            }
        }

        protected override void OnWindowCreated(Window window)
        {
            NinjaTrader.Gui.ControlCenter controlCenter = window as NinjaTrader.Gui.ControlCenter;
            if (controlCenter == null)
                return;

            controlCenter.Dispatcher.InvokeAsync(new Action(delegate()
            {
                if (_menuItem != null)
                    return;

                var toolsMenu = controlCenter.FindFirst("ControlCenterMenuItemTools") as NTMenuItem;
                if (toolsMenu == null)
                    return;

                _menuItem = new NTMenuItem
                {
                    Name = "PnLMonitorROIMenuItem",
                    Header = "PnL Monitor ROI"
                };

                Style ccStyle = Application.Current.TryFindResource("MainMenuItem") as Style;
                if (ccStyle != null)
                    _menuItem.Style = ccStyle;

                _menuItem.Click += MenuItem_Click_Handler;
                toolsMenu.Items.Add(_menuItem);
            }));
        }

        protected override void OnWindowDestroyed(Window window)
        {
            var controlCenter = window as NinjaTrader.Gui.ControlCenter;

            if (controlCenter != null)
            {
                controlCenter.Dispatcher.InvokeAsync(new Action(delegate()
                {
                    if (_menuItem != null)
                    {
                        _menuItem.Click -= MenuItem_Click_Handler;

                        var parent = _menuItem.Parent as ItemsControl;
                        if (parent != null && parent.Items.Contains(_menuItem))
                            parent.Items.Remove(_menuItem);

                        _menuItem = null;
                    }
                }));
            }

            if (_monitorWindow != null && window == _monitorWindow)
            {
                _monitorWindow = null;
                _windowOpening = false;
            }
        }

        private void MenuItem_Click_Handler(object sender, RoutedEventArgs e)
        {
            System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(delegate()
            {
                if (_windowOpening)
                    return;

                if (_monitorWindow != null)
                {
                    if (_monitorWindow.WindowState == WindowState.Minimized)
                        _monitorWindow.WindowState = WindowState.Normal;

                    _monitorWindow.Activate();
                    return;
                }

                _windowOpening = true;

                try
                {
                    _monitorWindow = new PnLMonitorWindowvROI(this);
                    _monitorWindow.Closed += delegate(object s, EventArgs args)
                    {
                        _monitorWindow = null;
                        _windowOpening = false;
                    };

                    _monitorWindow.Show();
                    _monitorWindow.Activate();
                }
                catch
                {
                    _windowOpening = false;
                    throw;
                }
            }));
        }

        protected void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

///second part of the code
 public class PnLMonitorWindowvROI : Window
    {
        private PnLMonitorROI _addOn;
        private ComboBox _accountComboBox;
        private TextBlock _pnlTextBlock;
        private TextBlock _accountValueTextBlock;
        private TextBlock _accountLabel;
        private TextBox _profitTextBox;
        private TextBox _lossTextBox;
        private ItemsControl _positionsControl;
        private RotateTransform _needleRotation;

        public PnLMonitorWindowvROI(PnLMonitorROI addOn)
        {
            _addOn = addOn;

            Title = "PnL Monitor in Real-Time";
            Width = 360;
            Height = 620;
            MinWidth = 340;
            MinHeight = 500;
            Background = new SolidColorBrush(Color.FromRgb(30, 30, 30));
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            Topmost = true;

            Grid mainGrid = new Grid();
            mainGrid.Margin = new Thickness(12, 10, 12, 10);

            mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(30) });                       // 0
            mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(20) });                       // 1
            mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });                          // 2
            mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });                          // 3
            mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(140) });                      // 4
            mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });                          // 5
            mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });                          // 6
            mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });     // 7 (bottom)

            StackPanel accountPanel = new StackPanel() { Orientation = Orientation.Horizontal };
            TextBlock selectText = new TextBlock()
            {
                Text = "Account: ",
                Foreground = Brushes.White,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 10, 0)
            };

            _accountComboBox = new ComboBox() { Width = 180, Height = 24, VerticalAlignment = VerticalAlignment.Center };
            _accountComboBox.SelectionChanged += OnAccountSelectionChanged;

            lock (Account.All)
            {
                foreach (Account acc in Account.All)
                    _accountComboBox.Items.Add(acc.Name);
            }

            accountPanel.Children.Add(selectText);
            accountPanel.Children.Add(_accountComboBox);
            Grid.SetRow(accountPanel, 0);
            mainGrid.Children.Add(accountPanel);

            _accountLabel = new TextBlock()
            {
                Text = "Monitoring: No Account Selected",
                Foreground = Brushes.LightGray,
                FontSize = 11,
                VerticalAlignment = VerticalAlignment.Center
            };
            Grid.SetRow(_accountLabel, 1);
            mainGrid.Children.Add(_accountLabel);

            Grid limitsGrid = new Grid();
            limitsGrid.Margin = new Thickness(0, 2, 0, 2);
            limitsGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
            limitsGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

            StackPanel profitPanel = new StackPanel() { Margin = new Thickness(0, 0, 4, 0) };
            TextBlock profitLbl = new TextBlock() { Text = "Profit Target ($):", Foreground = Brushes.White, FontSize = 11, Margin = new Thickness(0, 0, 0, 2) };
            _profitTextBox = new TextBox()
            {
                Text = _addOn.ProfitTarget.ToString(CultureInfo.InvariantCulture),
                Height = 22,
                Background = new SolidColorBrush(Color.FromRgb(45, 45, 45)),
                Foreground = Brushes.White,
                BorderBrush = Brushes.Gray
            };
            profitPanel.Children.Add(profitLbl);
            profitPanel.Children.Add(_profitTextBox);
            Grid.SetColumn(profitPanel, 0);
            limitsGrid.Children.Add(profitPanel);

            StackPanel lossPanel = new StackPanel() { Margin = new Thickness(4, 0, 0, 0) };
            TextBlock lossLbl = new TextBlock() { Text = "Loss Limit ($):", Foreground = Brushes.White, FontSize = 11, Margin = new Thickness(0, 0, 0, 2) };
            _lossTextBox = new TextBox()
            {
                Text = _addOn.LossLimit.ToString(CultureInfo.InvariantCulture),
                Height = 22,
                Background = new SolidColorBrush(Color.FromRgb(45, 45, 45)),
                Foreground = Brushes.White,
                BorderBrush = Brushes.Gray
            };
            lossPanel.Children.Add(lossLbl);
            lossPanel.Children.Add(_lossTextBox);
            Grid.SetColumn(lossPanel, 1);
            limitsGrid.Children.Add(lossPanel);

            Grid.SetRow(limitsGrid, 2);
            mainGrid.Children.Add(limitsGrid);

            Button applyLimitsButton = new Button()
            {
                Content = "Apply Limits",
                Width = 120,
                Height = 28,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 6, 0, 8),
                Background = new SolidColorBrush(Color.FromRgb(50, 100, 180)),
                Foreground = Brushes.White,
                BorderBrush = new SolidColorBrush(Color.FromRgb(210, 210, 210)),
                FontSize = 11,
                FontWeight = FontWeights.SemiBold,
                Cursor = System.Windows.Input.Cursors.Hand
            };
            applyLimitsButton.Click += OnApplyLimitsClicked;
            Grid.SetRow(applyLimitsButton, 3);
            mainGrid.Children.Add(applyLimitsButton);

            Grid gaugeGrid = new Grid();
            gaugeGrid.Width = 320;
            gaugeGrid.Height = 140;
            gaugeGrid.HorizontalAlignment = HorizontalAlignment.Center;
            gaugeGrid.VerticalAlignment = VerticalAlignment.Top;

            System.Windows.Shapes.Path backgroundArc = CreateSemicircularArc(Color.FromRgb(55, 58, 63), 14);
            gaugeGrid.Children.Add(backgroundArc);

            LinearGradientBrush arcGradient = new LinearGradientBrush();
            arcGradient.StartPoint = new Point(0, 0);
            arcGradient.EndPoint = new Point(1, 0);
            arcGradient.GradientStops.Add(new GradientStop(Color.FromRgb(239, 83, 80), 0.0));
            arcGradient.GradientStops.Add(new GradientStop(Color.FromRgb(100, 110, 120), 0.5));
            arcGradient.GradientStops.Add(new GradientStop(Color.FromRgb(42, 184, 115), 1.0));

            System.Windows.Shapes.Path coloredArc = CreateSemicircularArc(Colors.Transparent, 2);
            coloredArc.Stroke = arcGradient;
            coloredArc.StrokeThickness = 3;
            gaugeGrid.Children.Add(coloredArc);

            Grid needleContainer = new Grid();
            needleContainer.Width = 220;
            needleContainer.Height = 220;
            needleContainer.VerticalAlignment = VerticalAlignment.Top;
            needleContainer.Margin = new Thickness(0, 20, 0, 0);

            System.Windows.Shapes.Polygon premiumNeedle = new System.Windows.Shapes.Polygon();
            Point pointLeft = new Point(107, 110);
            Point pointTip = new Point(110, 15);
            Point pointRight = new Point(113, 110);
            premiumNeedle.Points.Add(pointLeft);
            premiumNeedle.Points.Add(pointTip);
            premiumNeedle.Points.Add(pointRight);
            premiumNeedle.Fill = new SolidColorBrush(Color.FromRgb(255, 110, 0));
            premiumNeedle.Stroke = new SolidColorBrush(Color.FromRgb(242, 244, 247));
            premiumNeedle.StrokeThickness = 0.5;

            System.Windows.Shapes.Ellipse needleCap = new System.Windows.Shapes.Ellipse();
            needleCap.Width = 18;
            needleCap.Height = 18;
            needleCap.Fill = new SolidColorBrush(Color.FromRgb(30, 30, 30));
            needleCap.Stroke = new SolidColorBrush(Color.FromRgb(242, 244, 247));
            needleCap.StrokeThickness = 3;
            needleCap.HorizontalAlignment = HorizontalAlignment.Center;
            needleCap.VerticalAlignment = VerticalAlignment.Center;

            _needleRotation = new RotateTransform(0, 110, 110);
            premiumNeedle.RenderTransform = _needleRotation;

            needleContainer.Children.Add(premiumNeedle);
            needleContainer.Children.Add(needleCap);
            gaugeGrid.Children.Add(needleContainer);

            Grid.SetRow(gaugeGrid, 4);
            mainGrid.Children.Add(gaugeGrid);

            _pnlTextBlock = new TextBlock()
            {
                Text = "$0.00",
                Foreground = Brushes.White,
                FontSize = 34,
                FontWeight = FontWeights.Bold,
                FontFamily = new FontFamily("Segoe UI"),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 15, 0, 4)
            };
            Grid.SetRow(_pnlTextBlock, 5);
            mainGrid.Children.Add(_pnlTextBlock);

            _accountValueTextBlock = new TextBlock()
            {
                Text = "Account Value: $0.00",
                Foreground = Brushes.White,
                FontSize = 18,
                FontWeight = FontWeights.SemiBold,
                FontFamily = new FontFamily("Segoe UI"),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 0, 12)
            };
            Grid.SetRow(_accountValueTextBlock, 6);
            mainGrid.Children.Add(_accountValueTextBlock);

          
            Grid bottomSplitGrid = new Grid();
            bottomSplitGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
            bottomSplitGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
            bottomSplitGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            bottomSplitGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
            Grid.SetRow(bottomSplitGrid, 7);
            mainGrid.Children.Add(bottomSplitGrid);

        
            TextBlock authorLabel = new TextBlock()
            {
                Text = "@ProyectoROI25",
                Foreground = Brushes.DarkGray,
                FontSize = 11,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Top,
                Margin = new Thickness(0, 0, 0, 18)
            };
            Grid.SetRow(authorLabel, 0);
            Grid.SetColumn(authorLabel, 0);
            Grid.SetColumnSpan(authorLabel, 2);
            bottomSplitGrid.Children.Add(authorLabel);

           
            StackPanel logoButtonPanel = new StackPanel
            {
                Orientation = Orientation.Vertical,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center
            };

            try
            {
                string imagePath = System.IO.Path.Combine(NinjaTrader.Core.Globals.UserDataDir, "templates", "ROIPro.png");

                if (System.IO.File.Exists(imagePath))
                {
                    System.Windows.Media.Imaging.BitmapImage bitmap = new System.Windows.Media.Imaging.BitmapImage();
                    bitmap.BeginInit();
                    bitmap.UriSource = new Uri(imagePath);
                    bitmap.EndInit();

                    System.Windows.Controls.Image logoImage = new System.Windows.Controls.Image
                    {
                        Source = bitmap,
                        Height = 65,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                        Margin = new Thickness(0, 0, 0, 8),
                        Stretch = System.Windows.Media.Stretch.Uniform
                    };

                    logoButtonPanel.Children.Add(logoImage);
                }
            }
            catch (Exception)
            {
            }

            Button closeAllButton = new Button
            {
                Content = "Close All Trades",
                Width = 120,
                Height = 28,
                HorizontalAlignment = HorizontalAlignment.Center,
                Background = new SolidColorBrush(Color.FromRgb(180, 45, 45)),
                Foreground = Brushes.White,
                BorderBrush = new SolidColorBrush(Color.FromRgb(210, 210, 210)),
                FontSize = 11,
                FontWeight = FontWeights.SemiBold,
                Cursor = System.Windows.Input.Cursors.Hand
            };

            closeAllButton.Click += delegate(object s, RoutedEventArgs e)
            {
                if (System.Windows.MessageBox.Show(
                    "Close all open trades for the selected account?",
                    "Confirm Close All",
                    MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    _addOn.CloseAllOpenTrades();
                }
            };

            logoButtonPanel.Children.Add(closeAllButton);

            Grid.SetRow(logoButtonPanel, 1);
            Grid.SetColumn(logoButtonPanel, 0);
            bottomSplitGrid.Children.Add(logoButtonPanel);

            // --- "Open Positions:" + lista: fila 1, columna 1, alineado arriba ---
            StackPanel posContainerPanel = new StackPanel()
            {
                Margin = new Thickness(8, 0, 0, 0),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top
            };
            TextBlock posHeader = new TextBlock()
            {
                Text = "Open Positions:",
                Foreground = Brushes.Gray,
                FontSize = 10,
                FontWeight = FontWeights.Bold,
                Margin = new Thickness(0, 0, 0, 4)
            };
            posContainerPanel.Children.Add(posHeader);

            _positionsControl = new ItemsControl();
            _positionsControl.ItemTemplate = new DataTemplate();

            ScrollViewer positionsScrollViewer = new ScrollViewer
            {
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
                VerticalAlignment = VerticalAlignment.Top
            };
            positionsScrollViewer.Content = _positionsControl;

            posContainerPanel.Children.Add(positionsScrollViewer);

            Grid.SetRow(posContainerPanel, 1);
            Grid.SetColumn(posContainerPanel, 1);
            bottomSplitGrid.Children.Add(posContainerPanel);
            // ================== /BOTTOM AREA ==================

            Content = mainGrid;

            if (_addOn.AccountName != "No Account Selected")
            {
                _accountComboBox.SelectedItem = _addOn.AccountName;
                UpdateAccountLabel(_addOn.AccountName);
            }

            this.Closed += delegate(object sender, EventArgs e)
            {
                _addOn.ClearWindowReference();
            };
        }

        private void OnApplyLimitsClicked(object sender, RoutedEventArgs e)
        {
            double newProfitTarget;
            double newLossLimit;

            bool profitValid = double.TryParse(_profitTextBox.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out newProfitTarget);
            bool lossValid = double.TryParse(_lossTextBox.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out newLossLimit);

            if (!profitValid || !lossValid)
            {
                System.Windows.MessageBox.Show(
                    "Please enter valid numeric values for both Profit Target and Loss Limit.",
                    "Invalid Limits",
                    MessageBoxButton.OK);
                return;
            }

            bool valuesChanged = (_addOn.ProfitTarget != newProfitTarget) || (_addOn.LossLimit != newLossLimit);

            _addOn.ProfitTarget = newProfitTarget;
            _addOn.LossLimit = newLossLimit;
            _addOn.ResetThresholdAlertState();

            string msg = valuesChanged
                ? "Profit Target and Loss Limit updated.\nThreshold alert state has been reset."
                : "Limits reapplied.\nThreshold alert state has been reset.";

            System.Windows.MessageBox.Show(
                msg,
                "Limits Applied",
                MessageBoxButton.OK);
        }

        private void OnAccountSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_accountComboBox.SelectedItem == null)
                return;

            string selectedAccountName = _accountComboBox.SelectedItem.ToString();
            lock (Account.All)
            {
                Account selectedAccount = Account.All.FirstOrDefault(a => a.Name == selectedAccountName);
                if (selectedAccount != null)
                    _addOn.SetAccount(selectedAccount);
            }
        }

        public void UpdateAccountLabel(string accountName)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.InvokeAsync(new Action(delegate()
                {
                    UpdateAccountLabel(accountName);
                }));
                return;
            }

            _accountLabel.Text = "Monitoring: " + accountName;
        }

        public void UpdatePnL(double pnlValue, double accountValue, double maxProfit, double minLoss)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.InvokeAsync(new Action(delegate()
                {
                    UpdatePnL(pnlValue, accountValue, maxProfit, minLoss);
                }));
                return;
            }

            if (pnlValue >= 0)
            {
                _pnlTextBlock.Text = pnlValue.ToString("C2", new CultureInfo("en-US"));
                _pnlTextBlock.Foreground = new SolidColorBrush(Color.FromRgb(42, 184, 115));
            }
            else
            {
                _pnlTextBlock.Text = pnlValue.ToString("$#,0.00;-$#,0.00", new CultureInfo("en-US"));
                _pnlTextBlock.Foreground = new SolidColorBrush(Color.FromRgb(239, 83, 80));
            }

            if (pnlValue >= 0)
            {
                _accountValueTextBlock.Text = "Account Value: " + accountValue.ToString("C2", new CultureInfo("en-US"));
                _accountValueTextBlock.Foreground = new SolidColorBrush(Color.FromRgb(42, 184, 115));
            }
            else
            {
                _accountValueTextBlock.Text = "Account Value: " + accountValue.ToString("$#,0.00;-$#,0.00", new CultureInfo("en-US"));
                _accountValueTextBlock.Foreground = new SolidColorBrush(Color.FromRgb(239, 83, 80));
            }

            if (maxProfit <= minLoss)
                maxProfit = minLoss + 1;

            double targetScale = pnlValue >= 0 ? maxProfit : Math.Abs(minLoss);
            if (targetScale <= 0)
                targetScale = 1;

            double percentage = pnlValue / targetScale;
            double angle = percentage * 90.0;

            angle = Math.Max(-90.0, Math.Min(90.0, angle));
            _needleRotation.Angle = angle;

            if (_addOn != null)
            {
                string currentAccName = _accountLabel.Text.Replace("Monitoring: ", "");

                Account targetAccount = null;
                lock (Account.All)
                {
                    targetAccount = Account.All.FirstOrDefault(a => a.Name == currentAccName);
                }

                _positionsControl.Items.Clear();

                if (targetAccount != null && targetAccount.Positions != null)
                {
                    var openPositions = targetAccount.Positions
                        .Where(p => p.MarketPosition != MarketPosition.Flat)
                        .Select(p =>
                        {
                            double posPnL = p.GetUnrealizedProfitLoss(PerformanceUnit.Currency);

                            int signedQuantity = p.MarketPosition == MarketPosition.Short
                                ? -Math.Abs(p.Quantity)
                                : Math.Abs(p.Quantity);

                            string directionSign = posPnL >= 0 ? "+" : "";
                            string displayStr = p.Instrument.MasterInstrument.Name
                                + " (" + signedQuantity + ") "
                                + directionSign
                                + posPnL.ToString("C0", new CultureInfo("en-US"));

                            Brush textBrush = posPnL >= 0 ? Brushes.LimeGreen : Brushes.Red;

                            return new
                            {
                                DisplayText = displayStr,
                                ColorBrush = textBrush,
                                RawPnL = posPnL
                            };
                        })
                        .OrderByDescending(p => p.RawPnL)
                        .ToList();

                    if (openPositions.Count > 0)
                    {
                        foreach (var pos in openPositions)
                        {
                            _positionsControl.Items.Add(new TextBlock
                            {
                                Text = pos.DisplayText,
                                Foreground = pos.ColorBrush,
                                FontSize = 10,
                                FontWeight = FontWeights.SemiBold,
                                Margin = new Thickness(0, 1, 0, 1)
                            });
                        }
                    }
                    else
                    {
                        _positionsControl.Items.Add(new TextBlock
                        {
                            Text = "No Active Trades",
                            Foreground = Brushes.DarkGray,
                            FontSize = 10,
                            FontStyle = FontStyles.Italic
                        });
                    }
                }
                else
                {
                    _positionsControl.Items.Add(new TextBlock
                    {
                        Text = "No Active Trades",
                        Foreground = Brushes.DarkGray,
                        FontSize = 10,
                        FontStyle = FontStyles.Italic
                    });
                }
            }
        }

        private System.Windows.Shapes.Path CreateSemicircularArc(Color strokeColor, double thickness)
        {
            System.Windows.Shapes.Path path = new System.Windows.Shapes.Path();
            path.Stroke = new SolidColorBrush(strokeColor);
            path.StrokeThickness = thickness;
            path.StrokeEndLineCap = PenLineCap.Round;
            path.StrokeStartLineCap = PenLineCap.Round;
            path.VerticalAlignment = VerticalAlignment.Top;
            path.HorizontalAlignment = HorizontalAlignment.Center;
            path.Margin = new Thickness(0, 20, 0, 0);

            PathGeometry pathGeometry = new PathGeometry();
            PathFigure pathFigure = new PathFigure();
            pathFigure.StartPoint = new Point(10, 110);

            ArcSegment arcSegment = new ArcSegment();
            arcSegment.Point = new Point(210, 110);
            arcSegment.Size = new Size(100, 100);
            arcSegment.SweepDirection = SweepDirection.Clockwise;

            pathFigure.Segments.Add(arcSegment);
            pathGeometry.Figures.Add(pathFigure);
            path.Data = pathGeometry;

            return path;
        }
    }
}

How to install the PnLMonitorROI Add-On (quick start for beginners)

In NinjaTrader 8, open New → NinjaScript Editor.

In the left panel, right-click the AddOns folder → New → Add On. Name it PnLMonitorROI (or any name you like) and click OK. A template file opens.

Select everything in the file (Ctrl+A) and delete it.

Paste the full code from the two code blocks above (Ctrl+V), one after the other. Make sure you include the entire file — from the first using System; line all the way to the closing brace at the bottom. Nothing in between should be omitted.

Press F5 to compile. A green check in the toolbar means success. If any error appears, it is almost always because a piece of the code was cut off during copy — re-select and paste again.

Required — add the logo image (see next message for ROIPro.png image). The add-on displays a custom logo (ROIPro.png) in the bottom-left corner. Save your logo file as ROIPro.png inside the NinjaTrader templates folder:

Documents\NinjaTrader 8\templates\ROIPro.png

If the file is not there, the logo and the “Close All Trades” button will not be displayed, since both are rendered within the same UI block.

Now close NinjaTrader completely, including the tray icon (right-click it → Exit). Reopen NinjaTrader. This step is required — add-ons are only registered at startup.

In NinjaTrader, open the Control Center → Tools → PnL Monitor ROI. The monitoring window opens.