Skip to main content

smartbroker-plus-sdk

Build Python Versions License: MIT PRs Welcome

Typed Python SDK and CLI for the Smartbroker+ B2B API.

Features

  • OAuth2 Authorization Code + PKCE helpers — full RFC 7636 implementation; the SDK handles token exchange, refresh, and revocation.
  • Sync and async parity — SmartbrokerClient and AsyncSmartbrokerClient expose identical resource surfaces.
  • Full B2B resource coverage — orders, order modifications, portfolios, positions, account transactions, market state, tradeability, cost report, and profile.
  • 2FA token header support — automatic X-2fa-Token injection for order-modifying endpoints.
  • Typed end-to-end — Pydantic v2 models throughout, ships py.typed.
  • RFC 9457 error mapping — HTTP problem details mapped to a typed exception hierarchy.
  • Python 3.11+

Installation

Python 3.11, 3.12 and 3.13 are supported.

# The SDK alone
pip install smartbroker-plus-sdk

# The SDK plus the `sbplus` command-line interface
pip install 'smartbroker-plus-sdk[cli]'

The sbplus console script is registered either way, but it needs the cli extra to do anything: after an SDK-only installation it starts, finds Typer and Rich missing, and tells you to run pip install 'smartbroker-plus-sdk[cli]'.

Quick Start (sync)

Your application owns the browser half of the OAuth flow: it registers the redirect URI with the authorization server and serves it, it compares the state it receives on the callback against the one it sent, and it decides where the returned tokens are persisted. The SDK owns the half that follows — exchanging the authorization code, refreshing the access token, and signing every request.

from smartbroker_plus_sdk import (
    Environment,
    SmartbrokerClient,
    generate_code_challenge,
    generate_code_verifier,
    resolve_environment,
)

# 1. Generate PKCE pair before starting the authorization flow
verifier = generate_code_verifier()
challenge = generate_code_challenge(verifier)
# → Send `challenge` as `code_challenge` in the authorization URL your
#   application builds, together with a `state` value you keep for the callback

# 2. Create a client — it handles token exchange and refresh internally
endpoints = resolve_environment(Environment.PROD)
client = SmartbrokerClient(
    base_url=endpoints.api_base_url,
    token_url=endpoints.token_url,
    client_id="your_client_id",
    client_secret="your_client_secret",
)

# 3. Exchange the authorization code for tokens — after your application has
#    checked the returned `state` and decided where to persist the result
tokens = client.exchange_authorization_code(
    code="authorization_code_from_callback",
    redirect_uri="https://your-app.com/callback",
    code_verifier=verifier,
)

# 4. Use resources
portfolios = client.portfolios.get_portfolios()
print(f"{len(portfolios)} portfolio(s) reachable")

Quick Start (async)

The async client mirrors the sync one, and the same division of duties applies: your application serves the redirect URI, validates state, and persists tokens.

import asyncio

from smartbroker_plus_sdk import (
    AsyncSmartbrokerClient,
    Environment,
    generate_code_challenge,
    generate_code_verifier,
    resolve_environment,
)


async def main() -> None:
    verifier = generate_code_verifier()
    challenge = generate_code_challenge(verifier)

    endpoints = resolve_environment(Environment.PROD)
    client = AsyncSmartbrokerClient(
        base_url=endpoints.api_base_url,
        token_url=endpoints.token_url,
        client_id="your_client_id",
        client_secret="your_client_secret",
    )

    await client.exchange_authorization_code(
        code="authorization_code_from_callback",
        redirect_uri="https://your-app.com/callback",
        code_verifier=verifier,
    )

    portfolios = await client.portfolios.get_portfolios()
    print(f"{len(portfolios)} portfolio(s) reachable")


asyncio.run(main())

Error Handling

All SDK errors extend SmartbrokerApiError:

