Broker API HubMenu

Stage 1 of 4, lesson 1 of 31. No coding experience needed

Your first Python script: profit and loss on one trade

Write and run a script that works out the profit or loss on one trade. It introduces variables, arithmetic, an if statement and print.

Independent and unofficialCode run

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: A computer with Python installed. No broker account.

Every trading tool, however large, is built from the pieces in this script: values with names, a little arithmetic, a decision and some output. Start here even if you have never written code.

Getting it to run the first time takes five small steps. Step one: install Python from python.org. On Windows, tick the box that says Add python.exe to PATH on the first screen of the installer. That box is what lets a terminal find Python.

Step two: save the code below in a file called first_script.py, in a folder you can find again, for example a new folder called trading inside your Documents folder. Use a plain text editor: Notepad on Windows, or TextEdit on a Mac after choosing Format, then Make Plain Text.

Step three: open a terminal, which is a window where you type commands instead of clicking. On Windows, press the Windows key, type PowerShell and press Enter. On a Mac, press Command and Space, type Terminal and press Enter.

Step four: move the terminal to the folder that holds the file. Type cd, a space and the path of the folder, then press Enter. For the example folder that is cd Documents\trading on Windows and cd Documents/trading on a Mac.

Step five: run the script. On Windows type python first_script.py and press Enter. If Windows answers that python is not recognized, or opens the Microsoft Store, type py first_script.py instead: py is a launcher that the python.org installer adds on Windows, and it finds Python even when the word python is not set up. On a Mac type python3 first_script.py, because the word python on its own may not exist there.

If none of those work, close the terminal, open a new one and try again: a terminal that was already open during the install does not know about Python yet. The later lessons write python for short. Use whichever of python, py or python3 worked for you here.

Change the four values at the top and run it again. Try an exit price below the entry price. Predict the answer before you run it: that habit is most of what testing is.

The code

# Your first script. No broker, no account, no internet.
# It works out the profit or loss on one trade from four numbers.

entry_price = 7650.2   # the price you bought at
exit_price = 7655.1    # the price you sold at
size = 1               # pounds per point on a spread bet, or contracts on a CFD
direction = "BUY"      # "BUY" or "SELL"

points = exit_price - entry_price
if direction == "SELL":
    points = -points

profit = points * size

print("Points moved:", round(points, 2))
print("Profit or loss:", round(profit, 2))

What you should see

Points moved: 4.9
Profit or loss: 4.9

Run with Python 3.12 on Windows. No network and no account.

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.

Where does the 4.9 in the output come from?

It is the exit price, 7655.1, minus the entry price, 7650.2. The round function then trims the answer to two decimal places for printing.

Which lines make the script work for a SELL as well as a BUY?

The if statement. When direction is SELL it replaces points with its negative, because a seller gains when the price falls.

If size were 3, which of the two printed lines would change?

Only the second. Points moved is still 4.9. Profit or loss is points times size, so it becomes 14.7.

Exercise

Change direction from BUY to SELL and run the script again. Before you run it, say what both lines will print.

What the changed script prints
Points moved: -4.9
Profit or loss: -4.9

Captured from a run of the solution on . Run with Python 3.12 on Windows. No network and no account.

One solution
# Exercise solution: the lesson script with the one change the exercise asks for.
# Your first script. No broker, no account, no internet.
# It works out the profit or loss on one trade from four numbers.

entry_price = 7650.2   # the price you bought at
exit_price = 7655.1    # the price you sold at
size = 1               # pounds per point on a spread bet, or contracts on a CFD
direction = "SELL"     # "BUY" or "SELL"

points = exit_price - entry_price
if direction == "SELL":
    points = -points

profit = points * size

print("Points moved:", round(points, 2))
print("Profit or loss:", round(profit, 2))

Your progress

Next: Variables and types

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.

Where this sits in the path

Stage 1 of 4: First steps. Values, decisions, loops and functions, and the habit of testing what you wrote. No files and no account.

  1. First Python scriptYou are here
  2. Variables and types
  3. If and comparisons
  4. Lists and loops
  5. Functions and sizing
  6. Test your functions

The whole path, every stage

Next: Variables and types