Register
Learn guide

Broker API Python Course

Broker API Python Course (beta) teaches you to model a read-only historical-data request without connecting to a broker. You will write an adapter around a fictional response contract, test success and failure locally, and record the questions to ask before using a real provider. This course does not call a market-data endpoint, place orders, expose tokens or provide trading advice. QuantPower is software, not an adviser.

QuantPower Research · Updated 27 Nov 2026 · 18 min read

Use Python 3.10 or later and a text editor. Complete Python basics for traders if functions and exceptions are new. The market data and candles course explains which quality checks belong after the adapter. This lesson separates the mechanics of requesting and decoding a result from the process of verifying the rows and deciding what a dataset means.

The course uses lessons, exercises and answer checks. You can complete every check with a local fixture. Use Quanty exercise review (beta) only for a small synthetic example and a specific expectation. Do not paste keys, tokens, customer data, live endpoint responses that include identifiers, or real account records.

Lesson 1: Describe the direction of the request

Fixture request boundary: Python adapter → Read-only test request → Local fixture.
Fixture request boundary: Python adapter → Read-only test request → Local fixture.

Start with the problem in plain words: “Ask for one bounded block of fictional historical candles and tell the caller whether a conforming response arrived.” Notice the absence of an action verb such as buy, sell, cancel or amend. The client learns the shape of a read result without being capable of sending an order. A good teaching example asks for the narrowest capability that proves the lesson.

An interface that reads data is different from an interface that makes changes. In HTTP, GET is defined as a safe method in the sense intended by the standard, but the actual endpoint must still be documented as read-only and the provider may keep operational side effects such as logs. That definition is not permission to call an arbitrary URL because it looks like a getter. Refer to HTTP Semantics, RFC 9110 for the standard's distinction between the methods.

The practice transport has no real host. It accepts a request object and returns an in-memory response object. A function supplied at runtime can count the request, capture its arguments and choose a response fixture. That is enough to test the flow. It is not trying to mimic all production network properties. In particular, it has no authentication or connection timeouts to configure, and no actual market data provider recognises its invented path.

For the exercise, write down an input symbol label, interval and expected shape. Declare the maximum number of response rows and body bytes you would accept. Then write one request that fails validation before it reaches the transport. Your goal is to show where the boundary lies. Do not create an example containing a real broker hostname or claimed compatibility with a provider.

Answer check. Ask Quanty why a local transport is an adequate test for request construction but not for an exchange connection. An accurate answer should distinguish the request object you built from authentication, transport reliability and provider policy. Those later concerns are not tested by a Python fixture that returns a dictionary.

Lesson 2: Keep configuration and private credentials out of the lesson

Configuration boundary: Example config → No private secrets → Offline exercise.
Configuration boundary: Example config → No private secrets → Offline exercise.

There is no credential in this code. A real provider could require a particular login flow, API entitlement or access token. Those are separate design requirements and you must read that provider's current official documentation before implementing them. Do not assume a token from a web sign-in is an API token, or that permission to read one endpoint includes permission to send orders. Read-only scope should be enforced by the service where such a capability is offered rather than trusted solely to comments in client code.

Keep examples safe to share by designing them without any secret fields. The request fixture should show the method, path and public-shaped parameters, not an Authorization header copied from a real session. Do not log full requests or error bodies by default in a real client because they can carry identifiers, service configuration or private data. Log a short error class and operational context appropriate to the audience. Review approved options with your team before transporting actual credentials or records.

In this teaching adapter, the symbol DEMO1 is an invented identifier. It does not encode a trading instrument or prove that an exchange recognises it. In real integration work, use the documented identifier format and resolution method for the provider. A displayed name, a broker instrument identifier and an exchange symbol are not necessarily interchangeable. Treat identifier resolution as an independent task and do not guess based on the shape of a label.

For the exercise, list the parts of a hypothetical read client that could be placed in a test note and the parts that must stay out. Include one example identifier from this page, one boundary used for a request, one response error category, and a fictional user identity marked never to include. Then remove the identity entirely. Keeping a dummy case about what not to share does not require saving a real identifier anywhere. The purpose is to make an actual review easier to perform safely.

