Python in trading – data analysis, automation and research

Python helps you organise market data, analyse a trading journal and repeat calculations without manually copying formulas. It is especially useful when a spreadsheet becomes too small or difficult to maintain. This article takes you from setting up an environment to a script that loads data, checks its quality and saves the results. It also explains how research in a notebook differs from software connected to a trading account, and which safeguards that integration requires.

Python supports repeatable data analysis and result checks; code cannot replace data quality or sound testing methodology.

The date of an observation is not its availability time

A notebook can join two tidy tables and still use information from the future. The problem may be the joining key rather than the formula. A value describing a period is not necessarily available during that period. Store when it became available to the research process, together with the source and the observation it describes.

Our hypothetical example uses one instrument and one feature measured in index points. All times are UTC on 2026-10-31. Decisions occur at 10:00:00, 10:00:30 and 10:01:10. A rule may use only a feature available no later than the decision, with an age of at most 45 seconds. The feature condition is a value of at least 50 points. These arbitrary settings illustrate a data check, not a trading signal with demonstrated value.

The availability times below are assumed to be verified ingestion times from a synchronized clock. They are not guesses reconstructed from the latest downloaded file. In actual research, publication, receipt and processing may have separate timestamps; the usable time must reflect the information the particular process could access.

Match against the right timestamp

Hypothetical feature records; all times UTC
RecordPeriod labelAvailable to this processValue, points
A09:59:0009:59:5047
B10:00:0010:00:2053
C10:01:0010:01:2049

At the first decision, record A is available but record B is not. At the second, B has arrived. At the last decision, C is still in the future, even though its period label is earlier than the decision time. That last distinction is easy to lose when setting a convenient time index.

The official pandas merge_asof reference describes backward matching as choosing a right-hand key no later than the left-hand key. It also provides a tolerance and requires ascending time keys. Applied here, the decision time is the left key and availability time is the right key. Joining on a period label would answer a different question. With several instruments, also match the instrument key rather than borrowing another series' last observation.

Leave stale information missing rather than borrowing from the future

Result of the stated availability and age rules
Decision UTCLatest available recordAgeUsable valueCondition ≥ 50
10:00:00A10 seconds47False
10:00:30B10 seconds53True
10:01:10B50 secondsMissing: too oldUnknown

The first two ages come from 10:00:00 − 09:59:50 and 10:00:30 − 10:00:20. At the last decision, the latest available observation is B, but its age is 50 seconds, exceeding the 45-second limit by 5 seconds. C cannot fill the gap because it arrives 10 seconds after that decision.

Two of the three decision rows have a usable feature. Coverage is therefore 2 ÷ 3 = 66.67%, rounded to two decimal places. The missing row is not a feature-condition failure and should not silently become a zero. If the execution policy skips decisions with missing data, record that as a data-availability action, separate from the feature condition being false.

A backward match alone is insufficient when it permits stale data. A tolerance alone is insufficient if matching can look forward. The direction, timestamp meaning and tolerance work together.

Make a small data contract before a large backtest

For this example, the relevant pandas settings are direction="backward", a 45-second tolerance, and exact matches allowed. Sort both time keys and preserve the matched availability timestamp so the age can be checked afterwards. If several versions share an availability timestamp, resolve their order from the source's correction policy; do not let file order decide accidentally. This is a description of the required join, not a complete production data pipeline.

A small fixture containing the three records is more revealing than a long attractive equity curve. Check that the first decision cannot see B, that the second can see it, and that the last produces a missing value. Also retain the input data, time-zone interpretation, library versions, join settings and resulting rows. Re-running a notebook should reproduce the same information set before it reproduces the same profit.

This check demonstrates one boundary against look-ahead. It does not establish that the data are unbiased, revisions have all been handled, costs are realistic or a model predicts prices. Those remain separate checks. The full lesson below supplies environment setup, data-quality examples and the distinction between research code and a service connected to an account.

Three exercises with worked answers

The exercise data are hypothetical. Choose an answer, then check the calculation.

1. Which feature is usable at 10:00:00 UTC?

A becomes available at 09:59:50 with value 47. B is labelled 10:00:00 but becomes available at 10:00:20. Maximum age is 45 seconds.

Show the answer and explanation

A. Use availability time, not the period label. The backward match selects A and its age satisfies the 45-second limit.

  • A. A has been available for 10 seconds. B arrives after the decision and cannot be used.
  • B. The period label does not make B available before its 10:00:20 arrival.
  • C. Averaging in an unavailable observation still leaks future information.
  • D. Earlier-period information is allowed when it is available and within the stated age limit.
2. What should the join return at 10:01:10 UTC?

B became available at 10:00:20; C becomes available at 10:01:20. Maximum age is 45 seconds.

Show the answer and explanation

C. The correct missing value preserves the limitation of the information set. Filling it from C would rewrite what was knowable at the decision.

  • A. The stated contract includes an age limit as well as backward direction.
  • B. Nearest matching can choose future information and does not meet this contract.
  • C. B is 50 seconds old, beyond the 45-second tolerance; C arrives 10 seconds later.
  • D. Averaging does not repair either stale data or a future observation.
3. How should usable-feature coverage be reported?

The first two decision rows have usable values; the third has a missing value. There are three decision rows.

Show the answer and explanation

B. Count usable-feature rows over all decision rows. A skip policy for missing data is separate from classifying the feature condition as false.

  • A. A manufactured zero does not become an observed feature.
  • B. Usable data exist for two of three rows: 66.67% after rounding. Condition truth and data coverage are different measures.
  • C. That changes the denominator and measures the condition among known values instead of data coverage.
  • D. The example does not impose an all-or-nothing rule for the whole dataset.

From an information-set check to a reproducible workflow

Use the timestamp contract as you work through environments, data quality, code examples and account-connected automation below.

1. Where Python genuinely helps, and where it only looks like a solution

A spreadsheet copes with a trade journal for as long as it fits inside your patience – and where that boundary lies depends on the machine, the number of formulas and how the sheet is built, so no round number of trades will describe it for you. One boundary, however, is hard and depends on nothing, because it is written into the file format specification: a single Excel worksheet holds 1,048,576 rows and 16,384 columns [16]. One year of tick history for a single currency pair is a multiple of that number – and no trick gets around it.

Python is not magic here. It solves four specific problems that a spreadsheet either does not solve at all or solves at the cost of hours of work:

  • Data scale – you are limited by the machine's memory and the storage format, not by a worksheet row limit
  • Repeatability – the same script run tomorrow on the same data gives the same result. A spreadsheet with hand-dragged formulas guarantees nothing of the sort
  • Changing the interval without manual work – aggregating M1 to H4 while preserving OHLCV is a single resample call, not a column of helper formulas
  • Automating the fetching and tidying of data – a scheduled script will download, check and store data without you being present

That is all. Python does not give you a market edge, does not improve strategy quality and does not change your execution conditions at the broker. It shortens the distance between a question and an answer – and that is precisely why it shows you faster that an idea does not work.

Table comparing spreadsheets and Python across five working criteria
Choose for task scale and repeatability; assess strategy quality separately.

What Python does not do. It is not suitable for ultra-low-latency trading – there microseconds matter, and an interpreted language with a garbage collector is a poor choice. But the sentence "Python is too slow for trading" is equally false: for a strategy that enters at the open of the next H1 candle, computation time in Python is negligible compared with the time it takes an order to travel through the network and the broker's server.

The speed-up from vectorization comes from a mechanism, not from magic: an operation on a whole column runs in compiled numpy code rather than in an interpreter loop. The order of magnitude of the difference depends on the data, the type of operation and the hardware – if you want to quote a specific number, measure it on your own machine with the timeit module from the standard library [4] and record it together with the library versions. Quoting somebody else's benchmark without the environment is not a measurement.

A comparison of a trader's analytical tools:

Comparison of Excel, Python, Pine Script and MQL4/MQL5 across trading tasks
FeatureExcelPythonPine ScriptMQL4/MQL5
Data limit1,048,576 rows per worksheetLimited by machine memoryDepends on the TradingView planHistory supplied by the broker
Where the code runsLocallyLocally, on a server or in the cloudInside the TradingView environmentInside the MetaTrader terminal
Account accessNoneOnly through a broker API or an intermediary packageNone – an alert can trigger a further chainNative within the terminal
Data sourceWhatever you loadAnything, but you have to name itThe TradingView feedThe broker feed
ReproducibilityLow (manual formulas)High, if you freeze versionsMedium (Pine version and platform data)Medium (terminal build and broker data)
Learning curveLowMediumLow to mediumMedium to high

The distinction in the last row of the table matters more than it looks. Pine Script executes inside the TradingView environment, MQL inside the MetaTrader terminal, and Python – wherever you run it. That freedom means you are responsible for the environment: library versions, the system time zone, uptime, and whether the script has any right to touch the account at all.

The boundaries of this article. This is not a Python course and not a backtesting course. Test methodology – splitting into training and validation samples, forward testing, the cost model – belongs to the article Demo accounts, backtesting and forward testing. Code run inside the terminal, and keeping it alive on a server, is covered by Trading automation: EAs, scripts and VPS. Language models and their limits – AI and LLMs in trading. Here we deal exclusively with Python as a layer of data, computation and integration.
You do not have to abandon the spreadsheet. You export results from Python to CSV and open them in a spreadsheet, or the other way round: you keep your trading journal in a spreadsheet and load it into pandas for analysis. The openpyxl library lets you read and write .xlsx files directly from Python; its most recent release dates from June 2024 (3.1.5) [13] and in this particular case that is not a warning sign – the .xlsx format is settled and the library depends on neither NumPy nor pandas, so the rule from section 2 does not rule it out, it only tells you to know that state [AS OF: 2026-08-22]. Python extends the spreadsheet where the spreadsheet ends.

2. A reproducible environment: versions, venv, requirements

A very common reason why somebody else's script "does not work" does not lie in the code. It lies in the fact that the author ran it on different library versions and recorded that nowhere. In market data analysis this is not an inconvenience – it invalidates the result, because the result cannot be reproduced.

An environment is reproducible when you can state six things: the Python version, the isolation method, the frozen dependency versions, the data source with its date range, the time zone, and the random seed everywhere the result depends on randomness. A missing element means the result is a story, not a measurement.

A virtual environment is not optional. Installing libraries "globally" leads to a situation where updating one project breaks another. Isolation is free, takes a dozen seconds and rests on the venv module from the standard library [4]:

# Windows, PowerShell
py -3.12 -m venv .venv
.venv\Scripts\Activate.ps1

# macOS / Linux
python3.12 -m venv .venv
source .venv/bin/activate

