Trading automation: EAs, MQL scripts, cBots and VPS
Automation moves repetitive tasks into a program, but responsibility for its behaviour stays with you. An Expert Advisor or cBot needs a defined runtime: a terminal, a VPS or a cloud service. We explain how those environments differ, how to diagnose errors and how to protect an account after a disconnection or restart. The article also covers hosting costs, execution latency and the checks needed before a program runs on an account trading on margin.

The connection fails after the request leaves
Imagine a robot reconnecting after a brief outage. Its last log line says “buy request sent”. There is no response in the local file. Buying again may feel like finishing an interrupted task, but the first request may already have changed the account. The missing response describes what the program knows; it does not establish what the broker did.
Our hypothetical account uses netting and has only this robot trading this symbol. One lot represents 100,000 EUR. The verified starting position is long 0.10 lot, the intended final position is long 0.30 lot, and the robot sends a buy request for 0.20 lot. A separate hard limit permits at most 0.35 lot of long exposure. These are demonstration settings, not recommended account limits. Prices, financing and profit are outside this volume-only example.
The first useful record is the intent: move from the confirmed starting position to the specified target. “Send another buy” is an action, not the target itself.
A missing reply creates an unresolved state
The program now has an unresolved request. It should retain that state across a restart and block another exposure-increasing action until reconciliation. A timeout is not evidence that the request failed. Equally, a local success flag alone is not a completed-fill record. The official MQL5 OrderSend documentation explicitly separates acceptance for processing from execution and explains that one request can generate several trade events.
| Record | What is established | Next step |
|---|---|---|
| Before sending | Verified long 0.10 lot; target 0.30 lot | Record the intended change |
| Request sent | Buy 0.20 lot submitted; reply unavailable | Keep the operation unresolved |
| After reconciliation | Matching history confirms a 0.20-lot fill; fresh position is long 0.30 lot | No additional buy is needed |
The last row assumes the request, account, symbol and execution records have been matched, no other actor has traded, and no relevant request remains pending. A cached position or a coincidentally similar volume does not satisfy those assumptions. On a shared account, the same arithmetic cannot establish ownership.
Calculate the consequence of a blind retry
After the verified fill, the target has already been reached: 0.10 + 0.20 = 0.30 lot. Resubmitting the same 0.20-lot buy and assuming it fills would produce 0.50 lot. That is 0.20 lot above the intended target and 0.15 lot above the separate 0.35-lot limit. In currency units, the target is 30,000 EUR, the duplicate result is 50,000 EUR, and the limit is 35,000 EUR.
The repeated instruction looks identical in a log, but its effect is additional exposure. A locally assigned intent identifier helps tie records together; writing that identifier into a comment does not by itself make a broker API reject duplicates. Any actual idempotency mechanism must be supported and verified for the particular API.
If reconciliation instead finds a partial fill, compute the remaining change from authoritative state, including outstanding orders and unresolved requests. Do not infer that remainder from the old request volume alone. If the evidence remains incomplete, leave the gate closed and record why.
Test recovery before paying for uninterrupted hosting
A VPS can keep a process running while a personal computer is off. It cannot turn an ambiguous response into a confirmed outcome. Before relying on hosting, rehearse a lost reply, restart during processing, partial execution and an account changed outside the robot. Begin in an isolated simulation or demo environment. Save both the expected state transition and the observation that would permit the next action.
A useful recovery record contains the broker server and account, symbol and account mode, intent identifier, confirmed initial state, request details, returned status, matched order and deal identifiers, and the reconciliation time. Keep credentials out of that record. Also distinguish stopping new requests from cancelling pending orders or closing a position: these are separate operations with separately confirmed results.
This case establishes a volume-control failure that can be checked on paper. It does not estimate how often disconnects happen, demonstrate profitable automation, or certify a production implementation. The detailed lesson below explains runtimes, platform differences, logs and hosting; read those choices against the recovery behaviour your own system must demonstrate.
Three exercises with worked answers
The exercise data are hypothetical. Choose an answer, then check the calculation.
From recovery behaviour to platform design
Keep the intent, the request and the confirmed account state separate as you compare runtimes, execution events and hosting.
1. Where a robot really runs — the EA, the terminal, the broker server
The recurring misunderstanding in retail automation goes: "my robot trades at the broker". It does not. An Expert Advisor on MetaTrader is a compiled program that executes inside the terminal process. The terminal receives the quote stream from the broker server, runs the robot's code on successive events and sends out finished trade requests. The broker validates those requests and either executes or rejects them. Everything the robot "knows" and "remembers" lives on the runtime side.
The chain worth keeping in mind during any failure analysis looks like this:
EA code → terminal (runtime environment) → broker server → order validation → execution or rejection → server response → log and EA state
Every link can fail on its own and each fails differently. A logic error stops at the first link. Closing the terminal stops local logic and new requests; the broker continues to handle orders already stored on its server. A rejected order is a problem in the fourth link, even though it shows up as "the EA did not open a position". The real infrastructure on the broker's and the hosting provider's side is far more complex — this chain is a working model, not a network diagram.
The events the code reacts to. On MT4 and MT5 a trading program is event-driven. OnInit() runs at start — this is where input parameters should be validated and state prepared. OnTick() fires on the next quote of the instrument the robot is attached to. OnDeinit() runs when the program is removed from the chart, when parameters change or when the terminal closes. OnTimer() for cyclical actions and OnChartEvent() for chart interaction exist in both languages — the MQL4 documentation lists both functions with full signatures, alongside OnInit(), OnTick() and OnDeinit() [10]. The difference between the environments lies in the trading layer: MT5 adds events that MQL4 does not have at all — OnTrade() and OnTradeTransaction() for reacting to changes in account state [14]. Separately, already outside the trading layer, MT5 also has OnBookEvent() — a market-data event that the documentation describes as handling changes in market depth, that is, the order book [14]. It works only where market depth is made available at all: order-book availability depends on the instrument and on the broker, and on retail forex accounts it is often simply absent. This is not a programming course — it is the minimum needed to understand when your code even gets a chance to act.
The practical consequence is inconvenient: OnTick() is not a clock. The number of calls depends on the incoming quotes and event-queue processing. In MQL5, a new NewTick event is not added while one is already queued or being processed[25]. Two brokers on the same pair can deliver noticeably different tick counts, because they filter the stream differently and use different liquidity sources. Logic that assumes a "more or less constant" call frequency is in reality broker-dependent and account-type-dependent logic — and it transfers between brokers worse than identical code suggests.
What is left when the terminal goes dark
This is the distinction that saves accounts, and at the same time the one in which the untrue shortcut "on MT4 everything is on the client side" keeps coming back.
Stop Loss and Take Profit levels attached to a position or to a pending order are stored on the broker server and work regardless of whether your terminal is running. The trailing stop built into the MetaTrader terminal interface works the opposite way: it is calculated locally, on incoming quotes, and stops moving the stop the moment the platform closes. This applies to both MT4 and MT5, but each platform is confirmed by a separate source: the MetaTrader 4 help describes the trailing stop as a mechanism that works in the client terminal rather than on the server, and that stops working once the terminal is switched off [8], while the MetaTrader 5 help repeats the same rule: the trailing stop is executed in the platform, not on the server side, as happens with Stop Loss [11]. Two clarifications are necessary here, because without them the sentence becomes untrue. First, closing the terminal stops the level from moving, but does not cancel the last modification the terminal managed to send — that one stays on the server and continues to protect the position. Second, this description must not be stretched to all platforms. In cTrader the mechanism is built differently: the vendor's help describes trailing stop loss as a server-side protection that remains active after the user's session ends [22]. The condition is therefore maintained outside the user application and does not require it to be running. The same function name, two different operating models — and precisely for that reason habits from one platform must not be carried over to another; the boundary between a server-side order and a local function is laid out more broadly in article 11.4 [as of 2026-08-22; confirm the scope of functions offered by your particular broker in its own documentation].
The third case is dangerous and recurs in amateur code: a "virtual" stop loss held only in a variable inside the EA. Such a stop does not exist for the broker. If the terminal process dies, the position is left with no protection beyond the account-level mechanisms. Before you decide you have a stop loss, check in the positions window whether the level is visible on the server side — not just on the chart and in the robot's log. Permissible levels and minimum distances for SL and TP follow from the instrument specification at a particular broker, so the same code can be accepted on one account and rejected on another.
Full and partial automation
A robot does not have to make the entry decision to be useful. Partial automation — moving the stop to break-even, managing position size, closing part of the volume at a defined level — covers exactly the fragment of the process that is performed inconsistently by hand. The code is shorter, the error surface smaller and diagnosis simpler. Full automation from signal to execution is a project of an entirely different order of responsibility.
The precondition, however, is common to both variants: the rules must be expressible unambiguously. If entry, exit and risk require judging the "quality" of a setup, you do not have a system to automate — you have an opinion about the market. An automated system will execute a defective specification just as consistently as a good one, only faster and without breaks. Whether the rules have a positive expected value at all belongs to the material on edge and expected value; here we deal solely with how to run such a specification safely.
- Knight Capital, 1 August 2012. A trading-software deployment error led to an avalanche of erroneous orders within a few dozen minutes and to a loss of the order of hundreds of millions of dollars; the case is documented in the SEC proceedings of 2013 [9]. The scale is incomparable to a retail EA, but the class of risk is identical: it was not the strategy that failed, but the deployment procedure and the absence of a stopping mechanism.
- SNB, 15 January 2015. After the Swiss National Bank abandoned its cap on EUR/CHF, the rate moved in a jump. How long the extreme conditions lasted is not established by the document cited here — and we do not settle that either. What it does establish is the consequence for accounts: in the analysis preceding the EU product intervention measures, ESMA recorded that after the franc event the balances of some investors were negative by tens of thousands of euros — many times more than the funds deposited with the CFD provider [13]. From a tooling perspective one thing matters: an automated system that at such a moment adds to a losing position or resends rejected orders is working against the account. Negative balance protection for retail clients in the EU came into force only later and is a topic for the regulation section, not for this article.
- Flash-type events — and why we do not describe one of them minute by minute here. The violent move in the yen on 3 January 2019 is described in secondary material in several mutually inconsistent ways, and we were unable to point to a dated document that would confirm the sequence at that resolution. What remains is what is institutionally documented and happens to matter most for automation. The Markets Committee report at the Bank for International Settlements, devoted to execution algorithms in the foreign exchange market (October 2020), states that analysis of recent flash events in FX usually points to a combination of factors such as "a concentration of stop-loss orders or the presence of less experienced staff outside a currency's core time zone" [20]. The second part of that quotation refers to less experienced staffing on the market side, not to an instrument working outside its own zone, and we do not stretch it further. For an automated system, what the report links to such events directly is enough: a concentration of protective orders at one level, plus a time outside the given currency's core time zone. In such conditions a spread filter calibrated on a normal session stops meaning what it meant at calibration, and retry logic for rejected requests begins to work against the account. If you want to judge what a particular session would have done to your automated system, take your own broker's tick data from that day and run your strategy through it — somebody else's description of the event tells you nothing about your account.
2. Indicator, script, EA and cBot — four different classes of tool
The question "I am looking for a script that will trade for me" comes up regularly and usually means something other than it sounds. A script on MetaTrader does have access to trading functions and can send many operations in a single run, so "a script that trades" is not in itself a contradiction. The contradiction lies elsewhere: a script has a single entry point, OnStart(), and finishes together with that function, so it has nothing with which to watch the market for a week. The three types of MetaTrader program differ in life cycle and scope of access; in cTrader the split looks different.
| Feature | Expert Advisor | Script | Custom indicator |
|---|---|---|---|
| Life cycle | Continuous — runs until removed from the chart | One-off — executes and finishes | Continuous — recalculates with chart data |
| Can it send orders? | Yes | Yes — including many operations in a single run | No access to trading functions |
| Main event | OnTick() | OnStart() | OnCalculate() |
| Drawing on the chart | Possible, but not its role | Not typical | Its core task |
| Typical use | Automated trading, position management | A bulk operation: closing positions, setting levels | An oscillator, zones, a multi-timeframe panel |
| How many on one chart | One | One at a time | Many at once |
Separating access is an advantage, but the guarantee that follows from it is narrower than it is usually stated. An indicator has no access to trading functions, so it will not send an order itself — and that is exactly all that follows. It does not mean an error in an indicator is harmless: if an EA reads its buffer and decides on that basis, a badly computed value turns into a bad trade sent by the EA. Clean architecture nevertheless looks the same: the indicator calculates and exposes the result in a buffer, the EA reads that buffer and makes the trading decision. Analysis is then separated from execution and each layer can be tested on its own — provided you also test the contents of the buffer, and not just the EA's logic.
In cTrader the split is different and cannot be mapped one to one. The equivalent of an EA is a cBot, the equivalent of an indicator is an indicator. There is no separate "script" category there; a one-off operation is carried out by a cBot that does its job in the start method and stops itself.
Three mistakes that cost time:
- Expecting an indicator to trade. An indicator on MetaTrader has no access to trading functions. A product advertised as "an indicator that trades by itself" either is not one, or has a separate program running in the background — and it is that program's code that is responsible for your orders
- An EA where a script would do. Closing all positions in a single run is a job for a script. An EA attached to a chart will go on living, reacting to further quotes and needing supervision
- One monolith instead of modules. A program that simultaneously runs five strategies, watches account-level risk, draws and sends notifications is harder to diagnose. A separate automated system per strategy and a separate risk supervisor is an arrangement you can switch off in parts
Before you write a robot, write an informational script. Not because it is a beginner's exercise, but because a program that deliberately contains not a single trading call lets you check whether you are reading the environment data correctly: the symbol, the quotes, the cost, the available funds. If those readings are wrong, the robot will build every decision on them.
What follows is not a program to compile. It is a structural outline: the order of checks and MQL4 function names to use in your own implementation. Do not paste and run it as a ready-made file. It has not been validated by compilation or by testing on a broker account. Compilation checks syntax, but does not by itself confirm the readings, permissions or behavior in the chosen environment. Keep the sequence, write a complete implementation and check its results on a demo account; a record of that test is what lets you assess how the program behaves.
STRUCTURAL SKETCH - environment diagnostics before writing a robot
Directional notation for MQL4. This is not complete, compilable code.
entry point: OnStart() - one-off, ends together with the function
1. symbol := Symbol()
Never hard-code the name - the broker suffix changes it.
2. bid, ask := MarketInfo(symbol, MODE_BID / MODE_ASK)
point := MarketInfo(symbol, MODE_POINT)
spread := if point > 0 then (ask - bid) / point
otherwise: reading unresolved
A zero point means a failed specification reading, not a zero
spread - these two cases must end in a different log entry.
3. lotMin := MarketInfo(symbol, MODE_MINLOT)
lotStep := MarketInfo(symbol, MODE_LOTSTEP)
Instrument properties at a given broker, not language constants.
4. to the journal: symbol, bid, spread, lotMin, lotStep,
OrdersTotal(), AccountFreeMargin()
5. tradePossible := IsTradeAllowed()
Label in the log: trading possible at this moment.
Not: automated trading permitted - see the paragraph below.
what this sketch does not contain and must not contain:
no call to OrderSend, OrderClose or OrderModify.
Three things from this sketch come back in every robot written later: the symbol name read from the environment instead of hard-coded, the volume step read from the instrument specification, and an explicit check of whether trading is possible at this moment. The last point requires correcting a popular shortcut. IsTradeAllowed() does not answer only the question of consent to automation — the MQL4 documentation describes it as a check of whether the "Expert Advisor is allowed to trade and trading context is not busy" [15]. A false result can therefore mean a lack of permission or a busy trading context, that is, a transient state that will pass by itself. So record the function result and the cause established by an additional check separately, because otherwise the diagnosis "trading disabled" lands on something that is not disabled at all. The section on production failures refers back to all three of these readings.
3. MQL4 and MQL5 — two environments, not two versions of one
The popular shortcut "MQL5 is MQL4 with more functions" is false precisely where it matters in practice: in the order and position model. It is also worth removing a second myth straight away. MQL4 is not a purely procedural language — the MetaQuotes documentation describes classes, inheritance, virtual functions and templates for it [1]. The difference therefore does not lie in the programming paradigm, but in the trading interface, in the way indicators are read and in how the platform represents open exposure.
The trading layer. In MQL4 a single function, OrderSend(), opens a position, while OrderSelect() switches the context to the next element in a list where pending orders and open positions sit side by side. In MQL5 the concepts are separated: order, position and historical deal are distinct. Sending a request means filling in a structure and checking the returned structure containing the server response code; standard library classes such as CTrade are a convenient wrapper over that mechanism, not a separate mode of operation [2].
The data layer. In MQL4 an indicator call returns the value for the specified candle. In MQL5 the same call returns a handle, created once — usually in OnInit() — and the values are fetched into an array by a buffer-copying function. Code rewritten literally creates a new handle on every quote instead of using the existing one — the compiler will not report it, because the error is in where the handle is created, not in the syntax. It is a classic migration trap precisely because it does not show up immediately.
| Criterion | MQL4 (MetaTrader 4) | MQL5 (MetaTrader 5) |
|---|---|---|
| Object-oriented programming | Supported | Supported |
| Trading model | A shared list of orders and positions | Separate orders, positions and deals |
| Sending a request | A single call with parameters | A request structure and a response structure with a return code |
| Reading an indicator | Value returned directly | A handle created once, values copied from the buffer |
| Exposure accounting | Separate positions on the same symbol | Netting or hedging — the broker sets the mode for the account |
| Standard timeframes | 9 | 21 |
| Strategy tester | One symbol | Multi-currency tests, forward tests, different tick generation models, latency emulation |
| Product status [as of 2026-08-22] | Licences can no longer be bought: the MetaQuotes page for brokers states that "The MetaTrader 4 trading platform licenses are no longer available for purchase" [19]. The halt in sales was reported by the trade press on 12 January 2018 [12]. Technical maintenance nevertheless continues: the vendor's release register records build 1460 of 5 March 2026 ("The update includes several important security improvements, bug fixes, and platform stability enhancements") and build 1470 of 12 March 2026 ("This build includes improved interface translations, bug fixes, and enhanced platform stability") [21] ; build 1490 of 2 October 2026 adds further fixes and improved SL/TP management on FIFO accounts[21]. This is maintenance of the existing platform rather than a return to its conceptual development. For how long and to what extent the vendor will support existing installations does not follow from any dated statement we were able to reach, so do not assume any deadline here in advance | Actively developed. The vendor announces that "further conceptual updates will only be released for this multi-asset platform" [19] |
The row about the accounting mode deserves a sentence of its own, because it is a source of surprising failures. Netting means one net position per instrument: sending an opposite order does not open a second position, it reduces or reverses the existing one. A robot moved over from MT4 that assumes many independent positions on the same symbol will, in that mode, start closing its own entries. The account mode is set by the broker, so this is not "MT5 default behaviour" — it is a property of a particular account that has to be checked before deployment, and preferably read in code.
When migration makes sense. When the old environment genuinely limits your work: you need a multi-currency test, a forward test in the tester, a more accurate tick model or instruments the broker does not offer on MT4. The platform simply being "newer" is not a reason: you rewrite the trading layer and the way indicators are read, so you get a new set of bugs in code that used to work. How long it takes depends on the size of the automated system — there is no number that could be given here honestly. If you do migrate, compare results trade by trade, not the aggregate result. A matching total with a different list of trades means two different pieces of logic happened to produce a similar outcome.
MT5 also offers paid, distributed optimisation in the MetaQuotes computing network. More power, however, means more parameter combinations tested, and that directly increases the risk of fitting to the past. Test methodology — data splits, costs, the number of variants — belongs to the article on demo, backtesting and forward testing and is covered there in full.
4. cTrader Algo — C#, Python, local and cloud execution
This is the section in which it is easiest to repeat an outdated product description, because older material describes cTrader's automation environment under the names cAlgo and cTrader Automate and presents it as C#-only and local-only. Both of those claims are untrue today.
According to the official Spotware documentation the environment is called cTrader Algo and supports building algorithms in two languages: C# and Python [3]. cBots can be run locally or in the cloud; the documentation of the cloud features states outright that a cBot runs in an isolated environment provided by cTrader, and that the user application — in its Windows, Mac, mobile or browser version — does not have to stay open or connected to the internet [4]. That changes the entire hosting calculation discussed later in this article.
Cloud execution limits, as of 2026-08-22. The documentation states that on a live account you can run up to ten simultaneous instances working continuously, and on a demo account one instance, which stops automatically after seven days at the latest. The documentation also notes that the rules may differ depending on the broker, and that cBots using external packages work in the cloud once additional conditions are met [4]. Treat these numbers as the state of the product on the day of publication and check them again before you base an architecture on them.
The structure of a cBot. The program inherits from a robot base class. The method run at start corresponds to the initialisation familiar from MQL, handling of the next quote corresponds to OnTick(), and the stop method to deinitialisation. A difference that is useful in practice is native handling of the bar-close event: in MetaTrader that condition has to be detected yourself, by comparing the open time of the current candle with a remembered one.
Open API is not REST. This is worth writing down precisely, because the shortcut "cTrader has a REST API" circulates in secondary material. The Spotware documentation describes data exchange in Open API through JSON objects or Google Protocol Buffers [5]. FIX API is a separate service. The scope of permissions, availability and connection terms depend on the broker, so plan an integration after reading the documentation of a specific provider, not the general platform description.
| Environment selection criterion | MetaTrader (MQL4 / MQL5) | cTrader Algo |
|---|---|---|
| Language | MQL4 or MQL5 | C# or Python |
| Editor and tooling | MetaEditor built into the platform | Editor in the app, work in an external IDE possible |
| External packages | No package manager; integrations through system libraries | Available, and in cloud execution once the service conditions are met |
| Running without your own computer | Platform hosting or a VPS with the terminal running | Cloud execution of a cBot or a VPS |
| Programming interface outside the platform | Python integration with the terminal, custom solutions | Open API (JSON or Protobuf), FIX API separately |
| Stock of ready-made code | Very large, of highly varied quality | Noticeably smaller |
| Availability | Depends on the broker's offering | Depends on the broker's offering |
Choosing an environment is not choosing "the better platform". If your broker offers only one of them, the decision has already been made. If it offers both, the criterion is practical: what you are able to write and maintain code in whose behaviour you understand, and how you want to solve continuity of operation. The language itself does not create an edge. It changes the maintenance cost and the number of mistakes you will make along the way.
A webhook as a bridge to other systems
The second automation path does not run through code executed inside the platform: an event in an external system — for example an alert from a charting platform — sends an HTTP request to an agreed address, and an intermediate application only then turns it into a call to the broker's API. The chain then takes the form event → webhook → intermediate application → broker API → validation → order → server response, and the webhook is responsible in it for exactly one link: sending the request. Delivery is not execution — a correctly received webhook says nothing about whether the volume fitted the instrument specification, whether the account had free margin and whether the broker server accepted the order. Every intermediate point adds its own latency and its own failure mode — including a repeat of the same request after the connection is re-established — and the webhook address should be protected, but knowing the address must not substitute for authorisation: the intermediary must validate the sender, request freshness and its unique identifier. Configuring alerts on the charting platform side belongs to a separate article; what matters here is only where in the execution chain this bridge stands and what it does not guarantee.
5. Permissions, compilation, logs and identifying your own positions
"The robot is not trading" is a typical report in retail automation and need have nothing to do with strategy logic. Before you start debugging entry conditions, check four things: whether the program is compiled, whether it is attached to the right chart, whether automated trading is permitted at every level, and what exactly the journal recorded.
Compilation and where the files live
Source code in MetaEditor has a text extension, but what goes onto the chart is a compiled file. The files must sit in the platform data folder, in the subfolder matching the program type — otherwise the platform will not see them. The data folder is opened from the platform menu; do not assume it is the installation folder, because usually it is not. After copying the files, refresh the program list in the navigator window. Read the compiler warnings — in trading code a warning about an implicit type conversion can mean a volume truncated to zero.
Three levels of consent to automated trading
Consent to automated trading is not a single switch. The first level is a whole-platform setting — the algorithmic trading button on the toolbar. The second level is the properties of the particular program, set when adding it to a chart. The third level is beyond you: the account. A broker can block automated trading for a given account type, or restrict trading altogether, for example on a read-only account. A robot that does not check these conditions will report only a failed order, without indicating the cause.
Below is another structural outline rather than a file to compile, this time for MQL5. It shows the sequence of permission checks and volume normalization, but is not a validated implementation. Compilation alone does not establish behavior on a particular account: separately check terminal responses, symbol properties and permissions while connected to the broker. This article does not present such a test. Use the outline as a basis for your own checks, rather than a ready-made trading module. It contains no call that sends an order.
STRUCTURAL SKETCH - permission checks and volume normalisation
Directional notation for MQL5. This is not complete, compilable code.
A. IS TRADING ALLOWED - four readings, each with its own log entry
TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)
false -> algorithmic trading disabled in the platform
MQLInfoInteger(MQL_TRADE_ALLOWED)
false -> trading disabled in the program properties
AccountInfoInteger(ACCOUNT_TRADE_ALLOWED)
false -> trading blocked on the account side
AccountInfoInteger(ACCOUNT_TRADE_EXPERT)
false -> broker does not allow automated trading here
Trading is allowed only when all four readings are true.
The log must show which one failed - otherwise diagnosis
ends at the sentence "the robot is not trading".
B. NORMALISING VOLUME TO THE STEP GRID
input: symbol, vol
output: a multiple of the step, or 0.0 meaning "do not send"
B1. if not MathIsValidNumber(vol) or vol <= 0.0
-> log the error and return 0.0
Ordinary comparisons do not reliably reject NaN. Validate
finite input explicitly before doing arithmetic; otherwise
the result may remain invalid.
B2. read the specification using the status-returning variant:
SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN, vmin)
SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX, vmax)
SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP, vstep)
any reading false or vstep <= 0.0
-> log _LastError and return 0.0
The variant returning only a number stays silent on error
and gives back a zero indistinguishable from a real zero.
B3. TOL := 1e-8 binary division tolerance
steps := MathFloor(vol / vstep + TOL)
result := NormalizeDouble(steps * vstep, 8)
The postcondition this function promises - and only this:
the result is a whole multiple of the step,
the result does not exceed the input by more than
TOL * vstep.
It does not promise the result will never exceed the input.
B4. if result > vmax
-> result := NormalizeDouble(MathFloor(vmax / vstep + TOL) * vstep, 8)
if result < vmin
-> return 0.0
The order matters: minimum and maximum are checked only on
a value already brought onto the step grid.
This second function looks like a detail, yet it is responsible for a whole class of rejections. The volume step, minimum and maximum are properties of the instrument at a particular broker and differ between accounts. A position size calculated from risk almost never lands exactly on the permitted step, and the server will reject a request with an invalid volume rather than round it for you.
Two details of this function deserve a sentence of their own, because both belong to the same class of error as the one the paragraph on compiler warnings warns about: the code works, and the result is quietly different from the one you calculated. The first detail: the volume is produced by counting whole steps and multiplying them back by the step, not by rounding to a predetermined number of decimal places. Rounding to two places would turn a volume of 0.003 into zero on an instrument with a step of 0.001 — found on cent accounts and on some CFD contracts — and deriving the number of places from the logarithm of the step breaks everywhere the step is not a power of ten: with a step of 0.25 a volume of 1.75 gets rounded to 1.8, that is, to a value that is not a multiple of the step, so the server will reject it exactly as it would reject a volume never brought onto the step at all. The second detail: division in floating-point arithmetic can fall minimally below a whole number, so without a small correcting value the downward rounding quietly takes away one step — 0.3 divided by 0.1 comes out below three, and the position enters smaller than the risk calculation implied. Minimum and maximum are therefore checked only at the end, on a value already brought onto the step grid: rounding down can fall below a minimum that was satisfied a moment earlier, and trimming to the maximum must land on the same grid as the rest of the result.
That same correcting value has a second side, however, and it has to be stated explicitly rather than promising more than the function delivers. Since we add something before rounding down, the result may minimally exceed the input: for a volume of 0.2999999995 with a step of 0.1 the function will return 0.3, that is, five ten-billionths of a lot more than it was given. For the step sizes in this example the difference is negligible — but the declaration has to read as it really is: the result is a multiple of the step and does not exceed the input by more than the accepted tolerance. It is a deliberately chosen boundary, because without it the same code loses a whole step at a volume of 0.3. Two things have to be stopped separately, and they are easy to forget: a non-finite input, which ordinary comparisons do not reliably reject, and a failed specification reading. That is why the sketch has MathIsValidNumber() at the input and the SymbolInfoDouble() variant that returns a status instead of the one returning only a number — the latter gives back, on error, a zero indistinguishable from a real zero.
Logs — the basic diagnostic trace after a failure
The platform keeps separate journals and that separation is useful. The tab with the program journal contains what your code printed, plus messages about its initialisation and removal. The platform journal records infrastructure events: logins, disconnections, reconnections, requests sent and server responses. The strategy tester keeps its own journal. Copies are written to files in the data folder, thanks to which they survive a restart — and only thanks to that can the course of a night-time failure be reconstructed.
The minimum a robot should record on its own: the moment of the decision with the price and the spread, the request parameters sent, the server response code, the actual execution price, every modification of levels, and every activation of a protective mechanism. Without a record of the price and the response code you will not tell a logic error from a rejection on the broker's side, and those are two entirely different problems.
One distinction is worth establishing here already, because it returns in the section on failures. The journal is the basic diagnostic trace: it says what the program did and what it saw at a given moment. It is not, however, the source of truth about execution — that is the account state and the trade history on the broker server. The distinction stops being academic exactly when it is needed: with a broken connection the robot's log may end at a send error while the server already has the trade executed. When one contradicts the other, the server decides.
Identifying your own positions
A robot has to be able to answer the question "is this position mine". An account may simultaneously hold trades opened by hand, by another robot and by the same strategy on a different symbol. What serves this purpose is a numeric identifier assigned to the order when it is sent — in both MetaTrader environments called the magic number — plus the comment field. The practical rule is simple: every loop over positions filters simultaneously by identifier and by symbol, and never by symbol alone.
The consequences of skipping that filter are painful. A robot without the filter will close a position opened by hand. Two robots with the same identifier will modify each other's levels. On a netting account the matter is harder, because a net position has no single owner — the robot must then keep its own record of the exposure it assigned to itself, and rebuild it after a restart from trade history rather than from the current state.
6. A catalogue of production failures — from reconnects to symbol specification changes
Some automation failures concern the runtime environment rather than the strategy rules. A standard backtest does not reproduce every such situation; some require separate failure tests. The list below is not a catalogue of exotica — these are things you have to be ready for when keeping a robot running for several months.
| Failure | How it shows up | Safeguard in code or procedure |
|---|---|---|
| Reconnecting after a dropped line | The program's memory stays intact — the problem is the request sent just before the drop, whose status remained unresolved: it is unknown whether it arrived and whether it was executed | After every request with an unconfirmed outcome, read the current positions and trade history, filtered by your own identifier, before the program tries again |
| Duplicate order | Two identical positions opened seconds apart | Checking existing exposure before sending, a time lock and a persistent identifier of a single decision — not the magic number alone |
| Stale quote | A decision made on a price from a dozen seconds ago; the server rejects the request | Checking the time of the last quote before the decision, giving up rather than retrying blindly |
| Wrong symbol or broker suffix | The robot does not see the instrument, or works on a different one than intended | Reading the symbol from the chart environment, validating availability in OnInit() |
| Mismatched volume step | Request rejected because of an invalid volume | Normalising volume to the instrument step, checking minimum and maximum |
| Unhandled server response code | The robot treats a rejected order as executed and counts a position that does not exist | Checking the result of every operation, logging the response code, a limited number of retries |
| Restart or reinitialisation of the program | Only here does state held in memory disappear: the daily loss counter resets, the equity peak is counted from scratch, levels watched in code stop being watched | Persistent state storage and rebuilding it at start from positions and history, not from variables; critical levels on the server side |
| Change of instrument specification | The minimum distance of levels, the volume step or the trading hours change | Reading the specification at initialisation and cyclically, instead of constants written into the code |
| Clock change and server time | The hour filter shifts by an hour after the clock change | Working on broker server time, explicit time-zone conversion, a test on the clock-change boundary |
| Platform or system update | A restart in mid-session: the set of charts together with attached programs comes back with the profile, but the programs are reinitialised, and automated trading need not be enabled after the start [24] | An update window outside trading hours, automatic restoration of the chart set, and a separate check after the restart of whether automated trading is enabled |
| No disk space or process failure | Log writing stops working, the program ends without a trace | Log file rotation, resource and process monitoring with notification |
A scenario to reproduce yourself: a duplicate order after reconnection
We describe this scenario separately, because it cannot be triggered on demand with a single click. The editorial team did not reproduce it — what follows contains no measurement result and no environment record in which such a measurement would have been taken. What there is, is the mechanism and instructions for checking it yourself.
Conditions. The robot establishes an entry condition and sends a request to open a position. While waiting for the response, the connection drops. The order did reach the server and was executed, but the response never came back to the terminal. The robot logs an error and concludes that there is no position.
Expected consequence. If the entry condition is still met once the connection is restored, the robot will send the request again. On a hedging account two positions will then be created instead of one, and the actual risk will be twice what was planned. On a netting account the records look different, but exposure still increases: the net position grows, but the robot still sees it as a single entry. That is a conclusion derived from the mechanism described above, not a reading from a trial that was carried out.
How to check it yourself. Manually switching off the network card "just after sending" is not a procedure, it is a lottery. You have no control over whether the request managed to reach the server, and if it did not, you are reproducing an entirely different case — an ordinary failed order. On a demo account, a firewall rule or diagnostic tool can interrupt connectivity in a controlled way, but confirmation that the request was sent does not prove execution. This scenario has occurred only if server history confirms execution while the terminal did not receive the response. The strategy tester will not reproduce this situation, so the trial is manual — and precisely for that reason it has to be recorded. Note down the full set of items below; without any one of them the result settles nothing and cannot be compared with a second trial:
- the platform, and the terminal version and build number — read from the program information window, not from memory
- the broker, the demo account number, the server the terminal was connected to, and the account type: hedging or netting — because the consequence depends on it
- the symbol with the full broker suffix, the request volume and the execution mode set for that instrument
- the date and time of the trial in broker server time, not in local time
- the way connectivity was interrupted and the moment it took effect relative to the request being sent — this is the only parameter that decides whether you are reproducing this case or an entirely different one
- the result: the full entry from the robot's journal set against the trade history on the server side. It is the history that settles whether the order arrived — the terminal journal alone is not enough, because its very ignorance is the phenomenon under study here
- the number of repetitions of the trial and how many of them gave the same result; a single pass proves nothing
A second thing needs correcting, because it is repeated as a ready-made recipe. The magic number identifies a strategy, not a single order intention: two requests sent by the same robot have an identical one, so on its own it does not suffice to settle the question "has this particular order already gone out". What is needed is a persistent identifier of a single decision, assigned and recorded before the request leaves, and stored outside process memory. Only that lets you distinguish, when reconciling state, between "I did not send it" and "I sent it and I do not know what happened". The comment field is a natural place to carry it into the order, but it is sometimes truncated or overwritten by the server — so treat it as a clue and base the resolution on comparing your own record with the server history.
The safeguard. The rule is simple and inconvenient: the account state is the source of truth, not the robot's memory. After every failed or request with an unconfirmed outcome, before the program tries again, it must read the current positions and the most recent historical trades and check whether its order is not already there — filtering by its own identifier. A time lock between successive sends on the same symbol is a cheap addition, but on its own it is not enough.
The same principle closes a second class of accidents: a robot with no check on existing exposure that, in a fast market, sends requests on every successive call. The effect is an avalanche of orders and, in the extreme case, a restriction of server access on the broker's side. A state check before sending and a limit on the number of operations per unit of time are two conditions without which a robot should not be let out beyond a demo account.
7. Continuity of operation: computer, VPS, platform hosting — and the cost calculation
A classic automated system on MetaTrader needs a running terminal. That is the only reason we are discussing hosting at all — not speed, not "professionalism", simply the fact that a process that is switched off computes nothing. The exception is the cloud path described in the cTrader Algo section: for a cBot that meets the cloud-execution conditions, an external VPS may not be needed at all. The qualification matters here, because the same ecosystem also permits local execution — and then the hosting question comes back in full. The limits on the number of instances depend on the account type and the broker, and cBots using external packages work in the cloud only once additional conditions are met.
What a home computer brings to the equation. Power cuts, a restart after an update, a failure of the internet provider's line, a system freeze. Each of these events cuts out the runtime environment, and therefore all of the robot's logic. What it does not cut out are the SL and TP levels recorded on the broker server — and that is exactly the boundary you have to know in order to judge how much you really lose during an outage.
What a VPS does not do. It does not improve the strategy. It does not remove slippage or rejections. It does not protect against a failure on the broker's side, or against the broker's own line to its liquidity provider going down. It does not guarantee continuity — a declared service availability is a contractual commitment, not a law of physics. You are buying one thing: the removal of your own hardware and your own connection from the list of failure causes.

