How do I fetch trades with a token, a job and a compressed file?

Get a token, submit a Tick History job and fetch its compressed result, collect several files with a limit on parallel downloads, and read the trades from the gzip bytes.

After this lesson, you can request a stock’s trades for one minute from LSEG Tick History, collect several compressed results at once, and read the individual trades.

How do I request the trades?

A Tick History request takes three calls, a POST of your DataScope user name and password that returns a token, a POST of the job, which answers 202 while the job runs and gives a status address, and a GET of the finished file with the job’s id. The example asks for the trade prices and volumes of Vodafone in London, RIC VOD.L, from 08:30 to 08:31 UTC on 1 May 2025.

The account needs permission for the data, and the box reads the credentials from the environment variables RTH_USER and RTH_PASS, as in the lesson on keys and folders. The token goes into the Authorization header after the word Token, and Prefer: respond-async lets the service run the job in the background. The loop checks the status every 30 seconds, at most 20 times, as in the lesson on job polling, and stream=True with .raw.read() keeps the result compressed. The post on LSEG tick data shows a full script.

The following box, which does not run on this page, makes the three calls.

import os
from time import sleep

import requests

base = "https://selectapi.datascope.lseg.com/RestApi/v1/"
reply = requests.post(base + "Authentication/RequestToken", json={"Credentials": {"Username": os.environ["RTH_USER"], "Password": os.environ["RTH_PASS"]}}, timeout=30)
reply.raise_for_status()
headers = {"Authorization": "Token " + reply.json()["value"], "Prefer": "respond-async"}

prefix = "#DataScope.Select.Api.Extractions.ExtractionRequests."
job = {
    "@odata.type": prefix + "TickHistoryTimeAndSalesExtractionRequest",
    "ContentFieldNames": ["Trade - Price", "Trade - Volume"],
    "IdentifierList": {"@odata.type": prefix + "InstrumentIdentifierList", "InstrumentIdentifiers": [{"IdentifierType": "Ric", "Identifier": "VOD.L"}]},
    "Condition": {"ReportDateRangeType": "Range", "MessageTimeStampIn": "GmtUtc", "QueryStartDate": "2025-05-01T08:30:00Z", "QueryEndDate": "2025-05-01T08:31:00Z"},
}
reply = requests.post(base + "Extractions/ExtractRaw", headers=headers, json={"ExtractionRequest": job}, timeout=60)
reply.raise_for_status()
status_url = reply.headers.get("Location")
for attempt in range(20):
    if reply.status_code != 202:
        break
    sleep(30)
    reply = requests.get(status_url, headers=headers, timeout=60)
    reply.raise_for_status()
if reply.status_code != 200:
    raise TimeoutError(f"job ended with status {reply.status_code}")
job_id = reply.json()["JobId"]
with requests.get(base + f"Extractions/RawExtractionResults('{job_id}')/$value", headers=headers | {"Accept-Encoding": "gzip"}, stream=True, timeout=60) as result:
    result.raise_for_status()
    packed = result.raw.read()

How do I collect several files at once?

ThreadPoolExecutor(max_workers=2) runs at most two downloads at the same time, and as_completed hands back each download as it finishes, so the three made-up files of AAA, BBB and CCC arrive in any order and each is stored under the RIC that download returns.

pool.submit(download, ric) schedules one call and returns a future, an object that stands for the call, and .result() gives its return value or raises its error. The made-up files are gzip-compressed CSVs of four trades in pence per share, held in memory, and download stands in for the GET above. The number of workers must stay within what the service allows.

Code: the made-up compressed files
import csv
import gzip
from io import StringIO

trades_by_ric = {"AAA": [("08:30:01Z", 50, 100), ("08:30:04Z", 51, 40)], "BBB": [("08:30:02Z", 30, 80)], "CCC": [("08:30:03Z", 70, 20)]}
blobs = {}
for ric, trades in trades_by_ric.items():
    buffer = StringIO(newline="")
    writer = csv.writer(buffer)
    writer.writerow(["#RIC", "Domain", "Date-Time", "Type", "Price", "Volume"])
    writer.writerows([ric, "Market Price", "2025-05-01T" + clock, "Trade", price, size] for clock, price, size in trades)
    blobs[ric] = gzip.compress(buffer.getvalue().encode("utf-8"))

The following box collects the three files with two workers.

from concurrent.futures import ThreadPoolExecutor, as_completed

def download(ric):
    return ric, blobs[ric]

files = {}
with ThreadPoolExecutor(max_workers=2) as pool:
    for future in as_completed([pool.submit(download, ric) for ric in blobs]):
        ric, packed = future.result()
        files[ric] = packed
print(sorted(files))
['AAA', 'BBB', 'CCC']

How do I read the trades from the compressed bytes?

gzip.decompress restores the CSV’s bytes, .decode("utf-8") turns them into text, and csv.DictReader names each row’s fields after the header, so AAA’s first trade reads as 100 shares at 08:30:01 UTC. Every value is still text, including Price and Volume.

StringIO(text) hands the text to the reader as lines, and list collects the rows.

The following box reads AAA’s file.

text = gzip.decompress(files["AAA"]).decode("utf-8")
print(text)
aaa_trades = list(csv.DictReader(StringIO(text)))
print(aaa_trades[0]["Date-Time"], aaa_trades[0]["Volume"])
#RIC,Domain,Date-Time,Type,Price,Volume
AAA,Market Price,2025-05-01T08:30:01Z,Trade,50,100
AAA,Market Price,2025-05-01T08:30:04Z,Trade,51,40

2025-05-01T08:30:01Z 100

Your turn

Print the time and volume of AAA’s trades of fewer than 100 shares. You should see 40 shares at 08:30:04.

int turns the volume text into a number before the comparison.

for trade in aaa_trades:
    if int(trade["Volume"]) < 100:
        print(trade["Date-Time"], trade["Volume"])
2025-05-01T08:30:04Z 40