Algorithmic trading: the complete guide
21 min read · Updated 27 Sept 2026
Algorithmic trading means handing some or all of your trading decisions to a computer program: when to enter, how large a position to take, where to exit. Once the preserve of banks and funds, algo trading is now within reach of retail traders through platforms such as MetaTrader 5 and languages such as Python. This guide explains how a trading algorithm works, which families of strategies exist, how to test them honestly, what risks they carry and which regulatory framework applies. It promises no profit: trading, automated or not, can lead to the loss of all the capital invested.
Key takeaways
- Algorithmic trading hands some or all trading decisions to a computer program: the algorithm reads market data, applies rules defined in advance and sends orders to the broker.
- Automating a trading strategy does not make it profitable: an algorithm is only profitable if its strategy keeps a real statistical edge once costs are deducted.
- A positive backtest is not enough to validate a trading algorithm: it must be complemented by out-of-sample tests, walk-forward analysis, Monte Carlo simulations and a forward test.
- Algorithmic trading removes none of the risks of trading and adds technical ones: with leverage, an algorithm can lose the entire capital deposited.
- Algorithmic trading is legal in Europe for a private individual trading on their own account; Article 17 of MiFID II regulates investment firms in the European Union that practise it.
What is algorithmic trading?#
Algorithmic trading, or algo trading, is the use of a computer program to make and execute trading decisions according to rules defined in advance. A trading algorithm is that set of rules translated into code: it reads market data, applies its logic and, when the conditions are met, sends an order to the broker or trading venue.
European law gives a precise definition. The MiFID II directive describes algorithmic trading as trading in financial instruments where a computer algorithm automatically determines the parameters of orders, such as whether to send them, their timing, price or quantity, with limited or no human intervention. A plain routing system, which forwards orders without setting any of their parameters, falls outside that definition.
The difference from discretionary trading lies in where the decision comes from. A discretionary trader reads the market case by case; an algorithm applies the same rule to every identical situation, without fatigue, hesitation or emotion. That consistency is its main strength. It is also a limitation: an algorithm only does what it was programmed to do, including when the market changes.
Whether people say algo trading, trading algorithm or automated trading, several overlapping terms are in use:
- Algorithmic trading: the umbrella term. It covers anything from helping execute a large order to making the complete decision, from entry to exit.
- Systematic trading: trading based on fixed, verifiable rules. It can be executed by hand, but it is usually automated.
- Automated trading: execution is left to the machine, with no manual approval of each order.
- Trading robot or Expert Advisor (EA): the program itself, as it runs on a platform such as MetaTrader 5.
- High-frequency trading (HFT): an institutional subset of algorithmic trading, defined by extremely short reaction times and a very large number of orders and cancellations sent to the market.
One point is often misunderstood: automating a strategy does not make it profitable. The algorithm faithfully executes an idea. If that idea has no real statistical edge once costs are deducted, the algorithm will faithfully execute a losing strategy, with a consistency a human might not have had.
How a trading algorithm works#
However sophisticated it is, a trading algorithm follows the same processing chain, from data to supervision. Each link can introduce an error, and the reliability of the whole depends on the weakest link.
- 1
Collect data
The algorithm receives prices (quotes, candles, ticks), sometimes volumes, an economic calendar or other sources. Data quality drives everything else: an incomplete or badly timestamped history distorts live decisions as much as backtest results.
- 2
Generate a signal
Rules turn the data into a decision: a moving-average crossover, a break of a recent high, a deviation from an average, a volatility threshold. The signal answers a single question: should we buy, sell or do nothing right now?
- 3
Filter market conditions
Filters discard signals that appear in poor conditions: a spread that is too wide, thin liquidity, an imminent major data release, an unsuitable market session. A good filter reduces the number of trades without destroying the strategy's edge.
- 4
Manage risk
Before sending the order, the algorithm sizes the position from the account balance and the distance to the stop-loss, then checks global limits: maximum daily loss, number of open positions, total exposure. This is the step that determines whether a losing streak remains survivable.
- 5
Execute the order
The order goes to the broker as a market, limit or stop order, with a stop-loss and possibly a take-profit. Between the expected price and the fill price come the spread, the commission and slippage, which are sometimes enough to make a strategy unprofitable.
- 6
Manage the position and supervise
Once the position is open, the algorithm manages it: trailing the stop, taking partial profits, closing on a signal or at the end of the session. On the human side, supervision means checking that the program is running, that orders are as expected and that results remain consistent with what was anticipated.
Take a deliberately simplified example. A trend-following algorithm on the Nasdaq 100 might buy when price closes above the highest high of the last twenty sessions, provided the spread is normal, placing a stop-loss at a distance based on recent volatility and risking a fixed fraction of the account. Every element of that sentence (twenty sessions, stop distance, fraction at risk) is a choice that has to be tested, then monitored over time.
Risk management deserves particular attention, because it decides whether the account survives far more than the quality of the entry signal does. Position sizing, daily loss limits, spread filters and the use of leverage are covered in our risk management documentation.
Institutional vs retail algorithmic trading#
The same name covers two very different worlds. At banks, funds and trading firms, the algorithm is first and foremost an industrial tool, built to execute large volumes or capture tiny price gaps at very high speed. For retail traders, it is mostly used to automate a trading strategy over horizons ranging from a few minutes to several weeks.
On the institutional side, there are three main uses:
- Execution algorithms. A fund manager who needs to buy a large number of shares does not send a single order that would push the price against them: the order is split into slices. A VWAP (Volume Weighted Average Price) algorithm distributes the slices according to the session's usual volume profile; a TWAP (Time Weighted Average Price) algorithm spreads them evenly over time. The goal is not to predict the market but to reduce execution cost.
- Market making. The algorithm continuously quotes a bid and an ask, aims to capture the spread between them and manages the inventory it accumulates. In the European Union, a firm pursuing an algorithmic market-making strategy must, under MiFID II, provide continuous quotes during a specified proportion of trading hours, under a written agreement with the trading venue.
- High-frequency trading (HFT). These strategies rely on infrastructure designed to minimise latency (servers co-located next to matching engines, direct electronic market access) and on very high volumes of orders, quotes and cancellations. The gaps they exploit are measured in fractions of a second and fractions of a cent.
Retail traders do not play in that league, and that is fine as long as they know it. They have no co-location, no direct data feeds and none of a large firm's transaction costs. Trying to compete on speed is a dead end. They can, however, work on longer horizons, where a few milliseconds of latency make no difference and execution discipline matters more than speed.
| Criterion | Institutional | Retail |
|---|---|---|
| Main goal | Execute large orders, make markets, arbitrage | Automate a directional strategy |
| Horizon | From microseconds to one day | From a few minutes to several weeks |
| Infrastructure | Co-location, direct market access, order book data | Broker platform (MetaTrader 5, for example), virtual private server (VPS) |
| Instruments | Equities, futures, options, bonds, currencies on regulated venues | Mostly CFDs on currencies, indices, commodities and crypto-assets |
| Regulation | Organisational and control requirements (MiFID II, Article 17) | Retail client protection rules applied by the broker |
This difference in playing field is why promises of “institutional-grade returns” aimed at retail traders should raise suspicion. A large firm's edge usually comes from its infrastructure, its costs and its market access, not from a secret formula that can be bought.
The main families of algorithmic strategies#
Most trading algorithms available to retail traders fall into a handful of families. Each rests on an assumption about how the market behaves, and each has its weak spot: none of them works in all conditions.
| Strategy | Principle | Typical market | Main risk |
|---|---|---|---|
| Trend following | Buy what is rising, sell what is falling and stay in the position while the trend lasts | Indices, commodities, currencies, crypto-assets | Long streaks of small losses when the market has no direction |
| Mean reversion | Bet that price returns to an average after a move judged excessive | Range-bound currency pairs, equities and indices over short horizons | A strong trend that never reverts and deepens the loss |
| Breakout | Enter when price leaves a consolidation zone or a recent high or low | Indices at the session open, commodities | False breakouts and slippage at entry |
| Scalping | Take many very short positions to capture small moves | Major currency pairs, highly liquid indices | Extreme sensitivity to costs: spread, commission, slippage |
| Arbitrage | Exploit a price gap between two related instruments or two venues | Equities and correlated asset pairs, crypto-assets across exchanges | Gaps that close very fast, execution risk, infrastructure costs |
Trend following is probably the best-documented family. Its profile is distinctive: many small losses, offset or not by a few large gains during major moves. It requires patience and risk management able to absorb long unfavourable phases without untimely intervention. An MT5 EA such as VECTOR X1 belongs to this family: it buys gold (XAUUSD) on trend breakouts, only while the underlying trend is up, and opens few positions. Its risk profile, aggressive and adjustable from 1 to 5, does not suit every investor.
Mean reversion shows the opposite profile: an often high win rate, but occasional heavier losses. This is the family where the most dangerous drifts occur, when the stop-loss is replaced by repeatedly adding to the losing position.
A breakout strategy tries to enter at the start of a move, when price leaves a zone of balance. It tends to work best on markets and at times when volatility is released decisively, such as a session open. Its main enemy is the false breakout, followed by an immediate return into the range.
Scalping calls for a specific warning, because its per-trade gains are close to transaction costs. A few tenths of a pip of extra spread can turn a profitable strategy into a losing one. A scalping EA therefore has to be assessed with the actual costs of the broker used. As an example, we tested and rejected about 1,100 forex scalping variants: none remained robust once real costs were included.
Pure arbitrage, finally, is largely dominated by institutional players, who have the speed and cost structure it requires. For a retail trader, “guaranteed arbitrage opportunities” are usually a sales pitch, and sometimes a scam.
In practice, many algorithms combine several ideas: a breakout filtered by the underlying trend, mean reversion restricted to certain hours, trend following reserved for a single market. The simpler the logic, and the better it is justified by an identifiable market behaviour, the easier it is to understand why it works, and to detect when it stops working.
Tools: MetaTrader 5, MQL5, Python and other platforms#
Choosing a tool depends less on the intrinsic quality of each platform than on three questions: which market do you want to trade, with which broker, and how much programming are you prepared to learn?
MetaTrader 5 (MT5), developed by MetaQuotes, is one of the most widely used platforms among forex and CFD brokers. Algorithms run on it as Expert Advisors written in MQL5, a language close to C++. MT5 includes a strategy tester that can replay history from real ticks, optimise parameters and test several instruments at once. Its main advantage is direct integration with the trading account: the EA runs where the orders are executed.
Python has become a reference language for quantitative research, thanks to its data analysis and statistics libraries. It is particularly well suited to exploring ideas, analysing results and running statistical tests. MetaQuotes provides a Python package that can pull data from an MT5 terminal and send orders to it; many brokers also offer their own application programming interfaces (APIs).
Other environments exist, each with its own ecosystem: cTrader and its cBots written in C#, NinjaTrader, widely used for futures, TradingView and its Pine Script language, mainly geared towards indicators, alerts and backtesting, or research platforms such as QuantConnect. None is better in absolute terms; the right choice is the one that fits your market, your broker and your skills.
Whatever environment you choose, a few pieces of infrastructure are essential:
- A regulated broker that offers the instrument you want to trade, with transparent costs. If you use MT5, check the exact name of your broker's server in your account opening email or client area.
- A virtual private server (VPS) if the algorithm has to run continuously. A personal computer that shuts down, updates or loses its connection interrupts the strategy, often at the worst moment.
- A demo account to validate the installation and the program's behaviour before committing real money.
- A rigorous installation procedure. For an MT5 EA, the steps (copying the file, allowing algorithmic trading, setting the inputs, checking initialisation) are covered in our installation guide.
You do not need to code to use an existing algorithm. You do need to code to build one, and starting from scratch that is an investment of several months. Either way, understanding a strategy's logic and knowing how to read a backtest report remain essential.
Backtest, forward test, live: why a backtest proves nothing on its own#
A backtest applies an algorithm to historical data to estimate how it would have behaved. It is an indispensable tool for weeding out bad ideas. It is, however, a very poor tool for proving that an idea is good, because it is easy, even in good faith, to produce a flattering backtest.
The main pitfalls are well known:
- Over-optimisation (curve fitting): by tweaking parameters again and again, you end up describing past noise rather than a lasting market behaviour. A perfectly smooth equity curve is often a warning sign, not proof of quality.
- Poor modelling: a test on opening prices only, or on artificially generated ticks, ignores part of what happens inside a candle. For a short-term strategy, only a test on real ticks with variable spread gives a credible picture of execution.
- Missing or underestimated costs: spread, commission, financing charges (swap) and slippage must be included, with values close to those of the broker you will actually use.
- Look-ahead bias: using, even unintentionally, information that was not available at the time of the decision, such as the close of a candle that is still forming.
- Survivorship and selection bias: testing only assets that still exist today, or keeping only the best variant out of hundreds of attempts.
- A period that is too short or too uniform: a history that covers a single market regime, a long rally for example, says nothing about how the strategy behaves in another regime.
Several methods reduce these biases, without ever eliminating them:
- Out-of-sample testing: develop the strategy on one part of the history, then test it once on a period it has never seen. If you then adjust the parameters to improve that result, the period is no longer out of sample.
- Walk-forward analysis: re-optimise the parameters on a rolling window, test them on the following period, and repeat across the whole history. This evaluates the optimisation method itself rather than one lucky parameter set.
- Monte Carlo simulation: resample the order of trades, perturb costs or randomly remove trades to obtain a distribution of possible outcomes, maximum drawdown in particular, rather than a single historical path.
- Parameter stability: favour settings surrounded by neighbouring values that produce comparable results, rather than an isolated performance peak.
Then comes the forward test: running the algorithm unchanged, on a demo account or with reduced capital, for long enough to observe a meaningful number of trades. It checks that real execution (spread, slippage, rejected orders, disconnections) resembles what the backtest assumed.
Going live is a stage in its own right. Differences between backtest and live results are normal; what matters is knowing in advance which differences are acceptable and at what threshold the algorithm should be stopped. Our own approach (settings chosen on an in-sample period, out-of-sample validation against criteria set in advance, variable spread and swaps included), and its limits (no commission or slippage simulated, no demo track record yet), is described on our strategy and research page.
Risks and limitations of algorithmic trading#
Automating trading removes none of the risks of trading. It even adds a few technical ones. These are the main risks.
- Capital loss: an algorithm can lose money, and keep losing it. Losing all the capital committed is possible.
- Leverage: CFDs and forex are traded on leverage. Leverage magnifies gains and losses alike, and a string of losing trades can shrink an account much faster than people expect.
- Regime change: volatility, correlations and price behaviour evolve. A strategy suited to one regime can stop working, sometimes without any clear warning.
- Over-optimisation: an algorithm calibrated too finely on the past can deteriorate as soon as it meets new data.
- Technical failures: an internet outage, a VPS restart, a platform update, a coding error, a mistyped input. Professionals are not immune: in August 2012, a software deployment error cost the US firm Knight Capital more than 400 million dollars in less than an hour.
- Execution risks: slippage around economic releases, price gaps at the open, spreads widening overnight or during periods of stress.
- Broker risk: trading conditions (spread, leverage, trading hours) and the broker's financial soundness directly affect results.
- Behavioural risk: switching the algorithm off after three losses, back on after three wins, changing its settings mid-course. Automation does not protect you from your own interventions.
Methods that hide risk instead of managing it also need to be addressed. Grid strategies open additional positions at regular intervals against a losing position. Martingale increases the position size after each loss to “win it back”. Both approaches produce very smooth equity curves, until the day a prolonged move in the wrong direction wipes out the account within hours.
Scams exploit precisely this appearance of regularity. France's AMF, for example, has warned about forex trading robots sold on subscription, promising unrealistic returns, tied to unauthorised brokers and to referral schemes (AMF warning). A promised monthly return, no stop-loss, an unverifiable track record, deposits accepted only in crypto-assets: each of these signals is reason enough to walk away.
For a full description of the risks involved in using our systems, read our risk disclosure.
The regulatory framework for algorithmic trading#
Algorithmic trading is legal. What is regulated is the activity of the professionals who practise or offer it, as well as the products offered to retail clients. The framework varies by country and by the status of each party.
In the European Union, the MiFID II directive, in force since January 2018, devotes its Article 17 to algorithmic trading. An investment firm that uses it must have effective systems and risk controls, business continuity arrangements in case of failure, and must notify its activity to the competent authorities. Commission Delegated Regulation (EU) 2017/589, known as RTS 6, details these requirements: testing algorithms before deployment, pre-trade controls, real-time monitoring, and the ability to cancel all orders immediately in an emergency. High-frequency traders must also keep time-stamped records of all their orders.
These obligations apply to investment firms and members of trading venues. A private individual running an algorithm on their own account, with a broker, is not subject to them. They do, however, benefit from the rules that protect retail clients.
The most important of these concern CFDs, the instruments most retail algorithms trade. Since 2018, following ESMA product intervention measures that national authorities later made permanent, brokers in the European Union must apply to retail clients, among other things:
- leverage limits when opening a position: 30:1 for major currency pairs, 20:1 for other pairs, gold and major indices, 10:1 for commodities other than gold and non-major indices, 5:1 for individual equities and 2:1 for crypto-assets;
- closing out positions when the account margin falls to 50% of the minimum required margin;
- negative balance protection, which caps total losses at the funds held in the CFD account;
- a standardised risk warning stating the percentage of the broker's retail accounts that lose money;
- a ban on commercial incentives, such as bonuses, designed to encourage CFD trading.
In France, the AMF protects savings and oversees the proper functioning of markets. Together with the ACPR, it publishes blacklists of websites not authorised to offer investments, forex in particular, and regularly warns about fraudulent automated trading offers. Before opening an account or buying a service, check that the provider is authorised and does not appear on those lists.
In Switzerland, which is not an EU member, ESMA measures do not apply directly. FINMA supervises, among others, banks, securities firms and financial market infrastructures; a currency dealer that holds accounts for clients generally needs a banking licence. FINMA also publishes a warning list of providers that may be operating without authorisation.
That leaves the status of an algorithm sold to a private individual. An Expert Advisor offered under licence is software: it is not investment advice tailored to your personal situation, nor portfolio management on your behalf. The decision to use it, the choice of broker and the risk setting remain the user's responsibility. Conversely, a service that takes control of your account or sends you personalised recommendations falls under other regimes that may require authorisation: if in doubt, check the seller's status with the regulator.
Build your own algorithm or use an existing one#
A retail trader has two ways into algo trading: developing their own trading algorithm or using a system designed by someone else. Both are legitimate, provided you know their real cost.
Building it yourself gives you full control over the logic and parameters. The price is time: learning a language, understanding how the target market works, learning to test without fooling yourself. The main risk is mistaking a flattering backtest for a robust strategy.
Using an existing algorithm saves that time but shifts the difficulty: you have to evaluate a system you did not design. The useful questions are well known.
- Is the logic explained, at least in broad terms: strategy family, market, horizon, risk profile?
- Is every position protected by a stop-loss? Does the system use a grid or a martingale?
- Are backtests run on real ticks, with variable spread, commissions and slippage? Do they cover several market regimes?
- Can the user adjust the risk per trade?
- Is the business model clear (licence, subscription) and independent of any imposed broker?
- Does the seller refrain from promising returns?
We go through this checklist in detail in a dedicated guide: how to choose a trading robot. To illustrate how different profiles can be, an MT5 EA such as APEX is dedicated to intraday momentum on the Nasdaq 100, buy only, with an aggressive risk profile, while QUANTIS only opens long positions on Bitcoin, with a long-term horizon and a moderate profile. Two algorithms, two logics, two risk levels: the choice depends first on your tolerance for losses, not on a headline return.
Where to start as a retail trader#
There is no shortcut, but there is a logical order. The steps below guarantee no result; they reduce the risk of losing money for the wrong reasons.
- 1
Learn the basics
Understand the instruments (CFDs, leverage, margin), the costs (spread, commission, swap) and the concepts of drawdown, expectancy and position size. Without these basics, it is impossible to interpret a backtest or an algorithm's behaviour.
- 2
Set your framework
Decide in advance how much capital you accept losing entirely, the maximum risk per trade and the loss level at which you stop the algorithm. These numbers are set with a cool head, never in the middle of a losing streak.
- 3
Test on demo
Install the algorithm on a demo account with your intended broker and let it run for several weeks. Check execution, trading hours and costs, then compare with the backtest.
- 4
Go live with small risk
Start with reduced capital and a low risk per trade. The purpose of this phase is to validate real execution, not to make money.
- 5
Keep a journal
Record every parameter change, every technical incident and each week's results. A journal lets you tell a normal unfavourable period from a genuine malfunction.
- 6
Supervise over time
Check regularly that the program is running, that the VPS is up and that drawdown stays within the expected range. An algorithm automates execution, not responsibility.
If you are starting from an existing MT5 EA, our getting started page covers system requirements, a first-run checklist and why you should begin on a demo account.
Frequently asked questions
Is algorithmic trading profitable?
It can be, but it is not profitable by nature. An algorithm is only profitable if the strategy it executes has a statistical edge that survives costs, and that edge can disappear when the market changes. Many algorithms, including well-built ones, lose money over certain periods, and some lose it permanently. No result is guaranteed, and past performance is not indicative of future performance.
Is algorithmic trading legal?
Yes. In France, Switzerland and the rest of Europe, a private individual may use an algorithm to trade on their own account. It is the professionals who practise or offer it that are regulated, in particular by Article 17 of MiFID II for investment firms in the European Union. You do, however, need to use an authorised broker, comply with its terms (some prohibit latency arbitrage, for example) and beware of unauthorised providers.
How much capital do I need to start algorithmic trading?
There is no universal minimum. The capital must allow a low risk per trade given the broker's minimum position size and, above all, be an amount whose total loss would not affect your financial situation. Starting on a demo account, then with a small live amount, remains the most prudent approach.
Do I need to know how to code for algorithmic trading?
To build your own algorithm, yes: MQL5 for MetaTrader 5, Python for research, or the language of your chosen platform. To use an existing algorithm, no: installing an Expert Advisor on MT5 requires no programming. You do, however, need to understand the system's logic, its risk settings and how to read a backtest report.
Trading robot vs algorithmic trading: what is the difference?
Algorithmic trading refers to the method: handing trading decisions to programmed rules. A trading robot, called an Expert Advisor on MetaTrader, is the concrete tool that applies those rules to an account. Every trading robot is therefore a form of algorithmic trading, but algorithmic trading also includes institutional uses, such as VWAP or TWAP execution algorithms, which are not robots in the sense retail traders mean.
Is a positive backtest enough to validate an algorithm?
No. A backtest can be over-optimised, poorly modelled or leave out part of the costs. It must be complemented by out-of-sample tests, walk-forward analysis, Monte Carlo simulations and then a forward test on a demo account. Even after these steps, it guarantees nothing about the future.
Can a trading algorithm lose all my capital?
Yes. An algorithm can suffer a long losing streak, a market regime change, a technical failure or a violent move. With leverage, losses can reach the entire capital deposited. A stop-loss on every position and a limited risk per trade reduce that danger without removing it.
How do I spot a trading robot scam?
The warning signs are recurring: a promised or guaranteed monthly return, an equity curve that never dips, no stop-loss, a grid or martingale strategy, an unverifiable track record, an obligation to open an account with a “partner” broker, deposits only in crypto-assets, a referral scheme. Always check the provider's status with the regulator, such as the AMF in France or FINMA in Switzerland.

