Page 2 of 2

Re: Desk deep dive: when adding an EA

Posted: Tue Oct 06, 2026 5:20 am
by PTScalper
The New Mechanics in Action

The "Fat Finger" News Refusal (OnPositionOpened): Instead of just checking rules on a tick, this version subscribes to the broker's position-opened event. If you manually click "Buy" on the chart exactly at 13:29 UTC right before US CPI drops, the cBot intercepts the event and instantly fires a ClosePositionAsync command. It physically refuses to let you hold a trade in the blackout window.

Time-Based Weekend Flat: If EnableFridayClose is true, the OnTick method watches the server clock on Fridays. Once the clock crosses your designated time (e.g., 20:45), it sweeps the book, cancels all pending limits, and shuts itself down. You walk away clean for the weekend.

The HUD Panel: Using a StackPanel, the code now mounts a clean, dark-themed UI in the top right corner. It tracks your exact daily PnL (realized plus floating) and changes color based on performance. During the designated news window, the text shifts to [NEWS BLACKOUT ACTIVE].

This setup essentially treats the C# code like an over-the-shoulder risk manager. It never attempts to read market structure or predict liquidity sweeps—it just enforces your boundaries so you can focus entirely on reading the 15-minute chart.

Re: Desk deep dive: when adding an EA

Posted: Tue Oct 06, 2026 5:20 am
by PTScalper
To elevate this from a basic retail script to an enterprise-grade utility, we need to apply proper software engineering principles.

When you write production C#, you don't dump all your business logic into a single unmanaged loop. The previous iteration relied on the OnTick event, which is a classic algorithmic trading trap: if the market volume dries up or the broker feed stalls, the ticks stop arriving, and your defensive time checks never execute.

Re: Desk deep dive: when adding an EA

Posted: Tue Oct 06, 2026 5:21 am
by PTScalper
A professional implementation requires:

Deterministic Execution: Decoupling time and equity checks from the tick stream by using a hardware-backed OnTimer loop.

State Management & Concurrency Control: Ensuring the "Flatten" command doesn't trigger 50 times simultaneously during a high-volatility event, causing API rate-limiting.

Broker Rejection Handling: Asynchronous order execution with explicit TradeResult validation. If the broker rejects a close command due to "Off Quotes" or liquidity gaps during a news spike, the script must catch it and retry.

Architectural Separation: Segregating the UI layer, risk logic, and execution layer.

Re: Desk deep dive: when adding an EA

Posted: Tue Oct 06, 2026 5:21 am
by PTScalper
Here is the "Pro" tier implementation.

Code: Select all

