|
нет
опыт работы
|
2
продуктов
|
0
демо-версий
|
|
0
работ
|
0
сигналов
|
0
подписчиков
|
An EA can set spread and tick-gap thresholds by percentile without storing every tick. CPSquare implements the P-Square algorithm, and two order-independent classes serve as alternatives: CCountQuantile returns exact percentiles of rounded spreads, and CLogQuantile keeps a chosen relative error within a set range. Unit tests, mutation runs, and a Python consistency check cover the code. On EURUSD and XAUUSD ticks in time order, the P-Square estimates of high percentiles stayed far from the exact values.
Golden-file testing compares the trade decisions of a modified Expert Advisor with an accepted run, so an unintended logic change appears as changed decisions. CDecisionRecorder writes each recorded request with run context and a tick hash, and CGfFile refuses truncated or malformed files. CGoldenCompare pairs rows by time and returns a verdict that separates changed decisions from different settings or ticks. Random execution delay made the tested runs differ, so compare runs with the same fixed delay or none.
CTradeWindows blocks EA entries during the daily rollover spread spike. Each window is a clock time in a zone such as New York, so it follows that zone through DST. CSpreadProfile learns the windows from tick spreads and saves them to a file that an EA can load. Unit tests and Strategy Tester runs on one server show that a window fixed in server time misses the spike in weeks when the US and EU DST dates differ.
CLabelBlock lets an EA show a long text as labels wrapped by pixel width and detect a truncated label. On the tested builds, native text objects and object names keep only the first 63 UTF-16 code units without an error. CCanvasBlock draws wider lines on one bitmap without that cap but cannot read its text back. Unit tests and screenshot checks cover one system and a few fonts.
When an EA trades several symbols, each new lot size must account for the risk already open. CRiskBudget returns the largest volume that five caps allow: risk per trade, open risk budget, free margin share, SYMBOL_VOLUME_MAX, and SYMBOL_VOLUME_LIMIT, and it names the cap that decided. Unit tests, a tester EA, and a Python consistency check cover these decisions. In the tested runs, the budget did not reduce drawdown.
With CTradingDay, an EA can reset its daily loss limit at the time its rule names, such as the New York close, not at the end of the broker's feed. CServerClockFit finds the server time zone and its DST rule from hourly bars. On the tested server, the New York close falls one hour before server midnight between the US and EU clock changes. Unit tests and tester runs check these clock times for that server only.
An EA can detect a wrong ONNX model in OnInit, before its first prediction, instead of failing or returning other probabilities in OnTick. COnnxContract checks the model's signature, features, class labels, and SHA-256 hash against a contract file. COnnxParity compares the terminal's probabilities with onnxruntime on a golden file of reference rows, and a Python tool builds both files from your data. The tool also audits the EA's prediction log, because a golden pass covers only its own rows.
CStopOutGuard shows how far a symbol's price can move before the modeled margin level reaches stop-out, and how much closer a planned order would bring that threshold. Positions are valued with OrderCalcProfit() and OrderCalcMargin() at each tested price instead of a fixed tick value, so volume margin tiers are included. Unit tests, test EAs, and a Python consistency check cover the search. The model keeps the spread and swaps at their current values, and CanAdd() does not replace OrderCheck().
Строки групп в пользовательском индикаторе занимают позиции параметров в iCustom() и IndicatorCreate(), поэтому числа, переданные без заполнителей, незаметно смещаются и попадают не в те входные параметры. Класс CIndicatorInputs считывает фактическую схему параметров, заполняет позиции групп, отклоняет значения, которые терминал изменил бы, и проверяет хендл на графике, так что советник получает либо запрошенные настройки, либо ошибку. В тестере стратегий класс создает хендл на основе сохраненной схемы параметров без проверки. Оба режима демонстрируются в модульных тестах и в советнике для тестера стратегий.
A pause after a losing streak assumes that losses come in clusters. CRunsTest turns the closed trades of an account or a tester run into a sequence of wins and losses and checks it with the Wald-Wolfowitz runs test, streak checks against shuffled orders, and a drift test. No dependence was detected on the tested EAs. A power simulation shows which effects each check could see, and on the shorter test runs a "not detected" result carries little weight.
CTradePreflight проверяет торговый запрос перед вызовом OrderSend(), благодаря чему советник обнаруживает объем, не кратный шагу, стоп-уровень по неверную сторону от цены, нехватку маржи или закрытую торговую сессию, вместо того чтобы получить отклонение запроса сервером. Класс вносит исправления только в безопасных случаях, считывает код возврата OrderCheck() и ведет подсчет отказов по причинам. Модульные тесты и советник для стресс-тестирования со случайной задержкой показывают, что уровни, установленные очень близко к цене, все равно могут приводить к отклонению запросов, а необязательный буфер задержки предотвращает такие отклонения ценой блокировки некоторых корректных запросов.
Советник, прошедший валидацию в CodeBase, все равно может дать сбой при задержке исполнения и действующем уровне заморозки. На примере тикового скальпера в статье воспроизводятся четыре таких сбоя в тестере стратегий и для каждого показывается исправление с указанием его ограничений. Абляционный эксперимент при фиксированной задержке позволяет оценить эффект каждого изменения по отдельности. Расчет расстояния до стоп-уровней на основе ценового импульса устраняет большинство отказов в модификации, тогда как случай на выходных, из-за которого был введен буфер перед закрытием сессии, в этих прогонах не повторился.
Большинство советников торгуют по нескольким сетапам, однако тестер стратегий оценивает их все по одной кривой средств. CSetupLedger — небольшой класс на MQL5, который кодирует сетап каждой торговой операции в ее магическом номере и восстанавливает учет по сетапам из истории сделок счета, так что при перезапуске данные не теряются. Класс сравнивает интервал Уилсона для доли прибыльных операций каждого сетапа с безубыточной долей прибыльных операций, рассчитанной по средней прибыли и среднему убытку этого же сетапа, и не выносит вердикт, пока не завершатся 30 торговых операций. Каждый сетап в итоге получает статус "подтвержденный" (trusted), "отклоненный" или остается со статусом "неопределенный". В двух исторических тестах итоговые показатели по сетапам точно совпадают с результатами тестера. В приложении приведен полный исходный код и два рабочих советника.
Account Guard watches your account and does one job. When a limit is reached it closes every position and every pending order. It keeps closing any new trade until the lock ends. It opens no trades of its own. It works for manual trading and for any EA on the same account. I built it from a set of tested modules. Each module came out of my own MQL5 articles about trading days, drawdown peaks, open risk, and order checks. What it checks - Daily loss limit (percent or money, the stricter one
Account Guard Daily Limit is the free version of Account Guard. It watches the whole account and enforces two rules: a daily loss limit and a maximum drawdown. It opens no trades of its own. It works for manual trades and for any EA on the account. The panel shows the state, the day result against the limit, and how much room is left above the drawdown floor. The two rules Daily loss limit in percent of the initial balance. When it is hit, every position and pending order is