MetaTrader Script Development

Overview

Not every MetaTrader automation requirement needs an Expert Advisor that runs continuously. Many of the most valuable automation tasks in a trading workflow are discrete operations — actions that need to be performed once, on demand, reliably and quickly. Close all losing positions. Move every stop loss to breakeven. Place a set of pending orders at defined price levels. Export the day's trade history to a file. Flatten the account before a news release. Calculate and display the position size for a defined risk percentage. These are operations that a trader performs manually through multiple clicks and calculations, and that a MetaTrader script performs with a single click in a fraction of a second.

MetaTrader scripts — the MQL4 and MQL5 programs that execute once when run and then terminate — provide the automation for these discrete operations without the overhead of a continuously running EA. Scripts can be assigned to keyboard shortcuts or toolbar buttons in MetaTrader, making them accessible as instant operations during live trading without navigating menus or performing multi-step manual processes.

The value of scripts is in the speed and reliability they provide for operations that a trader performs frequently or that need to be performed correctly under time pressure. A position management script that moves all stops to breakeven takes a fraction of a second and makes no calculation errors. A batch order placement script that places a defined set of pending orders executes all placements atomically rather than requiring the trader to place each order manually while the market moves. A risk calculator script that instantly displays the correct lot size eliminates the mental arithmetic that position sizing under pressure introduces.

We build custom MetaTrader scripts for forex traders, prop firm traders, and trading operations that need reliable, one-click automation for the discrete trading operations that manual execution currently handles.


What MetaTrader Script Development Covers

Position management scripts. The category of scripts that manipulates existing open positions — the tools that give traders rapid, reliable control over their current exposure.

Close all positions script: closes every open position on the account simultaneously, or filtered by symbol, by direction, by magic number, or by any combination of criteria. The emergency flatten script that exits the entire account in a single action. The symbol-specific close that exits all positions in EUR/USD without touching other positions. The direction-specific close that closes all short positions while leaving longs open.

Close profitable positions: closes all positions with positive floating P&L above a defined threshold, locking in gains while leaving losing positions to recover. Close losing positions: closes all positions below a defined floating P&L threshold to stop the bleeding on positions that have moved significantly against the trade.

Breakeven script: moves the stop loss of every qualifying position to the entry price, eliminating risk on positions that have moved into profit. The breakeven distance is configurable — only moving stops when the position has moved a defined minimum distance into profit to avoid premature breakeven triggers. Single-position and all-position variants that apply the breakeven adjustment to one chart's position or to all positions across all symbols.

Trailing stop script: applies a trailing stop to all qualifying positions, setting the stop at a defined distance behind the current price and updating it as the script runs. For traders who want to apply a trailing stop to existing positions that were opened without one, or who want to apply a different trailing stop distance than the one configured in the EA.

Partial close script: closes a defined percentage of each qualifying position while leaving the remainder open. The scale-out script that takes partial profit at a defined level, reducing risk exposure while maintaining upside participation with the remaining position.

Set stop loss script: sets the stop loss of qualifying positions to a defined price level or to a calculated level based on current price and a defined distance. Useful for applying or updating stop losses on positions that were opened without one, or for adjusting multiple positions' stops simultaneously to a new reference level.

Set take profit script: analogous to the stop loss script but for take profit levels. Setting take profits on positions opened without targets, or updating targets across multiple positions to a new price level.

Order management scripts. Scripts that manage pending orders rather than open positions.

Cancel all pending orders: removes every pending order from the account, or filtered by symbol, by order type, or by magic number. The order cleanup script that removes all working orders before a news event or at the end of the trading session.

Cancel expired orders: removes pending orders that were placed more than a defined time ago or that have not been triggered within their expected validity window. Useful for automated cleanup of orders placed at the start of the session that should not carry over.

Batch pending order placement: places multiple pending orders at defined price levels from a single script execution. The bracket order script that places a buy stop above and a sell stop below the current price simultaneously. The level-based placement script that places limit orders at a defined series of support or resistance levels.

Risk and position size calculators. Scripts that calculate and display the information a trader needs to size a new position correctly, without requiring manual calculation under the time pressure of a live trading decision.

Position size calculator: given the entry price, stop loss level, and a defined risk percentage or dollar amount, calculates the correct lot size for the trade and displays it on the chart or in an alert. Eliminates the mental arithmetic of position sizing during live trading. Accounts for the current account equity, the symbol's tick value and tick size, and the currency pair between the account currency and the instrument's quote currency.

Risk-reward calculator: given entry, stop loss, and take profit levels, calculates the risk-reward ratio, the expected profit and loss amounts at the configured risk percentage, and the probability of profit required for the trade to have positive expectancy at the configured win rate.

Account risk summary: calculates and displays the current open risk across all positions — the total dollar amount at risk if every open position hits its stop loss simultaneously, the percentage of account equity currently at risk, and a breakdown by symbol and by direction.

Trade analysis and reporting scripts. Scripts that process the account's trade history and display analytical results without requiring the trader to export data to an external tool.

Trade history summary: reads the account's closed trade history and displays summary statistics — total trades, win rate, average win, average loss, profit factor, total P&L, largest winning trade, largest losing trade, and other summary metrics for the period. Configurable time range — today's trades, the current week, the current month, or any defined period.

Symbol performance report: breaks down the trade history by currency pair, showing the win rate, P&L, and trade count for each symbol. Identifies which pairs have contributed positively and which have been a drag on performance.