# common to both systems
python -m pip install --upgrade pip
python -m pip install pandas numpy matplotlib requests python-dotenv
python -m pip freeze > requirements.txt

The last line is the one most often skipped. pip freeze records the exact versions of everything that actually got installed – including dependencies you did not know about. You put that file into the repository next to the code. Recreating the environment on another machine is then python -m pip install -r requirements.txt, not guesswork.

The environment used for the current offline verification of the computational examples in sections 4 and 9: Windows 11, Python 3.12.10, pandas 3.0.5 and NumPy 2.5.3, checked on 8 October 2026. The list below records the packages associated with those calculations; it is a limited inventory, rather than an export of every package installed on the machine[1][3].

# Dependency versions used for the local computational verification
numpy==2.5.3
pandas==3.0.5
python-dateutil==2.9.0.post0
six==1.17.0
tzdata==2026.4

# interpreter
Python 3.12.10

Notice that pandas also uses other packages: an environment description does not end with one library version. Dependencies can cause differences between machines. The installation commands above illustrate a project setup procedure; they are not a record of installation performed during this audit. Create the complete requirements.txt in your own environment with python -m pip freeze and keep it with the code.

Nor is this file a full description of the environment for the whole article, only of the environment for the computational sections, and that is how it must be read. The fragment that checks HTTP error handling in section 7 was run in an environment with requests 2.34.2 added, and the safety-gate test in section 8 needs no package outside the standard library. The versions of matplotlib and python-dotenv are not given, because they were not used in any example that was actually run – and listing them "for tidiness" would mean writing down a number nobody checked. If you are building an environment for the whole thing, treat the install command above as a starting point and freeze your own pip freeze; that is the only dependency file that says anything about your results.

Conceptual research notebook with UTC data, missing-value checks and result export, without order submission.
A notebook supports reproducible data analysis. Its output needs validation before use in a separate execution system.

Notebook or .py file? Both, but for different things. Jupyter is good when you do not yet know what you are looking for: you run a cell, look at the result, change a parameter. It has one property, however, that disqualifies it as a home for execution code – the state of the variables depends on the order in which cells were run, not on the order in which they are written in the file. A notebook whose cells were executed in the order 1–3–2 looks identical to one executed in sequence. Code that touches the account must be a plain .py file, run top to bottom, with tests and a log.

Anaconda and Google Colab are shortcuts with their own costs. Anaconda installs a large set of packages at once and has its own dependency manager, which makes starting easier but makes describing the environment precisely harder if you mix conda with pip. Colab runs in the browser without installation and is fine for learning, but the environment is recreated from scratch at every session and library versions change without your involvement. For material that has to be repeatable a year from now, both demand extra discipline.

Libraries to start with – four entries, not forty (there are five packages: the first entry is a pair):

  • pandas and numpy – data structures and computation
  • matplotlib – charts
  • requests – HTTP communication with an API
  • python-dotenv – loading configuration from a file outside the repository

Add technical indicators when you actually need them. One correction to older guides: TA-Lib publishes official binary wheels with the C library on PyPI, so for a supported OS, architecture and Python combination, a plain pip install TA-Lib requires neither an unofficial download nor your own compilation[9]. Check the particular wheel before installation; this is not a promise that it works on every computer. Metadata checked on 8 October 2026 lists TA-Lib 0.8.1 and pandas-ta still at 0.4.71b0, released in September 2025[13]. The latter pins numba==0.61.2, so checking its pandas requirement alone is insufficient. A historical installation test on Python 3.14.3, dated 22 August 2026, failed on that dependency with only versions >=3.10,<3.14 are supported. That observation does not automatically apply to the current examples running on Python 3.12.10. The present audit read PyPI metadata; it did not install or run TA-Lib or pandas-ta. The check rule alongside is therefore too narrow: a recent release and a compatible pandas requirement do not prove that the complete dependency set can be installed and run correctly. Check pinned compiled libraries, wheel availability for your interpreter and a small-data test too. Metadata for the latest two releases does not describe the project's entire history; assess earlier gaps in its repository.

Before you add a library, check the date of its last release. A project that has not been developed for a long time will sooner or later drift away from a new NumPy or pandas version – and then you either freeze old versions in a separate environment or rewrite the code. The date of the last release is visible on the package page on PyPI [13] and says more than the number of stars on GitHub. This applies especially to older backtesting frameworks.

The random seed. Everywhere the result depends on randomness – sample splitting, bootstrapping, simulation, model initialization – set and record the seed. In numpy: rng = np.random.default_rng(20260822) [3], and then use only that object. Without it, two runs of the same script give two different results and it is unclear which one you are describing.

3. pandas and numpy: OHLCV data, the time index, time zones

numpy handles computation on arrays of numbers, pandas handles structure: a DataFrame is an array with named columns and an index, most often a time index. When working with market data the time index matters more than the calculations themselves, because it decides whether you are computing what you think you are computing at all.

Loading – pd.read_csv() copes with files of millions of rows, recognises separators and will parse dates itself if you point it at a column. By default, however, it knows nothing about the time zone, and that is the first thing that has to be settled.

Changing the interval – aggregating M1 to H4 while preserving OHLCV is a single call: df.resample('4h').agg({'open':'first', 'high':'max', 'low':'min', 'close':'last', 'tick_volume':'sum'}). Watch out for two arguments nobody sets and which decide the interpretation: label determines whether the window is labelled by its start or its end, and closed – which edge of the interval belongs to the window. The default behaviour for most frequencies puts the label on the left edge [1], meaning the candle timestamp is the moment it opened; in pandas 3.0.5, resample('4h') over eight hourly candles from midnight yields the labels 00:00 and 04:00. If your signal convention assumes the close of the candle while the data is labelled by the open, you shift the entire result by one interval without noticing.

Rolling statistics – df['close'].rolling(20).mean() gives a moving average, .rolling(20).std() the deviation used for Bollinger Bands, .ewm(span=20).mean() an exponential average [1]. All of them are computed exclusively from data in the past relative to the current row – and that is the property on which the correctness of everything else rests.

Filtering – a compound condition is written once: df[(df['sma20'] > df['sma50']) & (df['rsi'] < 30)]. Parentheses around each condition are mandatory, because & binds more tightly than comparison in Python – omitting them gives an error rather than a silent wrong answer, and in this one place that is good news.

Consistent table of four synthetic OHLCV candles and data checks
A DataFrame format does not establish data quality; check values, time and volume definition.

The time zone is a decision, not a detail. Data from a broker usually carries the broker server's timestamp, data from an external provider is most often in UTC, and the operating system may use local time with clock changes determined by the chosen zone. If those three clocks get mixed, an analysis of "the London session" is studying something other than the London session.

The practical rule is to establish the source time zone first and perform calculations in UTC. For timestamps with an explicit offset or Z, use pd.to_datetime(column, utc=True). For server timestamps without an offset, first parse them, assign the confirmed zone with tz_localize() while handling ambiguous and nonexistent hours, then apply tz_convert("UTC"). Using utc=True alone treats timezone-naive values as UTC; it does not infer the broker’s zone. Convert to Europe/London only for presentation[1]. An explicitly zoned index and a recorded data source let you combine series consistently.

Broker server time is a separate value. Many brokers run their server in a zone offset from UTC, and the offset is sometimes changed together with the clock change in the US or in Europe. Do not assume the offset from memory: check it in the broker's specification and record it in the project configuration as a parameter, not as a number typed into the code. [FEATURE DEPENDS ON BROKER/ACCOUNT]

Missing data. OHLCV history has gaps: weekends, holidays, technical breaks, an instrument not quoted. pandas offers df.ffill(), which fills gaps with the last known value – and in price data that is usually a bad idea, because it creates candles with zero volatility and depresses the standard deviation. It is better to remove the missing periods and count how many there were.

A correction against older material. The form df.fillna(method='ffill'), common in guides from a few years ago, has been withdrawn: the method parameter of fillna() was marked deprecated in pandas 2.1 [2] and removed in pandas 3.0. That is a practical difference: the old form no longer prints a warning, it terminates the program with the message TypeError: NDFrame.fillna() got an unexpected keyword argument 'method'. The correct forms are df.ffill() and df.bfill(). The signature in the pandas 3.0.5 documentation no longer contains that parameter – DataFrame.fillna(value, *, axis=None, inplace=False, limit=None) [1]. The signature and the text of the message were checked by running them on pandas 3.0.5, not by reading the documentation. [AS OF: 2026-08-22]
Tick volume is not market volume. On the decentralised currency market a retail client does not get consolidated turnover volume – they get the number of quote changes from one specific broker's feed. It can be used cautiously as a proxy for activity, but a column named "volume" in a file is not market volume and is not comparable between brokers.

Several instruments at once. For currency portfolio analysis pandas offers a hierarchical index (MultiIndex): one DataFrame holds data for many pairs, indexed by pair and time. This lets you compute correlation between instruments on a common time axis – provided all the series have first been brought into the same zone and onto the same grid of timestamps. Without that you are computing correlation between data that is shifted relative to itself.

Saving results. df.to_csv() is human-readable and universal. df.to_parquet() gives a smaller file and faster reading, and along the way preserves column types and the time zone of the index [1] – CSV writes everything as text and the parsing has to be repeated on reload. For high-volume working data Parquet is more convenient, but it requires an extra write engine, so add it to requirements.txt.

Macro context in Python. Positioning reports and calendar data can be pulled with a script exactly like prices – with the same discipline about the time zone and the moment of publication. Interpreting that data, however, belongs to another part of the course: COT reports and positioning.

4. A minimal example: CSV → UTC → returns → gap check → save

Your first script should not send an order or even connect to a broker. It should do something useful, checkable and completely safe: load a file, sort out the time, compute returns, say plainly what is wrong with the data, and save the result.

Assumptions. A CSV file with the columns time,open,high,low,close,tick_volume. The time column in ISO 8601 format with a zone marker (Z means UTC). The interval is declared as hourly. The file used for the run deliberately contains three defects that occur in real exports: one duplicated timestamp, one missing hour and one empty volume cell. Those six rows are pasted straight into the code so that you can run the example and get exactly the same result without downloading any file – a result that cannot be reproduced is not a result. Environment: Python 3.12.10, pandas 3.0.5, numpy 2.5.3, Windows 11, [AS OF: 2026-10-08].

"""Minimal example: CSV -> UTC -> log return -> gap check -> save."""
import io
from pathlib import Path

import numpy as np
import pandas as pd

