Skip to main content

tradesquares (SDK)

Open-source Python SDK for building TradeSquares agents. It holds no data and no secrets: every call is an authenticated HTTPS request to the TradeSquares agent gateway, which does all checks.

pip install tradesquares

What is in this repo

Path What
tradesquares/ The package published to PyPI
examples/ Example agents (agent.yaml + agent.py)
tests/ SDK tests; results in tests/results/ (not committed)

The gateway and the sandbox server are private and live in tradesquares-agent-platform.

Settings

Create a .env file in the folder you run your agent from, with one line:

TS_API_KEY=tsk_live_...

That is the only setting. Get a key by signing up for a free trial (the gateway emails a link that shows the key once); the key's agent has every public-data scope.

The key decides which gateway the SDK talks to; your code is the same for both:

Key Gateway ctx.portfolio returns
tsk_sandbox_... sandbox a fake customer's portfolio, safe to test with
tsk_live_... live your own linked brokerage accounts

ctx.environment is "sandbox" or "live", and every portfolio reply says the same.

Limits

Limit Paid Trial When it is reached
Calls per minute, per agent 120 30 The SDK waits (the gateway says how long) and retries by itself
Calls per day, per account (resets 00:00 UTC) 20,000 1,000 QuotaExceededError, saying when access resumes

Replies carry the remaining daily calls; the SDK logs one warning when 80% of the day's calls are used, and keeps the latest numbers in ctx.quota (limit, remaining, reset).

Writing an agent

from tradesquares import Agent, Context

agent = Agent()

@agent.on_schedule
async def run(ctx: Context) -> dict:
    bars = await ctx.history.daily("SPY", "2026-10-01", "2026-10-30")
    ema = await ctx.indicators.compute("SPY", "ema", [200], start="2026-10-01", end="2026-10-30")
    cross = await ctx.indicators.evaluate("SPY", start="2026-06-01", end="2026-10-30",
                                          condition="crossover(ema(9), ema(21))")
    income = await ctx.fundamentals.periods("SPY", "income_statement", "2020-01-01", "2026-12-31", period="FY")
    return {"close": bars[-1].close, "ema_200": ema.latest(), "crossed_on": cross.true_dates()}

asyncio.run(agent.run_once()) runs it once with public data. A full example is in examples/ema_200/.

Call Scope Returns
ctx.history.daily(symbol, start, end, adjusted=True) history:read list of Bar
ctx.history.intraday(symbol, start, end, timeframe) history:read list of IntradayBar (.time = bar open, New York time; regular hours; split-adjusted). timeframe: 1min 3min 5min 15min 30min 1h 4h
ctx.indicators.compute(symbol, name, args, start=, end=, adjusted=True, src=None) indicators:read IndicatorSeries (.value, .outputs, .latest())
ctx.indicators.evaluate(symbol, start=, end=, value= or condition=) indicators:read EvaluatedSeries (.values, .true_dates()) — any one-line StratQL expression
ctx.fundamentals.periods(symbol, type, start, end, period=None, as_of=None) fundamentals:read list of PeriodRow (.data)
ctx.fundamentals.snapshots(symbol, type, start, end, as_of=None) fundamentals:read list of DatedRow
ctx.fundamentals.events(symbol, type, start, end, as_of=None) fundamentals:read list of DatedRow

Indicators are computed with StratQL, the same engine as TradeSquares backtests; the warm-up before start is handled for you. as_of returns fundamentals as they were known at the end of that day, so backtests do not see restated or later-filed numbers.

Fundamentals type values:

  • periods: income_statement, balance_sheet, cash_flow, income_statement_growth, balance_sheet_growth, cash_flow_growth, key_metrics, ratios, income_statement_as_reported, balance_sheet_as_reported, cash_flow_as_reported, revenue_by_product, revenue_by_region, insider_statistics
  • snapshots: ratios_ttm, key_metrics_ttm, scores, dcf, peers, price_target_summary, analyst_consensus, etf_holdings, rating, analyst_grades, market_cap
  • events: earnings, earnings_surprise, dividend, split, grade_change, price_target_change, insider_trade, employee_count, sec_filing, analyst_estimate_annual, analyst_estimate_quarter

