Learn to code by building trading tools
A path for traders who have never written code. It starts with a script of a few lines and ends with a project you build yourself. 31 lessons in 4 stages, in order, each with a check and an exercise, and then the capstone project as the last step.
Risk warning: CFDs and spread bets are complex instruments and come with a high risk of losing money rapidly due to leverage. You can lose money on these products, and each provider publishes its own loss figure under FCA rules. You should consider whether you understand how they work and whether you can afford to take the high risk of losing your money. Automated and API trading can amplify losses through bugs, connectivity failures and runaway orders.
This track teaches programming. It does not teach what to trade, and nothing in it is investment advice. Every example rule is an illustration and every sample price is invented. Not sure whether to start at all? Is API trading for you? is one screen on who should not bother and what the first win is.
The path
Work down the page. Each stage builds on the one before it, and the finish line is a project that uses all of them.
Stage 1: First steps
6 lessons
Values, decisions, loops and functions, and the habit of testing what you wrote. No files and no account.
- Your first Python script: profit and loss on one tradeDoneWrite and run a script that works out the profit or loss on one trade. It introduces variables, arithmetic, an if statement and print.No coding experience needed. Code run
- Variables and types: what a value can beDoneMeet the four kinds of value every script is made of, see why text does not do arithmetic, and convert between them. It introduces str, int, float, bool and f-strings.No coding experience needed. Code run
- If statements and comparisons: let the program decideDoneAsk a question in code and do different things depending on the answer. It introduces comparisons, if, elif and else, and the words and, or and not.No coding experience needed. Code run
- Lists and loops: work through many pricesDoneKeep a run of prices in a list, pick values out of it, and repeat work over it. It introduces indexing, slices, for, while, range, enumerate and append.No coding experience needed. Code run
- Write a function: size a position from the risk you chooseDoneWrap a calculation in a function you can reuse and test, using position sizing as the example. It introduces functions, parameters, return values and raising an error.Beginner. Code run
- Test your own functions with plain assertsDoneWrite down what a function must do as small checks that run in a second, so a later change cannot break it unnoticed. It introduces assert, test functions and testing that an error is raised.Beginner. Code run
Stage 2: Working with data
6 lessons
Read prices and trades from files, get dates and money right, and turn a list of trades into a journal.
- Read prices from a file and work out a moving averageDoneLoad a CSV file of daily prices, keep the closing prices in a list and work out a moving average. It introduces opening files, the csv module and turning a column into numbers.Beginner. Code run
- Dates, times and time zones in PythonDoneTurn timestamps from text into values you can subtract, compare and show in another time zone. It introduces datetime, timedelta, UTC, zoneinfo and the naive datetime trap.Beginner. Code run
- Read and write JSON, the format broker APIs speakDoneLoad a JSON file into Python, pick out what you need, write your own JSON file and read it back. It introduces dictionaries, json.load, json.dump, missing keys and invalid JSON.Beginner. Code run
- Handle money with Decimal, not floatDoneSee where ordinary decimal numbers go slightly wrong, and use Decimal to add up and round money exactly. It introduces the decimal module, quantize and choosing a rounding rule.Beginner. Code run
- Build a trade journal from a list of closed tradesDoneRead closed trades from a file, work out the win rate, average win and loss and the total per market, and write the result to a new file. It introduces grouping with a dictionary, list comprehensions and writing CSV.Beginner. Code run
- Measure drawdown and losing runsDoneTrack a running balance through a list of trades and find the worst fall from a high and the longest losing run. It introduces keeping state inside a loop.Improver. Code run
Stage 3: Talking to a broker
8 lessons
What an API sends back, real requests to a practice API that needs no account, how to keep a key safe, a first read only call on a demo account, and histories that arrive in pages.
- What a broker API sends back, and how to read itDoneOpen a mock response in the shape a positions call returns and work out the running profit or loss on each position. It introduces endpoints, nested data and reading a reply one level at a time.Beginner. Code run
- Your first HTTP request: ask the practice APIDoneMake a real HTTP request from Python to this site's practice API and read the account summary it sends back. It introduces GET, status codes, headers and checking a reply before you trust it.Beginner. Code run
- Read your positions and work out exposure by instrumentDoneFetch the open positions from the practice API, work out how much of each market they hold, and check your own sums against what the API reports. It introduces grouping with a dictionary over live replies.Beginner. Code run
- API keys, demo accounts and how not to leak eitherDoneWhat an API key is, why you start on a demo account, and the one habit that keeps a key out of your code: environment variables.Beginner. Code run
- Your first API call: read your positions on a demo accountDoneLog in to a demo account from Python and read your open positions. The script only reads: it cannot place a trade. It introduces HTTP requests, headers, sessions and pacing.Improver. Needs a demo account. Code not yet run end to end: test pending
- Collect a long history one page at a timeDoneBroker APIs hand back long histories in pages. Loop until the last page and collect every row. It introduces while loops with a stop condition and separating the call from the logic.Improver. Code run
- Pagination over HTTP: follow the pointer to the next pageDoneCollect a trade history from the practice API one page at a time, by following the pointer each page gives to the next, with a pause between requests and a proof that nothing is missing.Improver. Code run
- Turn a price history into moving averages and a CSV fileDoneFetch ten daily candles from the practice API, work out a three day and a five day simple moving average, write them to a CSV file a spreadsheet can open, and read the file back to prove it is right.Improver. Code run
Stage 4: Building things that survive
11 lessons
Failure, limits, repeated orders, logs, settings, tests and backtests that do not fool you: what separates a script from a tool.
- Handle a failed call: retry, back off, give upDoneDecide which failures are worth retrying, wait longer after each one, and stop after a fixed number of attempts. It introduces exceptions, try and except, and exponential backoff.Improver. Code run
- Stay under a rate limit on purposeDoneBuild a small pacer that knows how many calls you have made in the last window and tells you how long to wait. It introduces classes, a sliding window and testing with a pretend clock.Improver. Code run
- Handle an error reply: read it, then retry, sign in or stopDoneFetch an expired session and a rate limit refusal from the practice API, read what each body says and act on it: retry only what can succeed on a second try, a fixed number of times.Improver. Code run
- Idempotency: do not send an order twiceDoneSee a retry open the same position twice on a mock broker, then prevent it by sending one reference with every attempt. It introduces idempotency, client references and a mock you can break on purpose.Improver. Code run
- Log what your program did, so you can find out laterDoneReplace print with logging: messages with a level and a time, sent to the screen and to a file at once. It introduces loggers, handlers, levels and formatters.Improver. Code run
- Log every API call, and keep secrets out of the logDonePut logging inside the one function that makes requests, so that every call to the practice API leaves a line saying what was asked and what came back, and nothing secret is ever written down.Improver. Code run
- Backtest a trading rule in plain PythonDoneTurn a rule into code and run it over past prices, with costs, before it goes anywhere near an account. It introduces functions, state and the most common way a backtest lies.Improver. Code run
- The look ahead mistake in a backtest signalDoneWrite a signal as a function, write it again with a small slip that lets it see the future, and catch the slip with a test. It introduces look ahead bias and how to test for it.Improver. Code run
- Keep settings and secrets out of your codeDoneRead every setting in one function, from environment variables with safe defaults, refuse a wrong value before any request is made, and never print a secret. The secret here is a made up name with nothing in it.Improver. Code run
- Write tests with unittest, on saved replies, with no networkDoneSave two order confirmations from the practice API to disk once, then test the function that reads them with unittest, with the network switched off for every test.Improver. Code run
- Build a command line tool that summarises one instrumentDoneTurn a script into a small tool: name an instrument when you run it and it prints a summary from the practice API, says plainly when it cannot, and tells the terminal whether it worked.Improver. Code run
The finish line
The path ends when a program you wrote meets a written brief.
- Capstone: build a read only daily report on the practice APIDoneThe project at the end of the path. Build a daily report on the practice API: a program that only reads, paces its requests, handles refusals, tests itself and writes what it found to a file.Reference solution run
Your marks are kept in this browser only, in its local storage. They are not sent anywhere, there is no account, and they will not follow you to another browser or device. To remove them, use Clear my progress on the learning track page, or clear this site's data in your browser's settings. Marking needs JavaScript. With scripts off the track reads the same, without the ticks.
This browser refused to store anything for this page, so marks cannot be kept here.
What this track gets you to, and what it does not
By the end you can
- Read and write a Python script that runs to a page or two, and say what each line does.
- Load prices and trades from CSV and JSON files, and write your results back out.
- Handle times in UTC and money as exact decimals.
- Read what a broker API sends back, make real HTTP requests to a practice API, and collect a history that arrives in pages.
- Write code that expects failure: it reads an error reply, retries with care, paces itself, does not repeat an order, and logs what it did.
- Keep settings and secrets out of your code, and turn a script into a small command line tool.
- Test your own functions without the network, and spot the commonest way a backtest flatters itself.
It does not
- Teach what to trade, or say that any rule works. Every rule in it is an illustration on invented prices.
- Place an order with a broker. The only order in the track is sent to a mock that lives inside the lesson's own file, and the practice API cannot take one.
- Make you a professional developer. It is a beginner's path, and it is honest about being short.
- Cover live price streams, databases, running a program on a server, or libraries such as pandas.
- Keep your progress anywhere but your own browser.
Of the 31 lessons, 30 have code that was run before publication, and each of those pages prints the file that was run with what it printed. The exception: First API call needs a broker's demo account, has not been run end to end, and reads Test pending. It is optional. Everything else runs offline, on sample files of invented values, apart from First HTTP request, Positions and exposure, Follow the next page, Price history to CSV, Handle an error reply, Log your API calls, Settings from environment, Test with saved replies, A command line tool, which make real requests to this site's practice API: invented data, no account and no key.
How each lesson works
- A short explanation, then one script. The script on the page is the file that was run.
- What you should see, captured from that run, so you can tell at once whether yours worked.
- Check yourself: questions about the code, each answer hidden until you open it.
- An exercise: one small change to make, with the output the changed script gave when it was run.
- Mark as done, which puts a tick on the map above in this browser.
You need a computer with Python installed. Some lessons use small sample files of invented values, which you download from the lesson page. The lessons that call the practice API also need an internet connection.