# Data inline in the code, so the result can be reproduced without downloading a file.
# Six rows with three deliberate defects: a duplicated 01:00 timestamp,
# a missing 03:00 hour and an empty volume cell at 02:00.
CSV_DATA = """time,open,high,low,close,tick_volume
2026-06-01T00:00:00Z,1.08140,1.08170,1.08131,1.08153,812
2026-06-01T01:00:00Z,1.08153,1.08190,1.08150,1.08176,640
2026-06-01T01:00:00Z,1.08153,1.08195,1.08149,1.08182,655
2026-06-01T02:00:00Z,1.08182,1.08188,1.08130,1.08141,
2026-06-01T04:00:00Z,1.08120,1.08125,1.08040,1.08050,903
2026-06-01T05:00:00Z,1.08050,1.08061,1.07980,1.07993,774
"""

OUTPUT = Path("EURUSD_H1_returns.csv")
INTERVAL = "1h"  # declared frequency of the input data


def load_data(source) -> pd.DataFrame:
    """Loads the CSV and sets a time-zone-aware index, in UTC.

    Deliberately does not sort: the order of rows in the file is itself
    information about the quality of the export. Sorting happens after the report.
    """
    df = pd.read_csv(source)
    # utc=True forces a single zone; without it pandas may return a naive index
    df["time"] = pd.to_datetime(df["time"], utc=True, format="ISO8601")
    return df.set_index("time")


def quality_report(df: pd.DataFrame, interval: str) -> dict:
    """The counters you have to see before anything is computed."""
    expected = pd.date_range(df.index.min(), df.index.max(), freq=interval, tz="UTC")
    return {
        "rows": int(len(df)),
        "index_duplicates": int(df.index.duplicated().sum()),
        "missing_cells": int(df.isna().sum().sum()),
        "missing_timestamps": int(len(expected.difference(df.index))),
        # Measured BEFORE sorting: after sort_index() this check would always be
        # true and would never detect a file with scrambled chronology.
        "file_chronology_ok": bool(df.index.is_monotonic_increasing),
    }


def add_returns(df: pd.DataFrame) -> pd.DataFrame:
    """Log return = ln(close_t / close_(t-1)). Unit: natural logarithm, dimensionless."""
    df = df[~df.index.duplicated(keep="last")].copy()
    df["log_return"] = np.log(df["close"]).diff()
    return df


def main() -> None:
    df = load_data(io.StringIO(CSV_DATA))  # in practice: load_data(Path("EURUSD_H1.csv"))
    print("quality check:", quality_report(df, INTERVAL))
    df = add_returns(df.sort_index())
    print("candles after deduplication:", len(df))
    print("log-return sum:", round(float(df["log_return"].sum()), 6))
    print("log-return standard deviation (1h and 2h intervals):",
          round(float(df["log_return"].std()), 6))
    df.to_csv(OUTPUT)
    print("saved:", OUTPUT)


if __name__ == "__main__":
    main()

The output of the run on the data pasted into the code and in the environment described – you can reproduce it exactly:

quality check: {'rows': 6, 'index_duplicates': 1, 'missing_cells': 1, 'missing_timestamps': 1, 'file_chronology_ok': True}
candles after deduplication: 5
log-return sum: -0.00148
log-return standard deviation (1h and 2h intervals): 0.000467
saved: EURUSD_H1_returns.csv

Interpretation. The script detected all three planted defects before it computed anything – and that is its entire value. The sum of log returns came to −0.00148, which with five candles remaining after deduplication – that is, four intervals between consecutive observed prices – means a total fall in the rate of about 0.15 per cent over the window studied. Six is the number of rows in the file, not the number of candles: one row was a duplicate. The standard deviation of 0.000467 is a quantity per single H1 candle, not annual and not daily; comparing it with anything without stating the interval makes no sense. Log return is dimensionless and additive over time – which is why you sum it rather than multiply, unlike simple returns.

Limitations. Five candles is an illustration of mechanics, not a statistical sample – nothing about the market follows from that many observations. The script does not model spread, commission or slippage, because it is not a backtest; it computes price returns, not an account result. Detecting a missing timestamp assumes the data really does have the declared hourly frequency – on data spanning a weekend the number of "missing" timestamps will be large and entirely normal, so the alarm threshold is set with the trading calendar in mind. A separate trap concerns the measure itself: the script detects the gap but does not fill it, so the return computed across the missing hour spans two intervals, not one. In this example that is one of the four returns, and the whole thing was nonetheless labelled a quantity "per H1 candle" – that is a simplification, not a precise measure. Done honestly you have two roads: either reindex the data onto a full hourly grid and leave an empty value in the gap, or report the mixing of horizons as an explicit limitation of the measurement.

Why chronology is checked before sorting. If load_data() ended with a sort_index() call, the file_chronology_ok field would always be true – the check advertised in the report would have no way of detecting anything, and a file with scrambled ordering would pass without a trace. A check that cannot fail is worse than no check at all, because it gives a false sense of validation. That is why the ordering is measured on the data as loaded from the file, and sorting only happens after the report.

Verification status: this fragment was run in the environment stated and the output above is the real output of the program. On other pandas versions the dictionary formatting or the rounding may look different.

5. Visualization: one question per chart

A single number summarising a result hides what matters most: when the strategy was losing, for how long, and whether the whole result rests on three trades. A chart is not a decoration in a report – it is a way of asking the data a question that a table does not answer.

matplotlib is the basic charting library in Python: static and fairly clumsy syntactically. plotly gives interactive charts – hover over a point and see the date and value, zoom into a fragment, export to an HTML file. On very large datasets it can be slower and it needs a separate installation. For exploration in a notebook plotly is more convenient; for charts saved into a report, matplotlib.

Four charts worth being able to draw, because each answers a different question:

  1. Equity curve – cumulative result over time. It answers "whether and when it grew", not "how much will I make"
  2. Drawdown chart – distance from the running peak at every moment. It shows the deepest drawdown and the time needed to recover it. Always state whether you compute it on balance or on running equity, and whether in per cent or in currency
  3. Session heat map – result broken down by hour and day of the week. It requires the time zone to have been sorted out first, otherwise it describes hours that do not exist
  4. Distribution of returns – a histogram of individual trade results. It shows the fat tails and the asymmetry that a single risk metric will not show
Synthetic equity and running-peak chart with a minus ten percent drawdown
Drawdown is measured from the running peak, with explicit handling of capital flows.

For candlestick charts straight from a DataFrame there is mplfinance, a layer on top of matplotlib – with a caveat that follows directly from the rule set out in section 2: its last release dates from August 2023 and it still carries a pre-release number (0.12.10b0) [13] [AS OF: 2026-10-08]. That does not disqualify it in advance, but before you add it to requirements.txt, check on your own data whether it works with your matplotlib and pandas versions – a new release will not do that for you. To turn a script into a simple dashboard with sliders and drop-downs there is streamlit, a project released regularly [13], launched with streamlit run dashboard.py. Both libraries save time, both add dependencies to requirements.txt, so add them consciously.

A practical rule: if you cannot say in one sentence what question a given chart answers, you do not need it. A chart without a question is decoration, and decoration in results analysis can be expensive – it suggests conclusions the data does not contain.

6. Backtesting in Python: what belongs to the code and what to the methodology

This is where a boundary runs that is easy to miss. Python is responsible for the implementation of the test: loading the data, computing the signal, assigning the result to the right period, charging costs, computing the metrics. It is not responsible for the methodology: the sample split, the number of variants tested, the execution model, the assessment of how robust the result is. Methodology is the subject of a separate article – Demo accounts, backtesting and forward testing – and no better library can substitute for it.

pandas on its own is not a backtest. Multiplying a signal column by a returns column gives a series of results, but it models nothing of what happens between decision and execution: the moment of entry, the entry price, spread, commission, swap points, partial fills, order rejection. That can be an acceptable simplification at the idea-screening stage – provided you call it a simplification and not a result.

Fixed versus variable spread costs for three synthetic trades
Under the stated assumptions, costs are USD 3.00 or USD 8.80; these are not typical-spread claims.

If you want to go beyond your own loop, three approaches to ready-made tools exist in the Python ecosystem. The table below compares them by how they work, not by performance promises – concrete timings depend on the data, the hardware and the version, so if you need them, measure them yourself and record the environment.

Comparison of full event-driven, vectorized and minimal event-driven backtesting
FeatureFull event-driven approachVectorized approachMinimal event-driven approach
Example librarybacktradervectorbtbacktesting.py
How it computesCandle by candle, with its own order and portfolio modelOperations on whole arrays at onceCandle by candle, simplified model
Amount of code for a simple strategyLarge (classes, inheritance)Small, if you think in columnsSmall
Natural usePortfolio logic, many instruments, complex ordersMass screening of variants and initial filteringLearning and quickly checking whether an idea makes sense
Main costSteep learning curveHarder debugging; a silent shift error is easyLimitations with complex strategies
What to check before useThe date of the last PyPI release, compatibility with your pandas and NumPy versions, how costs and the moment of fill are modelled
The development pace of these three projects differs greatly. This is not a detail for collectors: a framework that has stopped keeping up with pandas and NumPy releases will sooner or later force you to freeze old versions in a separate environment. Before you pick any of them, open its PyPI page and check the date of the last release and the range of supported Python versions. Now that you know what to look for, these three projects diverge more sharply than a shared table suggests: backtrader has multi-year gaps between releases behind it, and its last release dates from April 2023 – community forks of varying upkeep exist alongside it; vectorbt exists in parallel as an open project and as a separately developed commercial version (the open release dates from July 2026), so first establish which one the documentation you are reading refers to; backtesting.py has a multi-year break in releases behind it, but it broke that break and shipped another version in July 2026 – the past tense matters here. All three dates come from the package registry [13]. None of these things disqualifies a library in advance – what disqualifies it is incompatibility with the versions you work on. [AS OF: 2026-08-22]

The last row is not a formality. Every framework makes some assumption about the price at which and the moment when it fills an order – and it is that assumption, not the logic of your strategy, that often decides the result. Before you trust any library, find the answer to three questions in its documentation: at what price it fills an entry, how it charges cost, and what it does with a price gap between candles.

Two synthetic curves with an explicit in-sample and out-of-sample boundary
Separate variant selection from evaluation on later data; report every trial.

The freedom of code is simultaneously a risk. A tester built into a platform imposes certain rules and thereby protects you from some errors. Your own code protects you from nothing: it will not ask whether the training and validation data are separated, it will not notice that the signal uses a price that did not exist at that moment, it will not count how many variants you tested. That moves the entire responsibility onto the author – and that is why the next sections deal with exactly what can be broken silently in code.

