Codes sources MQL5 des bibliothèque pour MetaTrader 5
Les bibliothèques sont de petits sous-programmes contenant une certaine fonctionnalité qui peuvent ensuite être utilisés pour développer de nouvelles applications. Une fois écrite et soigneusement vérifiée, une bibliothèque permet aux utilisateurs d'accélérer le développement de nouvelles applications MQL5. L'un des exemples illustratifs est la bibliothèque ALGLIB qui contient de multiples fonctions d'analyse numérique.
Les codes sources des bibliothèques peuvent être téléchargés et utilisés dans MetaEditor lors du développement de stratégies de trading. Ils ne peuvent pas être lancés indépendamment dans MetaTrader 5.
- Applications de trading gratuites
- Plus de 8 000 signaux à copier
- Actualités économiques pour explorer les marchés financiers
Autorisez l'utilisation de cookies pour vous connecter au site Web MQL5.com.
Veuillez activer les paramètres nécessaires dans votre navigateur, sinon vous ne pourrez pas vous connecter.
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 véritable filtre d'actualités du calendrier économique qui fonctionne également dans les backtests. Exportez les événements une seule fois à l'aide d'un script, puis bloquez les nouvelles entrées liées aux actualités, aussi bien en temps réel que dans le Strategy Tester. Corrige le décalage d'une heure lié au passage à l'heure d'été dans les horaires historiques du calendrier.
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.
Évalue chaque type de configuration de votre EA dans son propre historique, au lieu de les regrouper dans une seule courbe de capital. Se reconstitue à partir de l'historique des transactions du compte lors de son initialisation, de sorte qu'un redémarrage ne puisse pas effacer l'historique. Affiche une limite inférieure du score de Wilson à côté du taux de réussite brut, afin qu'une série de trois transactions gagnantes ne soit plus considérée comme un avantage.
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.
Trois mécanismes de protection liés au dimensionnement des positions qui fonctionnent différemment ; c’est en les confondant que tant de comptes se retrouvent à zéro : - « ladder » : un contrat par X du solde, toujours appliqué comme un plafond (CAP), même en cas de dimensionnement manuel des lots ; - « floor » : en dessous du capital minimum, le système ne négocie plus ; un nouveau dépôt est nécessaire ; - « breaker » : s'arrête à X % en dessous du pic, quelle que soit la taille du compte, et ne se réactive pas automatiquement. Ce que cette bibliothèque résout, et que presque aucune autre ne fait : un dépôt n’est pas un bénéfice, et un retrait n’est pas une perte. Le « breaker » mesure la baisse par rapport au pic du solde. Sans traitement particulier, un dépôt effectué PENDANT un drawdown fait augmenter à la fois le solde et le pic, et la protection cesse de détecter la baisse exactement au moment où elle serait utile. Ici, les dépôts et les retraits font varier le pic du même montant. Le pic est enregistré dans un fichier : un « breaker » qui oublie le pic lors du redémarrage du terminal n’est pas un « breaker ». La démo simule un dépôt au plus bas d’un drawdown. Lancez-la avec et sans dépôt, puis comparez la colonne « baisse ».
La taille de la position est calculée à partir d'un montant de risque, lui-même déterminé en fonction de la valeur réelle du tick du symbole, de la taille du tick et du pas de volume, plutôt qu'à partir d'une valeur de pip supposée. Le volume est toujours arrondi à l'unité inférieure, et lorsque votre risque est inférieur au lot minimum, le programme vous le signale et indique le coût réel de ce lot. Aucun état du terminal n'est requis, ce qui permet de tester la logique de calcul de la taille de la position hors ligne — un script de test comportant 41 assertions est fourni.
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.
Une bibliothèque de 24 classes MQL5 qui surveille le respect des règles d'une société de trading pour compte propre (drawdown, perte journalière, régularité des gains, nombre minimum de jours de trading, période d'interdiction d'accès aux informations) pour n'importe quel compte, et qui clôture toutes les positions en cas de non-respect, sans jamais ouvrir de position pour son propre compte.
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.
Une classe d'en-tête MQL5 (.mqh) légère et conforme à la programmation orientée objet (POO), permettant un calcul précis de la valeur du pip et un dimensionnement dynamique des lots pour tous les instruments, avec conversion automatique des taux de change entre devises et normalisation des volumes par courtier.
Il détecte le symbole « or », quel que soit le nom que lui donne le courtier, lit les spécifications du contrat à partir du terminal au lieu de les supposer, et convertit un risque exprimé dans la devise du compte en une taille de lot adaptée à ce courtier.
Look after open positions in an Expert Advisor: break-even, trailing stop, two partial closes, and a stop and target for positions that have none. It never opens a trade.
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.
A daily process writes "today's decision" (which strategy runs, or FLAT) to a file the EAs read at the open. One day the writer did not run. The EAs read yesterday's file, compared its date with TimeCurrent() - the server clock, which had stepped back to the previous day overnight - saw a match, and traded all morning on a 24-hour-old decision. No error anywhere. Two rules, both in this class: 1) staleness is judged against TimeLocal(), which always moves forward; TimeCurrent() is the last tick's stamp - it freezes without ticks and can step back on reconnect. 2) When in doubt the answer is FLAT: missing file, bad date, wrong day, empty line - every failure path returns "do nothing", and each is logged ONCE per state change, not on every tick and not never. File format: line 1 = ISO date, line 2 = decision string. The demo writes a fresh, a stale, a malformed, an empty and a missing file, and shows that only the first is allowed to trade.
Four EAs on the same symbol, each one honest on its own: each checks "do I have a position?" with its own magic number, sees none, and enters. On a demo account this reached 22 contracts on a symbol meant to carry 1, and a watchdog had to close 16 positions in one morning. The cap belongs at the door, not after the fact. ExposureCap::Allowed(symbol, lots, cap) sums the volume of every open position on the symbol - all magic numbers, manual trades included - and refuses the order BEFORE it is sent when it would breach the cap. One log line with the three numbers (held, requested, cap) says why. Deliberately simple: gross exposure, no netting of longs against shorts, no per-EA quota. It is a check, not a lock: two EAs deciding on the same tick can both pass; in practice EAs on different charts decide on different ticks. The demo script prints held / cap / room for the current symbol and shows the refusal line. Nothing is traded.
Une bibliothèque permettant de récupérer des signaux de proximité pour des indicateurs basés sur les canaux
Une petite bibliothèque aux dépendances légères qui introduit dans MQL5 un type « Result » inspiré de Rust. Les fonctions renvoient un objet unique de type « valeur ou erreur » au lieu de s'appuyer sur l'état global GetLastError() ; les échecs sont ainsi explicites et impossibles à ignorer. Elle comprend ResultValue (types de valeurs) et Result (objets pointés), une structure Error, des macros de retour anticipé (TRY, RETURN_ON_ERROR, …) ainsi que des callbacks optionnels Then/Match/MapError.