Skip to content
TradingBox
← All posts

Algorithmic Trading for Beginners: How It Works

"Algorithmic trading" sounds like something only banks and hedge funds do. In reality, if you have ever written down a rule like "I buy when the price closes above the 200-day average" and followed it every time, you already have the core of an algorithm. Algorithmic trading simply hands those rules to a computer, which follows them without hesitation, fatigue or emotion.

This guide explains how automated strategies really work, what parts every trading algorithm needs, which programming language to choose, and the honest result of a real, simple algorithm tested on 26 years of EURUSD data. No promises of easy money: just how it works.

Key takeaways

  • An algorithm is a set of exact rules a computer can follow: when to enter, when to exit, how much to trade and when to stop.
  • Every working algorithm has five parts: data, signal, risk, execution and monitoring. Beginners focus on the signal; most failures come from the other four.
  • A simple, well-known algorithm tested on real EURUSD data from 2000 to 2026 made about +5% after costs in 26 years. Simple rules are not magic, and a backtest is the only way to find that out before risking money.
  • MQL5 runs directly inside MetaTrader 5, Python is best for research and data, Pine Script is the fastest way to test ideas on TradingView.
  • Automation removes emotional mistakes but adds technical ones. You need logs, alerts and a way to switch it off.

What algorithmic trading is (and is not)

Algorithmic trading means using a computer program to make or carry out trading decisions according to predefined rules. It is not all-or-nothing: see algorithmic vs manual trading for the levels in between.

It is not the same as:

  • AI trading. Most trading algorithms contain no artificial intelligence at all: they are plain if-then rules. We explain the difference in AI trading bots vs MT5 Expert Advisors.
  • High-frequency trading. HFT firms trade in microseconds from servers next to the exchange. A retail Expert Advisor checking prices on every tick is a different world, and that is fine.
  • A guaranteed profit. An algorithm executes a strategy exactly. If the strategy has no edge, the algorithm loses money exactly and efficiently.

Algorithms are also widely used by large institutions simply to execute orders, splitting a big trade into small pieces over time. A 2020 report by the Bank for International Settlements found that FX execution algorithms had become a standard tool for large market participants, while warning that they bring new risks to watch.

The five parts of every trading algorithm

The five parts of a trading algorithm: data, signal, risk, execution and monitoring, with a feedback loop

1. Data. What the algorithm sees: prices (bid/ask, bars, ticks), volume, time of day, sometimes economic release times or other markets. Bad or incomplete data creates false signals.

2. Signal. The entry and exit rules. "Buy when the 50-day average crosses above the 200-day average; sell when it crosses below." This is the part everyone talks about.

3. Risk. How big each trade is, where the stop goes, how many trades can be open at once, and the maximum daily or weekly loss before the algorithm stops. Our position size guide shows why this part decides whether you survive.

4. Execution. Sending the order to the broker and dealing with what comes back: partial fills, slippage, requotes, rejected orders, the market being closed, the connection dropping.

5. Monitoring. Logs of every decision, alerts when something unusual happens, and a kill switch. An algorithm that nobody watches is an accident waiting for a date.

Then you review, change one thing, and test again.

A real example: the 50/200-day moving-average crossover

The "golden cross" is one of the most quoted trading rules in the world. We turned it into an algorithm and tested it on official daily EURUSD prices from the Federal Reserve, from 2000 to October 2026.

The rules:

  1. Every day, calculate the average closing price of the last 50 days and of the last 200 days.
  2. If the 50-day average is above the 200-day average, be long (bought) EURUSD. If it is below, be short (sold).
  3. Act on the next day, never on the same day's data (no peeking into the future).
  4. Pay a 1.5-pip spread every time the position changes.

Growth of 100 for the 50/200-day crossover on EURUSD with and without costs, compared with buying and holding, 2000–2026

The result:

2000s2010s2020s (to Oct 2026)Whole period
Crossover, after costs+3.4%-4.5%+6.8%+5.4%

About 38 position changes in 26 years, and roughly break-even overall, with long flat stretches and losing periods.

What this teaches:

  • Famous does not mean profitable. A rule everyone knows has usually been arbitraged away, or only works in some market conditions.
  • Simple rules are not useless. This one did stay out of a few big one-way moves on the wrong side. As a filter (only take buy trades when the trend is up) it can be more useful than as a complete system.
  • You only find this out by testing. Ten minutes of code saved you from discovering it with real money. Our backtesting guide shows how to test properly, and how easy it is to fool yourself.

This is an educational example, not a strategy we recommend trading.

Common types of trading algorithms

TypeThe ideaWhere it struggles
Trend followingBuy strength, sell weakness, ride long moves (moving averages, breakouts of highs and lows)Choppy, sideways markets: many small losses
Mean reversionPrices stretched far from an average tend to come back (RSI extremes, Bollinger Bands)Strong trends: "cheap" keeps getting cheaper
BreakoutTrade the move out of a range, often at the open of a sessionFalse breakouts, slippage on fast moves
Time / session basedPatterns tied to the clock: London open, end of month, rolloverPatterns fade once widely known
News awareAvoid or trade around scheduled releases (see our economic calendar guide)Spreads widen and prices jump past stops
Grid and martingaleAdd more trades, often bigger ones, as the price moves against youLook perfect for months, then one trend wipes the account

The last row deserves a picture.

Martingale lot growth: starting at 0.01 lots and doubling after each loss reaches 10.24 lots after 10 losses

