Guarda come scaricare robot di trading gratuitamente
Ci trovi su Telegram!
Unisciti alla nostra fan page
Accedi al CodeBase dal tuo terminale MetaTrader 5
Non hai trovato il codice che fa per te? Ordinane uno dalla sezione Freelance
Come scrivere un Expert Advisor o un indicatore

Codici sorgente MQL5 di Script per MetaTrader 5

icon

Gli script eseguono azioni uniche in MetaTrader 5, utilizzando un programma MQL5 e vengono eliminati dal grafico subito dopo. Le funzioni esemplificative includono il caricamento della cronologia di trading, la generazione di rapporti e il loro invio via e-mail, il download e l'elaborazione dei dati da un file. Gli script possono essere utilizzati anche per creare un'interfaccia grafica o per eseguire rapidamente operazioni di trading di un solo tipo, per esempio per chiudere immediatamente tutte le posizioni.

È possibile scaricare e lanciare gli script disponibili in MetaTrader 5. La libreria di script è anche disponibile direttamente dalla piattaforma MetaTrader 5 e dall'ambiente di sviluppo MetaEditor.

Invia il tuo codice
più recenti | migliori

Strumento di analisi delle sessioni di trading nativo del broker, in sola lettura, con visualizzazione dello stato attuale, della transizione successiva, con ambito multi-simbolo ed esportazione in formato CSV.

Script MT5 di sola lettura che riporta il volume, il prezzo, gli stop, il congelamento, lo spread e i vincoli di esecuzione del broker.

Test di accettazione sintetici deterministici per la logica di ingresso degli EA di MT5, senza accesso al mercato, al conto o agli ordini.

Uno script di audit in sola lettura per i conti su cui sono in esecuzione diversi EA (o operazioni manuali in parallelo). Raggruppa la cronologia delle operazioni chiuse in base al “magic number” e visualizza una riga per ogni “magic”: operazioni chiuse (round turn), P/L netto comprensivo di swap e commissioni da ENTRAMBI i lati dell’operazione, percentuale di successo, fattore di profitto, profitto/perdita medio, posizioni attualmente aperte e in sospeso, date di attività e simboli – ordinati in base al risultato netto, con esportazione in formato CSV per fogli di calcolo.

TimeCurrent() is not a clock. It is the stamp of the LAST TICK. Two consequences break robots in production: 1. It freezes. With no tick it does not move: illiquid instrument, end of session, unstable connection - and any rule based on it stops with it. 2. It steps backwards: on a symbol switch, a reconnection or a tick from another instrument, the value can go back. The case that cost me a whole protection: I compared the date of a daily decision with TimeCurrent() to reject an expired one. The server clock stepped back to the previous day, the comparison matched, and four EAs accepted YESTERDAY's decision as valid. The gate that should have failed closed failed open - without a single error in the log. Rule: TimeLocal() for timestamps, dates, day changes, expiry - all that must always move forward; TimeCurrent() for session hours and market data. The script measures the divergence in your environment and reports both symptoms live. Run it with the market closed.

Measures, hour by hour, how far a symbol travels and how much of that the spread takes away. Built for gold, works on any symbol, compares several side by side.

Opens a virtual bracketed trade on every M1 bar, walks it forward on the real tick history, and reports for a sweep of stop distances how often 1-minute OHLC modelling would score the trade the wrong way round.

Exports one CSV line per closed trade with the numbers a statement does not carry: the best unrealised profit the trade showed (MFE), the worst unrealised loss it survived (MAE), how much of the MFE was actually kept, how many bars it spanned, and how long it was held. Same measurement as the Trade Excursion indicator, written to a file instead of drawn, because the questions worth asking of this data are ones a chart cannot answer: does the capture ratio depend on the hour of entry? Are the trades I close early the ones I hold longest? Do losers on Mondays reach a different MAE than on Fridays? Those are one pivot table away once the CSV exists. Output is semicolon separated with a header row, in MQL5\Files; opens in any spreadsheet. Measurement limit: excursions come from bar highs and lows on the chosen timeframe; the path inside a bar is unknown. The bars column reports the resolution each trade got, and the summary counts single-bar trades separately instead of averaging them in.