Answer check. Present the shortened error “read not permitted,” the fictional route name, and the fixture's expected status. Ask what information would make that debugging question more precise without revealing credentials. A useful response asks for scope and official documentation, not a token, live account dump or proof by trying a different account.

Lesson 3: Model response outcomes before writing the parser

Response outcomes: Fixture response → Inspect status → Decode or report.
Response outcomes: Fixture response → Inspect status → Decode or report.

Write down what makes a result usable. This example expects status 200, the media type application/json and a top-level object containing an array called candles. The rows must be objects with a short fixed set of fields and nonempty string values. It also expects a compact response within explicit size and row bounds. This is a fictional contract, not a description of any specific broker's shape. A provider might return a different status, schema or timestamp representation.

Separate transport outcomes from content validation. A successful request at the HTTP layer does not prove the body contains the right representation. A service might return a text maintenance message or an unexpected HTML login page. Do not decode those bytes and then call a partial parse “close enough.” First check the status and media type, then the byte size and character encoding, then the JSON and its shape. Only after getting the expected shape should the data-quality layer inspect time and numeric values.

For this practice contract, a 401 or 403 is reported as access denied, 429 is reported as rate limited and other disallowed statuses are reported as unavailable. In a real interface, the precise meaning and action can depend on the provider. A response can include useful retry guidance such as a Retry-After field, but its presence is not assumed. See RFC 6585 on 429. This example neither waits nor retries. It gives the caller one clear result without trying to evade a limit or change the number of requests invisibly.

For the exercise, write five cases with provider-shaped fixtures: a valid empty result, a valid result with one row, a 403 response, an unexpected HTML body, and an oversized body. Specify which cases should propagate a usable result. A valid empty result means the documented array contained no rows; a service or parse failure means the client never received an interpretable result. These should not be represented interchangeably.

Answer check. Ask Quanty which change would cause an HTML response with status 200 to pass incorrectly. Provide the content type and an invented short placeholder body, not a downloaded provider error page. A useful test demonstrates that the media type alone can be wrong even when the status is the expected one.

Lesson 4: Build an adapter with no network dependency

Offline adapter: Fake transport → JSON fixture → Validate rows.
Offline adapter: Fake transport → JSON fixture → Validate rows.

Save the example as read_candles.py. It has no implementation capable of reaching the network. The transport argument receives a request object and returns one in-memory response. The caller chooses the function. The request has no base URL, headers, account identifier or secret.

Python
from dataclasses import dataclass
import json
import re
from typing import Callable


MAX_BYTES = 128 * 1024
MAX_ROWS = 1000
INTERVALS = {"5m", "15m", "1h"}
FIELDS = {"start", "open", "high", "low", "close", "volume"}


@dataclass(frozen=True)
class Request:
    method: str
    path: str
    params: tuple[tuple[str, str], ...]


@dataclass(frozen=True)
class Response:
    status: int
    content_type: str
    body: bytes


class ReadError(Exception):
    pass


def candle_request(symbol: str, interval: str, limit: int) -> Request:
    if not re.fullmatch(r"[A-Z][A-Z0-9]{0,11}", symbol):
        raise ValueError("expected a fictional uppercase symbol label")
    if interval not in INTERVALS:
        raise ValueError("unsupported exercise interval")
    if type(limit) is not int or not 1 <= limit <= MAX_ROWS:
        raise ValueError("limit must be an integer within the exercise range")
    return Request("GET", "/fixture/candles", (
        ("symbol", symbol), ("interval", interval), ("limit", str(limit)),
    ))


