In Guides

How to connect to our API using Python

We show you step-by-step how to connect to and use our API.


Introduction

In this guide, we will cover two methods of connecting to our API:

  1. Using the thalex Python library, or
  2. Using the WebSockets API

Both achieve the same result, but the latter explains the underlying process in more detail. This knowledge is also easily transferable to many other API documentations across the web.

Quick Development Setup

For Windows users, we recommend either using Windows Subsystem for Linux (WSL) and setting up VScode on the Windows side, using a Linux virtual machine or downloading cmder to run the code.

For the rest of the blog, we assume you will be using MacOS, Linux or cmder on Windows.

Create a new directory for the project, navigate into it, and create a new Python file called login.py:

mkdir thalex_api    # create a new directory/folder called thalex_api
cd thalex_api       # navigate into the new folder
touch login.py      # create a new python file called login.py

Connect Using thalex Python Library

The easiest way to connect to our API is by using the thalex Python library.

  1. Download the keys template and place it in the same directory as your login.py file or use the following command to download it directly:
curl https://raw.githubusercontent.com/thalextech/thalex_py/master/_keys.py > keys.py
  1. Open the keys file and insert your public and private keys. You can generate them in the API page in your Thalex account.
  2. Add the following code in your login.py file to connect and login:
import asyncio
import json
import keys
import thalex

NETWORK = thalex.Network.TEST  # or thalex.Network.PROD for production

async def main():
    tlx = thalex.Thalex(network=NETWORK)
    await tlx.connect()
    await tlx.login(keys.key_ids[NETWORK], keys.private_keys[NETWORK])

    raw_msg = await tlx.receive()
    msg = json.loads(raw_msg)
    print(json.dumps(msg))

asyncio.run(main())
  1. Create a Python virtual environment (venv) in the directory and activate it

MacOS/Linux:

python -m venv .venv
source .venv/bin/activate

Windows (via cmder):

python -m venv .venv
.venv\Scripts\activate
  1. Install the thalex python library and run the login.py file:
pip install thalex
python login.py

If successful, you should see a response similar to:

{"id":null,"result":{"account_number":"A123456789"}}

You can now use any of the thalex library functions found here to interact with our API. If you are not sure how to use a specific function, you can check out some examples here.

Connect Using Websockets

We assume you came from the Quick Development Setup section and have already created a login.py file.

Login Endpoint

From the public/login endpoint in the API docs, we see that the following are required/requested to login via WebSockets:

  • A method parameter, and
  • The params parameter containing a token. Specifically a JWT token (look at the payload request example to the right of the docs).

Let's see how to create this JWT token.

Authentication

If you search for JWT using ctrl+f in the API docs, we find the Authentication section which describes the parameters needed for the JWT token:

  • An encryption algorithm of RS512 or any of the other choices listed,
  • A kid header containing your key ID,
  • An iat (issued at) containing the current time as a unix timestamp, and
  • The token signed with your private key.

Private Key and Key ID

First create a python file called keys.py:

touch keys.py

Next add the following template code in the keys.py file and replace the private keys and key_ids with your own. You can generate them from your testnet or production account.

# In your keys.py file

private_keys = {
    'TESTNET': """-----BEGIN RSA PRIVATE KEY-----
    ...replace_with_your_testnet_private_key...
    -----END RSA PRIVATE KEY-----
    """,
    'PROD': """-----BEGIN RSA PRIVATE KEY-----
    ...replace_with_your_prod_private_key...
    -----END RSA PRIVATE KEY-----
    """,
}

key_ids = {'TESTNET': "K123456789", 'PROD': "K123456789"}



Creating the JWT Token

Recall that the JWT token requires:

  • An encryption algorithm of RS512,
  • A key id kid header containing your key ID,
  • An iat (issued at) containing the current time as a unix timestamp, and
  • The token signed with your private key

We've already replaced the private key and key ID in the keys.py file but now we need to import this file, the jwt and time libraries and define our key_id and private_key variables in the login.py file:

import keys
import jwt
import time

key_id = keys.key_ids['TESTNET'] # or 'PROD' for production
private_key = keys.private_keys['TESTNET'] # or 'PROD' for production

Then to create the token:

token = jwt.encode(
    {"iat": time.time()}, 
    private_key, 
    algorithm="RS512", 
    headers={"kid": key_id}
)


Connecting

WebSockets Connection

Now that we've created the JWT token variable, we can connect to the WebSockets API as a client and send the login request to Thalex.

The WebSockets API requires a connection to wss://<api_endpoint>.thalex.com/ws/api/v2.

For testnet, we use wss://testnet.thalex.com/ws/api/v2 and for production, we use wss://thalex.com/ws/api/v2.

So let's create a variable for testnet and production (or just one of them if you prefer):

Network = {
    "TEST": "wss://testnet.thalex.com/ws/api/v2",
    "PROD": "wss://thalex.com/ws/api/v2",
}

We can now send the login request with our JWT token. We import the libraries: websockets, json to handle the json response and asyncio to handle the asynchronous connections.

import websockets
import json
import asyncio

async with websockets.connect(Network["TEST"]) as ws:
    await ws.send(
        json.dumps(
            {
                "method": "public/login", 
                "params": {"token": token}
            }
        )
    )

    print(await ws.recv())




Main Function

Now we put it all inside a function called main since we want to run it easily with one function call:

async def main():
    token = jwt.encode(
        {"iat": time.time()}, 
        private_key, 
        algorithm="RS512", 
        headers={"kid": key_id}
    )

    async with websockets.connect(Network["TEST"]) as ws:
        await ws.send(
            json.dumps(
                {
                    "method": "public/login", 
                    "params": {"token": token}
                }
            )
        )
        print(await ws.recv())

asyncio.run(main())

The End Result

Here is the complete code to login via websockets using JWT authentication.

# In your login.py file

import asyncio
import json
import time
import jwt
import websockets
import keys

Network = {
    "TEST": "wss://testnet.thalex.com/ws/api/v2",
    "PROD": "wss://thalex.com/ws/api/v2",
}

key_id = keys.key_ids["TEST"]
private_key = keys.private_keys["TEST"]


async def main():
    token = jwt.encode(
        {"iat": time.time()}, 
        private_key, 
        algorithm="RS512", 
        headers={"kid": key_id}
    )
    async with websockets.connect(Network["TEST"]) as ws:
        await ws.send(
            json.dumps(
                {
                    "method": "public/login", 
                    "params": {"token": token}
                }
            )
        )
        print(await ws.recv())


asyncio.run(main())

To run this code, we need to create a Python virtual environment (venv) in the directory and activate it

MacOS/Linux:

python -m venv .venv
source .venv/bin/activate

Windows (via cmder):

python -m venv .venv
.venv\Scripts\activate

Next install the required libraries and run the login.py file:

pip install websockets pyjwt cryptography
python login.py

When you run this code, you should see a successful login response from the server in the form of:

"id":null,"result":{"account_number":"A123456789"}}

With this knowledge, you can now explore the other API endpoints in the API docs and start getting market data or building your own trading bots on Thalex!








Disclaimer

Thalex may provide you with certain educational and software tools that you may use for your benefit, at your own risk, and for your own account. Thalex disclaims any responsibility for the use, reliance or utilization of the software, and you agree without limitation to hold Thalex harmless and wholly indemnified of your conscious use of the software, for whatever purposes you may have, related or unrelated with the activities on Thalex or any other service provider that caters for the use of the software, or similar software. Use of the software presupposes acceptance of these conditionals.