Stage 3 of 4, lesson 13 of 31. Beginner
What a broker API sends back, and how to read it
Open 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.
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.
You need: The lesson on reading and writing JSON. No broker account.
An API is a way to ask a broker's computer a question and get a structured answer. You send a request to an address called an endpoint, and the answer comes back as JSON: names and values, nested inside each other.
Before you talk to a real broker, practise on a saved answer. The file on this page is a mock in the shape a positions call returns. The values are invented.
Read the script with the file open beside it. Each square bracket in the code walks one level into the file. When a real response surprises you later, this is the skill you will use: print it, read it, then walk into it one level at a time.
Files for this lesson
- mock-positions.json, sample data with invented values
The code
# Read the kind of answer a broker API sends back.
# Download mock-positions.json from this lesson and keep it in the same folder as this script.
# It is a mock: the shape is what a positions call returns, the values are invented.
import json
with open("mock-positions.json") as f:
data = json.load(f)
for item in data["positions"]:
position = item["position"]
market = item["market"]
# A BUY is closed by selling at the bid. A SELL is closed by buying at the offer.
if position["direction"] == "BUY":
points = market["bid"] - position["level"]
else:
points = position["level"] - market["offer"]
print(market["instrumentName"])
print(" Direction:", position["direction"], "Size:", position["size"])
print(" Opened at:", position["level"], "Now:", market["bid"], "/", market["offer"])
print(" Running profit or loss:", round(points * position["size"], 2), position["currency"])What you should see
FTSE 100 (mock) Direction: BUY Size: 1 Opened at: 7650.2 Now: 7655.1 / 7656.1 Running profit or loss: 4.9 GBP
Run with Python 3.12 on Windows against the sample files on this page. No network and no account.
Endpoints this lesson uses
Check yourself
Answer each question from the code above before you open it. The answers were written from the script on this page and what it printed.
Why does the script use the bid, not the offer, to value a BUY?
A BUY is closed by selling, and you sell at the bid. A SELL is closed by buying at the offer. The comment above the if says the same.
Where does the running profit of 4.9 come from?
The bid of 7655.1 minus the level the position was opened at, 7650.2, times a size of 1.
Which two keys do you walk through to reach the name of the market?
Each entry in positions has a market object, and inside it instrumentName. In the script that is item["market"] and then market["instrumentName"].
Exercise
Add one more indented line of output for each position that prints its deal id and the market status, straight after the line with the direction.
What the changed script prints
FTSE 100 (mock) Direction: BUY Size: 1 Deal: DIAAAAMOCK01 Status: TRADEABLE Opened at: 7650.2 Now: 7655.1 / 7656.1 Running profit or loss: 4.9 GBP
Captured from a run of the solution on . Run with Python 3.12 on Windows against the sample files on this page. No network and no account.
One solution
# Exercise solution: the lesson script with the one change the exercise asks for.
# Read the kind of answer a broker API sends back.
# Download mock-positions.json from this lesson and keep it in the same folder as this script.
# It is a mock: the shape is what a positions call returns, the values are invented.
import json
with open("mock-positions.json") as f:
data = json.load(f)
for item in data["positions"]:
position = item["position"]
market = item["market"]
# A BUY is closed by selling at the bid. A SELL is closed by buying at the offer.
if position["direction"] == "BUY":
points = market["bid"] - position["level"]
else:
points = position["level"] - market["offer"]
print(market["instrumentName"])
print(" Direction:", position["direction"], "Size:", position["size"])
print(" Deal:", position["dealId"], "Status:", market["marketStatus"])
print(" Opened at:", position["level"], "Now:", market["bid"], "/", market["offer"])
print(" Running profit or loss:", round(points * position["size"], 2), position["currency"])Your progress
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.
Where this sits in the path
Stage 3 of 4: Talking to a broker. 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.
- Read an API responseDoneYou are here
- First HTTP requestDone
- Positions and exposureDone
- Keys and demo accountsDone
- First API callDone
- Paged resultsDone
- Follow the next pageDone
- Price history to CSVDone