Skip to content

The code example below shows how to make a request for options data using the Python programming language. The example uses the httpx HTTP library, which supports both sync and async APIs. This example only uses the sync API, but more information about the async API can be found on the library's site. The full code can be downloaded here.

REQUIRED

The Theta Terminal must be running to access data.

py
import httpx  # install via pip install httpx
import csv

BASE_URL = "http://127.0.0.1:25510/v2"  # all endpoints use this URL base

# set params to fetch a snapshot of all contracts for Microsoft
params = {'root': 'MSFT', 'exp': '0', 'use_csv': 'true'}

#
# This is the non-streaming version, and the entire response
# will be held in memory.
#
url = BASE_URL + '/bulk_snapshot/option/ohlc'

while url is not None:
    response = httpx.get(url, params=params)  # make the request
    response.raise_for_status()  # make sure the request worked

    # read the entire response, and parse it as CSV
    csv_reader = csv.reader(response.text.split("\n"))

    for row in csv_reader:
        print(row)  # do something with the data

    # check the Next-Page header to see if we have more data
    if 'Next-Page' in response.headers and response.headers['Next-Page'] != "null":
        url = resp.headers['Next-Page']
    else:
        url = None


#
# This is the streaming version, and will read line-by-line
#
url = BASE_URL + '/bulk_snapshot/option/ohlc'

while url is not None:
    with httpx.stream("GET", url, params=params) as response:
        response.raise_for_status()  # make sure the request worked
        for line in response.iter_lines():
            print(line)  # do something with the data

    # check the Next-Page header to see if we have more data
    if 'Next-Page' in response.headers and response.headers['Next-Page'] != "null":
        url = resp.headers['Next-Page']
    else:
        url = None