def decode_rows(response: Response, limit: int) -> list[dict[str, str]]:
    if response.status in (401, 403):
        raise ReadError("read not permitted")
    if response.status == 429:
        raise ReadError("read rate limited")
    if response.status != 200:
        raise ReadError("read unavailable")
    media_type = response.content_type.partition(";")[0].strip().lower()
    if media_type != "application/json":
        raise ReadError("expected a JSON response")
    if len(response.body) > MAX_BYTES:
        raise ReadError("response exceeds byte limit")
    try:
        decoded = json.loads(response.body.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError, RecursionError, ValueError) as error:
        raise ReadError("response is not valid UTF-8 JSON") from error
    if not isinstance(decoded, dict) or not isinstance(decoded.get("candles"), list):
        raise ReadError("response needs a candles list")
    candles = decoded["candles"]
    if len(candles) > limit:
        raise ReadError("response exceeds requested row limit")
    if any(
        not isinstance(row, dict)
        or set(row) != FIELDS
        or any(not isinstance(v, str) or not v.strip() for v in row.values())
        for row in candles
    ):
        raise ReadError("unexpected candle row shape")
    return candles


def read_candles(
    symbol: str,
    interval: str,
    limit: int,
    transport: Callable[[Request], Response],
) -> list[dict[str, str]]:
    request = candle_request(symbol, interval, limit)
    try:
        response = transport(request)
    except OSError as error:
        raise ReadError("fixture transport unavailable") from error
    return decode_rows(response, limit)

The request uses a tuple of named parameters; it does not construct a real query string. If you later need URL construction for a documented host, use an appropriate library rather than concatenating irregular values into a URL. Read Python's URL-parsing documentation for the library's boundaries and caveats. This course does not permit a caller to supply a host or run a request through an arbitrary location.

The decoder performs deliberately shallow validation of each row before returning it. For example, a nonempty string in the close field is not assumed to be a valid finite number. The next validation layer must check dates, ordering, duplicates and relationships among prices as described in the prior course. Keeping those boundaries visible lets you distinguish a broken response shape from a well-shaped response containing a bad price. The parser does not put an unknowable number in place of a malformed field.

For the exercise, create a one-row synthetic result and inspect the exact request seen by a capturing transport. Change the interval and negotiate the expected tuple before changing the expected output body. Now change only the output media type to a text type and run again. The exercise verifies that these are separate concerns: request construction may be correct even though the response is refused.

Answer check. Explain why the body-byte check is done before decoding. Ask for a test that distinguishes a row limit from a byte limit. One long representation with a few rows could exceed the byte limit; many compact rows could exceed the requested row limit without exceeding the byte cap. Checking only one gives different results from the specified contract.

Lesson 5: Use local response fixtures to prove the adapter

Response test set: Success fixture → Bad schema fixture → Error fixture.
Response test set: Success fixture → Bad schema fixture → Error fixture.

The next file is test_read_candles.py. Run it with python -m unittest -v. The test suite uses no connector, real token or live response.

Python
import json
import unittest

from read_candles import MAX_BYTES, ReadError, Response, read_candles


ROW = {
    "start": "2026-01-05T04:30:00+00:00",
    "open": "100", "high": "103", "low": "99", "close": "102", "volume": "12",
}


def payload(rows):
    return json.dumps({"candles": rows}).encode("utf-8")


