Codici sorgente MQL5 di Librerie per MetaTrader 5

icon

La libreria di script è inoltre disponibile direttamente dall'ambiente di sviluppo MetaEditor per permetterti di imparare la programmazione in MQL5. Una volta scritta e controllata accuratamente, una libreria permette agli utenti di accelerare lo sviluppo di nuove applicazioni MQL5. Uno degli esempi illuminanti è la libreria ALGLIB che contiene molteplici funzioni di analisi numerica.

I codici sorgente della libreria possono essere scaricati e utilizzati in MetaEditor durante lo sviluppo di strategie di trading. Non possono essere lanciati separatamente in MetaTrader 5.

Invia il tuo codice
più recenti | migliori

Standalone MQL5 library for storing custom settings separately for each trade and following a verified pending-order-to-position lifecycle. It supports double, ulong and price-unit fields, terminal-local Global Variables, safe cleanup gates and an offline self-test. Includes a demo EA, source archive, and installation guide. A different-ticket transition, reconnection as a separate scenario, and netting behavior remain untested.

Converts broker server time to UTC and New York time with US and EU daylight saving rules. Works the same live and in the Strategy Tester, where TimeGMT() returns server time.

Minimal include file to license your own EAs and indicators: allowed account numbers, expiry date, demo-only trial mode and broker server filter. Example EA included.

Persistent MQL5 outbox with a Telegram demo and offline tests. An uncertain result is never retried automatically. Manual retry may duplicate a message; SENT means API acceptance, not a read receipt.

Gestisci le posizioni aperte in un Expert Advisor: break-even, trailing stop, due chiusure parziali e uno stop e un target per le posizioni che non ne hanno. Non apre mai un’operazione.

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.

Fits five bivariate copulas on ranks, with Kendall's tau, tail dependence, the probability of joint extreme days, AIC and the conditional probabilities of pairs trading.

Online detection of changes in the mean or volatility (Adams-MacKay): probability of a change in the last k bars, current segment length, forecast, and an indicator.

Exact maximum likelihood of an Ornstein-Uhlenbeck spread and Bertram's optimal entry and exit levels for a given cost, with the expected length of a trade cycle.

A lightweight tab bar for chart panels, drawn with the standard CCanvas class. One include file, several independent instances per chart, click selection, resizing and safe cleanup. Includes a demo Expert Advisor.

Parkinson, Garman-Klass, Rogers-Satchell and Yang-Zhang estimators, daily realized and bipower variance from intraday bars, and HAR volatility forecasts.

Five tests to tell a random walk from a mean-reverting series: KPSS, Phillips-Perron, DF-GLS, Zivot-Andrews with the break date, and the variance ratio.

Detects the broker's GMT offset and its daylight-time rule (fixed, US or European) from the weekly closes in the H1 history, the same way live and in the Strategy Tester, with functions that convert New York times to server time and back.

Is the best of many strategies really better than the benchmark? Hansen's SPA test, White's Reality Check, Romano-Wolf StepM and the model confidence set.

Unit root and cointegration tests (ADF, Engle-Granger, Johansen) with MacKinnon p-values, hedge ratio, half-life and z-score of the spread, and a pair scanner.

Kalman filter and smoother with an exact diffuse start, missing values and maximum likelihood: local level, local linear trend and a regression whose hedge ratio drifts.

Gaussian hidden Markov model fitted by Baum-Welch: regime probabilities without look-ahead, most likely path, expected durations and regime forecasts.

Holidays and early halts of the CME equity index futures (S&P 500, Nasdaq-100, Dow, Russell 2000, E-mini and Micro), computed from the US holiday rules for any year, with a script that checks the calendar against your broker's own M1 history.

Include for EAs running 24/7 on an MQL5 VPS or PC: run-where switch, order send with OK/FAIL/UNKNOWN result (no duplicate orders after a timeout), restart-safe counters, positions closed while the EA was off, append-only log and optional Telegram. No trading logic inside.

Fits GARCH(1,1), GJR-GARCH and EGARCH with normal, Student t or GED shocks by maximum likelihood, with robust standard errors and variance forecasts.

Un vero e proprio filtro per le notizie del calendario economico che funziona anche nei backtest. È sufficiente esportare gli eventi una sola volta tramite uno script, per poi bloccare i nuovi inserimenti in corrispondenza delle notizie sia in tempo reale che nel Strategy Tester. Corregge lo scostamento di un’ora dovuto all’ora legale rispetto agli orari storici del calendario.

Probability of Backtest Overfitting (PBO) of an MT5 optimization by combinatorially symmetric cross-validation. Every pass sends its daily results as a frame, and the PBO is computed when the optimization ends.

Block bootstrap of daily results: how deep the drawdown of an account or strategy can get over the next months, with percentiles and a seeded generator for repeatable runs.

Portfolio weights from the returns of symbols or Expert Advisors: inverse volatility, risk parity, hierarchical risk parity, minimum variance, maximum diversification, Ledoit-Wolf covariance.

Reads a Strategy Tester report saved as HTML into its deals, closed trades, net profit and balance drawdowns, for comparing, combining or exporting backtests.

Single-header account lock for MT5 EAs: licensed account numbers, optional demo allowance, expiry date, tester bypass. Licence compiled in with #define. No DLL.

