Metadata-Version: 2.4
Name: tradesquares
Version: 0.3.1
Summary: Open-source Python SDK for building TradeSquares agents
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.27
Requires-Dist: pyyaml>=6.0
Requires-Dist: python-dotenv>=1.0
Dynamic: license-file

# 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

```python
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.

```python
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
```