A datetime in MQL5 is seconds since 1970 - but server time (TimeCurrent, bar times, deal times) is the broker's wall clock stored AS IF it were UTC. Export it to CSV, read it in Python or a spreadsheet with a "seconds since 1970 UTC" parser, and every timestamp shifts by the server's UTC offset. On a UTC-3 broker that is three hours: the daily bar dated 00:00 reads as 21:00 of the previous day, and "yesterday's session" silently becomes "today's, half formed". That happened to a morning report of mine before this script existed. The script prints TimeTradeServer, TimeCurrent, TimeGMT and TimeLocal, the three offsets between them, the tick lag, and this chart's last bar time in server time and in real UTC - then states the rule: export server timestamps as wall-clock text, or export the epoch together with the offset, and never let the consumer apply its own timezone.

A simple MQL5 script that calculates the correct lot size for a trade based on your account risk percentage and stop loss distance in pips, so every trade risks a consistent, controlled amount of your balance.

Sizes your next trade based on the correlated risk you already have open across other positions — not just the trade in isolation.

Checks your trade history against common prop-firm challenge rules — profit target, max daily loss, max drawdown, consistency rule, and minimum trading days — with a clear PASS/FAIL report.

Customize your MetaTrader 5 AI Assistant with selectable language, personality, menu and behavior using a simple prompt file.

Reports, month by month, whether your symbol really has ticks or only bars - so you know which part of your backtest ran on generated ticks before you trust the curve. The Strategy Tester gives you one History Quality figure after the test has finished, and it never says which months were the problem. This script asks first.

Analisi in sola lettura per i conti su cui sono in esecuzione diversi Expert Advisor. Raggruppa le operazioni chiuse in base al "magic number" e misura il risparmio effettivo derivante dall'esecuzione congiunta di tali sistemi: drawdown in modalità autonoma rispetto a quello combinato, la matrice di correlazione a coppie rappresentata come mappa termica sul grafico e una riorganizzazione con il metodo Monte Carlo dei rendimenti periodici del portafoglio.

The script prices one night of holding: for every open position and every Market Watch symbol it prints the swap per night in your account currency, the annualized cost in percent for both directions, the broker's rate-independent markup (|swap long| + |swap short| never depends on interest rates - it is pure broker margin), and the triple-swap day. Honest "n/a" where a swap mode cannot be converted reliably.

A read only MT5 script that reports broker symbol specifications, volume limits, price settings, execution modes, trading permissions, margin requirements and estimated profit values.

Lo script rileva lo spread effettivo del proprio broker dal campo "spread" dei grafici M1 e visualizza la mediana, il 90° e il 99° percentile in unità di prezzo, in punti e in frazioni di ATR, oltre a esportare in un file CSV lo spread medio e massimo per ogni ora del giorno. È utile per testare le strategie in base ai costi reali del proprio conto, anziché rispetto a uno spread “tipico” stimato a occhio.

Measures whether a drawing indicator repaints, instead of asserting that it does not. The invariant: once a bar has closed and been processed, no object drawn on it may ever change - not move, not recolour, not change its text, and not disappear. The script seeds a custom symbol with real history, attaches your indicator through a template, records every object, appends bars, forces a full recalculation, and compares object by object. Changes and disappearances are counted separately, because only a change means the claim is false. A run that compared nothing is reported as INCONCLUSIVE, never as a pass. Output is a CSV you can publish next to the number.

Legge la cronologia delle operazioni chiuse (un file CSV o un file generato automaticamente dalla cronologia delle operazioni del conto corrente tramite lo script RuinExport.mq5) e riporta quattro indicatori di rischio indipendenti: aumento del volume a seguito di una perdita, esposizioni sovrapposte nella stessa direzione che determinano in media un prezzo sfavorevole, asimmetria dei rendimenti tra guadagni e perdite e una stima classica del rischio di rovina a un determinato livello di rischio per operazione. I quattro punteggi si combinano in un unico voto da A a F accompagnato da raccomandazioni in linguaggio semplice. Se non viene individuato alcun file CSV, lo script genera automaticamente un registro dimostrativo riproducibile, in modo che il report sia visibile già al primo esecuzione.