class ReadCandlesTests(unittest.TestCase):
    def test_builds_read_request(self):
        observed = []
        def simulate(request):
            observed.append(request)
            return Response(200, "application/json; charset=utf-8", payload([ROW]))
        self.assertEqual(read_candles("DEMO1", "5m", 2, simulate), [ROW])
        self.assertEqual(len(observed), 1)
        self.assertEqual(observed[0].method, "GET")
        self.assertEqual(observed[0].path, "/fixture/candles")
        self.assertEqual(dict(observed[0].params), {"symbol": "DEMO1", "interval": "5m", "limit": "2"})

    def test_valid_empty_result_is_not_unavailable(self):
        r = Response(200, "application/json", payload([]))
        self.assertEqual(read_candles("DEMO1", "15m", 1, lambda _: r), [])

    def test_invalid_request_never_reaches_transport(self):
        def should_not_run(_):
            self.fail("transport must not run on invalid input")
        with self.assertRaises(ValueError):
            read_candles("DEMO1", "1m", 1, should_not_run)

    def test_error_categories(self):
        for code, kind in ((401, "not permitted"), (403, "not permitted"), (429, "rate limited"), (503, "unavailable")):
            with self.subTest(code=code), self.assertRaisesRegex(ReadError, kind):
                read_candles("DEMO1", "5m", 3, lambda _: Response(code, "text/plain", b"ignored"))

    def test_rejects_wrong_body_and_bounds(self):
        cases = [
            (Response(200, "text/html", b"<h1>Outside fixture</h1>"), "JSON response"),
            (Response(200, "application/json", b" " * (MAX_BYTES + 1)), "byte limit"),
            (Response(200, "application/json", b'{"candles":[}'), "valid UTF-8 JSON"),
            (Response(200, "application/json", payload([ROW, ROW])), "row limit"),
            (Response(200, "application/json", payload([{"close": "100"}])), "row shape"),
        ]
        for response, expected in cases:
            with self.subTest(expected=expected), self.assertRaisesRegex(ReadError, expected):
                read_candles("DEMO1", "5m", 1, lambda _: response)

    def test_transport_error_contains_no_response_body(self):
        def simulate(_):
            raise OSError("fictional transport detail")
        with self.assertRaisesRegex(ReadError, "^fixture transport unavailable$"):
            read_candles("DEMO1", "5m", 1, simulate)

The capturing test checks the method and bound independently from whether the fixture returns a row. If you changed the string representing the method while leaving the fixture unchanged, the row could still come back. The capture is what detects that the code no longer implements a read request as intended. Testing the outgoing shape and the decoded result with one fixture does not require you to connect to a remote server.

The error-category test supplies arbitrary bodies on non-200 responses. The adapter does not attempt to turn these bodies into chart data. The bad-body suite targets different failures at successive layers: the media type, the byte bound, JSON structure and the list shape. For a new classroom exercise, add a case where the body uses an invalid Unicode byte sequence. Use a few bytes and don't reproduce a real response. The failure should identify the decoding boundary rather than leaking the raw body in a general status message.

Answer check. Ask which test would fail if the adapter silently returned an empty list whenever the service responded 429. Confirm the fixture expects a rate-limit exception, not a list; then restore the mutation. A result reader needs to distinguish “no rows” from “we do not know because the read failed.”

Lesson 6: Make pagination and retry decisions visible before coding them

Pagination decisions: Current page → Check cursor → Stop or next page.
Pagination decisions: Current page → Check cursor → Stop or next page.

Not every provider returns all requested history in one page. This fixture deliberately does not paginate. If you extend it, first determine whether the documented endpoint uses a continuation token, an offset, timestamps or a different method. Avoid guessing continuation rules from an example response. The same token could be allowed once, or it could represent a cursor over data that changes; those semantics must come from the provider.

Draw a graph of three fictional pages: A points to B, B points to C, and C ends. Next create a graph in which B points back to A. Write the maximum pages, maximum total rows and what to do if the same continuation appears twice. A bounded loop and a clear error are easier to test than an assumption that the last page will always be reached. Decide whether partial results are returned, and if so how the caller knows they are partial. Do not silently pass them to a calculation expecting complete history.

Separate defensive control from attempts to bypass restrictions. If a documented endpoint limits requests, respect the bound and report when the service refuses further reads. A production policy could say “stop and notify” or “try later using a bounded wait after guidance,” depending on permissions and requirements. Never rotate identities, evade limits or assume a retry is harmless in a workflow that could change state. This exercise doesn't add automatic retries even for fictional data. It tests the immediate category that a later, documented policy could consume.

For a review exercise, model the second page as unavailable after the first returned two rows. Make that different from a documented second page with no rows and an explicit end marker. Then change the order of the returned rows and note where chronological validation should happen. The adapter is responsible for the sequence of successful responses under the transport contract. The candle audit is responsible for checking the resulting data against its documented interval contract. A single “it works” assertion should not substitute for those independent checks.