Errors are subclasses of TradeSquaresError with the gateway's .code: AuthError, ScopeError, PlanLimitError (e.g. a trial reading older than 30 days), AccountError, RateLimitError, QuotaExceededError (a RateLimitError), BadRequestError, NotFoundError, UnavailableError.

Portfolio

Needs scope portfolio:read. Without a customer (agent.run_once()) it reads your own accounts, or a fake customer's on a sandbox key.

Call Returns
ctx.portfolio.positions() list of Position: account (opaque label, e.g. acct_3f9a0c12d4), symbol, underlying, quantity (negative = short), asset_type (equity, option, crypto, ...), is_option, avg_price, market_value, unrealized_pnl, multiplier
ctx.portfolio.balances() Balances: environment, as_of, equity, cash, buying_power (all accounts added together)

The same symbol held in two accounts is two positions with different account labels. No reply contains an account number. Example: examples/portfolio_check.

Orders

Needs scope orders:read. Like the portfolio, it reads your own accounts (a fake customer's on a sandbox key).

Call Returns
ctx.orders.history(days) list of Order, newest first: account, symbol, side (buy / sell), quantity (always positive), price, fee, asset_type, trade_date

Only filled trades exist; brokers report no cancelled or unfilled orders here. Example: examples/order_habits.

Running for customers

agent.run_for_customers() runs your function once per customer who approved the agent, with ctx.subject_id set (an opaque id such as sbx_4f1c9a2e7b03d6e1, never a name, email or account) and ctx.portfolio / ctx.orders reading that customer.

  • Sandbox key: you get 100 fake customers, always the same 100 for you, treated as approved.
  • Live key: the list is empty until customers can approve agents (a later platform phase), so the same code runs and simply has no one to run for yet.
if __name__ == "__main__":
    for result in asyncio.run(agent.run_for_customers()):
        print(result["subject_id"], result["output"])

ctx.report arrives with that later phase.

Releasing (maintainers)

From /Users/vivekren/BrokerApp/tradesquares-sdk:

  1. Raise version in pyproject.toml (PyPI never accepts the same version twice).
  2. python -m build
  3. twine check dist/*
  4. twine upload dist/tradesquares-<version>*

Tests

python3 -m venv .venv && source .venv/bin/activate
pip install -e . -r tests/requirements.txt
bash tests/run_tests.sh

Metadata

Release files for tradesquares 0.4.3

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

Source distribution (sdist)

Source distribution for tradesquares 0.4.3
File Size Uploaded Provenance Actions
tradesquares-0.4.3.tar.gz 31.9 kB Without provenance Details for tradesquares-0.4.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tradesquares 0.4.3
File Interpreter ABI Platform Actions
tradesquares-0.4.3-py3-none-any.whl Python 3 none any Details for tradesquares-0.4.3-py3-none-any.whl

Total release size: 59.0 kB

Release files / tradesquares-0.4.3.tar.gz

Download URL tradesquares-0.4.3.tar.gz
Size 31.9 kB
Tags Source
SHA-256 checksum
How to use checksums
0ffb26126361788bdc922cbfade4159f75cfefee9d5c4d11bb6085ced2d8945c
BLAKE2b-256 checksum
How to use checksums
3084ee044a192d5b155b509e3f3d6ca295d89688609f5ee01cdd0ba0a4c9b170
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Release files / tradesquares-0.4.3-py3-none-any.whl

Download URL tradesquares-0.4.3-py3-none-any.whl
Size 27.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
71925c1a39291a00f978c003af9ca9a8cf88f61a40ec63d5bf2f1d7b3657c21e
BLAKE2b-256 checksum
How to use checksums
9ad95064fc40af73c28f445b614ff1eb554aa3f7e2930c9238000c4eddcac19a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Security for tradesquares 0.4.3

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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