Algorithmic Trading: What It Is and How to Test a Trading Algorithm

Cover of the article “Algorithmic Trading: What It Is and How to Test a Trading Algorithm”: a chain of algorithm blocks—data, rules, and risk—with a circular verification frame and check mark between risk and the order

What is algorithmic trading in simple terms?

This concept also has a legal definition, and it is more precise than its everyday meaning. The European MiFID II Directive defines it in Article 4(1)(39). It calls transactions algorithmic trading when a computer algorithm determines order parameters itself. The original wording is: "a computer algorithm automatically determines individual parameters of orders such as whether to initiate the order, the timing, price or quantity of the order or how to manage the order after its submission, with limited or no human intervention". The boundary in this definition is carefully drawn: if a program merely routes an order whose parameters have already been determined, confirms it, or processes it after the trade, the same article does not classify this as algorithmic trading. There is one decisive criterion: the machine determines the order parameters.

In Regulatory Notice 15-09, FINRA describes algorithmic strategies as a distinct class of trading activity with its own risks and control practices, from code testing to an emergency stop button. Research by Hendershott, Jones, and Menkveld in the Journal of Finance showed that algorithmic trading improves market liquidity and makes quotes more informative. That answers the question of what it is at the market level.

For a retail trader, the essence is more modest and practical. Algorithmic trading is a way to remove emotion and human reaction speed from a trade, retaining only what you have been able to define explicitly. If a rule cannot be written so that another person can execute it without asking you for clarification, it is still an idea rather than an algorithm. The section below explains how to turn an idea into rules, but first let us examine what an algorithm physically consists of.

What a trading algorithm consists of

  1. 1

    Data

    Candles, volume, tape, calendar

  2. 2

    Rules

    Unambiguous entry and exit conditions

  3. 3

    Risk

    Stop-loss, position size, loss limit

  4. 4

    Execution

    Order type, channel, failure handling

Data feeds the rules, the rules generate a signal, risk limits the size, and execution submits the order. The diagram shows the sequence, not a specific strategy.

Diagram 1. Components of an algorithm. The components in descending order of responsibility are risk first, followed by rules and then execution.

Data is what the algorithm observes: candles, volume, the order book, and the event calendar. Rules form the core: the conditions under which to buy and the conditions under which to close. Risk defines how much is lost if the decision is wrong: the stop-loss order, position size, and daily limit. Execution determines how an order reaches the exchange: the order type, channel, and response to a lost connection.

A similar list appears in guidance from the supervisory authority. ESMA's supervisory briefing of February 26, 2026 lists activities considered to determine trading parameters: generating orders from signals, choosing an execution strategy, analyzing market conditions, rebalancing a portfolio, configuring risk limits, seeking liquidity, and optimizing across venues. It also states the point most important to us: "the algorithms must be testable and controllable". It sounds bureaucratic but works as a practical criterion: if your idea cannot be subjected to a repeatable test, you do not yet have an algorithm.

A common beginner's mistake is to focus entirely on the "rules" component and pay almost no attention to the "risk" component. On a live account, it is the third component that determines whether the account survives a series of losing trades. The fundamentals of position sizing are covered in the article on risk per trade.

Algorithmic trading, trading bots, and HFT: what is the difference?

TermWhat it isWho uses itWhat it achieves
Algorithmic tradingA method: rules instead of decisions made in the momentRetail and institutional tradersDiscipline and repeatability
Trading bot / expert advisorA program that executes rulesRetail traders, most commonly in Forex and cryptoAutomation of manual routine tasks
HFTUltra-fast strategies running on infrastructure close to the exchangeSpecialized firmsMicrosecond latency rather than the quality of the idea