A martingale system doubles the trade size after every loss, so the first win recovers everything. Starting at 0.01 lots with a 20-pip stop, after ten losses in a row the next trade is 10.24 lots and you have already lost about $4,100, all to win back $2. Ten losses in a row is not rare (see the losing streak section of our position size guide). Many "never losing" robots sold online are martingale or grid systems underneath.

MQL5 vs Python vs Pine Script

MQL5PythonPine Script
Runs inMetaTrader 5 (your PC or a VPS)Anywhere; connects to MT5 with the official MetaTrader5 package (Windows)TradingView's servers
Best forLive automated trading with an MT5 brokerResearch, data analysis, statistics, machine learningFast idea testing on charts, alerts
BacktestingMT5 Strategy Tester, including real tick dataAny method you build or a libraryBuilt-in Strategy Tester on TradingView data
Places real ordersYes, directlyYes, through the MT5 terminalVia alerts and webhooks or supported brokers
Learning curveMedium (C-like syntax)Gentle start, huge ecosystemEasiest to start

Our honest suggestion for beginners:

  1. Test the idea quickly in Pine Script or by hand.
  2. Research it properly in Python if it involves data or statistics.
  3. Run it live in MQL5 as an Expert Advisor once it has survived testing.

You don't need all three. Many traders only ever use one.

What you need to run your first algorithm

  • A platform and a broker. MetaTrader 5 is free and supported by most retail forex and CFD brokers.
  • A demo account. Run every new algorithm on demo first, for weeks, not hours.
  • Clean history. For MT5, download the broker's history in the Strategy Tester. For research, use a source you trust and check for gaps.
  • A machine that stays on. An Expert Advisor only trades while MetaTrader is running and connected. Many traders rent a small VPS (virtual private server) near their broker's servers.
  • A log. Every trade should record why it was opened, at what price it was intended and at what price it was filled.

Why live results differ from tests

Expect your live results to be worse than your backtest, for reasons that have nothing to do with your rules:

  • Spread widens at the daily rollover, during news and on Monday mornings.
  • Slippage: on fast moves you are filled at a worse price than the one you saw.
  • Execution: brokers differ in speed, rejections and minimum stop distances.
  • Weekend gaps: the Monday open can jump straight past your stop.
  • Your own interference: switching the algorithm off after three losses is the most common reason a sound system fails.

Our article on A-book, B-book and C-book brokers explains why the same order can be handled very differently from one broker to the next.

Monitoring: the part nobody talks about

On 1 August 2012, Knight Capital, then one of the largest US market makers, started the trading day with a faulty update to its order-routing software. In about 45 minutes the system sent a flood of unintended orders into the stock market, and the company reported a pre-tax loss of about $440 million. The company had to be rescued and was taken over months later.

You are not Knight Capital, but the lesson scales down perfectly. Your algorithm needs:

  • a maximum daily loss after which it stops trading by itself,
  • a maximum number of trades and open positions,
  • alerts to your phone when it opens trades, hits errors or loses connection,
  • a kill switch you can use in seconds.

A beginner's roadmap

  1. Write the rules in plain language first, so precisely that someone else could follow them without asking you a question.
  2. Test by hand on past charts. Twenty to fifty trades will show you if the idea is even worth coding.
  3. Code it in the language you chose. Start with entries and exits, then add risk rules.
  4. Backtest properly: realistic costs, enough history, and a period you did not use to design the rules.
  5. Run it on demo for at least a few weeks and compare every trade with the backtest.
  6. Go live small, with the minimum risk, and keep comparing.
  7. Change one thing at a time, and test again.

Common beginner mistakes

  1. Optimising until the backtest looks perfect. That is curve fitting, and it is the most common reason algorithms fail live.
  2. Ignoring costs. A system with many trades can be profitable before costs and losing after them.
  3. No risk rules in the code. An algorithm without a stop and a daily limit is not finished.
  4. Buying a "profitable EA" based on screenshots. Ask for a full, verified history and a backtest you can run yourself.
  5. Going live too fast because the demo week was good.

Frequently asked questions

Is algorithmic trading profitable? It can be, but automation is not an edge in itself. It makes a good strategy consistent and a bad strategy consistently bad. Most retail traders who use leveraged CFDs lose money, automated or not.

Do I need to know programming? To build your own, yes, at least the basics. Pine Script is the gentlest start. Alternatively, you can describe your rules to a developer who codes them for you.

How much money do I need? You can start algorithmic trading on a demo account for free. For live trading, enough that your risk rules work with the broker's minimum lot (see the small-account section of our position size guide).

Is algorithmic trading legal? Yes, for retail traders using their broker's platform. Check your broker's terms: a few restrict certain styles, such as very high-frequency trading or latency arbitrage.

What is the difference between an algorithm and an Expert Advisor? An Expert Advisor (EA) is MetaTrader's name for an algorithm that runs inside the platform and can trade automatically. Our guide shows how to install an EA in MT5.

Next steps

  • Learn the tools: Python for Trading A–Z (data, testing and connecting to MT5) and Pine Script A–Z (indicators and strategies on TradingView). Both are coming soon: press Notify me to hear first.
  • Already have a strategy written down? We can turn it into an MT5 Expert Advisor with risk limits, logs and alerts built in: custom EA development.
  • Size every test trade correctly with the free Lot Size Calculator.

Sources

This article is education, not financial advice. Past results, real or simulated, do not guarantee future results. Trading on margin carries a high risk of losing money.

Trading involves risk. See the risk disclaimer.