7. Broker APIs: authentication, limits, errors, the test environment

The sentence "the broker provides an API" is sometimes read as "I have unlimited access to the account from a script". That is not how it works. An API is a set of endpoints with authentication, permissions, a request rate limit and a defined set of error codes. It is sometimes, though not always, split into a test and a production environment – and how that split is done is a separate question for the documentation, not a rule you can assume. Before you write the first line you should be able to answer nine questions: what authentication looks like, what permissions the token has, how many requests per second you may send, how the test environment is distinguished from production, what data types it returns, what error codes it defines, whether there are regional restrictions, what the connection-keeping policy is, and whether the token has any right to place orders at all.

Architectures for MT5 IPC, TWS or IB Gateway, and direct REST APIs
A library does not remove a required terminal or intermediary application.

Limits are concrete and published – but you have to read which limit it is. That distinction gets lost in most guides, and it decides how you design the loop. At OANDA v20 the two numbers sit in two different documents and mean two different things. The developer guide gives the enforced value: "120 requests per second. Excess requests will receive HTTP 429 error" for the REST API, alongside a limit of twenty active streams and two new connections per second – all counted for the IP address sending the requests [15]. The best-practices document, by contrast, gives a recommendation: the vendor advises limiting yourself to one hundred requests per second within an established connection and to two new connections per second [5]. [AS OF: 2026-08-22]

So one hundred per second is the threshold the vendor advises you to stay below, and one hundred and twenty is the threshold above which the server answers with error 429. Code written on the assumption that "100/s is the maximum" will do no harm, but code that takes that number for a hard limit and does not handle 429 will fall over at the first overshoot – because the enforced limit lies somewhere other than the recommendation. These are one provider's numbers, not a market rule: at another broker they will be different and [FEATURE DEPENDS ON BROKER/ACCOUNT]. Check them in your own provider's documentation before you write a polling loop.

A correction against popular guides – and against an earlier version of this paragraph. A lot of material circulates the figure of "about 30 requests per second" for OANDA. It is out of date. A more common and harder-to-spot error, however, is something else: quoting the recommended 100 requests per second as a maximum. That is what this article did before the correction. A recommendation and an enforced limit are two different quantities from two different documents by the same vendor [5] [15], and code designed around a confused limit either wastes throughput or runs into a block with no handling prepared. Verify limits in the documentation, not in a tutorial – and check whether the number you are reading is advice or a cut-off threshold.

The test environment is a different host, not a different mode. At OANDA the split is visible in the address itself: api-fxpractice.oanda.com for the practice environment and api-fxtrade.oanda.com for production, with an analogous pair of addresses for the data stream [15] [AS OF: 2026-08-22]. That is good news, because the mistake can be caught in code: the production host can be fenced off with an extra condition. It is worse when a provider uses a single address and distinguishes environments only by the token – then the only barrier is your configuration.

Four typical paths for connecting Python to an account – each with a different architecture, not a different level of "sophistication":

Broker API connection models, runtime requirements and operational limits
SolutionWhere the connection actually runsConditionsNotes
OANDA v20 (REST + streaming)Script → broker servers, directly over HTTPAn account with that broker; separate hosts for the practice and production environmentsPublic documentation, limits described explicitly. This is not an industry standard, it is one provider's API
Interactive Brokers (TWS / IB Gateway)Script → a locally running intermediary application → broker serversRequires a running TWS or IB Gateway application; asynchronous modelClosing the intermediary application breaks the script's connection. Wrapper libraries simplify the handling but do not remove that dependency. Watch the name: the widely quoted ib_insync has had no new release since July 2023 and rests on an older TWS API release; an actively maintained continuation is ib_async [13] [AS OF: 2026-10-08]
The official MetaTrader5 packageScript → an installed MT5 terminal on the same machine → broker serverThe MT5 terminal must be installed on the same machine; the initialize() call starts it if it is not running, and uses the login details stored in the terminal or passed in the call [18]; the integration has been available since build 2085 (2019) [7]This is communication with the terminal, not an independent broker API [6]. The dependency on the terminal is a property, not a defect. The official PyPI package installs on Windows only – on macOS and Linux it requires running the terminal together with Python under Wine, or a separate intermediary layer [FEATURE DEPENDS ON VERSION/ENVIRONMENT]
An external cloud bridge (e.g. MetaApi)Script → external service → a terminal in the provider's cloud → broker serverRequires handing account access to a third party; pricing and limits depend on the planAdds a link to the chain and a point of trust. A bridge that is to place orders needs the master password, not the investor one – that is, the right to dispose of the account, not merely to read it. Check pricing with the provider [FEATURE DEPENDS ON PLAN]
The investor password and the master password are two different decisions. An account at a MetaTrader broker has two passwords. The investor password gives read-only access: a view of positions and history, with no right to place or modify orders. The master password gives full control over the account. To an external service – a journal, a results verifier, a statistics dashboard – you give at most the investor password. A cloud bridge that is to send orders cannot by definition work with the investor password: to function it needs the master password, so connecting it is a qualitatively different decision from plugging in a journal. Check in the current documentation of the specific provider what access it actually demands. If the master password has already been handed over and you do not want to keep that access alive: change it in the terminal or in the broker's dashboard (this invalidates the third party's access), review the order history for operations you do not recognise, and enable additional authentication wherever the broker offers it. And one more thing: even read-only access reveals your style, your working hours and your position sizes – that is a privacy decision, not a formality.

Outside the currency market it is also worth knowing ccxt – a library that unifies access to cryptocurrency exchanges. It does not apply to an FX/CFD account at a retail broker, but it is sometimes mistaken for a universal solution.

cTrader. If your platform is cTrader, algorithms are written in the cTrader Algo environment, which natively supports both C# and Python – including cBots, indicators and plugins [8] [AS OF: 2026-08-22]. That is a different model from the ones described above: the code runs inside the platform, not as a separate process connecting to an API. Check the range of functions and the way things are launched in the vendor's current documentation, because the product is under active development.

Keys and passwords: never in the code

An API key typed into a script travels with it into the repository, into the backup and into the version history – and it does not vanish from the Git history when you simply delete the line. Public repositories are automatically scanned for such strings. The only acceptable places for a secret are an environment variable, a configuration file kept outside the repository and listed in .gitignore, or a secrets manager that supplies the value through one of those.

"""Configuration and secrets: nothing sensitive goes into the code file."""
import os
from dataclasses import dataclass

HOSTS = {
    "practice": "https://api-fxpractice.oanda.com",
    "live": "https://api-fxtrade.oanda.com",
}


class MissingConfiguration(RuntimeError):
    """Raised when data is missing without which we must not start."""


@dataclass(frozen=True)
class Configuration:
    token: str
    account: str
    environment: str

    @property
    def host(self) -> str:
        return HOSTS[self.environment]


def _required(name: str) -> str:
    value = os.environ.get(name, "").strip()
    if not value:
        # The absence of a default is deliberate: an empty token would send the request
        # without authorization instead of stopping the program.
        raise MissingConfiguration(f"Missing environment variable {name}")
    return value


def load_config() -> Configuration:
    environment = os.environ.get("BROKER_ENV", "practice").strip().lower()
    if environment not in HOSTS:
        raise MissingConfiguration(f"BROKER_ENV must be one of {sorted(HOSTS)}")
    return Configuration(
        token=_required("BROKER_API_TOKEN"),
        account=_required("BROKER_ACCOUNT_ID"),
        environment=environment,
    )

Three decisions in this fragment are deliberate. The default environment is practice, not production – a configuration mistake then leads to a demo account, not a real one. A missing environment variable stops the program instead of substituting an empty string. And nowhere is there a default value for the token, not even a commented-out one, because a commented-out secret is a disclosed secret.

The python-dotenv mentioned earlier does not replace this code – it precedes it. Calling load_dotenv() (after from dotenv import load_dotenv) loads a .env file kept outside the repository into the process environment variables; only then does load_config() read them. Thanks to that the configuration function does not know, and does not need to know, where the value comes from: a file, system settings or a secrets manager. The .env file itself goes into .gitignore along with the whole configuration directory.

Fetching data: timeout, retries, response codes

A request with no time limit can hang indefinitely and freeze the whole process. A request retried without limit can exhaust the rate limit and get you cut off. The fragment below shows the minimal set of safeguards for reading data – and one distinction that later saves the account: you may only retry idempotent operations, that is, ones that when repeated do not change state on the broker's side.

import logging
import time

import requests

TIMEOUT_S = 10.0        # connect/read inactivity seconds, not a total job deadline
MAX_ATTEMPTS = 4            # number of attempts including the first
BACKOFF_S = 1.0         # base of the exponential delay, in seconds

log = logging.getLogger("data")


class ApiError(RuntimeError):
    """An error that cannot be fixed by retrying."""


def fetch_candles(session: requests.Session, host: str, token: str,
                   instrument: str, parameters: dict) -> dict:
    """Retries GET only - a request that changes nothing on the broker's side."""
    url = f"{host}/v3/instruments/{instrument}/candles"
    headers = {"Authorization": f"Bearer {token}"}

    for attempt in range(1, MAX_ATTEMPTS + 1):
        delay = BACKOFF_S * 2 ** (attempt - 1)
        try:
            response = session.get(url, headers=headers, params=parameters, timeout=TIMEOUT_S)
        except requests.RequestException as error:
            if attempt == MAX_ATTEMPTS:
                raise ApiError(f"No connection after {MAX_ATTEMPTS} attempts") from error
            log.warning("attempt %s: %s", attempt, error)
            time.sleep(delay)
            continue

        if response.status_code == 429:
            # Rate limit exceeded. The Retry-After header, if the broker returns it,
            # is more trustworthy than guessing for yourself.
            try:
                wait = float(response.headers.get("Retry-After", delay))
            except (TypeError, ValueError):
                # The specification also allows an HTTP date instead of a number of seconds;
                # without this branch float() would kill the whole data download.
                wait = delay
            log.warning("rate limit, waiting %.1f s", wait)
            time.sleep(wait)
            continue

        if 500 <= response.status_code < 600:
            log.warning("error serwera %s, ponawiam", response.status_code)
            time.sleep(delay)
            continue

        if response.status_code != 200:
            raise ApiError(f"HTTP {response.status_code}: {response.text[:200]}")

        try:
            data = response.json()
        except ValueError as error:
            raise ApiError("Invalid JSON response") from error
        if not isinstance(data, dict):
            raise ApiError("JSON response must be an object")
        if not isinstance(data.get("candles"), list) or not data["candles"]:
            raise ApiError("No candles in response - check instrument and date range")
        return data

    raise ApiError(f"No valid response after {MAX_ATTEMPTS} attempts")