The boundary between algorithmic trading and HFT is also defined by law. Article 4(1)(40) of MiFID II requires three characteristics to be present simultaneously: infrastructure specifically designed to minimize latency, such as colocation, proximity hosting, or high-speed direct access; no human intervention in decisions concerning individual orders; and a high intraday message rate. Remove any one of the three and it is ordinary algorithmic trading rather than HFT. The US regulator is more candid in its qualification: the SEC's 2010 concept release states directly that the term was new and did not yet have a clear definition, listing five typical characteristics instead, including colocation and ending the day with a flat position.

There is a practical conclusion here for a retail trader in Russia. The Moscow Exchange's foreign exchange market officially charges an additional fee for inefficient orders, and its rules specify the threshold: the fee is not calculated if no more than 30 000 orders are submitted for SPOT instruments during the day. In other words, the venue financially penalizes a high proportion of canceled orders. A home-built algorithm does not usually reach this threshold. The idea of "submitting and canceling thousands of orders," however, will run into it immediately.

The scale of human involvement illustrates the boundary between these approaches well. Testing a ready-made robot on a specific platform is a separate practical task, demonstrated with MetaTrader in the article on testing an expert advisor.

123

A human clicks the button

An HFT robot on a server at the exchange

  1. 1.Manual trading according to a plan
  2. 2.The machine generates a signal; a human clicks
  3. 3.The bot executes the trade itself

Manual trading according to a plan

The machine generates a signal; a human clicks

The bot executes the trade itself

From entirely manual trading to high-frequency trading. The further to the right the position is, the fewer decisions remain for a human to make in the moment and the greater the infrastructure requirements.

Diagram 2. A retail trader usually operates in the left and middle portions of the scale. The far right is high-frequency trading, a separate industry with different economics.

Which tasks can be automated, and where does risk remain?

What algorithmic trading can and cannot provide
Suitable if you need
  • Discipline: the algorithm does not deviate from its rules
  • A fast response to a formal condition
  • Testing an idea on a long historical period in minutes
  • Simultaneous monitoring of dozens of instruments
Not suitable if you expect
  • Profit without a tested idea behind it
  • Guaranteed results: the market changes, and a rule may stop working
  • A substitute for risk management and a trading plan
  • Predictions of news or other people's actions

Card 1. The method's boundaries. An algorithm can formalize an edge if one exists; it cannot create an edge from nothing.

The honest point of this section is that automating execution is a solvable engineering problem, but the edge you automate remains the subject of your own research. That is why testing an algorithm matters more than writing it, and the next part of the article addresses testing. More materials about rules and strategy testing are collected in the trading strategies section.

How to turn a trading idea into unambiguous rules

A typical unrefined idea sounds like this: "I buy a bounce when the market is oversold." It conceals decisions that intuition makes in live trading: what constitutes an oversold condition, which bounce counts as confirmed, and where to exit if the bounce does not occur. An algorithm requires every one of these decisions to be made explicit.

The formalization process:

  1. Express the entry condition using numbers and indicators: which indicator, which period, which value, and which timeframe.
  2. Define separate exit conditions for profits and losses. "I will close when I realize it is not working" is not an acceptable formulation.
  3. Define what the algorithm does if data is unavailable or the connection is lost.
  4. Set the position size using a formula based on the stop-loss order, not on a feeling.

This list is a shortened version of what the regulator recommends to firms as an effective strategy-documentation practice: a plain-language description that allows control and development teams to understand the same thing without reading the code. The logic is the same; only the scale differs. The article on a trader's trading plan explains how to assemble such rules into a coherent document.

How to backtest an algorithm without overfitting

A backtest is a run of an algorithm on historical data. The main trap is called overfitting: the more rule variants you try on the same segment of historical data, the more likely it is that the best one performs well specifically on that segment—and only because it was selected on that segment.

This trap has a measured cost. In "Pseudo-Mathematics and Financial Charlatanism" (Notices of the AMS, May 2014), Bailey, Borwein, Lopez de Prado, and Zhu derived the minimum historical-data length for a given number of trials. Their numerical conclusion was that with two years of data, after only seven independent configurations, the expected in-sample Sharpe ratio is one while the out-of-sample ratio is zero. With five years of data, the limit is 45 configurations. The logic behind the figures is simple: the more configurations you try, the greater the probability that the final backtest is overfit to historical data.