using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class EnterpriseDeskDefender : Robot
    {
        #region Parameters

        [Parameter("Start Enabled", Group = "System", DefaultValue = false)]
        public bool StartEnabled { get; set; }

        [Parameter("Max Daily Loss ($)", Group = "Risk Management", DefaultValue = 500, MinValue = 0)]
        public double MaxDailyLoss { get; set; }

        [Parameter("Enable News Blackout", Group = "News Defense", DefaultValue = true)]
        public bool EnableNewsBlackout { get; set; }

        [Parameter("Blackout Start (HH:mm)", Group = "News Defense", DefaultValue = "13:25")]
        public string BlackoutStartStr { get; set; }

        [Parameter("Blackout End (HH:mm)", Group = "News Defense", DefaultValue = "13:35")]
        public string BlackoutEndStr { get; set; }

        [Parameter("Friday Flat Enable", Group = "Weekend Defense", DefaultValue = true)]
        public bool EnableFridayClose { get; set; }

        [Parameter("Friday Close Time (HH:mm)", Group = "Weekend Defense", DefaultValue = "20:45")]
        public string FridayCloseTimeStr { get; set; }

        #endregion

        #region State & Domain Models

        private enum SystemState
        {
            Offline,
            Monitoring,
            Flattening,
            Halted
        }

        private SystemState _currentState;
        private TimeSpan _blackoutStart;
        private TimeSpan _blackoutEnd;
        private TimeSpan _fridayCloseTime;
        private readonly object _stateLock = new object();

        // UI Components
        private Button _toggleButton;
        private TextBlock _statusText;

        #endregion

        #region Initialization

        protected override void OnStart()
        {
            try
            {
                ParseTimeConfigurations();
                InitializeUI();

                // Hook global events
                Positions.Opened += OnPositionOpened;

                SetState(StartEnabled ? SystemState.Monitoring : SystemState.Offline);

                // Start a 1Hz deterministic hardware timer - independent of tick data
                Timer.Start(TimeSpan.FromSeconds(1));
                
                Print("Enterprise Defender Initialized. Async Execution enabled.");
            }
            catch (Exception ex)
            {
                Print("CRITICAL INITIALIZATION ERROR: " + ex.Message);
                Stop(); // Terminate cBot if initialization fails
            }
        }

        private void ParseTimeConfigurations()
        {
            if (!TimeSpan.TryParse(BlackoutStartStr, out _blackoutStart) ||
                !TimeSpan.TryParse(BlackoutEndStr, out _blackoutEnd) ||
                !TimeSpan.TryParse(FridayCloseTimeStr, out _fridayCloseTime))
            {
                throw new FormatException("Invalid time format. Please use HH:mm (24-hour UTC).");
            }
        }

        #endregion

        #region Core Loop (Timer-Based)

        protected override void OnTimer()
        {
            if (_currentState != SystemState.Monitoring) return;

            double currentDailyPnL = CalculateDailyPnL();
            UpdateHUD(currentDailyPnL);

            EvaluateRiskBoundaries(currentDailyPnL);
        }

        private void EvaluateRiskBoundaries(double currentPnL)
        {
            // 1. Hard Daily Stop
            if (currentPnL <= -MaxDailyLoss)
            {
                InitiateFlattenSequence("Daily Risk Limit Breached");
                return;
            }

            // 2. Weekend Gap Avoidance
            if (EnableFridayClose && Server.Time.DayOfWeek == DayOfWeek.Friday && Server.Time.TimeOfDay >= _fridayCloseTime)
            {
                if (Positions.Count > 0 || PendingOrders.Count > 0)
                {
                    InitiateFlattenSequence("Friday Market Close Protocol");
                }
            }
        }

        #endregion

        #region Execution & Error Handling

        private void InitiateFlattenSequence(string reason)
        {
            lock (_stateLock)
            {
                // Prevent concurrent execution of the flatten loop
                if (_currentState == SystemState.Flattening || _currentState == SystemState.Halted) return;
                SetState(SystemState.Flattening);
            }

            Print($"[CRITICAL ACTION] Executing Flatten Sequence. Trigger: {reason}");

            // Cancel Pending Orders
            foreach (var order in PendingOrders)
            {
                CancelPendingOrderAsync(order, OnOrderCancelCallback);
            }

            // Close Active Positions
            foreach (var position in Positions)
            {
                ClosePositionWithRetry(position, 3);
            }

            SetState(SystemState.Halted);
            _statusText.Text = $"SYSTEM HALTED: {reason}";
            _statusText.ForegroundColor = Color.Red;
            
            // Optional: Play alert sound
            Notifications.PlaySound(SoundType.Doorbell); 
        }

        private void ClosePositionWithRetry(Position position, int remainingRetries)
        {
            if (remainingRetries <= 0)
            {
                Print($"[ERROR] Failed to close position {position.Id} after multiple attempts. Manual intervention required.");
                return;
            }

            ClosePositionAsync(position, result =>
            {
                if (!result.IsSuccessful)
                {
                    Print($"[WARNING] Failed to close {position.Id}: {result.Error}. Retries left: {remainingRetries - 1}");
                    // Simple recursive retry on callback failure
                    ClosePositionWithRetry(position, remainingRetries - 1);
                }
                else
                {
                    Print($"[SUCCESS] Position {position.Id} secured and closed.");
                }
            });
        }

        private void OnOrderCancelCallback(TradeResult result)
        {
            if (!result.IsSuccessful)
            {
                Print($"[WARNING] Failed to cancel order. Broker error: {result.Error}");
            }
        }

        #endregion

        #region Event Handlers (News Blackout)

        private void OnPositionOpened(PositionOpenedEventArgs args)
        {
            if (_currentState != SystemState.Monitoring || !EnableNewsBlackout) return;

            var currentTime = Server.Time.TimeOfDay;
            bool insideBlackoutWindow = currentTime >= _blackoutStart && currentTime <= _blackoutEnd;

            if (insideBlackoutWindow)
            {
                Print($"[DEFENSE] Manual order {args.Position.Id} intercepted during News Blackout.");
                // Immediately flatten the offending position without triggering a full system halt
                ClosePositionWithRetry(args.Position, 3);
            }
        }

        #endregion

        #region State Management & UI

        private void SetState(SystemState newState)
        {
            _currentState = newState;
            UpdateUIState();
        }

        private double CalculateDailyPnL()
        {
            var todaysHistory = History.Where(t => t.ClosingTime.Date == Server.Time.Date);
            double realizedPnL = todaysHistory.Sum(t => t.NetProfit);
            double unrealizedPnL = Positions.Sum(p => p.NetProfit);
            
            return realizedPnL + unrealizedPnL;
        }

        private void InitializeUI()
        {
            var panel = new StackPanel
            {
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment = VerticalAlignment.Top,
                Margin = new Thickness(15),
                BackgroundColor = Color.FromArgb(220, 15, 15, 15),
                Width = 200
            };

            _toggleButton = new Button
            {
                Text = "INITIALIZING...",
                ForegroundColor = Color.White,
                FontWeight = FontWeight.Bold,
                Height = 40,
                Margin = new Thickness(5)
            };
            _toggleButton.Click += args => ToggleSystemState();

            _statusText = new TextBlock
            {
                Text = "Loading Data...",
                ForegroundColor = Color.LightGray,
                Margin = new Thickness(5, 0, 5, 10),
                TextAlignment = TextAlignment.Center
            };

            panel.AddChild(_toggleButton);
            panel.AddChild(_statusText);
            Chart.AddControl(panel);
        }

        private void ToggleSystemState()
        {
            if (_currentState == SystemState.Monitoring) SetState(SystemState.Offline);
            else if (_currentState == SystemState.Offline || _currentState == SystemState.Halted) SetState(SystemState.Monitoring);
        }

        private void UpdateUIState()
        {
            switch (_currentState)
            {
                case SystemState.Monitoring:
                    _toggleButton.Text = "DEFENDER: ACTIVE";
                    _toggleButton.BackgroundColor = Color.SeaGreen;
                    break;
                case SystemState.Offline:
                    _toggleButton.Text = "DEFENDER: OFFLINE";
                    _toggleButton.BackgroundColor = Color.Crimson;
                    _statusText.Text = "System Standby";
                    _statusText.ForegroundColor = Color.Gray;
                    break;
                case SystemState.Halted:
                    _toggleButton.Text = "SYSTEM HALTED";
                    _toggleButton.BackgroundColor = Color.DarkOrange;
                    break;
                case SystemState.Flattening:
                    _toggleButton.Text = "FLATTENING BOOK...";
                    _toggleButton.BackgroundColor = Color.Goldenrod;
                    break;
            }
        }

        private void UpdateHUD(double currentPnL)
        {
            var currentTime = Server.Time.TimeOfDay;
            bool insideBlackoutWindow = EnableNewsBlackout && currentTime >= _blackoutStart && currentTime <= _blackoutEnd;

            string statusMsg = insideBlackoutWindow ? "[NEWS BLACKOUT ENFORCED]" : "Monitoring Equity";
            _statusText.Text = $"Daily PnL: ${Math.Round(currentPnL, 2)}\n{statusMsg}";
            _statusText.ForegroundColor = currentPnL < 0 ? Color.IndianRed : Color.MediumSeaGreen;
        }

        #endregion
    }
}