Verification status: tested offline, without connecting to a broker. The published fetch_candles() function was run with an in-memory HTTP-session mock rather than a real server. Nine scenarios cover 429 with Retry-After in seconds, 503 followed by success, an empty candle list, 404, an HTTP-date header, exhausted attempts, a connection exception, invalid JSON, a non-object response and an invalid candles type. Calls to sleep() were replaced with a record of the requested delay; the test opens no sockets and measures no network timing. Environment: Python 3.12.10, requests 2.34.2, Windows 11, checked 2026-10-08. The actual scenario report follows:

A: 429 seconds -> 503 -> 200: calls=3; waits=[3.0, 2.0]; one candle
B: empty candles: calls=1; waits=[]; expected error
C: HTTP 404: calls=1; waits=[]; expected error
D: HTTP-date fallback: calls=2; waits=[1.0]; one candle
E: retry limit: calls=4; waits=[0.0, 0.0, 0.0, 0.0]; expected error
F: transport failure: calls=4; waits=[1.0, 2.0, 4.0]; expected error
G: invalid JSON: calls=1; waits=[]; expected error
H: non-object JSON: calls=1; waits=[]; expected error
I: wrong candles type: calls=1; waits=[]; expected error

What this result confirms and what it does not. It confirms the expected behaviour in nine prepared scenarios. A checks that a 429 selects the server's three-second delay rather than the code's one second; D checks the fallback when float() cannot parse an HTTP date. F checks that timeout=10 is passed, four attempts are made and an exception ends the simulated transport failures. It does not establish a deadline for a real connection: a requests timeout is not a total job deadline, and waiting was mocked here. B, C and G–I check rejection of empty or invalid responses. The test does not verify API availability, every data field or network behaviour at a particular broker.

It confirms nothing about the broker itself, however. The endpoint path, the parameter names, the shape of the response and whether the provider returns Retry-After at all are properties of one specific API [FEATURE DEPENDS ON BROKER/ACCOUNT] and need checking in its documentation and testing on a practice account. The mock proves the correctness of your code, not the correctness of your assumptions about somebody else's server – and that distinction is the entire value of this test.

Polling versus streaming with separate quote, request and receipt times
Fast receipt of a message does not establish quote freshness or order-execution timing.

Latency has to be measured, not quoted. The ranges that circulate in guides – "50–200 ms for this API, 100–500 ms for that one" – are worthless, because they state neither the client's location, nor the link, nor the time of day, nor the measurement method. Instead of copying somebody else's numbers, separate what you are measuring: the response time of the data endpoint, the time from sending an order to confirmation of acceptance, the time to confirmation of the fill, and the age of the market data at the moment of decision. Those are four different quantities and only one of them is what is colloquially called "latency". Measure each of them in your own chain, record the result in the log, and quote it together with the date, the broker and the number of attempts. An ICMP ping is none of those four values.

Polling or streaming. With cyclical REST polling the age of the data depends on the interval between requests: polling every five seconds means that in the worst case you make a decision on a price from five seconds ago, and more frequent polling costs rate limit. A stream — WebSocket or HTTP streaming, depending on the API — reverses the arrangement – it is the server that sends an update when one arises – and it makes sense where reaction within a candle matters, or where polling would eat the limit. For a strategy entering at the open of the next H1 candle, plain polling is enough and is simpler to maintain. A stream, on the other hand, adds three problems that polling does not have. First, the gap after reconnection: when the connection drops for thirty seconds, nobody replays those thirty seconds from the socket – the missing fragment has to be fetched with a separate historical request before you can call the series complete. Second, detecting a dead connection: a socket that has stopped delivering data looks from the code exactly like a market where nothing is happening, so you need a presence signal (a heartbeat or a keep-alive message) and your own silence counter after which you declare the connection broken and re-establish it. Third, ordering and duplicates: after resuming you can receive again a message you have already processed. That is the same problem as with orders – it is solved by an event identifier and a check of whether it has already been recorded.

Separate limits for data and for orders. A serious API separates the price stream from the transactional one, and the limits for operations that change account state are sometimes far lower than for reading. Code that in a nervous market tries to modify a stop-loss a dozen times a second may be cut off precisely on the transactional path – and leave you with an open position to which you temporarily have no programmatic access. That is an argument for writing the modification rate limit on your own side rather than counting on the broker to forgive.

Automation does not change execution conditions. The broker's order execution model, how flow is handled and the quality of the feed affect the result regardless of whether a human or a script sends the order – and with strategies sensitive to entry cost they can decide the outcome. That is the subject of the broker-selection part of the course: execution models and execution quality. From the code's point of view one conclusion suffices: an API speeds up the sending of a request for execution, but it does not create liquidity that is not there. This is especially visible on days of violent moves. On 15 January 2015 the Swiss National Bank removed the minimum exchange rate of 1.20 francs per euro and simultaneously cut the rate to −0.75 per cent [17]. The mechanism that operated then is general and requires trusting no anecdote: if there is no liquidity on the other side at the level of a protective order, the order does not fill at the price written in, but at the first available one – and how far away that lies is decided by the order book, not by your connection. The scale of what happened at particular brokers at the time is described in the broker-selection part of the course; here the conclusion for the code is enough: speed of sending does not create a price at which nobody wants to trade.

8. From notebook to service: how execution code differs from a script

This is the real boundary of this article. A notebook that computes journal statistics can blow up halfway through and nothing happens – you run it again. Code that is allowed to touch the account leaves state behind after the same error: an open position, a partially modified order, a double entry. The difference is not one of code quality, but of the fact that one of them has irreversible consequences.

A research notebook ≠ an execution program. Before any code gets the right to place orders, it must have the full set: configuration separated from the code · secrets outside the repository · a log of every decision and every server response · tests of the logic that run without a network · retries with a limit and only for idempotent operations · timeouts on every network call · state that survives a process restart · monitoring with a presence signal · a kill switch that stops new entries · a deployment procedure describing how a new version is rolled out. Missing even one element means you have a prototype, not an execution program – and that is how it should be treated, no matter how good the equity curve from the test looks.

Three levels of automation – differing not in technology, but in who makes the final decision:

Level 1: notifications. The script checks conditions and sends a message. It has no access to the account; a token for placing orders is not needed. The decision and the execution are taken by a human. This is the only level at which an error in the code costs nothing but irritation.

Level 2: preparation with confirmation. The script assembles the order – instrument, direction, size – and waits for an explicit confirmation from the operator. Only then does it send. This level catches arithmetic mistakes before they become a position, and keeps the human in the decision loop. For a retail trader who does not intend to maintain software, this is usually the destination level, not a transitional stage – but that is an editorial judgement, not a research finding.

Level 3: running without confirmation. The script opens and closes positions on its own. It requires everything from the box above, a test on a practice account, then on an account with minimum position size, and supervision through the first period of operation. How many trades are enough before moving on is a question about sample size and statistical power, not about a round number; it belongs to the article on testing.

Offline-analysis branch separated from gates and the execution adapter
Establish analytical correctness first; submission requires separate design, tests and state confirmation.

An execution layer with safety gates

If you show code that places an order, you must also show what stops it. The module below is runnable in full and contains not a single network call: it builds an order, checks the limits and stops at the gates. The sending itself is a separate fragment – and deliberately not code.

"""Execution layer: validation, test mode and an explicit gate before live mode."""
import logging
import os
import sys
import time
import uuid

ALLOWED_INSTRUMENTS = {"EUR_USD"}
MAX_UNITS = 1_000          # units of the base currency, not lots - the convention depends on the API

# The live-mode confirmation cannot be read out of this file, because it is not here.
# The program takes it from an environment variable, and accepts as a correct value the
# number of the account the operator consciously wants to trade - typed by hand in the shell
# before starting. The reach of this barrier is described in the box below the test output.
CONFIRMATION_VARIABLE = "BROKER_LIVE_CONFIRMATION"

# Without this configuration no log.info entry is created: the default root level
# is WARNING and there is nowhere to write. The file leaves a trace after a failure, the
# stream shows the same thing live. In a larger program the logging configuration
# belongs to the program's entry point, not to a module.
# Format audit timestamps in UTC with an explicit Z marker.
logging.Formatter.converter = time.gmtime
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s.%(msecs)03dZ %(levelname)s %(name)s %(message)s",
    datefmt="%Y-%m-%dT%H:%M:%S",
    handlers=[logging.FileHandler("execution.log", encoding="utf-8"),
              logging.StreamHandler(sys.stdout)],
)

log = logging.getLogger("execution")


class SafetyGateError(RuntimeError):
    """Stops the order before it leaves the process."""


def new_order_id() -> str:
    """Called ONCE per order intent and stored before sending.

    The same value must come back on every subsequent attempt at the same
    order - otherwise there is nothing by which to recognise a duplicate.
    """
    return str(uuid.uuid4())


def build_order(instrument: str, units: int, order_id: str) -> dict:
    if instrument not in ALLOWED_INSTRUMENTS:
        raise SafetyGateError(f"Instrument is not allowlisted: {instrument}")
    # bool is a subclass of int, so isinstance(True, int) is true: without an explicit
    # rejection a boolean would pass validation and end up in the payload.
    if isinstance(units, bool) or not isinstance(units, int) or units == 0:
        raise SafetyGateError("Size must be a nonzero integer")
    if abs(units) > MAX_UNITS:
        raise SafetyGateError(
            f"Size {abs(units)} exceeds limit {MAX_UNITS}")
    return {
        "order": {
            "type": "MARKET",
            "instrument": instrument,
            "units": str(units),
            # The identifier comes from outside and does not change between attempts.
            # If it were created here, every retry would carry a different value.
            # The name of this field and its constraints belong to the specific API.
            "clientExtensions": {"id": order_id},
        }
    }


def _operator_confirmation() -> str:
    """Reads a value from outside this file. The code does not know it and has it nowhere."""
    return os.environ.get(CONFIRMATION_VARIABLE, "").strip()


def submit_order(session, cfg, instrument: str, units: int, order_id: str,
                  test_mode: bool = True) -> dict | None:
    """By default sends nothing. The production host requires two decisions."""
    order = build_order(instrument, units, order_id)

    if test_mode:
        log.info("TEST MODE [%s] order built; nothing sent: %s",
                 cfg.environment, order)
        return None

    if cfg.environment == "live" and _operator_confirmation() != cfg.account:
        raise SafetyGateError(
            "Production host requires explicit operator confirmation")

    # The gates have passed - and this is where the module ends. There is no sending in it,
    # because there is no honest way to run it; its structure is described in the sketch below.
    raise NotImplementedError(
        "Sending is not implemented in this module - see structural sketch")