This gives us a practical criterion worth applying to other people's results as well as our own: a backtest that does not state how many configurations were tried does not allow you to assess the risk of overfitting. The same paper presents an uncomfortable implication: a sufficiently persistent researcher can always find a backtest with any desired Sharpe ratio.

Practical methods for combating overfitting:

  • Divide the historical data into a development period and a test period. Select parameters only on the first, then run the second once.
  • Count your attempts. Record how many configurations you have already run: that is the quantity that devalues the result.
  • Use fewer parameters. Every adjustable value provides another degree of freedom for overfitting.
  • Test the rule on related instruments and timeframes: robustness matters more than a record result on one chart.
  • Be skeptical of perfect results. A smooth historical equity curve is more likely to indicate a data error or lookahead bias than a genuine edge.

The same authors provide an important qualification concerning sample splitting. In "The Probability of Backtest Overfitting," they explain why an ordinary holdout sample is unreliable with short histories and cite Weiss and Kulikowski's rule that this method should not be used with fewer than one thousand observations. For a strategy that trades once a week, this means a backtest covering at least twenty years. In their numerical example, the gap between historical testing and live performance is stark: all Sharpe ratios are positive in-sample, while about 78 percent are negative out-of-sample.

A related problem is the quality of the sample itself. If the data includes only instruments and funds that have survived to the present day, the test observes survivors and overstates the result. Regulatory research addresses this deliberately: an SEC working paper describes a database that retains closed funds, "ensuring that poorly performing or high-fee funds that exited the market are still represented in the data".

Keep the time horizon in mind as well: even an honest backtest describes the past. Market regimes change, and a rule that worked during a trending year may lose money in a range-bound market.

How to account for commissions, slippage, and the execution model

An honest test must include three types of costs:

  1. Broker and exchange commissions on every trade, including the closing trade.
  2. Slippage—the difference between the signal price and the execution price. For market orders during fast moves, it is systematically unfavorable to you.
  3. The spread: an algorithm that "trades inside the spread in a backtest" will in reality pay half the spread on entry and half on exit.

Cost estimates should come from official fee schedules rather than guesswork. The Moscow Exchange equity market uses a maker-taker model: in the main trading mode, a passive order is generally executed at a zero rate, while an active order costs 0.03 percent of its value. The same fee schedule contains a separate 0.0025 percent surcharge on both sides, but it does not apply to an ordinary market order in the main trading mode: it is charged on iceberg orders, orders in the closing auction, and market orders in the opening auction. On the Binance spot market, the standard rate for a regular user is 0.1 percent, deducted from the asset received. Interactive Brokers' fixed rate for US stocks is calculated per share: $0.005 per share, with a minimum of one dollar per order and a maximum of one percent of the trade value. The differences between these regimes determine whether your apparent edge survives on a live account.

The execution model comes next, and its trap is subtler. TradingView's built-in strategy tester does not know how the price moved within a candle and reconstructs the path according to a rule: if the open is closer to the high, the emulator assumes that the price moved from open to high, then low, then close. The documentation states this explicitly and also says that the emulator does not assume intrabar price gaps when processing pending orders. Bar Magnifier mode forces the tester to use a lower timeframe instead of guessing. Two other default settings favor you and therefore produce misleading results: Slippage is zero, and Verify price for limit orders is also zero, meaning that limit orders receive more generous fills than they would in real trading. A separate line in the documentation notes that on non-standard charts such as Renko, a strategy trades synthetic prices and the result "typically produces unrealistic results".

There can also be direct lookahead bias. Requesting data from a higher timeframe with lookahead mode enabled returns information on historical bars that was not yet known at the time; the Pine Script documentation calls this "dangerously misleading". No such source of information exists in real time, so the attractive historical result cannot be reproduced.