Neural Loss-Pattern Auditor trains a small feed-forward neural network, written from scratch in native MQL5, on closed-deal history to test whether behavioral and market-context features predict which trades are more likely to lose. It reports an accuracy uplift over a naive baseline, a probability-calibration table, a permutation feature-importance ranking, and a configurable A-F composite grade with recommendations. On first run it uses a built-in synthetic demo, so the output is visible immediately with no setup; switch one input to InpUseDemoData=false to analyze real account history instead. Pure MQL5: no external libraries, no Python, and no AI service of any kind.

Most reports give you one drawdown number - the worst one. This read-only script measures all three that matter on your own closed history: depth, duration and frequency. It prints the maximum drawdown with its peak, trough and recovery dates, the longest underwater period in days, whether you are at a new peak or how far below it and for how long, and a table of the deepest episodes with the days each took to recover. An episode is not a losing streak: it closes only when a NEW high is made, so a dip that never reclaims the old peak stays the same episode - which is what makes the duration column meaningful. Entry commissions are included and a partial close counts as one round turn, so the curve carries full cost. Optional percentage figures and CSV export. Deposits and withdrawals are excluded: this is the drawdown of your trading, not of your balance line.

Measures whether an entry signal actually beats transaction costs, before you spend weeks building an EA around it. Reports net result after cost, an honest t-statistic on non-overlapping samples, and a random control. Places no orders.

Prints the invisible contract limits that silently reject orders: stops level, freeze level, min/step/max lot, tick size and value, spread type, execution mode, swaps, and the margin needed for the minimum lot against your free margin.

Read-only MT5 script that estimates stop-distance cash loss in account currency, reserves explicit cash costs and floors volume to the broker grid. It never sends or modifies an order.

A native MQL5 tool that reconstructs closed positions from deal-level history, flags the ones closed through more than one exit, and reprices each one at its own first, last, and best exit rates to measure whether scaling out actually added value. Reports a Value-Add Ratio, a Scale Out Win Rate, an Efficiency figure, and a single-trade dependence check, combined into an A+ to F score with recommendations. Runs out of the box against a built-in demonstration data set; a companion script exports the real input file from your own account history. Pure MQL5, no external libraries.

Checks a hypothetical MT5 market or pending order against current symbol, volume, tick-size, stop-distance and filling rules without sending a trade.

Prints a privacy-conscious snapshot of the current MT5 broker, account, symbol and terminal environment to the Experts log for diagnostics and support.

Uno script interamente in MQL5 che misura la robustezza del vantaggio competitivo di una strategia rispetto ai costi di esecuzione. Legge un file CSV contenente data, profitto e volume delle operazioni chiuse e modella il costo di ciascuna operazione come una componente fissa più una componente per lotto. Visualizza il costo di pareggio per operazione, il margine di sicurezza (il multiplo di un costo realistico ipotizzato al quale l’utile netto raggiunge lo zero), l’utile netto e il fattore di profitto ricalcolati in base al costo ipotizzato, la percentuale di operazioni vincenti che il costo trasforma in perdenti e un punteggio composito di robustezza rispetto ai costi da A+ a F con raccomandazioni. Se non è presente alcun file, genera un campione riproducibile e lo analizza, in modo che il risultato sia visibile già al primo esecuzione. Nessuna libreria esterna, nessun Python, nessuna intelligenza artificiale.

Calcola la dimensione corretta del lotto per un’operazione pianificata in base al rischio (percentuale del capitale proprio o importo fisso) e alla distanza dello stop-loss (punti o livello di prezzo). Tiene conto delle specifiche contrattuali del titolo – dimensione e valore del tick, volume minimo/massimo/incremento – e stima il margine richiesto.

Esporta le posizioni chiuse relative a un periodo configurabile in un file CSV per l'analisi del registro in Excel o Google Sheets: ora e prezzo di apertura e chiusura (ponderati in base al volume per le esecuzioni parziali), volume, risultato in punti, commissione, swap, profitto netto e durata dell'operazione.

