Libreria di Codici Sorgente MQL4 e MQL5

icon

Vuoi imparare il linguaggio di programmazione MQL5 o MQL4, ma non sai da dove cominciare? Qui sono disponibili vari programmi per il tuo terminale MetaTrader. Scarica e studia questi esempi di codici pubblicati e sviluppa per conto tuo degli indicatori e degli Expert Advisor. Le tue applicazioni pubblicate nella più grande libreria di codici MQL5 e MQL4 saranno disponibili in ogni terminale MetaTrader e nel MetaEditor.

I tuoi esempi di codice in MQL4 e MQL5 saranno distribuiti in tutto il mondo, permettendoti di entrare in contatto con migliaia di trader!

Invia il tuo codice

Esegue un controllo sulla cronologia dei tick riprodotta dai backtest basati su "Ogni tick basato su tick reali". Cinque controlli per simbolo negli ultimi N giorni: quotazioni impossibili e incrociate, timestamp che scorrono all'indietro o si ripetono, inversioni di prezzo di un tick di entità pari a multipli dello spread mediano del simbolo stesso, silenzi all'interno delle sessioni di quotazione dichiarate dal broker e minuti in cui i tick e le barre M1 non coincidono. Ogni risultato viene salvato in un file CSV con il relativo timestamp in millisecondi, e lo strumento riporta i propri calcoli in modo che il report possa essere ricontrollato. Solo lettura: nessuna funzione di trading, nessuna DLL, nessuna connessione di rete.

Un EA gratuito e completamente aperto per l'indice JPN225 (Nikkei 225) su timeframe M15. Effettua acquisti quando il prezzo tende al rialzo, lo slancio non è eccessivo e il volume è contenuto. Backtest dal 2022 al 2026: profit factor 1,68, +18,5% all’anno, ha superato 15 stress test. In pareggio alle 17:00.

Draws the daily opening range and its breakout levels, with a dashboard showing how the range resolved over your lookback: broken up, down, both ways or not at all, and how often a breakout hit its target before the opposite side.

Prop Firm Guard Panel is an on-chart panel for prop firm challenges and funded accounts. It shows in real time the daily loss used and the room left, the max loss room and equity floor, and the progress toward the profit target. The start-of-day balance is rebuilt from today's closed deals, so the values stay correct after a restart. Colors change from green to orange to red as limits get closer, with optional popup and push alerts. Auto, dark or light theme. Display only: it never opens, modifies or closes trades.

Mouse Scroll Zoom in Zoom Out

Trending up, trending down or ranging: a verdict for every bar, and how long it has held. Each stretch of one regime is boxed on the price chart, ADX columns below show how strong it is, and a one-line panel gives the regime, its age and the ADX. Values for Expert Advisors and an alert on closed bars.

Reads your closed positions and the M1 bars after each exit. Shows how many stopped-out trades later reached their take profit, how far take-profit trades kept running and how much move was left after manual or EA exits. Summary panel, per-position log table and CSV.

Free educational EA — a single-position trend-following EMA crossover system for XAUUSD M30, released as open source for beginners to study trade ownership guards, preflight order validation, risk-based lot sizing, and server-time session filtering. This code demonstrates how a strategy - identifies and manages only its own positions and orders through MagicNumber and comment tags, - wraps CTrade with an OrderCheck preflight that blocks invalid or margin-breaking requests, - sizes each trade from a fixed stop-loss and risk percentage, - and restricts entries to a configurable broker session window with a daily close-all — all evaluated on completed bars only, so signals never repaint.

Traccia i range delle sessioni asiatiche, londinesi e newyorkesi e evidenzia gli "sweep" di liquidità: una barra chiusa la cui ombra si estende oltre il massimo o il minimo di una sessione completata, per poi richiudersi all'interno di tale intervallo. Frecce che non si aggiornano, livelli di sessione estesi, avvisi e buffer compatibili con iCustom.

Modello EA "Opening Range Breakout" con protezione del conto integrata. Individua i massimi e i minimi dei primi N minuti dopo l'apertura della sessione e inserisce ordini stop OCO al di sopra e al di sotto dell'intervallo. Include il dimensionamento delle posizioni basato sul rischio, il limite di perdita giornaliero, il limite massimo di drawdown, il filtro dell'intervallo ATR, il filtro della direzione di trading e la protezione contro le posizioni mantenute durante la notte. Tutti gli orari delle sessioni sono parametri configurabili. Modello didattico, non un sistema che garantisce profitti. Testare su conto demo prima di qualsiasi utilizzo in live.

Non-repainting fair value gaps on closed bars, with zone states (active, touched, mitigated) and iCustom buffers for EAs.

Real-time daily drawdown buffer monitor and exact breach price line indicator for prop firm accounts. Features 00:00 server-time deal history reconstruction (including entry commissions), 00:00 HWM snapshot locking, two-stage OrderCalcProfit cross-rate calibration, and iCustom() data buffers for Expert Advisors.