Assegna un punteggio a ogni tipo di configurazione del tuo EA in un registro separato, anziché raggrupparli in un’unica curva di equity. Si ricostituisce automaticamente a partire dalla cronologia delle operazioni del conto al momento dell’avvio, in modo che un riavvio non possa cancellarne la cronologia. Visualizza un limite inferiore del punteggio di Wilson accanto alla percentuale di vincita grezza, in modo che una serie positiva di tre operazioni non sembri più un vantaggio competitivo.

AttachExpert.mqh attaches an Expert Advisor to a chart from MQL5 code, with the inputs you choose and with "Allow Algo Trading" on or off.

Tre meccanismi di protezione per il dimensionamento delle posizioni che funzionano in modo diverso; confonderli è il motivo per cui così tanti conti vengono azzerati: - ladder: un contratto ogni X del saldo, applicato sempre come limite massimo (CAP), anche con il dimensionamento manuale dei lotti; - floor: al di sotto del capitale minimo non effettua operazioni; è necessario un nuovo versamento; - breaker: si attiva all’X% al di sotto del picco, indipendentemente dalle dimensioni del conto, e non si riattiva automaticamente. Ciò che questa libreria risolve e che quasi nessuna altra fa: un versamento non è un profitto, e un prelievo non è una perdita. Il «breaker» misura il calo rispetto al picco del saldo. Se non gestita, un'operazione di deposito effettuata DURANTE un drawdown fa aumentare contemporaneamente sia il saldo che il picco, e la protezione smette di rilevare il calo proprio nel momento in cui sarebbe utile. In questo caso, depositi e prelievi spostano il picco dello stesso importo. Il picco viene salvato in un file: un «breaker» che dimentica il picco al riavvio del terminale non è un «breaker». La demo simula un deposito al punto più basso di un calo. Eseguila con il deposito attivato e disattivato e confronta la colonna «calo».

La dimensione della posizione viene calcolata in base all'importo di rischio, determinato dal valore reale del tick del simbolo, dalla dimensione del tick e dall'incremento di volume, anziché da un valore ipotetico del pip. Il volume viene sempre arrotondato per difetto e, quando il rischio è inferiore al lotto minimo, il sistema lo segnala e indica il costo effettivo di quel lotto. Non è richiesto un terminale, quindi la logica di calcolo delle dimensioni è verificabile offline: è incluso uno script di test con 41 asserzioni.

Calculates the Strategy Tester report statistics from the deal history, including Z-Score, AHPR, GHPR, LR Correlation and LR Standard Error, which TesterStatistics() does not return. Checked value by value against the tester.

An include file that writes real Excel workbooks (.xlsx) from MQL5 without DLLs: several sheets, numbers, text and real Excel dates, a frozen bold header and filters. Example script: the account deals and the daily results to Excel.

A small include file that tells your Expert Advisor when it is inside a news window, using the economic calendar built into MetaTrader 5. No web requests and no DLL.

Una libreria di 24 classi MQL5 che monitora il rispetto delle regole di una società di trading con capitale proprio — drawdown, perdita giornaliera, costanza dei profitti, numero minimo di giorni di trading, blackout delle notizie — su qualsiasi conto e chiude tutte le posizioni in caso di violazione, senza mai aprire una posizione propria.

The library reconstructs a complete MQL4-style order model on top of the native MQL5 Position, Order, Deal, and History APIs. This design allows legacy MQL4 Expert Advisors to operate with minimal code changes while preserving MQL5.

Una classe di intestazione MQL5 (.mqh) leggera e conforme ai principi della programmazione orientata agli oggetti (OOP), che consente il calcolo accurato del valore del pip e la determinazione dinamica delle dimensioni dei lotti per tutti gli strumenti, con conversione automatica dei tassi di cambio tra valute e normalizzazione dei volumi da parte del broker.

Rileva il simbolo “gold”, indipendentemente dal nome con cui lo chiama il broker, legge le specifiche del contratto dal terminale invece di ipotizzarle e converte il rischio nella valuta del conto in una dimensione del lotto corretta per quel broker.

A small include file for Expert Advisors and trade managers. It turns your risk rules into yes/no answers: how many lots does this stop allow, is the daily loss limit reached, is the maximum drawdown (static or trailing) reached, how much is at risk across all open positions, and are spread and session acceptable. The lot is never rounded up: if the broker minimum lot would risk more than allowed, the trade is skipped and the reason is returned. Limits survive a terminal restart. The library only measures: it sends no order. Includes a demo account guard (no trading by default) and a self-test with 78 checks.

Four EAs writing to the same file, all with FILE_SHARE_READ|FILE_SHARE_WRITE, FileSeek(SEEK_END), FileWrite, FileClose. Looks correct. Every FileOpen returns success. No error in the log. And the lines vanish. Reason: FILE_SHARE_WRITE lets all four open at the same time. All four call FileSeek(SEEK_END) and get THE SAME offset, because none has written yet. All four write at the same position. Whoever closes last wins. Three lines vanish silently. In my case: 12 events expected, 8 in the file. The fix is to open EXCLUSIVELY (no FILE_SHARE_WRITE) and retry while another EA holds the file. And to shout in the log when the retries run out: a log that fails silently is worse than no log at all, because you trust it. The demo script reproduces both modes. To see the loss, drag it onto four charts at the same time with safe mode off and count the lines in the CSV. On a single chart the defect does not show up - which is why it passes in testing and breaks in production.

1234567891011