The rule is simple: if the edge disappears after costs and a realistic execution model are honestly included, it never existed.

A reproducible testing protocol in Midas BackTester

BackTester is a bot strategy designed as a testing tool: you define the conditions, and it shows how those conditions would have performed on historical data. For our purposes, this means that the step of "running the predefined rules" is performed consistently and reproducibly, and the results can be compared across different sets of rules.

  1. 1

    Define the rules

    In writing, with no room for interpretation

  2. 2

    Run a backtest

    Develop on one segment of historical data

  3. 3

    Perform one out-of-sample test

    Use a segment that was not involved in parameter selection

  4. 4

    Include costs

    Commissions, spread, slippage

  5. 5

    Forward-test with a small position size

    Live market, minimum size

Five steps from predefined rules to live trading with a small position size. Each step filters out some of the errors from the preceding one.

Diagram 3. The protocol is the same for any platform; BackTester handles steps 2–4 reproducibly and without code.

How to move from a backtest to a forward test

  1. Stage 1

    Demo account

    Execution with demo funds, logic testing

  2. Stage 2

    Minimum live position size

    Real commissions and slippage

  3. Stage 3

    Operating position size

    Gradual scaling when the statistics remain consistent

  4. Stage 4

    Regular monitoring

    Compare live results with the test

The sequence of live-testing stages. The timeframes in the diagram are guidelines: a stage may be extended but not shortened.

Diagram 4. Progression between stages is determined by the similarity between live and test execution. A discrepancy indicates a modeling error and is a reason to return to development.

Along this path, demo mode answers the question "does the code work?", while the minimum live position size answers "do the economics work after costs?" You should not skip the second question: it is where most home-built algorithms fail. The algorithm does not become untouchable afterward—the statistics from live trades are compared regularly with the test, and a significant discrepancy sends you back to the development stage.

There is no single official standard for the duration of a forward test: no regulator or platform specifies a minimum number of calendar days. There is, however, a widely used proportion based on the data. The MetaTrader 5 tester can divide historical data into optimization and forward periods in fractions of 1/2, 1/3, and 1/4: the final quarter or third of the period is excluded from parameter selection and used for testing. The practical guideline is simple and is not based on the calendar: a forward test should accumulate enough trades for its statistics to be meaningful.

Professionals impose even stricter launch controls, and their logic is worth adopting. RTS 6 under MiFID II requires a firm to set limits before launching an algorithm: limits on the number of instruments, order price, value and quantity, position size, and number of venues. A separate article in the same regulation requires kill functionality—the ability to cancel all unexecuted orders immediately as an emergency measure. The law does not impose this on a retail trader, but a daily limit and a preplanned way to shut everything down are just as valuable.

Risks and limitations

What you should know before launching any algorithm:

  • Market risk remains: an algorithm tested on historical data may encounter a regime in which its rule does not work.
  • Technical risk: a lost connection, delayed data, or a coding error. FINRA considers an emergency stop button that disables an algorithm in as few steps as possible to be an effective practice, and a retail trader should demand the same of themselves.
  • Third-party code risk: a purchased or downloaded bot contains someone else's rules without a history of how they were tested. Ready-made collections of robots and third-party management of your account form a separate category of risk for which FINRA has issued a special investor warning.
  • Overconfidence risk: one successful run does not prove an edge, and a series of unsuccessful runs is not necessarily a final verdict either. The protocol is what supports conclusions in this field.
  • Risk of losing capital: exchange trading can lead to the loss of invested funds, and automation does not change that.

The SEC's Knight Capital enforcement case shows how costly an untested launch can be. On August 1, 2012, because an update had not reached one server, the firm submitted millions of orders in 45 minutes and received 4 million executions across 154 securities. The loss exceeded $460 million. The regulator's document identifies the causes, all of which were organizational: a module that had been unused for years remained in the code, new code reused the flag that activated this module, and the code was not retested after the function for calculating the number of shares was moved. The SEC states the conclusion directly: a simple written procedure for double-checking the deployment could have detected the missed server and prevented the events of August 1. Seven of the eight servers operated correctly.