The order identifier is created once, not once per attempt. For a duplicate to be recognisable at all after a dropped connection, the value must be computed on the intention to place the order, stored durably before sending, and reused on every subsequent attempt at that same order. If uuid.uuid4() sat inside the order building, every retry would send a different value and there would be no basis for treating the second request as a repeat of the first. That is why build_order() takes the identifier as an argument rather than generating it itself.

What that identifier does not solve. The clientExtensions field in the payload above is one provider's solution, not an industry standard, and it is not a documented guarantee of idempotency. OANDA's documentation describes it as optional custom data attached to an order and separately warns: "Do not set, modify, delete tradeClientExtensions if your account is associated with MT4" [14] (checked 2026-08-22). There is no promise there that a repeated market order with the same identifier will be rejected as a duplicate – and a market order fills immediately, so the window for recognising a repeat is minimal. Recognising a duplicate therefore rests not on a field in the payload, but on two things on your side: a durable register of the intent written before sending, and reconciling it against the list of orders and transactions fetched from the broker after a failure. Check the field name and its constraints in your own API's documentation – at another provider it is called something else or does not exist.

Sending an order: a structural sketch

Below there is no function to copy. There is a structural sketch: the order of the steps and the names of the operations, written so that they can be carried into your own code, but not so that they can be pasted and run. That form is a choice, not an omission. The editors did not run this branch and do not intend to: sending an order requires an account at a broker, and transactional code checked on somebody else's account is not a test, it is somebody else's risk. A complete function would therefore land here as an artefact nobody ran – and such an artefact teaches, above all, trust in unverified code. We made the same choice for the MQL sketches in art. 11.5 and for the Pine Script sketch in art. 11.2.

STRUCTURAL SKETCH - sending an order and handling a missing response
A directional record for the HTTP layer. This is not complete, runnable code.

declaration: StanNieznany - the response did not arrive, so it is not known whether
             the order exists. A separate type, not a subclass of a network error: a network
             error may be retried, this state must never be retried.

input:  the order (built and validated), order_id, configuration, HTTP session
output: the broker's response or StanNieznany - never a silent success

1. DURABLE REGISTER - before anything else
   write outside process memory: order_id, UTC timestamp,
   instrument, units, environment, status := INTENT
   force the write to disk before you go further
   without this step a process restart loses the information about the intent,
   and after starting the program does not know what it has already tried

2. JOURNAL - also before sending
   write to the log: order_id + environment + the content of the order
   the token never goes into the journal
   mask the account number down to the last four characters
   the journal is read by a human after the fact; the register from step 1 is read by the program

3. ONE REQUEST, ZERO RETRIES
   POST to the order path indicated by your API's documentation
   authorization header with the token from configuration, never from the code
   a timeout is mandatory - without it the call can hang forever

4. THE RESPONSE DID NOT ARRIVE (timeout or transport error)
   DO NOT retry - POST is not idempotent
   status in the register := UNKNOWN
   raise StanNieznany
   STATE RECONCILIATION: query the broker for orders and transactions
   from the last few minutes, look for order_id in them, and only after
   establishing whether the order exists, make a new decision
   (this sketch does not contain that procedure - see the paragraph below the sketch)

5. THE RESPONSE ARRIVED
   write to the log: HTTP code + truncated response body
   if the code is outside (200, 201) -> status := REJECTED -> raise an error
   if the body is not JSON          -> status := UNKNOWN  -> raise StanNieznany
   otherwise                        -> status := ACCEPTED -> return the response

what this sketch does not and cannot contain:
   no ready-made function that could be pasted and run against an
   account - nor the name of the protective-level field, because that comes
   from the documentation of a specific API, not from somebody else's example.

What this sketch does not do – and that is as important as what it describes. It does not add protective levels: neither a stop loss nor a take-profit level. That is not an oversight – the convention for expressing them differs between APIs (separate payload fields, distance or absolute price, their own time in force), so such a fragment comes from your own broker's documentation, not from somebody else's example. The consequence is practical and concerns exactly step 4: after a StanNieznany you may have an open position with no protection and no certainty that it exists at all. In code that is allowed to send orders, the protective level travels in the same request as the entry – otherwise a window opens in which the position lives without a stop.

Protective levels are not the only thing missing, either. From the list in the box "A research notebook ≠ an execution program", neither the runnable module above nor this sketch yet has monitoring, a kill switch or a deployment procedure; state that survives a restart appears in the sketch as step 1, but only as a requirement, not as an implementation. The section on logs, state and tests talks about those elements – talks, rather than shows in code. The conclusion is one and the same as in the box: this is material for learning architecture, not an execution program.

The safety gates were tested offline – with no network, no broker and no secrets, on a mock configuration. Below is the whole test, not just its output: without it you would have to take our word for it, and that is exactly the kind of trust this article warns against.

"""Testing the gates without a network: mock configuration, no secret, no POST."""
from dataclasses import dataclass


@dataclass(frozen=True)
class MockConfiguration:
    environment: str = "practice"
    host: str = "https://api-fxpractice.oanda.com"
    token: str = "dummy-token-for-offline-test"
    account: str = "000-000-0000000-000"


def test_gates() -> None:
    cfg = MockConfiguration()
    order_id = new_order_id()
    print("configuration:", cfg.environment, cfg.host, "token_length=", len(cfg.token))

    # session=None is deliberate: if the code nevertheless tried to send a POST,
    # the test would blow up on AttributeError instead of passing silently.
    result = submit_order(None, cfg, "EUR_USD", 100, order_id)
    assert result is None
    print("1. test mode: nothing sent - OK")

    for description, instrument, units in [
        ("instrument not allowlisted", "GBP_JPY", 100),
        ("size above limit", "EUR_USD", 5000),
        ("zero size", "EUR_USD", 0),
        ("boolean instead of an integer", "EUR_USD", True),
    ]:
        try:
            build_order(instrument, units, order_id)
        except SafetyGateError as error:
            print(f"2. gate [{description}]:", error)
        else:
            raise AssertionError(f"Expected gate was not triggered: {description}")

    cfg_live = MockConfiguration(environment="live", host="https://api-fxtrade.oanda.com")
    try:
        submit_order(None, cfg_live, "EUR_USD", 100, order_id, test_mode=False)
    except SafetyGateError as error:
        print("3. gate [live mode without confirmation]:", error)
    else:
        raise AssertionError("Live mode passed without confirmation")

    print("all gates passed")


if __name__ == "__main__":
    test_gates()

The output of the run – Python 3.12.10 as in section 2, with no network connection and no package outside the standard library: once the sending was taken out, the execution module no longer needs requests. The second line is a journal entry: the same content goes simultaneously to the file execution.log and to standard output. The timestamp and the order identifier differ on every run – the rest of the output is repeatable to the character:

configuration: practice https://api-fxpractice.oanda.com token_length= 28
2026-11-01T11:07:20.011Z INFO execution TEST MODE [practice] order built; nothing sent: {'order': {'type': 'MARKET', 'instrument': 'EUR_USD', 'units': '100', 'clientExtensions': {'id': '4ae82fd8-2de4-4117-97fc-c4aac3d11d99'}}}
1. test mode: nothing sent - OK
2. gate [instrument not allowlisted]: Instrument is not allowlisted: GBP_JPY
2. gate [size above limit]: Size 5000 exceeds limit 1000
2. gate [zero size]: Size must be a nonzero integer
2. gate [boolean instead of an integer]: Size must be a nonzero integer
3. gate [live mode without confirmation]: Production host requires explicit operator confirmation
all gates passed

What this output confirms and what it does not. Five negative cases triggered the expected gates: a non-allowlisted instrument, excessive size, zero, a boolean and live mode without confirmation. Assertions also check test mode; the audit additionally checked the ±1000 boundaries, limit breaches and invalid types. The first call argument is None, and submission is not implemented, so this test cannot place an order. The output does not test a broker API, logging resilience or the masking of every possible sensitive field. The dummy token is not printed: the program shows only its length. In your project, separately check log writing and recovery, data-redaction rules and disk failures.

It confirms nothing, however, about behaviour against a real API – and it cannot, because the branch that sends an order simply does not exist in this module. A structural sketch took its place, and with it disappeared the only place where this code could send anything. That is precisely the difference between "we did not run it" and "there is nothing to run": the first leaves the reader an artefact ready to paste, the second leaves them a structure they have to implement themselves – and, along the way, read their own broker's documentation.

The test must also detect a missing safety gate. It therefore asserts the test-mode result and raises AssertionError after each negative case if the expected exception was not raised. The final message appears only after those checks pass. This remains a small example test: it does not cover broker response formats, every data type or state recovery. In a larger project, move the cases to pytest, add positive cases and run them whenever the validator changes.

The confirmation gate is a barrier against a mistake, not against a program. It is worth naming its reach explicitly, because it is easy to take it for something more. The confirmation value is not a constant of this file: the program reads it from the environment variable BROKER_LIVE_CONFIRMATION and compares it with the account number, so the operator has to consciously type into the shell the number they want to trade. That is enough against three real mistakes: running the production configuration "just to try", mixing up the account, and accidentally switching off test mode. It is enough against nothing more. Code running in the same process can set that variable for itself, and then the gate will not stop it for a moment – no confirmation a program reads from its own environment is a safeguard against a program. The real restriction of permissions sits outside your code: a token with no right to place orders, where the broker distinguishes that, and position size limits set on the account side [FEATURE DEPENDS ON BROKER/ACCOUNT].

Units are not lots. The comment next to MAX_UNITS is not decoration. Different APIs describe position size in different conventions – in units of the base currency, in lots, in contracts – and a mistake here causes neither a syntax error nor an exception. It causes exposure two or three orders of magnitude larger than you intended, with the code working correctly. Before you send anything, check the convention in the documentation and confirm it with one minimum-size trade on a practice account. Two limits of this validator are worth knowing before you plug it into your own calculations. A size computed in pandas or NumPy has the type numpy.int64, and that is not a subclass of the built-in int – the validator will reject it with a message about integers, even though the value is an integer in every sense. It fails safely, but confusingly, so pass a number read from a DataFrame through int(...) before it reaches build_order(). The second limit: order_id is not checked here at all, and a type annotation enforces nothing – since duplicate recognition rests on that identifier, check the permitted length and format in your API's documentation and enforce them exactly as you do the size limit.

Logs, state and tests