Answer check. Ask Quanty for one fixture that detects repetition and one that detects a shape mismatch halfway through a series. Do not ask for live connection steps, trading permissions or workarounds. The goal is more reliable software, not forcing an endpoint to respond.

Capstone: Write a review note for a provider-specific extension

Prepare a short note describing exactly what your tested adapter supports: a fixture-only GET shape, bounded results, explicit media type, row shape and error categories. List the official provider documentation you would need before real integration: authentication, permitted account scope, available candle intervals, exchange or instrument identifiers, date semantics, response limits and rate limits. Confirm separately whether that planned scope requires access to a paid data feature. The practice project does not make a promise about any provider's service or rules.

Add a section describing your chosen limits and where they apply. This fixture checks a body already provided by the transport, not a network streaming download. A real transport must bound time and size while receiving data, rather than allocating any response and then checking its length. Likewise, this fixture catches a make-believe transport error and does not prove your app handles DNS, certificates, proxies or production availability. Naming what was not tested is an important part of a user-facing launch decision.

Share your own synthetic input, expected result and one failing local test with Quanty exercise review (beta), if you choose to use it. Ask for a minimal explanation and one missing test. Do not ask it to infer a broker's current behaviour from this made-up response. After making a change, rerun the tests yourself and keep the previous expected result visible. If a suggested change broadens the scope from read-only to account actions, it does not belong in this course.

Applied case: Tell a schema error from a numerical error

A well-shaped response can still contain impossible values. Make five fixtures and label the first step at which each should fail. Use a JSON response with the top-level key written as data instead of candles. Use another with candles as an object rather than an array. Use a third with the correct array and all fields, but a close that is empty. Use a fourth with a nonempty close that says “not a number”. Use a fifth with everything present and a high that is lower than the open.

The first three examples fail in this adapter because they break the expected representation. The last two should pass this layer as shaped records and fail in the separate numerical audit. That difference is useful. If a vendor changes the name of a field, the person investigating needs to compare API versions and documentation. If the field name is correct but the values are impossible, the person needs to compare the records to the source. One error report saying “no candles” cannot describe both situations.

Document what you do after each failure. A general “retry now” rule is not helpful for a stable schema mismatch. Nor should a client stop validating all fields because one service uses a different version. The first response should be a diagnostic: the expected shape and first category that failed. If you need to record a small structural sample, remove users, credentials and irrelevant payload content. Use each lesson fixture's invented values when you ask for help.

Make a separate test of how a body is counted. Text strings are measured differently from encoded byte strings when a file contains characters outside basic ASCII. The cap in this example is defined in bytes, so apply it to the result before decoding. Do not compute a Content-Length header from a decoded string and treat that as a receipt. A real server could already have transformed or compressed a representation; the meaning of a particular length should be checked against the networking library and provider contract. The fixture operates on response bytes as given and does not claim to cover transport-level bounds.

The adapter reads the top-level object and checks for the array but does not reject all additional top-level keys. That reflects a local compatibility choice: future harmless metadata can accompany the array, while the candle rows themselves have exact fields. Make one sample with a permitted top-level metadata key and one row with an extra field. Predict the difference. If you prefer to require exact top-level keys too, change the written schema first and test the same samples against the new decision.

Applied case: Reproduce a failure without a live API

Imagine a classmate reports “it stopped working after the first response.” That statement leaves several possibilities: the next request was never built, it did not reach the transport, an HTTP category was returned, or the parser rejected an otherwise normal-looking success response. You can simulate each possibility by giving the adapter a compact fixture. Before adding logging, decide which part of the flow can be observed without touching real data.

In the first trace, let validation reject the input. The capturing transport should see no call. In the second, give the transport valid arguments and have it raise a fictional unavailable error. The request can still be observed, while no response is available. In the third, provide a status representing temporary unavailability. The adapter should return the relevant error even if the fictional response body contains text. In the fourth, provide the expected success status and an unsupported content type. That exercises the representation guard rather than the status guard.