Re: Desk deep dive: when adding an EA

Posted: Tue Oct 06, 2026 5:22 am
by PTScalper
The Architectural Upgrades

The Hardware Timer (OnTimer): By shifting logic away from OnTick() and calling Timer.Start(TimeSpan.FromSeconds(1)), the script evaluates your equity and time limits exactly once per second, directly off the system clock. If liquidity dries up before a news event and no ticks come through, your defense mechanisms still trigger flawlessly.

Recursive Trade Validation (ClosePositionWithRetry): This is where retail EAs fail. If you hit your daily loss limit during a high-impact news drop, the broker's servers are overloaded. A single standard ClosePosition() call will often bounce with an "Off Quotes" error. This script uses the asynchronous callback signature (Action<TradeResult>) to read the broker's response. If it fails, it recurses and tries again until the position is dead or it maxes out its attempts.

Thread-Safe State Machine: Added an explicit SystemState enum and a thread lock (lock (_stateLock)). If a massive candle breaches your daily limit, the loop could evaluate the rules multiple times before the async orders settle. The state machine ensures the flatten sequence fires exactly once, transitioning immediately into a Halted state so it doesn't spam the broker API and get your account restricted.

Try/Catch Initialization Guard: If a time parameter is typed incorrectly (e.g., 25:00), the OnStart method catches the FormatException, prints a clean error to the log, and shuts the cBot down gracefully, rather than letting it run with null/invalid objects.

Re: Desk deep dive: when adding an EA

Posted: Tue Oct 20, 2026 12:48 pm
by FXS Prop Desk
A strict checklist is a good habit before deploying any third-party code. Another item to add: does the EA log its actions to a file with timestamps? If something goes wrong, a clear log is the only way to understand what happened. Also worth testing what happens if two instances run on different charts, as some EAs interfere with each other's positions.

Another check is how the EA behaves after a terminal restart. Some EAs lose track of positions they opened before the restart, which can lead to unmanaged trades.