Errors & retries
Describes stx-python 0.10.1, the current release.
What each endpoint can return is in the API reference, and request limits are in Rate limits. The SDK raises one exception per HTTP status, so you can catch the case you care about.
Exceptions
Section titled “Exceptions”str(exc) is the API’s error message, and exc.status_code, exc.body, exc.method and exc.path describe the request.
| Status | Exception | Typical cause |
|---|---|---|
| 400 | STXValidationException |
A bad parameter: status has invalid value: foo |
| 401 | STXAuthenticationException |
Bad key, bad signature, or a clock more than 30 s off |
| 403 | STXForbiddenException |
A read_only key on an order route |
| 404 | STXNotFoundException |
Unknown id, or one belonging to another account |
| 422 | STXRejectedException |
The exchange refused: closed market, insufficient funds, fractional quantity |
| 429 | STXRateLimitException |
Too many requests; retry_after in seconds when sent |
| 5xx | STXServerException |
Server failure |
Some refusals have a more specific class, still a subclass of the one above:
| Exception | Subclass of | When |
|---|---|---|
STXInvalidTokenException |
STXAuthenticationException |
An OAuth access token that is expired or revoked (after the SDK’s own refresh) |
STXInsufficientScopeException |
STXForbiddenException |
An OAuth token without the scope the call needs; required_scopes names it |
STXIpNotAllowedException |
STXForbiddenException |
An app writing from an address not on its IP allow-list |
STXTermsRequiredException |
STXForbiddenException |
A member who has to accept new STX terms; terms_url is the page |
STXBlockedException |
STXForbiddenException |
The request was blocked before it reached the exchange; see Blocked requests |
STXRestrictedJurisdictionException |
STXBlockedException |
Blocked: a location the exchange does not serve |
STXUnusualNetworkException |
STXBlockedException |
Blocked: a network the exchange does not accept traffic from |
STXFillModeNotAllowedException |
STXRejectedException |
A fill_mode the market does not take (combination markets); fill_mode names it |
STXPostOnlyWouldMatchException |
STXRejectedException |
A post-only order would have matched on arrival; reason, and order when the exchange cancelled it |
All of those derive from STXAPIException, which derives from STXException. Three more:
STXTransportException: no answer at all (connection refused, DNS, TLS, timeout)STXConfigException: the client is misconfigured (unknown region, missing key, bad PEM)STXChannelException: a WebSocket join or control event was refused;.replyholds the reason
Not available on this exchange
Section titled “Not available on this exchange”A feature an exchange does not offer yet raises STXNotAvailableError, whatever way the exchange said so. feature names it (combos, oauth, markets.create…) and host the exchange:
STXNotAvailableError: Market types are not available on demo.stxapp.ca yet.Nothing else on the client is affected. client.capabilities() tells you ahead of time; see What you can do. The OAuth flow’s own errors (oauth.STXOAuthException and its subclasses) are on Apps: connect members.
from stx import STX, STXNotFoundException, STXRejectedException, STXValidationException
with STX() as client: try: client.order("09b3c058-f9c0-4b0d-a6e9-f1295b7f0b33") except STXNotFoundException as exc: print("404:", exc)
try: client.markets(status="not-a-status") except STXValidationException as exc: print(exc.status_code, exc)
market = next( m for m in client.iter_markets(status="open", trading=True, sort_by="event_start", sort_direction="desc") if m.event_status == "scheduled" ) try: client.place_order(market.market_id, "buy", "limit", quantity="1") except (STXRejectedException, STXValidationException) as exc: print(exc.status_code, exc)Blocked requests
Section titled “Blocked requests”Some requests are refused in front of the exchange, before it sees them. Those raise STXBlockedException (403), with reason ("restricted_jurisdiction", "unusual_network", or "blocked" when no reason was given) and reference, the request id to quote to Support (from the x-amz-cf-id response header). They are never retried: the same request is blocked again. A 403 with no reason most often means the request had no User-Agent header; the SDK sends one, so check any code that replaces the HTTP client’s headers.
Too many requests from one address is STXRateLimitException (429) with retry_after and reference. The limits are in Rate limits.
from stx import STX, STXBlockedException, STXRateLimitException
with STX() as client: try: client.me() except STXBlockedException as exc: print(exc.reason, exc.reference, exc) except STXRateLimitException as exc: print("retry in", exc.retry_after, "s, reference", exc.reference)Sample output, from a network the exchange does not accept traffic from:
unusual_network Fm2a5Xq0pZ8Lw3YbH7rT9kUeN1cVdJ6oSgA4iQ-BzMxPyWl5RtOk3A== We can't connect you from this network. Quote the reference when you contact STX support.And when rate limited:
retry in 60.0 s, reference Fm2a5Xq0pZ8Lw3YbH7rT9kUeN1cVdJ6oSgA4iQ-BzMxPyWl5RtOk3A==What is retried
Section titled “What is retried”| Failure | GET, DELETE |
POST |
|---|---|---|
| 429 | retried, waiting Retry-After |
retried, waiting Retry-After |
| 403 blocked before the exchange | not retried | not retried |
| 5xx | retried | not retried |
| Connection error or timeout | retried | not retried |
| 400, 401, 403, 404, 422 | not retried | not retried |
A POST that failed with a server error or a dropped connection may still have placed the order, so the SDK does not send it again. Use client_order_id and look the order up (see Avoid duplicate orders).
Every attempt is signed afresh. Backoff is exponential with jitter: 0.5 s, 1 s, 2 s, capped at 30 s, over 3 attempts by default. When Retry-After asks for longer than the cap (max_backoff), the SDK raises STXRateLimitException at once rather than retry early. timeout is seconds per HTTP request (default 30).
from stx import NO_RETRY, STX, RetryPolicy
policy = RetryPolicy(max_attempts=5, initial_backoff=0.25, max_backoff=10)with STX(retry=policy, timeout=10.0) as client: print(len(client.markets(limit=1)))
with STX(retry=NO_RETRY) as client: print(client.me().scope)WebSocket failures
Section titled “WebSocket failures”The socket reconnects on its own (see Reconnects). A channel that the server closes or errors is rejoined; a rejoin refused as unauthorized closes that channel instead of retrying forever. ReconnectPolicy(max_attempts=...) bounds reconnects; after the last one, run_forever() returns and every channel’s iterator ends.
Logging
Section titled “Logging”The SDK logs to the stx logger (and stx.ws for the socket): requests at DEBUG, retries and reconnects at INFO and WARNING.
import logging
from stx import STX
logging.basicConfig(level=logging.INFO)logging.getLogger("stx").setLevel(logging.DEBUG)
with STX() as client: client.me()