Uno script nativo MQL5 che analizza la struttura dei drawdown di un conto, non solo il singolo valore del “drawdown massimo”. Legge una curva di equity giornaliera (CSV con Date e DailyPnL), ricostruisce la curva “underwater” e la suddivide in singoli episodi di drawdown con la rispettiva profondità, durata e tempo di recupero. Successivamente riporta l’Ulcer Index, il Pain Index, il Recovery Factor e il tempo trascorso in zona negativa, combinandoli in un unico punteggio di resilienza (da A+ a F) corredato di raccomandazioni, visualizzato nella scheda “Esperti”. Non richiede librerie esterne; se non viene trovato alcun file, genera una curva di esempio, consentendo così l’esecuzione immediata senza configurazioni aggiuntive.

Uno script nativo MQL5 che misura il grado di concentrazione del profitto di una strategia — ovvero se il vantaggio competitivo è ampio o si basa su poche operazioni fortunate. Legge un file CSV con i dati per singola operazione (Data, Profitto) e riporta la quota di profitto netto derivante dalle operazioni più redditizie, il coefficiente di Gini delle operazioni vincenti, un profilo di concentrazione, un test di sopravvivenza che rimuove le poche operazioni migliori e ricalcola il profitto netto e il fattore di profitto, nonché il massimo giornaliero rispetto a un limite di coerenza configurabile, il tutto combinato in un punteggio di concentrazione e coerenza (da A+ a F) con raccomandazioni. Se non viene trovato alcun file, genera un set di dati di esempio, quindi è subito pronto all’uso. Nessuna libreria esterna, nessun Python, nessuna IA. Lo script di supporto ExportTrades.mq5 crea il file a partire dalla cronologia delle operazioni.

Script MT5 open source che registra nel log e, facoltativamente, in un file CSV le impostazioni relative al simbolo XAUUSD/GOLD, lo spread, il valore del tick, la dimensione del contratto, l'incremento di volume, i livelli di stop/freeze, lo swap e il contesto del conto.

Script diagnostico che confronta i valori SYMBOL_TRADE_TICK_VALUE, SYMBOL_TRADE_TICK_VALUE_LOSS e SYMBOL_TRADE_TICK_VALUE_PROFIT per ogni simbolo presente in Market Watch. Classifica ogni simbolo in una delle quattro categorie (ALL_EQUAL, TV_MATCHES_PROFIT, TV_MATCHES_LOSS, ALL_DIFFER) e fornisce un riepilogo aggregato insieme a un suggerimento interpretativo. Utile per verificare su quale proprietà del valore del tick fare affidamento quando si implementa il dimensionamento dei lotti basato sul rischio negli EA. Esporta il report completo per ogni simbolo in formato CSV nella cartella MQL5/Files.

Script per impostare lo Stop Loss su ogni posizione aperta in base a una perdita target espressa nella valuta del conto (ad es. 50 $ per posizione). Funziona con qualsiasi valuta di deposito e qualsiasi simbolo forex. Verifica i livelli di stop e di congelamento del broker. La conversione valutaria viene gestita automaticamente.

I flussi di lavoro di etichettatura a tripla barriera utilizzano spesso una costante arbitraria (0,5–1,0%) o un’ipotesi di spread tradizionale come soglia min_ret. Una soglia impostata al di sotto del costo effettivo di transazione round-trip fa sì che il flusso di lavoro etichetti il rumore determinato dai costi come segnale negoziabile. Il set di dati etichettato tende quindi a sovrastimare sistematicamente l’edge, e qualsiasi modello addestrato su tali etichette subisce un overfitting rispetto a un artefatto dello schema di etichettatura piuttosto che alla struttura di mercato reale. TransactionCostCollector.mq5 è uno script autonomo che risolve la fase di raccolta dati relativa a questo problema.

Chiudere le posizioni in profitto

Utility script that exports your MetaTrader 5 trading history to a CSV file. It automatically calculates Maximum Favorable Excursion (MFE), Maximum Adverse Excursion (MAE), and Forward Returns (Time-Based Excursions) in whole points for deep quantitative analysis in Excel. It will allow you to understand whether you close your trades too early and can help optimize overall trading execution.

The script shows the usage of L1 Trend Filter methods in MQL5 for float and double vectors on random walk simulated data.

12345678...10