Colora lo sfondo del grafico in base al regime di volatilità (Compressione, Normale, Espansione) in base al rango percentile dell'ATR corrente. Mostra il regime corrente sul grafico, avvisa in caso di cambiamenti di regime e mette a disposizione buffer per gli Expert Advisor.

Colora lo sfondo del grafico in base al regime di volatilità (Compressione, Normale, Espansione) in base al rango percentile dell'ATR corrente. Mostra il regime corrente sul grafico, avvisa in caso di cambiamenti di regime e mette a disposizione buffer per gli Expert Advisor.

Apre i grafici relativi a tutti i simboli di Market Watch o a un elenco di simboli personalizzato con un solo clic, su qualsiasi intervallo di tempo, applicando un modello opzionale a ciascun grafico. Salta i grafici già aperti e limita il numero di grafici aperti contemporaneamente.

L'esportazione salva le operazioni in un file CSV indicando l'escursione massima sfavorevole (MAE) e l'escursione massima favorevole (MFE) in punti e in denaro, calcolate sulla base della cronologia M1, oltre alla percentuale del movimento disponibile catturata da ciascuna operazione.

See the real leverage of every Market Watch symbol, including floating margin tiers, with swap, commission and live spread in one panel.

Watches the whole account and closes everything before the daily loss or max drawdown limit is breached, then keeps the account flat until the block ends. Does not trade.

Expert Advisor template that shows safe execution practices: closed-bar signals once per bar, no duplicate entries after an MT5 or VPS restart, spread and stop-level checks, normalised volume and a log line for every decision.

Shows the current spread next to its recent average and maximum and compares it with ATR, so you can see at a glance when trading costs are too high relative to the symbol's normal movement.

On-chart panel that calculates the lot size for a given risk (% of balance, % of equity or fixed money) and stop-loss distance, using the broker's tick size and tick value. Works on forex, metals, indices and crypto.

Trailing stop and breakeven manager for Gold (XAUUSD), forex and any symbol: moves the stop to breakeven with an offset, then trails it in points or ATR multiples on manual trades and on any EA, filtered by magic and symbol. Open source code.

Script that reads the deal history of your account and writes a plain note on how an Expert Advisor really trades: entries, stops and trailing, lot changes, martingale, averaging, trades at once, hours and holding time, plus what to watch out for. It never trades and says nothing about profit

Automazione basata sui segnali per l'oscilloscopio WaveMaster. Motore di esecuzione automatizzata per l'oscilloscopio WaveMaster. Legge i buffer dei segnali in tempo reale. Gestione completa del rischio, trailing e break-even integrati.

Verifica la cronologia delle barre effettivamente conservata dal tuo terminale, ovvero la cronologia utilizzata da ogni backtest e da ogni indicatore. Sei controlli per ogni simbolo: valori OHLC impossibili, orari delle barre errati, barre mancanti mentre la tabella delle sessioni del broker indica che era in corso la quotazione, barre vuote e piatte, barre non coerenti con la serie M1 del broker stesso e correttezza dello spread. Il dato principale è la copertura della sessione, non una percentuale tabellare che misura principalmente quanti fine settimana sono stati verificati. Ogni risultato viene esportato in un file CSV con l’ora della barra, e le barre verificate insieme alla tabella delle sessioni possono essere esportate in modo che l’intero report possa essere rielaborato con strumenti diversi da questo.

Draws the previous day, previous week and previous month high and low, plus automatic round-number levels around the current price. Every level carries a label with how many times price touched it and how many times a bar swept it (pierced the level and closed back on the original side). Counts use closed bars only, so they do not repaint. Optional alerts (popup, push, email, sound) for sweeps and new touches. Touch tolerance is a fraction of ATR or a fixed number of points. The 6 previous-period levels and their touch counts are exposed in 12 indicator buffers for use from an Expert Advisor with iCustom(). Works on any timeframe up to H4. Read-only: it never opens, modifies or closes a trade. No DLLs, no web requests.

Draws the opening range of a configurable session (start time and length in minutes, with a server time zone adjustment), the 1R and 2R levels above and below the box, and the session VWAP (tick volume, or real volume when the broker provides it). A small panel counts, over the last N finished sessions, how many broke the range up only, down only, on both sides, or not at all, and how often price reached 1R and 2R after the first break. The statistics are historical counts: they describe the past and do not predict anything. Only closed bars are used, so nothing repaints; optional popup, push and sound alerts fire once per direction per session when a closed bar closes outside the box. Eight buffers (range, targets, VWAP, break state) can be read from an Expert Advisor with iCustom(). Works on M1 to M30, recalculates only new bars and deletes its chart objects when removed. Read-only: it never trades. No DLLs, no web requests.