A log instead of print(). The logging module gives you severity levels, a timestamp and writing to a file – but none of those things switches itself on. Without configuration the default level is WARNING and there is no destination at all, so log.info(...) calls are silently discarded: the code looks as if it were logging and records nothing. That is a recurring reason why the journal turns out to be empty after a failure. The configuration is set once and only at the program's entry point – in the script you run, not in the module you import. The logging.basicConfig(...) call sits in the execution module above only because that module is simultaneously the whole program there; a comment in that same code says outright that in a larger project this is the wrong place. The reason is concrete: configuration left in a module executes at import time and takes over logging for the whole process, and a later logging.basicConfig(...) in the real entry point then does nothing – the function is inert once the root logger already has its destinations (unless you call it with force=True), and it signals this with no error at all [4]. Your settings simply vanish, and the entries go wherever the imported module directed them: the same silent defect described a sentence earlier, only entered from the other side. Log the decision together with its premises, the content of the request and the server's response – truncate the last one so that an HTML error page does not flood the journal, and raise the limit when diagnosing. The token is the one exception: never write it down. A log without the broker's response will not let you establish later whether the problem was in the logic, in the network or on the server side.

The execution journal is sensitive data too. The full content of the order goes into execution.log, and in a complete program so does the broker's response: account number, order identifier, position size, prices. The token is not there and should not be – ten runs of the test produced eleven entries and zero occurrences of the token – but the rest is enough to treat that file exactly like a configuration file with a secret in it: put execution.log into .gitignore next to .env. And .gitignore itself is not access control: it does not restrict file permissions, does not delete the file after a time and does not redact its contents. That is why the sending sketch tells you to mask the account number down to the last four characters, and to send into the journal fields from a list you draw up yourself – not everything that happened to come back from the server. Two more things need fixing before such a sketch runs unsupervised. The path: execution.log is written relatively, so the file is created in the process's working directory, not next to the script. When launched from Task Scheduler or from cron – and that is exactly how such scripts are launched, as discussed below – the working directory can be quite different from the script's directory, and the journal on which the whole failure-recovery procedure rests will be somewhere other than where you look for it. Give an absolute path, computed from the script's location or from configuration. The size: with the recommendation from the paragraph above the file grows without limit, because this example has no rotation. logging.handlers.RotatingFileHandler lies in the same standard library and – after adding import logging.handlers, because import logging alone does not expose that submodule – goes in place of FileHandler without changing the rest of the configuration.

State must survive a restart. The process will be stopped at some point – by a system update, a power failure or your own Ctrl+C. If information about sent orders lives only in the process's memory, after a restart the program does not know what it has already done. The minimal solution is writing the identifiers of sent orders to a file or a database before sending, and after startup comparing that record with the account state fetched from the API. That is precisely the procedure that prevents a double entry after a dropped connection.

Tests without a network. Signal logic and limit validation can be tested on prepared data, without connecting to anything – exactly as was done above with the safety gates. A test that requires a working API is not a unit test and cannot be run on every code change. Start with tests of what can be checked offline: the entry condition, the position size calculation, the behaviour on empty data and on data with a gap.

A controlled stop. An execution program should react to a termination signal: finish the current operation, save state and exit – rather than being interrupted halfway through sending an order. Separately, it is worth having a condition that stops new entries once a daily loss threshold is exceeded. Where to set that threshold and how to compute it is described by the risk management part of the course; in code it is an ordinary condition checked before every entry, not a library function.

Where to run it. A server that runs without interruption, system clock synchronisation, continuity after a restart and a failure-recovery procedure are the subject of the article Trading automation: EAs, scripts and VPS. There are several ways of launching, and they differ not in convenience but in what happens after a failure: Task Scheduler on Windows or cron on Unix systems fire the script periodically and end it once it has run; a system service (for example a systemd unit) keeps a process running indefinitely and can restart it after it exits; a process manager does the same at the application layer. The choice between a short periodic run and a long-running process decides where you keep state and who ensures there is only one instance. From the Python code's point of view one thing matters: a script launched from a scheduler must tolerate the fact that the previous run may not have finished – that is, check state before acting rather than assume it is starting from zero.

See also: Algorithmic trading – system architecture and the place of automation in the whole decision process.

9. Look-ahead and data leakage in Python code

Look-ahead is not a methodology error. It is an error in a single line of code – and that is exactly why it belongs to this article rather than to the text on testing methodology. It consists in a result assigned to a given moment using information that did not yet exist at that moment.

The most common form in pandas is trivial: a signal column multiplied by the return column from the same row. The return in row t came about between the close of the previous candle and the close of candle t. A signal computed from the close of candle t is only known once that return has already happened. By multiplying one by the other, you award yourself the result of a move about which you knew nothing at the moment of decision.

Assumptions for the example below: eight synthetic hourly observations, a UTC index, illustrative values, no transaction costs – the aim is to show the mechanism of the shift, not to evaluate a rule. Environment as in section 2: Python 3.12.10, pandas 3.0.5.

"""Look-ahead in one line: the same rule, two different results."""
import pandas as pd

index = pd.date_range("2026-06-01", periods=8, freq="1h", tz="UTC")
df = pd.DataFrame(
    {"close": [1.0800, 1.0810, 1.0825, 1.0815, 1.0830, 1.0845, 1.0840, 1.0855]},
    index=index,
)
df["sma"] = df["close"].rolling(3).mean()
df["return"] = df["close"].pct_change()

# Rule: long position when the close is above the three-candle average.
df["position"] = (df["close"] > df["sma"]).astype(int)

# WRONG: the position from row t multiplied by the return from the same row.
# Return t came about between the close of t-1 and the close of t, so the decision
# uses a price that did not yet exist at the moment of entry.
df["result_with_lookahead"] = df["position"] * df["return"]

# CORRECT: a position decided at the close of t only works on the return of t+1.
df["result_without_lookahead"] = df["position"].shift(1) * df["return"]

print(df[["result_with_lookahead", "result_without_lookahead"]].sum().round(6))

The output of the run:

result_with_lookahead       0.005082
result_without_lookahead    0.001384
dtype: float64

Interpretation. The same rule, the same data, one shift(1) call of difference – and the sum of simple periodic returns falls from 0.005082 to 0.001384, that is, to under 30 per cent of the original value. On eight observations that is of course an illustration, not a measurement; over several years of data the same mistake can turn an average strategy into a spectacular one, and a spectacular one into an impossible one. Both values are dimensionless and do not account for spread or commission – after charging them the correct version would be lower still.

One caveat about the arithmetic itself. pct_change() gives simple returns, and those – as noted in section 4 – compound multiplicatively rather than by addition; only logarithmic returns may be summed. Summing them here is a conscious approximation, because at values on the order of thousandths the difference between the sum and correct compounding comes in this example to less than 0.00001, that is, more than two orders of magnitude smaller than the difference we want to show. In a calculation that is meant to describe an account result rather than the mechanism of the shift, you compound (1 + r) or switch to log returns and only then sum.

Watch out for a double shift. The shift is applied in one place: either to the position column or to the signal's input data – never to both at once. Code that first computes the signal from shifted prices and then shifts the position as well delays entry by two periods and quietly understates the result. An error in that direction is less dangerous than look-ahead, but equally false.

Price table comparing biased and shifted return alignment
Here, using a future close changes the result from −0.98% to an apparent +2.00%.

The remaining forms of look-ahead in Python code – each reduces to the same question: was this value known at the moment of decision?

  • Using the high or low of the current candle in an entry condition, even though you only learn them after it closes
  • Scaling or normalization computed on the whole dataset before splitting into training and validation parts – the scaling parameters then carry information from the future
  • Indicators that smooth or mark turning points using later candles; their historical value differs from the one you saw live
  • Macroeconomic data taken in its post-revision version instead of the value originally published
  • An order filled at the closing price of the candle on which the signal arose

Data leakage when preparing the dataset. The second point on that list deserves its own sentence, because in Python it is committed reflexively. Calling a scaler on the whole DataFrame before splitting into periods is one line and looks innocent, yet it carries knowledge of the future data distribution into the validation part. The parameters of a transformation are determined exclusively on earlier data and applied to later data – never the other way round.

Two code versions assigning the signal to the current or next return
Shifting the signal repairs the specified timing error under this model; it does not establish profitability.

Multiple testing. The more variants you test on the same data, the greater the chance that the best of them is a coincidence. Under an explicit null model, if 10,000 tests each have a false-positive probability of 0.05, the expected number of results labelled “significant” is 0.05 × 10,000 = 500. This expectation follows by summing probabilities and does not require independence; dependence changes the distribution of the count rather than its mean under those assumptions. The order of magnitude shows why the number of attempts must be reported alongside the result.

A formal correction accounting for the number of attempts exists – the Deflated Sharpe Ratio, proposed by Bailey and López de Prado in 2014 [12]. Before you reach for a ready implementation, check the status and licence of the library you find it in; some projects in this area have changed their distribution model. The formula itself is described in the source publication and can be implemented independently.

What this section does not cover. Overfitting, sample selection, walk-forward analysis, survivorship bias and testing the robustness of a result to rising costs are testing methodology, described in the article on backtesting and forward testing. Here we care solely about what can be broken in code – and what can be checked in code.

Checking the code before you trust the result:

  1. Does the result for row t use only data available before the moment of decision?
  2. Was the shift applied exactly once – to the signal or to the data, not to both?
  3. Are the moment and the price of the fill written down explicitly rather than left implicit?
  4. Are transaction costs in the model, or consciously omitted and described as such?
  5. Is the split of data into training and validation parts chronological?
  6. Were data transformations determined exclusively on the earlier part?
  7. Is the number of variants tested recorded together with the result?
  8. Does the time index have an explicit zone, and is it increasing without duplicates?
A practical rule: a surprisingly good result is a hypothesis about an error, not about an edge. Before you decide you have found something exceptional, walk through the list above point by point and run the code on data where you know what the result should be – for example on a constant-price series, where the price-change return is zero before costs; trades can lose money after costs. A test on data with a known answer detects more errors than staring at an equity curve.

10. How much code do you really need

You do not have to become a developer. You have to know enough not to be fooled by your own code or by somebody else's script downloaded from a repository.

Progressive Python learning levels and practical trading capabilities
LevelSkillsWhat it gives youRough time
0 – no codeNoneYou analyse what the platform allows, in the way it imposes—
1 – reading codeYou understand somebody else's script, change parameters, run it in an isolated environmentYou can check whether a script from a repository contains look-ahead and whether it charges costs at allA few weeks
2 – your own analysispandas, numpy, matplotlib; your own analytical scriptsAnalysis of your journal and of market data without the spreadsheet's limitsA few months
3 – integrationAPIs, error handling, logging, scheduling, testsNotifications and preparing orders with confirmationSix months and more
4 – execution codeAutomated tests, state management, deployments, monitoringA program allowed to run without confirming every decisionCounted in years of practice

