Broker API HubMenu

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.

Independent and unofficialDemo accounts onlyNo key is ever entered on this site

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.

Start at lesson 1See the whole path

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.

  1. Stage 1First steps6 lessons
  2. Stage 2Working with data6 lessons
  3. Stage 3Talking to a broker8 lessons
  4. Stage 4Building things that survive11 lessons
  5. Finish lineThe capstoneA project of your own

Stage 1: First steps

6 lessons

Values, decisions, loops and functions, and the habit of testing what you wrote. No files and no account.

  1. Your first Python script: profit and loss on one tradeWrite 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
  2. Variables and types: what a value can beMeet 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
  3. If statements and comparisons: let the program decideAsk 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
  4. Lists and loops: work through many pricesKeep 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
  5. Write a function: size a position from the risk you chooseWrap 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
  6. Test your own functions with plain assertsWrite 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.

  1. Read prices from a file and work out a moving averageLoad 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
  2. Dates, times and time zones in PythonTurn 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
  3. Read and write JSON, the format broker APIs speakLoad 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
  4. Handle money with Decimal, not floatSee 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
  5. Build a trade journal from a list of closed tradesRead 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
  6. Measure drawdown and losing runsTrack 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.

  1. What a broker API sends back, and how to read itOpen 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
  2. Your first HTTP request: ask the practice APIMake 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
  3. Read your positions and work out exposure by instrumentFetch 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
  4. API keys, demo accounts and how not to leak eitherWhat 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
  5. Your first API call: read your positions on a demo accountLog 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
  6. Collect a long history one page at a timeBroker 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
  7. Pagination over HTTP: follow the pointer to the next pageCollect 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
  8. Turn a price history into moving averages and a CSV fileFetch 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.

  1. Handle a failed call: retry, back off, give upDecide 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
  2. Stay under a rate limit on purposeBuild 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
  3. Handle an error reply: read it, then retry, sign in or stopFetch 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
  4. Idempotency: do not send an order twiceSee 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
  5. Log what your program did, so you can find out laterReplace 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
  6. Log every API call, and keep secrets out of the logPut 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
  7. Backtest a trading rule in plain PythonTurn 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
  8. The look ahead mistake in a backtest signalWrite 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
  9. Keep settings and secrets out of your codeRead 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
  10. Write tests with unittest, on saved replies, with no networkSave 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
  11. Build a command line tool that summarises one instrumentTurn 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.

  1. Capstone: build a read only daily report on the practice APIThe 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.

What this track gets you to, and what it does not

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

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.

Sections