SmartbrokerApiError           # every member has .status_code — the response's HTTP status, or None
├── AuthenticationError       # HTTP 401 — invalid/expired credentials
├── AuthorizationError        # HTTP 403 — insufficient permissions
├── NotFoundError             # HTTP 404 — resource does not exist
├── ValidationError           # the caller's request was the problem; the 400/412 fallback
│   ├── OrderRejectedError    # messageKey: ORDER_REJECTED
│   ├── InsufficientBalanceError   # messageKey: INSUFFICIENT_BALANCE
│   └── BuyingPowerExceededError   # messageKey: BUYINGPOWER_EXCEEDED
├── PriceQueryFailedError     # messageKey: REQUEST_ERROR — no live price; cause unknown
├── ServerError               # HTTP 5xx — vendor server-side failure
├── TwoFactorError            # 2FA token flow failed (timeout, rejection)
├── RetryExhaustedError       # all retry attempts exhausted; .last_error is the final attempt's error
├── NetworkError              # request never reached a response
└── ResponseParseError        # 2xx body was not JSON, or not the expected shape

Not every 400 is a ValidationError. A keyed refusal is classified by its messageKey first, and only an unkeyed or unrecognised one falls back to the status code — which is why PriceQueryFailedError sits beside ValidationError rather than under it. A live-price query that failed is not a request the caller can correct, so except ValidationError will not catch it; catch it by name, or by SmartbrokerApiError.

A failure the underlying HTTP client raises never reaches you as its own type: connect, timeout, protocol and proxy failures arrive as NetworkError, and a success body that cannot be parsed or validated arrives as ResponseParseError. Both keep the originating exception as __cause__.

from smartbroker_plus_sdk.exceptions import SmartbrokerApiError, ValidationError

try:
    client.orders.place(...)
except ValidationError as e:
    print(f"Validation failed: {e}")
except SmartbrokerApiError as e:
    print(f"API error: {e}")

Classifying a refusal

The typed classes above cover the refusals worth branching on by type. They are deliberately not exhaustive: the vendor documents more messageKey values than the SDK maps, and some refusals carry no key at all. To tell apart everything the classes do not separate, read message_key off the exception you caught.

Catch SmartbrokerApiError, not ValidationError. A keyed refusal is classified by its key first, and an unrecognised key falls back to the class its HTTP status implies — so an unmapped key on a 404 arrives as NotFoundError, which a validation-only handler misses.

from smartbroker_plus_sdk.exceptions import SmartbrokerApiError

try:
    client.orders.calculate(...)
except SmartbrokerApiError as e:
    if e.message_key == "REQUEST_ERROR":
        print("No live price right now — the vendor asks you to retry")
    elif e.message_key is None:
        print(f"Keyless refusal: {e}")
    else:
        print(f"Refused with {e.message_key}")

message_key is None for a keyless refusal and for a failure that never carried a problem body, so guard for it rather than comparing blindly.

message_key answers which refusal this was, and nothing more. The vendor's own words about it — the title and detail, the HTTP status, and the field-level violations — stay on problem_detail, which remains the route to all of that:

from smartbroker_plus_sdk.exceptions import SmartbrokerApiError

try:
    client.orders.calculate(...)
except SmartbrokerApiError as e:
    if e.problem_detail is not None:
        print(e.problem_detail.detail)

Reading how a failed call ended

Every exception carries status_code: the HTTP status of the response it was built from, or None when no response produced it. It is the status on the wire, so a ServerError says which 5xx arrived even when the body was a gateway page rather than a problem document. problem_detail.status is what the body claims; behind an intermediary the two can differ, and both stay readable.

Safe requests (GET, HEAD, OPTIONS) are retried on a ServerError or a retryable NetworkError. When the retries run out the SDK raises RetryExhaustedError, whose last_error is the exception the final attempt raised — always present, and the same object as __cause__:

from smartbroker_plus_sdk.exceptions import (
    NetworkError,
    RetryExhaustedError,
    ServerError,
)

try:
    client.marketstate.get_crypto_prices(...)
except RetryExhaustedError as exhausted:
    final = exhausted.last_error
    if isinstance(final, ServerError):
        print(f"The vendor faulted on the last attempt: HTTP {final.status_code}")
    elif isinstance(final, NetworkError):
        print("The last attempt never got an answer")

RetryExhaustedError delegates nothing: its own status_code is None and its message_key and problem_detail are empty, so read all three off last_error. Only the final attempt is kept. A request that is not retried — any other method — raises its ServerError or NetworkError directly, and status_code is read off that the same way.