Draws the high and low of the Asia, London and New York sessions as boxes or lines extended to the end of the day, with configurable session hours and a server time zone adjustment. Optional previous day and previous week high/low. When a CLOSED bar breaks the high or low of a session that has already finished, it can raise a popup alert, a push notification and/or a sound, once per level per day. Alerts are evaluated on closed bars only, so they do not repaint. The 10 levels are exposed in indicator buffers, so an Expert Advisor can read them with iCustom(). It recalculates only new bars, works on any timeframe up to H1, and deletes all its chart objects when removed. Read-only: it never opens, modifies or closes a trade. No DLLs, no web requests.

Marks bullish and bearish engulfing, bullish and bearish pin bar and inside bar patterns with arrows, using closed bars only, so nothing repaints. The definitions (wick and body proportions, minimum bar size in ATR) are inputs, with an optional EMA trend filter. For each pattern a small panel shows a rolling historical statistic: the share of the last N resolved cases where price moved X ATR in the pattern direction before moving Y ATR against it, together with the number of cases. X, Y, N and the waiting time are inputs. The numbers describe what happened on your chart history; they do not predict the next trade. Optional alerts on closed bars (popup, push, sound). 20 buffers (signal, hit rate and sample size per pattern) can be read with iCustom(). Uses prev_calculated, deletes its chart objects when removed. Read-only: it never trades. No DLLs, no web requests.

Utility Expert Advisor that watches the account equity against two limits: a maximum daily loss and a maximum total drawdown. Each limit can be set as a percentage or as a money amount, and the daily loss can be measured from the balance or from the equity at the start of the day, as many prop firms do. When a limit is touched the EA closes all positions, deletes all pending orders and keeps the account locked until the next trading day: anything opened in the meantime, by another EA or by hand, is closed again. Optional early warning at a percentage of the limit (Alert and push), a small on-chart panel, a magic number / symbol filter, a configurable day-reset time and retries when a close fails. The state is stored in terminal global variables, so a restart does not unlock the account. Works on hedging and netting accounts. No DLLs, no web requests. It never opens trades (only the optional Strategy Tester demo mode does).

Exports your closed trade history to a CSV file with one row per position (not per deal), ready for Excel, Python or any journal. Each row has ticket, symbol, magic number, comment, side, volume, entry and exit time and price, duration, initial SL and TP when known, gross profit, commission, swap, net result and R multiple. It also calculates MFE and MAE (best and worst price reached while the trade was open, in points and in money) from the M1 bars between entry and exit, plus the entry session (Asia, London, New York) and weekday. Filter by magic number (lists and ranges) and symbol (wildcards), pick the period, the column separator (; or ,) and the decimal mark, and save to MQL5\Files or the common folder. Tested on hedging accounts and in the Strategy Tester (netting logic included; feedback welcome), where the file is written when the test ends. Read-only: it never opens, modifies or closes a trade. No DLLs, no web requests.

XAUUSD grid EA that opens a basket when RSI leaves oversold or overbought on a closed candle, adds levels with a lot multiplier and closes the basket at a money or points target. Open source code.

Replica le operazioni aperte, modificate e chiuse da un altro EA sullo stesso conto di copertura, selezionato in base al numero magico. Per impostazione predefinita, inverte la direzione (Acquisto↔Vendita, SL↔TP), consentendo così di eseguire un test retrospettivo della versione inversa di una strategia con spread, slippage ed esecuzione reali.

Una versione adattata dell’Alpha Engine del gruppo Olsen: otto agenti che operano con ordini a limite negoziano variazioni direzionali nel tempo intrinseco su un conto di copertura. Approfittano degli overshoot e chiudono le posizioni in profitto in caso di inversioni di tendenza.

Manages positions that are already open: it adds a missing SL/TP, moves the stop to break even, trails it, caps the position count and applies daily equity limits. It never opens trades.

Draws the high and low of a chosen time window and alerts on the first break on each side. The levels are also available through iCustom.

Close all positions panel for MT5: seven buttons to close all, buys, sells, winners, losers, the chart symbol or delete pending orders, on Gold (XAUUSD), forex or any symbol, for manual trades and any EA. Open source code.

Auto Fibo Extended is a MetaTrader 5 indicator designed to automatically identify significant swing highs and swing lows and draw Fibonacci Retracement and Extension levels directly on the chart.

A stop distance in points is not money until the tick size and tick value make it one. This library turns four risk bases into a lot size, floors it to the volume step, caps it against free margin and tracks a daily loss limit. Two MQL5 headers, no DLL.

A one-file library that handles how an EA trades: pre-trade checks, normalisation to broker limits, safe retries, one order per signal, isolation by magic number and state recovery after a restart. Lot by risk, daily loss limit and equity floor included. Verified in the Strategy Tester.