The time in the last column is approximate and depends on your starting point and how many hours a week you actually put in – treat it as an order of magnitude, not a promise.

Levels 1 and 2 do not give a market edge. What they do give is the ability to check whether somebody else's solution makes sense, and to stop buying systems that cannot be verified. That is real value, only of a different kind from the one sold by vendors of ready-made tools. Level 4 is needed if you want to maintain an execution program – not in order to trade better. A survey of Python's applications in finance is given by Hilpisch's textbook [11], with one caveat that applies to every book about code: the fragments have to be checked against current library versions before use, because some interfaces have changed since it was published.

Code generated by a language model. Assistants can write a large part of analytical code faster than you can. They can also generate code with look-ahead that looks correct, and refer to a function that does not exist in the library version you have. Without level 1 skills you will detect neither. What language models can and cannot do is described in a separate article: AI and LLMs in trading.

A sensible order of learning – each step builds on the previous one and ends with something that works:

  1. Language basics – variables, lists, functions, conditionals. Enough to read somebody else's script without guessing
  2. pandas on your own data – load an export of your trading journal, compute statistics broken down by day of the week and instrument. If you prefer learning from a textbook rather than from documentation, this stage is covered in full by the book by McKinney, the author of pandas [10]
  3. A chart – draw an equity curve and a drawdown chart from what you computed in the previous step
  4. Data quality checks – repeat the example from section 4 on your own file: time zone, duplicates, gaps
  5. Read-only integration – fetch data from an API on a practice account, with a token that has no transactional permissions, if the provider distinguishes that

The order is deliberate. The fifth step appears only once you can check the data you are downloading – otherwise you are automating an error instead of work.

The most valuable application is the least spectacular. Analysing your own journal in pandas shows where the result actually comes from, and where it only seems to you that it does. That usually gives more than building an execution program and requires only level 2 – not because someone measured it, but because it is the only analysis that operates on your own data rather than on somebody else's.

Start with one task: load your own data, compute something you can check by hand on three rows, and compare the results. If the Python result agrees with counting on your fingers, you have a foundation. If it does not – you have found your first bug, and that is a better start than a script that works straight away and that you do not understand.

Python will not fix a bad strategy. At best it will show you faster that it was bad.

FAQ – Python in trading

Is Python fast enough for trading automation?
It depends where the bottleneck lies. For a strategy entering at the open of the next H1 candle, computation time in Python is negligible compared with the time it takes an order to travel through the network and the broker's server. For trading inside a one-minute candle the whole chain becomes relevant: the age of the data at the moment of decision, the endpoint response time and the time to fill confirmation. None of those quantities can be quoted from memory – they have to be measured in your own chain, at your own broker, and recorded together with the date and the number of attempts. Python is not suitable for ultra-low-latency trading, but that is a different class of problem from retail trading.
How long do I need to learn Python to a level that is useful in trading?
To the level where you read somebody else's code and change parameters – a few weeks of regular work. To analysing your own journal in pandas with charts on your own – a few months. Those ranges depend on your starting point and the number of hours a week, so treat them as an order of magnitude. You do not need a course covering the whole language: classes, decorators or concurrency are not needed to load a file and compute statistics. You learn fastest on your own data, because you immediately know whether the result makes sense.
Can I connect Python to an MT4 or MT5 account?
For MT5 there is an official MetaTrader5 package installed via pip – but on Windows only: on macOS and Linux there is no official installation and you have to run the terminal together with Python under Wine or set up a separate intermediary layer [FEATURE DEPENDS ON VERSION/ENVIRONMENT]. You also have to understand what that package is: it communicates with a MetaTrader 5 terminal installed on the same machine, not with the broker's server directly. It requires the terminal to be installed on the same machine – but not to have been started beforehand: the vendor's documentation states that the initialize() call starts the terminal itself if needed, and the login parameters are optional, because in their absence the package will use the data stored in the terminal [18]. That is not a cosmetic detail: a script launched from a scheduler can therefore bring up the terminal and log in without your involvement, which is convenient and at the same time means that the mere fact that "the terminal was closed" is no safeguard at all. The integration was introduced in the 2019 terminal version (build 2085) [7]. This is not a broker-independent REST API and should not be described as one. The alternative is an external cloud bridge, which adds another link and requires entrusting account access to a third party. The simplest and safest path to start with remains one-directional: export data from the terminal to a file, analyse in Python, decision and execution on the human side.
Where should I keep API keys, and what do I do if a key leaks?
Exclusively in environment variables or in a configuration file kept outside the repository and listed in .gitignore. Never in the code, never in a comment, never in a notebook – a notebook cell also saves the output, so a printed token stays in the file. If a key has made it into the repository, deleting the line achieves nothing: the value stays in the version history. The only effective response is revoking the key on the broker's side and generating a new one, and only then tidying up the history. Regardless of that, it is worth setting position size restrictions on the account side as a second layer of protection, independent of your code.
Has the code in this article been checked?
Yes – every code block, and the text sets this out block by block. The example loading a CSV file in section 4 and the signal-shift comparison in section 9 were run in the environment stated (Python 3.12.10, pandas 3.0.5) and the results shown are the real output of the program. The configuration-loading block was tested in all five of its branches, from missing environment variables through to rejecting an unrecognised environment name. The execution layer's safety gates were checked offline, with no network and no secrets. The fragment fetching data from an API was run against a mock HTTP server listening on 127.0.0.1 – not against a broker – and driven through every branch of the response handling, including exhaustion of the attempt limit and a dropped connection. There is not, however, a single line in this article that would send an order: the sending branch was replaced with a structural sketch, because transactional code is not tested on somebody else's account, and a ready function without a test would teach nothing but trust in unverified code. Running code is not the same as confirming assumptions about somebody else's server: check endpoint paths, response shapes and limits in your own broker's documentation and on a practice account.
Can I trust a strategy found in a public repository?
Not without checking it yourself, and this is not about the authors' bad faith. The typical gaps are an unverified signal shift, no cost model, an undescribed environment and library versions, and no information about how many variants were tested before this one was shown. Before you run anything: read where the signal arises and to which period the result is assigned, check whether costs appear in the code at all, recreate the environment from the dependency file and run it in isolation. If the repository does not state library versions, the result is not reproducible anyway – and a non-reproducible result can neither be verified nor refuted.

Sources and references

  1. pandas 3.0.5 documentation – pandas.pydata.org/docs – data structures, the time index and time zones, resample, handling of missing values; version checked 2026-08-22
  2. pandas – release notes for 2.2.0 and 3.0.0 – pandas.pydata.org/docs/whatsnew – deprecation of the method parameter in fillna() and changes to default behaviour
  3. NumPy – documentation and release notes – numpy.org/doc – vectorization, random number generators and seeding
  4. Python documentation – docs.python.org/3 – the venv, logging and timeit modules, exception handling
  5. OANDA v20 – Best Practices – developer.oanda.com/rest-live-v20/best-practices – the recommended request rate on an established connection (100/s) and new connections (2/s); checked 2026-08-22
  6. MQL5 – Python integration – mql5.com/en/docs/python_metatrader5 – the MetaTrader5 package and its communication with the terminal
  7. MetaTrader 5 – release notes for build 2085 – metatrader5.com/en/releasenotes/terminal/2085 – introduction of the terminal's Python integration
  8. cTrader Algo – documentation – help.ctrader.com/ctrader-algo – native support for C# and Python for cBots, indicators and plugins; as of 2026-08-22
  9. TA-Lib (Python bindings) – pypi.org/project/TA-Lib – binary packages published on PyPI, installation without compiling the C library
  10. McKinney, W. – Python for Data Analysis, O'Reilly, 3rd edition, 2022 – pandas, numpy, working with time series
  11. Hilpisch, Y. – Python for Finance, O'Reilly, 2nd edition, 2018 – applications of Python in finance; verify code fragments against current library versions
  12. Bailey, D. H., López de Prado, M. – The Deflated Sharpe Ratio, Journal of Portfolio Management, 2014 – correcting the Sharpe ratio for the number of variants tested
  13. PyPI – package pages and the registry's JSON interface – pypi.org – dates and numbers of the latest releases of the libraries mentioned in the text (mplfinance, streamlit, openpyxl, pandas-ta, backtrader, vectorbt, backtesting.py, ib_insync, ib_async); checked 2026-10-08
  14. OANDA v20 – Order and Transaction API – developer.oanda.com/rest-live-v20/transaction-df – clientExtensions as optional custom data attached to an order, and the warning against setting it on accounts associated with MT4; no documented guarantee of market order idempotency; checked 2026-08-22
  15. OANDA v20 – Development Guide – developer.oanda.com/rest-live-v20/development-guide – the enforced REST limit of 120 requests per second with an HTTP 429 response, a limit of 20 active streams and 2 new connections per second, counted for the IP address sending the requests; checked 2026-08-22
  16. Microsoft – Excel specifications and limits – support.microsoft.com – worksheet size: 1,048,576 rows by 16,384 columns; checked 2026-08-22
  17. Swiss National Bank – press release of 15 January 2015 – snb.ch – removal of the minimum exchange rate of 1.20 francs per euro and the rate cut to −0.75 per cent
  18. MQL5 – MetaTrader5.initialize() – mql5.com/en/docs/python_metatrader5/mt5initialize_py – starting the terminal when establishing a connection if required, and the optional path, login, password and server parameters with data stored in the terminal; checked 2026-08-22

Your learning progress

Finished this lesson? Mark it yourself. Opening or scrolling a page never marks it complete.

Progress requires JavaScript and browser storage.

Saved only in this browser. No account or cross-device sync. Clearing site data can erase your progress.

Jarosław Wasiński

Editor-in-chief, ForexMechanics.com • Macro & FX analyst

Independent analyst and practitioner with over 20 years of experience in financial markets. Actively involved in Forex since 2007, with a focus on fundamental analysis, OTC market structure, and disciplined capital risk management.

  • Creator and editor-in-chief of MyBank.pl, providing reliable financial education since 2004.
  • Author of hundreds of in-depth market commentaries, structural analyses, and educational materials for traders and investors.
  • Advocate for market transparency, promoting education grounded in hard data and institutional reports (BIS, ESMA, CFTC).

Full author profile, credentials & published research →

All content is educational and informational only – it does not constitute investment advice or a recommendation. Remember: leveraged trading (Forex/CFD) carries a high risk of rapid capital loss.