ServerError is not the set of all 5xx responses. A keyed refusal is classified by its messageKey first, so a 5xx carrying a mapped key arrives as that key's class, and the token endpoint keeps every error in the authentication family. Carrying the status changes neither which class is raised nor which failures are retried — to ask whether the answer was a 5xx, read status_code, not the class.

2FA Tokens

Order-modifying endpoints need an approved 2FA token. TwoFactorTokenSource serves one from the cache, refreshes it before it goes stale, and mints a fresh one — with a device approval — when there is nothing to refresh. get(..., force_refresh=True) rotates on demand.

See docs/two_factor_tokens.md for the cache branches, the forced-refresh contract and its fallbacks, and the concurrency rules.

CLI Quick Start

Install the package and run the CLI with sbplus:

# 1. Set credentials (or use env vars — see table below)
export SMARTBROKER_CLIENT_ID=my-client-id
export SMARTBROKER_CLIENT_SECRET=my-client-secret  # or enter at the prompt

# 2. Log in — prompts for environment (sand/prod), then opens browser for PKCE flow
sbplus auth login
# > Environment [sand/prod] (prod): prod
# > Credentials will be stored at ~/.cache/smartbroker-plus/tokens.json. Continue? [Y/n]:

# 3. Check status and browse data
sbplus auth status
sbplus portfolios list
sbplus orders list --portfolio <portfolioId>

# 4. Log out
sbplus auth logout

Use --output (or -o) to change the format: table, wide, detail, json. table is the default on a terminal; when stdout is redirected or piped, the format becomes json automatically unless -o says otherwise. --output is a global option, so it goes before the subcommand.

Scope orders list to a single account with --account (env: SMARTBROKER_ACCOUNT), and add --with-partial-executions to receive the richer V2 listing whose entries carry partial-execution summaries:

sbplus orders list --portfolio <portfolioId> --account <accountId> --with-partial-executions

Increase log verbosity with -v (info), -vv (debug — full HTTP wire dump), or -vvv (trace). Setting SBP_LOG=info|debug|trace has the same effect without flags. See docs/logging.md.

Placing an Order

The orders calculate → orders place pipeline previews fees before committing:

# 1. Approve a 2FA token (cached until expiry)
sbplus auth 2fa create --wait

# 2. Preview the order and capture the calc response
sbplus -o json orders calculate \
  --portfolio <portfolioId> \
  --isin US0378331005 \
  --exchange EDG \
  --direction buy \
  --units 1 > calc.json

# 3. Review fees, then place (prompts for confirmation)
sbplus orders place --portfolio <portfolioId> --order-data-file calc.json
# About to place: BUY 1.0 US0378331005 @ EDG MARKET. Proceed? [y/N]:

# One-liner via stdin (--yes skips the prompt, --2fa-token overrides cache)
sbplus -o json orders calculate --portfolio <portfolioId> --isin US0378331005 \
  --exchange EDG --direction buy --units 1 \
  | sbplus orders place --portfolio <portfolioId> --order-data-file - --yes

Environment Variables