Session analysis: analyses the trade history by time of day or trading session, identifying whether the strategy performs differently in the Asian, London, and New York sessions.

Trade export: writes the full trade history to a CSV file in a defined format for import into external analysis tools, spreadsheets, or trade journal applications. Configurable field selection and date range.

Setup and initialisation scripts. Scripts that prepare the trading environment for a session or a strategy.

Chart setup script: applies a defined chart template to multiple charts simultaneously — the script that opens a defined set of charts, applies the correct timeframe and template to each, and arranges them in a defined layout. Replaces the manual chart setup that starting a trading session requires.

Symbol specification display: reads and displays the current symbol's trading specifications — spread, tick size, tick value, minimum lot size, lot step, swap rates, trading hours — from the broker's server data. The reference information that position sizing and cost calculations depend on.

Account information summary: displays a comprehensive account status — equity, balance, margin, free margin, margin level, open positions count, total floating P&L, daily P&L, and any other account metrics the trader monitors.

Utility scripts. General-purpose automation tools that reduce manual operations in the trading workflow.

Magic number assignment: assigns or modifies the magic number of existing positions, useful when migrating positions between EA strategies or when correcting magic numbers applied incorrectly.

Comment update: updates the comment field of qualifying positions for trade tracking or identification purposes.

Chart screenshot: captures a screenshot of the current chart to a defined file path, with optional annotation of current price and time. Useful for trade journaling workflows that require chart documentation at specific points.

File and data operations: reading signal files written by external systems, writing trade data to files for external consumption, checking for the existence of configuration files that the EA or trading workflow depends on.


Script Design Principles

Confirmation dialogs for destructive operations. Scripts that close positions or cancel orders are performing irreversible operations — running the wrong script on the wrong chart, or running a close-all script when only a single position was intended for closure, has immediate financial consequences. Scripts for destructive operations include a confirmation dialogue that displays the action about to be taken and requires explicit confirmation before executing. The confirmation step is fast and can be bypassed for experienced users who do not need the confirmation prompt, but it is present by default to prevent accidental execution.

Clear visual feedback. Scripts that complete an operation that is not visually obvious — a batch stop loss modification that changes stops on multiple positions — provide clear confirmation that the operation completed successfully: an alert showing the number of positions modified, a chart comment showing the new stop level applied, or a visual indicator on the chart that the script has run.

Error reporting: when a script operation fails on any position or order — a stop modification that fails because the new stop violates the minimum distance, a close that fails because the position was already closed — the script reports the failure clearly with enough information to understand what went wrong and what action the trader should take.

Robustness for live trading conditions. Scripts run during live trading when price is moving and positions may be simultaneously changing state. Scripts must handle the conditions that live trading produces: an attempt to close a position that was simultaneously closed by its stop loss, an attempt to modify a stop loss on a position that no longer exists, a price update between the script's price calculation and its order placement. Scripts that crash or produce undefined results in these conditions are scripts that fail exactly when they are most needed.

Performance. Scripts must execute rapidly — a position management script running during a fast market needs to complete its operations before the market moves significantly. Scripts that iterate all account positions and perform operations on each are designed for minimal execution time: reading all required data before entering the modification loop rather than reading it within the loop, batching operations where the platform supports it, and avoiding unnecessary operations that add latency without adding value.


MT4 vs MT5 Script Development

MT4 scripts. MQL4 scripts using the OrderSelect()/OrderSend() API for position and order operations, running as single-execution programs on an MT4 chart. The MT4 script execution model — the script runs in the OnStart() function and terminates when OnStart() returns — is straightforward and well-understood.

MT5 scripts. MQL5 scripts use the position and order functions appropriate to the MT5 account model — PositionSelect(), PositionGetDouble(), trade request structures for modifications. For hedging mode MT5 accounts, position management is similar to MT4. For netting mode accounts, scripts must handle the single-position-per-symbol netting model correctly.

Cross-platform scripts. Where the same operational requirement exists on both MT4 and MT5, scripts written with compiler directives that select the correct platform-specific API calls compile and run correctly on both platforms. The position size calculator that works for both MT4 and MT5 accounts, the close-all script that handles both the MT4 hedging model and the MT5 netting model.


Technologies Used

  • MQL4 — MT4 script development
  • MQL5 — MT5 script development with standard library position and order management
  • MQL5 Standard Library — CTrade, CPositionInfo, COrderInfo for clean MT5 platform interaction in scripts
  • MetaTrader Strategy Tester — script testing on historical data where applicable
  • MetaTrader visual mode — manual testing of script execution on demo accounts before live deployment

Scripts as Operational Infrastructure

MetaTrader scripts are the operational tools that professional traders use to manage their trading workflow efficiently. The trader who can close all losing positions with a single keystroke, move all stops to breakeven with a single click, and place a batch of pending orders at defined levels with a single action has operational capabilities that the trader relying on manual multi-step execution does not. Under time pressure, in fast-moving markets, the difference between one click and ten clicks is the difference between executing the intended action and not.

Custom scripts built for a trader's specific workflow — the specific operations they perform repeatedly, the specific position management logic they apply, the specific analysis they review — are the tools that make professional MetaTrader trading operationally efficient.


One Click, Exactly What You Need

MetaTrader scripts that perform the right operation, on the right positions, with confirmation where needed, and with the speed and reliability that live trading demands — assigned to keyboard shortcuts, always ready.