Give your report one entry per run: what you passed, whether the transport ran, the category you observed and the expectation that justifies it. If you share the note, use the invented symbol label and fixture paths from this course. There is no reason to paste a real hostname, timestamped account history, cookies or a version of a token you believe is expired. A minimal reproducible case is easier to compare precisely because unnecessary values are absent.

If you later work with actual integration logs, review safe logging conventions with whoever owns the integration. Unexpected messages can include data intended only for an authorised user, or details specific to a provider. Even a timestamp and path can reveal operational context. In this lesson the adapter's public exception message is intentionally short. Python keeps the original exception as internal cause for debugging; do not turn full chained tracebacks into user-facing summaries. The tests inspect the short message rather than claiming the original details cease to exist.

Answer check. Ask what you can infer from the capture count being zero. The answer should distinguish an expected refusal before transport from a case where your capture simply did not observe the relevant function. Review the test setup first. It is useful to include one successful read in the same suite so you know the harness can record a request when it should.

Applied case: Define a read-only handoff before a provider review

Suppose the next team wants to bind the adapter to a documented sandbox. Keep this lesson unchanged and write a new interface contract. Identify the exact read endpoint, its required permissions, and who is allowed to configure those permissions. Confirm that the credentials used for the environment do not allow unrelated account actions if the service offers that narrower scope. Record how the sandbox is separated from other environments. A colourful demo showing candle values is not evidence that the calls used the intended account or permissions.

Choose two acceptance checks for the proposed interface. One checks that the authenticated request reaches the documented read path and returns a known educational symbol and interval. The other checks that a refused read does not turn into an empty success. If there is no authorised sandbox, stop at fixture testing and clearly label the gap. The course does not include instructions for obtaining credentials, creating an account or entering a provider's systems. It teaches how to reason about the interface before any such work is approved.

Add a plan for how a documented API update would reach your code. A change to interval identifiers belongs in request mapping; a change to row structure belongs in the decoder; a change in how bars are labelled belongs in data validation and interpretation. Use individual test fixtures that reproduce these distinctions. If every concern is buried inside one request function, it is harder to see what a proposed change affects. Keeping the modules separate limits that uncertainty without imposing a framework on the entire project.

Finally decide who gets the next action. The practice client consumes a response and prepares rows for inspection. It does not hand them directly to an account action or run any order logic. A person reviewing an integration can confirm documentation, environment and data behaviour independently. An answer review from Quanty can suggest a test but cannot create authority to access or modify someone else's account. This distinction is both a software boundary and a review boundary.

Applied case: Compare two sets without pretending they are the same market view

Two providers might supply historical records for the same named interval while encoding the time differently or including different sessions. Before writing a comparison, document what “same” means: the same instrument identifier, the same timezone and boundary convention, and the same source assumptions. The synthetic practice row only represents the exact fields required by its fixture. You cannot prove that it corresponds to another dataset just because the dates look similar.

Start by comparing the representation and record count. Next map the known time convention and validate the rows. Finally compare the values you care about under a written tolerance or exact-equality requirement. A missing comparison match should not be reported simply as a difference in price. The preceding candle-data course gives the shape of a test that distinguishes a missing row from unequal matched values. Keep the request and parsing tests even after adding that comparison; it does not replace them.

FAQ about this course

Will this code work against my broker's API?

No. It is an offline fixture and deliberately has no network transport. A real integration has a separate documented provider contract and permissions. The exercise shows how to isolate and test a read adapter without conflating it with market behaviour.

Is a 200 response enough to accept a candle file?

No. The status is one part of the contract. You still need the appropriate media type, valid encoding, correct structure and bounded results. The separate data layer then needs to check the values and time sequence. One valid-looking row does not establish that the full response is usable.

Why does the example not retry a refused request?

The course shows deterministic failure categories, not a live retry policy. A documented, optional policy can be tested separately without treating denial, limits and temporary unavailability as identical. A retry that changes an account or ignores scope is out of bounds.