Variable Flag Description
SMARTBROKER_BASE_URL --base-url API base URL
SMARTBROKER_ENV --env Deployment environment (sand or prod)
SMARTBROKER_AUTH_BASE_URL --auth-base-url Auth/IdP base URL (defaults to --base-url)
SMARTBROKER_CLIENT_ID --client-id OAuth2 client ID
SMARTBROKER_CLIENT_SECRET --client-secret OAuth2 client secret
SMARTBROKER_REDIRECT_URI --redirect-uri OAuth2 redirect URI (defaults to the loopback URI registered for the environment: http://127.0.0.1:8765/callback for sand, http://127.0.0.1:9442/reachme for prod)
SMARTBROKER_CACHE_DIR --cache-dir Token cache directory
SMARTBROKER_OUTPUT --output / -o Default output format (table, wide, detail, json)
SMARTBROKER_TIMEOUT --timeout HTTP request timeout in seconds (default: 30)
SMARTBROKER_PORTFOLIO --portfolio Default portfolio identifier
SMARTBROKER_ACCOUNT --account Default account number
SMARTBROKER_EXCHANGE --exchange Default exchange (Coperitus code)
SMARTBROKER_PAGE_SIZE --page-size Default page size for list commands
SMARTBROKER_NON_INTERACTIVE --non-interactive Disable interactive prompts; guarded commands fail instead of asking

Naming convention. Environment variable names mirror their flag: drop the leading dashes, uppercase, replace - with _, and prefix with SMARTBROKER_ (for example --page-size → SMARTBROKER_PAGE_SIZE).

Resolution precedence. An explicit flag overrides the environment variable. When neither is provided and the option is required, the CLI emits the standard missing-parameter error.

Env-sourced confirmation prompts. When the portfolio used in an order confirmation prompt was sourced from SMARTBROKER_PORTFOLIO, the prompt annotates it with the variable name so the source is unambiguous:

Portfolio: <portfolioId>  [env: SMARTBROKER_PORTFOLIO]
Account:   <accountNumber>

Values supplied via --portfolio are rendered without annotation. The account line is sourced from the calculate-response payload, never from SMARTBROKER_ACCOUNT, and therefore carries no [env: ...] annotation in the place/modify flow.

Exit Codes

Code Meaning
0 Success
1 General error / unexpected exception
2 Authentication or authorization failure
3 Resource not found
4 Validation error
5 Server error
6 2FA required
7 Retry limit exhausted
8 Network failure — the request never reached a response
9 Response body could not be parsed or validated
130 Interrupted (Ctrl-C)

Driving the CLI from an AI agent

skills/sbplus/ is an Agent Skill that orients a coding agent around sbplus and keeps account numbers, IBANs, portfolio ids and holder names out of its conversation transcript. Install it into an agent's configuration directory with vercel-labs/skills:

npx skills add stevenengland/smartbroker-plus-sdk

The skill ships redact.py, a stdlib-only filter the agent pipes every invocation through:

sbplus -o json portfolios list 2>/tmp/sbplus.err | python3 redact.py

It is guidance, not a sandbox — the CLI itself is unchanged, and an agent that ignores the skill can still print whatever the API returns. Give agents the portfolio and account via SMARTBROKER_PORTFOLIO and SMARTBROKER_ACCOUNT so they never need to read an identifier out of a response. See skills/sbplus/SKILL.md.

Troubleshooting

See docs/troubleshooting.md for common gotchas.

Changelog

See CHANGELOG.md.

Development

See docs/development.md for the full development guide.

Metadata

Release files for smartbroker-plus-sdk 0.14.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for smartbroker-plus-sdk 0.14.0
File Size Uploaded Provenance Actions
smartbroker_plus_sdk-0.14.0.tar.gz 222.0 kB With provenance Details for smartbroker_plus_sdk-0.14.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for smartbroker-plus-sdk 0.14.0
File Interpreter ABI Platform Actions
smartbroker_plus_sdk-0.14.0-py3-none-any.whl Python 3 none any Details for smartbroker_plus_sdk-0.14.0-py3-none-any.whl

Total release size: 472.5 kB

Release files / smartbroker_plus_sdk-0.14.0.tar.gz

Download URL smartbroker_plus_sdk-0.14.0.tar.gz
Size 222.0 kB
Tags Source
SHA-256 checksum
How to use checksums
44314196c9ca1fbc2ac367b3c3d196a81e365d5386808ae03eb6dd3b7ea0cd93
BLAKE2b-256 checksum
How to use checksums
7f921f3b650d5d1c1a96a5943fb9adcafb43bdb8930c46c1cdb40f3d2162428b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

Release files / smartbroker_plus_sdk-0.14.0-py3-none-any.whl

Download URL smartbroker_plus_sdk-0.14.0-py3-none-any.whl
Size 250.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
61b0228663023729f6b338d414e61be62d291c42bf7b8d30c5dd92c695082827
BLAKE2b-256 checksum
How to use checksums
2b2d2246552352c3a373042435d6d31abb9bec1c54709c1f9b59f4ca3834ac5d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

Security for smartbroker-plus-sdk 0.14.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for smartbroker_plus_sdk-0.14.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page