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.

Let TradeSquares run your agent (sandbox)

Upload the agent folder and TradeSquares checks it, builds it, gives it one trial run in a locked container, and then runs it for you: on the schedule in agent.yaml (New York time, US market trading days only) or when you ask, once per customer when it reads customer data. All commands use your admin key (TS_ADMIN_KEY). The agent id is <creator>.<name> from agent.yaml.

tradesquares push my_agent/ --environment sandbox                          # upload (never sends .env files)
tradesquares status vivek.portfolio-check 1.0.0 --environment sandbox      # UPLOADED ... APPROVED or REJECTED
tradesquares deploy vivek.portfolio-check 1.0.0 --environment sandbox      # runs on its schedule from now on
tradesquares run vivek.portfolio-check --environment sandbox               # run now
tradesquares logs vivek.portfolio-check --environment sandbox              # trial and real runs, newest first
tradesquares undeploy vivek.portfolio-check --environment sandbox          # stop

A run that breaks the rules of its key (another customer's data, an undeclared scope) fails as SECURITY and the version is QUARANTINED until TradeSquares reviews it. The full walk-through, upload rules and limits are in docs/guide.md ("Let TradeSquares run your agent").

Releasing (maintainers)

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

  1. Raise version in pyproject.toml (PyPI never accepts the same version twice).
  2. pip install --upgrade build twine, then python -m build
  3. twine check dist/tradesquares-<version>*
  4. twine upload dist/tradesquares-<version>* (only that version's files, not dist/*)

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.4

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.4
File Size Uploaded Provenance Actions
tradesquares-0.4.4.tar.gz 32.9 kB Without provenance Details for tradesquares-0.4.4.tar.gz

Built distribution (wheel)

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

Total release size: 60.5 kB

Release files / tradesquares-0.4.4.tar.gz

Download URL tradesquares-0.4.4.tar.gz
Size 32.9 kB
Tags Source
SHA-256 checksum
How to use checksums
2e31ad37f1e2d4bfcc3fa38989df349d69a136f2a144a6b6661f4047dc1de871
BLAKE2b-256 checksum
How to use checksums
ef7a0b71e51e688e4b2109327fd02927a7f22925abb7f552fb4921626a1ad559
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.4-py3-none-any.whl

Download URL tradesquares-0.4.4-py3-none-any.whl
Size 27.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c8d68cd6585b0b070889e2ea5d2615b6964a64917c2423e1c442fa5bdf75c940
BLAKE2b-256 checksum
How to use checksums
eef66604251d763c38f9c9b3a619dbb6577fe0b610b09f1312e33df3758cceda
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.4

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