Two different products under one name
The word "VPS" is used for two solutions that are administered in completely different ways.
A virtual server with a full operating system is rented like an ordinary computer in a data centre. You connect over remote desktop, install the platform yourself, and watch over system updates, autostart, monitoring and configuration backups yourself. You have full freedom — you can run several platforms, your own supervisory scripts, diagnostic tools — and full responsibility for maintenance, including the security of remote access.
Hosting integrated with the platform works differently. In MetaTrader's case, the MetaTrader VPS service is launched from within the platform itself, and the environment is migrated to it with a single command; the service hosts running automated systems and signal-copying subscriptions and does not require administering Windows or connecting over remote desktop [6]. Simplicity has a price: you will not install arbitrary software there and you work within imposed resources.
An infrastructure cost calculation on an explicit example
I take the numbers from the pricing above so that the example is checkable rather than illustrative. With annual billing the cost is 12 × 10 USD = 120 USD a year. With monthly billing, 12 × 15 USD = 180 USD a year.
| Account size | 120 USD a year | 180 USD a year |
|---|---|---|
| 2,000 USD | 6.00% | 9.00% |
| 10,000 USD | 1.20% | 1.80% |
| 25,000 USD | 0.48% | 0.72% |
I limit the conclusion to this example. On an account of the order of 2,000 USD the hosting alone eats several per cent of capital a year before you count spread and commission — and it competes with a realistically expected result. On an account ten times larger, the same service represents one tenth of that percentage of capital. It does not follow that a VPS "is worth it" or "is not worth it" to anyone else; all that follows is that infrastructure cost has to be calculated against your own capital, not against the price on the provider's page.
Choosing parameters and deployment
The requirements of a robot that only trades are modest — the load comes from optimisation in the tester, and that can be done elsewhere. The caveat to the table below matters more than its contents. The figures given are illustrative: they do not come from a measurement taken for this article or from vendor requirements, and serve solely to show which parameters to check. Measure them yourself — run the target configuration on a demo account, read the peak memory and processor usage of the platform process from task manager after a few days of work, and only then choose a machine on that basis.
| Parameter | Starting point | Note |
|---|---|---|
| Memory | 2 GB per platform instance with a few charts | Custom indicators and long history increase usage; measure it yourself |
| Processor | 1–2 cores for trading alone | More cores matter for optimisation, not for running an automated system |
| Disk | Solid-state storage, headroom for logs and history | Logs grow; plan file rotation |
| System | Compatible with the platform requirements | A compatibility layer on Linux requires checking the selected OS, Wine, platform and add-on versions; the vendor publishes installation instructions |
| Location | Close to the data centre of your broker's server | Ask the broker where your account's server sits before choosing a location |
| Availability | As declared in the contract | The difference between 99.5% and 99.9% is about 44 and about 9 hours of downtime in a 365-day year |
The provider market divides into three categories, and they differ not in price but in who bears the maintenance cost. Hosting from a broker is sometimes offered on preferential terms at a given level of activity — convenient, but it ties you to a single broker. Providers specialising in trading hosting place their servers in data centres used by FX brokers. General public clouds leave the entire configuration on your side. I deliberately give no company names here: availability, locations and terms change faster than an article, and a list of providers in an educational text turns into a recommendation far too easily.
Hosting deployment checklist:
- Run the whole configuration on a demo account and keep it there not for a fixed number of days, but until you have been through three events: a forced restart of the machine, a loss and restoration of connectivity, and a weekend market close and reopen. Only then swap the account
- Set the system update window outside trading hours and check what happens after a forced restart
- Configure automatic startup of the platform and restoration of the chart set together with the attached programs
- Check separately whether automated trading is enabled again after a restart — the platform starting up does not guarantee it
- Run independent monitoring of machine availability and, separately, monitoring of the platform process; ping alone will not detect a frozen application
- Disable screen blanking and sleep, set up log rotation and watch free disk space
- Secure remote access with a strong, unique password and multi-factor authentication if the provider offers it; restrict access by address if possible
- Back up chart templates and parameter sets. Do not keep account login details in configuration files or notes — that is what a password manager is for
- Plan a procedure for losing the machine: where you will restore the configuration from, and in what time
The last point is often skipped. Hosting is not a safeguard until you know how long it will take you to rebuild the environment after losing it — and until you have tested that once in calm conditions.
8. Latency — what exactly you are measuring and what the measurement does not tell you
"Ping 2 ms" does not mean "order executed in 2 ms". That sentence is worth reading twice, because selling trading infrastructure rests on blurring the difference. Latency in the execution chain consists of several segments and they are measured separately, with different tools and to different accuracies.
| Segment | What it covers | How it is measured |
|---|---|---|
| Network ping | Round-trip time of a packet to the host and back | A system tool; it says something about the network, not the application |
| Terminal – broker server | Round-trip time at the level of the platform protocol | The connection indicator in the platform; it already includes the application layer |
| Sending and accepting a request | From the moment the function is called to the server response | Timestamps in the robot's own log |
| Observed end-to-end | From the call of the order-sending function on your side to the trade visible in the account history — it covers transmission both ways and processing on the broker's side | A local high-resolution counter for the round trip; the trade timestamp from the server history noted separately. The execution time inside the broker's infrastructure cannot be isolated from this without their telemetry |
| Market data latency | The age of the quote on which the decision was made | The time of the last quote read in code at the moment of the decision |
Hosting providers' claims almost always concern the first or the second segment. When MetaQuotes states that from the MetaTrader VPS infrastructure access to 96% of broker servers falls below 10 ms [6], it is describing the network segment. Nothing follows from that for the time in which the broker will actually conclude your trade — because that depends on their execution policy, the available liquidity and the server load at that moment.
The only measurement that concerns your account comes from your own data. Record three timestamps and two prices in the log: the moment of the decision with the price the robot saw, the moment the request was sent, and the moment and price of execution read from the server response. After a sufficiently long series of trades you have a distribution, not a single number from a provider's page. Look at the distribution, not the average: individual slow executions during data releases or in thin liquidity weigh more than a calm median.
One caveat decides whether this measurement means anything at all. The first two timestamps come from your machine's clock, and the trade time in the account history from the broker server's clock. Subtracting one from the other mixes two clocks and adds an unknown offset to the result, invisible in the number. So measure the round trip locally, with a single high-resolution counter: from the call of the order-sending function to the response returning. Note the trade timestamp from the server history alongside, as a separate quantity, not as the other end of the same segment. How much time the request spent inside the broker's infrastructure remains unresolved without their telemetry — you can measure the whole and compare it between periods, but not break it down into stages.
For assessing the sensitivity of the logic itself there is the MetaTrader 5 strategy tester, which allows emulating execution latency and using different tick generation models, including real ticks supplied by the broker [7]. That is not a measurement of your connection — it is a check of whether the strategy survives worse execution conditions at all. The full methodology of such tests belongs to the article on strategy testing.
When it matters at all
The answer follows from arithmetic, not from convictions. For a given cost, its share grows as the average trade becomes smaller. The values below are illustrative — I assume a total cost per trade of 2.0 pips, made up of spread, commission converted into pips and typical slippage. You will read the actual cost from your own account specification and your own trades. Latency is not in that sum and cannot be: it is not a cost expressed in pips, but a parameter of the execution model. The table below therefore does not measure it and settles nothing about it either way.
| Trade target | Share of cost | What follows from it |
|---|---|---|
| 5 pips | 40% | The result is dominated by the cost of a single trade — the cost alone takes two fifths of the target |
| 10 pips | 20% | Execution still matters, and requires measurement on your own data |
| 20 pips | 10% | The influence is noticeable, but not decisive |
| 50 pips | 4% | The cost of a single trade stops being a deciding factor |
For an automated system targeting several dozen pips, this example suggests checking whether latency materially affects its results before spending money to reduce it. If it aims at a few pips, latency and slippage are a strategy problem, not a hosting problem — and no server will fix that.
Parameters that protect against poor execution conditions
Two mechanisms belong squarely in the robot's code. The first is a spread filter: before every decision, compare the current spread with a threshold and hold off opening positions once it is exceeded. Describe the threshold as a multiple of the instrument's typical spread during your trading hours, not as a hard-coded constant — the same threshold will make no sense on another symbol and at another broker.
The second is often described as a universal cap on execution price — and that is exactly what it is not. The maximum permitted price deviation when sending an order belongs to one execution mode only. The MetaTrader 4 help closes this in a single sentence: "Price deviation at placing of orders is used only in the instant execution mode" [18]. The same page also describes what the field actually does — and the description is the inverse of the colloquial "it is protection against slippage": "if the deviation is below or equal to the specified parameter, the order will be executed at the new price without any additional notifying. Otherwise, the broker returns new prices at which the order can be executed" [18]. A price change that falls within the limit is therefore executed at the new price without any additional notification, and a requote — new prices sent back for confirmation — happens only beyond the limit. In market mode the field does not exist at all: the MetaTrader 5 help describes the parameter for Instant Execution, and says the opposite about Market Execution — "In this order execution mode, a broker makes a decision about the order execution price without any additional discussion with the trader" — and adds outright: "Sending an order in such a mode means advance consent to its execution at this price" [11]. There the price is set by the broker, sending an order is consent granted in advance, and the form has a Fill Policy in that place, not a deviation.
The execution mode is set by the broker separately for each symbol, so the first question is not "what value should I enter" but "does this field apply to my instrument at all" — which you will check in its specification. If it does apply, you are choosing between two costs: a tighter limit means more frequent requotes and requests that do not go through on the first attempt, a looser one means fewer requotes and more executions at a price differing from the one you saw at the moment of the decision. So treat this value as an element of the strategy, not as a technical setting. If it does not apply, all you are left with is a log record of how much the difference between the decision price and the execution price actually was. That record is worth keeping in both cases.
The third mechanism is time-based and the simplest: a window in which the robot does not open new positions. The hours of daily rollover and of the most important data releases are the moments when the spread widens and liquidity thins out. Blocking entries in such a window is a few lines of code — provided you count broker server time rather than the machine's local time, and that you have tested the filter's behaviour on the clock-change boundary.
9. Kill switch, limits and the minimum deployment standard
A robot without a stopping mechanism has unlimited loss potential within the available margin. Not because it is badly written — because there is no condition on which it stops working. A kill switch is not an extra feature. It is the condition for talking about a managed system at all, rather than about a program left to its own devices.
The set of limits every automated system on a live account should have:
- An equity drawdown limit. Once a set drawdown from the peak equity value is exceeded, the robot closes its own positions, confirms by reading from the account that none is left, and only then stops working; if any is left, it is to stay active and raise an alarm. The size of the threshold follows from the risk plan you have adopted — the methodology for setting it belongs to the risk material; what matters here is that the threshold exists in the code and is checked before the strategy logic
- A daily loss limit. A counter reset at a set hour of server time, rebuilt after a restart from trade history rather than kept only in memory
- A limit on the number of open positions. A hard upper bound, independent of the entry logic
- A limit on the size of a single position. An upper bound applied to the result of the position size calculation, so that an error in the arithmetic does not turn into an order with a disproportionate volume
- A spread filter and — if your symbol's execution mode offers it — a maximum price deviation. Both described in the previous section
- An hour filter. Windows in which the robot does not open new positions
- A reaction to connection problems. Once a break or stale quotes are detected, the robot holds off opening new positions, but does not close existing ones blindly — closing on the basis of a stale price is sometimes worse than waiting
The order of checks matters. Safety conditions belong at the beginning of the event handler, before any entry logic. Once they are breached the program should not perform any operation that opens or increases exposure — the only thing it may do is close its own positions and record the event. Returning to work requires a conscious human decision, never an automatic resumption after a delay.
stop condition: current equity < peak equity × (1 − permitted drawdown) → write the log → close your own positions → recount your own exposure → remove the program only at zero positions and zero closing errors → otherwise raise an alarm and stay active
Below is the last structural sketch in this article and the only one that touches a position-closing function at all. That is why it has two gates, and both sit in default values, not in a comment. The first: dry-run mode is on by default — the program sends no operation, it only writes to the journal what it would have closed. The second: before the first quote arrives, the program reads the account type and, on an account other than a demo one, refuses to initialise until the reader sets a separate, explicit confirmation. MQL4 exposes this reading through AccountInfoInteger(ACCOUNT_TRADE_MODE), and the documentation distinguishes within it a demo, a contest and a live account [16]. A warning sentence in a comment is not a safeguard; the safeguard is a default value that has to be consciously changed for anything to happen.
STRUCTURAL SKETCH - kill switch on equity drawdown
Directional notation for MQL4. This is not complete, compilable code.
INPUT SETTINGS - the first two decide safety
DryRun := TRUE default value
The program sends no operation. To the journal it writes
what it would have closed: order number, volume and the
reference price. To close anything, this setting must be
changed by hand.
LiveAccountConsent := FALSE default value
Without it the program refuses to start on an account
other than a demo one. This consent cannot be given
by accident.
MagicNumber - identifier of your own positions
MaxDrawdownPct - permitted drawdown from peak equity
MaxDeviation - works in one execution mode only,
see the paragraph below the sketch
START - OnInit()
mode := AccountInfoInteger(ACCOUNT_TRADE_MODE)
if mode != ACCOUNT_TRADE_MODE_DEMO
and not LiveAccountConsent:
write log: account is not a demo one, consent missing
end initialisation with an error (INIT_FAILED) - that is all
peak := AccountEquity()
stopped := FALSE
lastAlert := 0 timestamp of the last alert
EVERY QUOTE - OnTick()
if stopped:
remaining := CountOwnPositions()
if remaining > 0
and TimeCurrent() - lastAlert >= 3600:
write log: stopped state, remaining
send an alert to a human
lastAlert := TimeCurrent()
end handling of this quote
the program does not retry closing by itself - the next
attempt is a human decision, taken by hand
equity := AccountEquity()
if equity > peak: peak := equity
threshold := peak * (1 - MaxDrawdownPct / 100)
if equity >= threshold:
this branch is empty - the sketch watches the threshold only
and contains no entry logic whatsoever
otherwise:
stopped := TRUE
write log: equity, threshold, peak, timestamp
errors := CloseOwnPositions()
remaining := CountOwnPositions()
if remaining == 0 and errors == 0 and not DryRun:
ExpertRemove() removal only after success
otherwise:
write log: errors, remaining
send an alert to a human
lastAlert := TimeCurrent()
DO NOT remove the program - it stays active, opens
nothing new, repeats the alert and waits for a human
CLOSING - CloseOwnPositions() returns the number of errors
errors := 0
for i from OrdersTotal() - 1 down to 0:
if not OrderSelect(i, SELECT_BY_POS, MODE_TRADES):
errors := errors + 1
write log: position i, GetLastError()
move to the next one do not stay silent here
if OrderType() > OP_SELL: skip
pending orders separately
if OrderMagicNumber() != MagicNumber
or OrderSymbol() != Symbol(): skip
leave other and manual ones
RefreshRates()
price := MarketInfo(OrderSymbol(),
MODE_BID for OP_BUY, MODE_ASK for OP_SELL)
if price <= 0:
errors := errors + 1
write log: no quote, GetLastError()
move to the next one
ticket := OrderTicket()
volume := OrderLots()
if DryRun:
write log: WOULD CLOSE order, volume, price
move to the next one nothing goes to the server
if not OrderClose(ticket, volume, price, MaxDeviation):
errors := errors + 1
write log: order number, GetLastError()
return errors
CONFIRMATION - CountOwnPositions()
Walks the list once more and returns the number of positions
with your own MagicNumber on this symbol, skipping pending
orders the same way as the loop above. This is a reading of
account state, not of the program's memory - and only it
settles whether it is allowed to finish.
What this sketch does not do — and that is as important as what it does. It does not remove pending orders. It does not handle partial closes. It will not survive a restart: the stop flag and the equity peak live in memory, so after the platform is restarted the program will start counting from scratch. Nor does it retry closing — and that is a choice, not a gap. After a failed close the sketch enters the stopped state and stays there: it opens nothing new, recounts its own positions on every subsequent quote, and as long as even one remains open, it repeats the journal entry and the alert no more often than once an hour. The next closing attempt is made by a human — by hand, from the terminal or from the broker's app. Behaviour described this way is complete: automatic retrying simply is not in this sketch and nothing here is waiting to be filled in. One decision, on the other hand, is hard. Removal of the program happens only after its own positions have been counted again, and only when there is not a single one left and no closing attempt reported an error. The order matters more here than it looks: a program that removed itself unconditionally after a failed close leaves open exposure and a log entry, and there is no longer anyone in the system to try to close it. That is why, on any error or remaining position, the sketch stays active and raises an alarm.
One thing looks like good practice along the way and is not. RefreshRates() returns a boolean value, but treating false as an error would be a mistake: the MQL4 documentation states that the function returns true when the data has been refreshed, and immediately explains that "the only reason for data cannot be refreshed is that they are the current data of the client terminal" [17]. False therefore means the data is current anyway. What has to be checked is something else — whether the price read after refreshing is a positive number at all. A zero price is a failed specification reading or a missing quote, and sending a close request at it ends in a rejection.
That leaves the deviation parameter, and here a caveat matters more than the value itself. MaxDeviation is not a universal cap on execution price: it belongs exclusively to Instant Execution mode, and within the set limit it means execution at the new price with no additional notification — only beyond the limit does the server send new prices back for confirmation. The mechanism and the source quotations are laid out in the section on latency, and more broadly in the article on platforms; what matters here is one consequence. Values of the order of three points, that is 0.3 pips on a five-digit account, are copied from examples without a second thought, and they are chosen as for a calm entry, not for an emergency close. An emergency close by definition lands in a moment of wide spread and slippage, so with such a tight threshold the server, instead of executing the request, will send new prices back — and a program that does not handle requotes is left with an open position and an error entry. The deviation for an emergency exit must therefore be distinctly looser than for an entry — and it has to be named for what that loosening is. It is not an increase in protection. It is consent granted in advance to closing at a price worse than the one seen at the moment of the decision, in exchange for a greater chance the request goes through at all. You are choosing between a worse price and open exposure, not between safety and risk. If, on the other hand, your symbol works in Market Execution, the field is not there: the price is set by the broker, sending the request is consent in advance, and all you are left with is a log record of how far the closing price departed from the decision price.
A second asymmetry does not depend on the execution mode and concerns scope. The threshold is calculated from AccountEquity(), that is from the equity of the whole account, while closing covers only the positions of the current symbol. The same automated system run on three charts will, once the threshold is exceeded, close only the instrument on which the quote happened to arrive — the other instances will go on counting their own peak. When working on many charts, supervision of whole-account risk has to be split out into a separate program. Each of these gaps is a separate design decision that has to be taken consciously before the code touches an account with real money.
Three layers of safeguards
No single layer is enough, because each fails in a different scenario.
- The robot's code. The limits described above. They work only when the program is running
- The broker server. SL and TP levels attached to a position, the margin call and automatic closure at the stop-out level. They work independently of your environment — and that is why every position opened by an automated system should have a protective level on that side, not only in a variable in the code
- The human. Phone notifications about opening, closing, stopping and errors, plus a tested ability to close a position by hand from the broker's mobile app. The last layer, for when the first two fail
The dependencies between the layers are concrete. A protective level on the server alone will not stop a run of small losses, each of which fits within the assumed risk while together they bleed the account dry — that is the job of the equity drawdown limit in the code. The limit in the code alone will not help when the machine running the terminal dies — then only the broker layer is working. Notifications without the first two layers only tell you how the loss is progressing.
Safeguards have to be tested too
A protective mechanism that has never been triggered is an assumption, not a safeguard. The test is done on a demo account and has two stages, because the first asks the correctness question more cheaply. Stage one: dry-run mode on, the stop threshold set low enough to be crossed within an hour. The program will then send nothing, but will write to the journal which positions it considered its own and what it intended to do with them. If that list does not match — and it sometimes does not on the first attempt, because the identifier or symbol filter is too broad — you know it without closing anything. Stage two: only once the list matches, switch off dry-run mode and repeat the test. Check three things separately: whether only your own positions were closed, whether the event reached the journal, and whether the program stopped only after confirming that nothing was left open. A separate test is a connection break: switch off the network for a few minutes and check the behaviour after it is restored — whether the robot reconciles state with the account history, or starts from scratch and opens a second position.
The minimum deployment standard looks like this: a compiled program with a set of limits, permissions checked at all three levels, decisions written to a file, work in the target environment on a demo account covering a forced restart, a dropped line and a weekend crossing, then, only if the risk plan permits it, a live account with minimum volume before considering any increase in exposure. How many trades and what results entitle you to move further is a separate topic of strategy validation — here it is solely about operational readiness.
A ready-made automated system from outside
One sentence about products bought on software marketplaces, because it concerns operational safety. The file sold is compiled, so you will not read the logic from it: you will not check whether an equity drawdown limit exists, whether positions have protective levels on the server side, or whether volume grows after a run of losses. Judging the strategy itself requires the tools described in the material on testing; from the perspective of this article a simpler rule applies — an automated system whose behaviour in a failure you cannot predict cannot be safely supervised, no matter what the presented performance curve looks like.
Writing a robot is often the easiest part of the work. Maintaining it is harder: a weekly review of the logs for rejections and unusual execution times, a check of whether the equity drawdown fits the assumptions, and an honest answer to the question of whether market conditions still resemble those in which the automated system was tested. Automation moves execution into code and removes some human errors from execution. It does not move responsibility — that stays on your side, together with the duty to stop the system in time.
FAQ — automation, EAs, MQL and hosting
Where does my Expert Advisor actually execute?
What stops working once the terminal is closed?
Will code from MT4 run on MT5?
Does a cBot on cTrader require the app to be running?
Do I need a VPS?
Does a low ping mean faster order execution?
How do I test a kill switch without risking money?
Sources and references
Vendor documentation describes the state of the products on the date of verification: 2026-08-22. Versions, limits and pricing may change — check the source again before making a decision.
- MetaQuotes Software Corp., "MQL4 Reference — Object-Oriented Programming" — documentation confirming support for classes, inheritance, virtual functions and templates in MQL4. docs.mql4.com/basis/oop
- MetaQuotes Software Corp., "MQL5 Reference" — trading functions, request and response structures, the standard library, handling of indicator handles. mql5.com/en/docs
- Spotware Systems, "cTrader Algo" — official documentation of the automation environment; support for the C# and Python languages. help.ctrader.com/ctrader-algo
- Spotware Systems, "cTrader Algo — Cloud features" — running cBots in the cloud independently of the user application, instance limits for live and demo accounts, dependence of the rules on the broker. help.ctrader.com/ctrader-algo/documentation/cloud-features
- Spotware Systems, "cTrader Open API" — data exchange through JSON objects or Google Protocol Buffers. help.ctrader.com/open-api
- MetaQuotes Software Corp., "MetaTrader VPS" — hosting launched from within the platform, environment migration, declared network parameters and pricing. Vendor data. mql5.com/en/vps
- MetaQuotes Software Corp., "MetaTrader 5 — Strategy Tester" — tick generation models, real ticks supplied by the broker, execution latency emulation, multi-currency and forward tests. metatrader5.com/en/terminal/help/algotrading/testing
- MetaQuotes Software Corp., "MetaTrader 4 Help — Trailing Stop" — the trailing stop executed in the client terminal, as distinct from Stop Loss and Take Profit levels handled on the server side. metatrader4.com/en/trading-platform/help/positions/trailing
- U.S. Securities and Exchange Commission, "SEC Charges Knight Capital With Violations of Market Access Rule", press release 2013-222 of 16 October 2013 and administrative proceeding no. 34-70694 — a description of the event of 1 August 2012 and the missing control mechanisms. sec.gov/newsroom/press-releases/2013-222
- MetaQuotes Software Corp., "MQL4 Reference — Event Handling" — the list of event handling functions in MQL4 together with their signatures, including
OnTimer()andOnChartEvent(). docs.mql4.com/basis/function/events - MetaQuotes Software Corp., "MetaTrader 5 Help — Performing Deals" — the trailing stop executed in the client platform rather than on the server side, as distinct from Stop Loss; the same page describes the Deviation parameter under Instant Execution mode ("Deviation is the difference between the order execution price and the specified price to which a trader agrees") and Market Execution mode ("In this order execution mode, a broker makes a decision about the order execution price without any additional discussion with the trader" and "Sending an order in such a mode means advance consent to its execution at this price") and the Fill Policy. Checked 2026-08-22. metatrader5.com/en/terminal/help/trading/performing_deals
- Finance Magnates, "Metaquotes Will No Longer Sell its MT4 Trading Platform", 12 January 2018 — a trade press report on the halt in sales of MT4 licences to new customers. A secondary source, used solely for the date of the event; the current product status is settled by the vendor's own statement — item [19]. financemagnates.com
- European Securities and Markets Authority, "Product Intervention Analysis — Measures on Contracts for Differences", ESMA50-162-215, 1 June 2018 — documented negative balances on retail client accounts after the Swiss franc event of 15 January 2015. esma.europa.eu
- MetaQuotes Software Corp., "MQL5 Reference — Event Handlers" — the list of event handling functions in MQL5, covering
OnTrade(),OnTradeTransaction()andOnBookEvent(), described as handling changes in market depth. mql5.com/en/docs/event_handlers - MetaQuotes Software Corp., "MQL4 Reference — IsTradeAllowed" — the function description: "Checks if the Expert Advisor is allowed to trade and trading context is not busy". Checked 2026-08-22. docs.mql4.com/check/istradeallowed
- MetaQuotes Software Corp., "MQL4 Reference — AccountInfoInteger" — reading
ACCOUNT_TRADE_MODEwith the distinction betweenACCOUNT_TRADE_MODE_DEMO,ACCOUNT_TRADE_MODE_CONTESTand a live account. Checked 2026-08-22. docs.mql4.com/account/accountinfointeger - MetaQuotes Software Corp., "MQL4 Reference — RefreshRates" — return value: "True if the data updated, otherwise false", plus the caveat: "The only reason for data cannot be refreshed is that they are the current data of the client terminal". Checked 2026-08-22. docs.mql4.com/series/refreshrates
- MetaQuotes Software Corp., "MetaTrader 4 Help — Open Positions" — the scope of the price deviation field: "Price deviation at placing of orders is used only in the instant execution mode"; the same page describes how the field works: "if the deviation is below or equal to the specified parameter, the order will be executed at the new price without any additional notifying. Otherwise, the broker returns new prices at which the order can be executed". Checked 2026-08-22. metatrader4.com/…/positions_open
- MetaQuotes Software Corp., "MetaTrader 4 for Brokers" — the vendor's statement on its own page: "The MetaTrader 4 trading platform licenses are no longer available for purchase. We focus our efforts on the development of MetaTrader 5, and further conceptual updates will only be released for this multi-asset platform". Checked 2026-08-22. metatrader4.com/en/brokers
- Bank for International Settlements, Markets Committee, "FX execution algorithms and market functioning", a working group report chaired by Andréa M Maechler, October 2020, p. 35 (p. 41 in the PDF file numbering) — on the causes of flash-type events in the foreign exchange market: "analysis of recent flash events in FX suggests that usually a range of factors, such as a concentration of stop-loss orders or the presence of less experienced staff outside a currency's core time zone, contribute to such events". A terminological note: in that report the abbreviation EA means an execution algorithm, not an Expert Advisor. bis.org/publ/mktc13.pdf
- MetaQuotes Software Corp., "MetaTrader 4 Release Notes" — the MT4 terminal release register: build 1460 of 5 March 2026 ("The update includes several important security improvements, bug fixes, and platform stability enhancements") and build 1470 of 12 March 2026 ("This build includes improved interface translations, bug fixes, and enhanced platform stability"). Checked 2026-08-22. metatrader4.com/en/releasenotes
- Spotware Systems, "Trade protections in cTrader" — a description of position protections covering the trailing stop loss and break-even: "All protections work across cTrader apps and remain active after your session ends". Checked 2026-08-22. help.ctrader.com/ctrader-web/trading/protections
- Spotware Systems, "cTrader Help — Trade Watch" — on the scope of the function: "Trailing stop loss works even when your cTrader app is closed or disconnected". Checked 2026-08-22. help.ctrader.com/ctrader/interface/trade-watch
- MetaQuotes Software Corp., "MetaTrader 5 Help — Templates and Profiles" — on the contents of a profile: "Chart templates with running Expert Advisors are also saved in profiles" and on its restoration: "When a profile is opened, each chart with all its settings is located exactly in the same position where it was during profile saving". Checked 2026-08-22. metatrader5.com/…/templates_profiles
- MetaQuotes, documentation: OnTick / NewTick, event queue and the condition under which a new NewTick event is not added. Accessed: 2026-10-08.