The second textbook case concerns parameters rather than code. A joint CFTC and SEC report on the events of May 6, 2010 describes a selling algorithm configured to maintain a rate of 9 percent of the trading volume from the previous minute "but without regard to price or time". Because of this setting, the program completed the order in 20 minutes, whereas the same participant had previously spread a comparable sale over several hours because price and time were taken into account. A five-second trading pause on CME stopped the cascade. The lesson for a home-built algorithm is the same: a rule with no price or time constraint behaves differently in a stressed market than it does in a test.

A separate point concerns promises. In its bulletin on auto-trading, the SEC advises investors to be very cautious if a firm claims that it always makes money in the market or earns exceptionally high profits for clients. In a 2024 warning, FINRA quotes typical scam slogans verbatim, such as "Our proprietary AI trading system can't lose!", and urges investors not to believe promises of extraordinary returns, even from registered firms. In its section on fraud, the Bank of Russia identifies the same warning signs: promises of extraordinarily high returns, encouragement to recruit a friend, and pressure to make a quick decision. Its regularly updated list of companies showing signs of illegal activity also includes "trading robots".

This material does not constitute investment advice.

Sources

Frequently asked questions

What is algorithmic trading in simple terms?

It is trading according to predefined rules executed by a program. You specify the entry, exit, and risk conditions, and the algorithm then applies them without your involvement in every trade. In algorithmic trading, the human is responsible for defining and testing the rules, while the machine is responsible for execution.

How does an algorithmic trader differ from a conventional trader?

A conventional trader makes decisions in the moment: sees a signal, evaluates it, and clicks a button. An algorithmic trader moves that decision into the development stage: first they write a rule, then test it on historical data, and only then entrust an account to it. The profession of an algorithmic trader combines trading, programming, and statistics.

What does investing in algorithmic trading mean, and what are the risks?

It means handing money over to be managed by someone else's algorithm or buying a ready-made trading robot. The main risk is that you know neither the rules nor how they were tested, while no one can guarantee the promised returns in this field. Before handing over money, check who tested the algorithm and how, and beware of unlicensed auto-trading services: FINRA has issued a separate warning about them.

What does “Tinkoff algorithmic trading” mean?

This is slang for trading through the T-Invest API, the official programming interface of the T-Bank brokerage. It provides access to data and orders from code, a testing sandbox, and SDKs for popular languages. Algorithmic trading through an API is still algorithmic trading; the only difference is that your robot submits the orders instead of you doing so manually through a terminal.

Can you test an algorithm without programming?

Yes. Part of the testing process is writing the rules down, which requires no code at all. Platforms with visual builders can run tests on historical data—for example, Midas BackTester, where entry and exit conditions are configured through settings. Code becomes necessary when the builder can no longer handle the logic of the rules.

What you will learn
  • Understand algorithmic trading in simple terms and what a trading algorithm consists of
  • Learn to distinguish algorithmic trading from trading bots and HFT
  • Get a reproducible algorithm-testing protocol: rules, costs, backtest, and forward test
beginner

Was this material useful?

Feedback is not available for this language version yet.

Comments

Source comments are not translated and are never replaced with Russian text.

Subject-matter contributor
Max Vitkovsky
Market analyst

Analyses cryptocurrency market structure, levels and on-chain context, with attention to risk and invalidation conditions.

TradingView chart with Buy and Sell signals from the Midas indicator
Midas multi-indicator for TradingViewOne of the most advanced indicators for trading
  • Non-repainting signals
  • Interactive technical analysis
  • 7 strategies to choose from
Midas multi-indicator for TradingViewSignal, stop, and 3 targets - directly on the chart
  • Signal locks at candle close
  • Stop and 3 targets build automatically
  • The trade plan is visible before entry