Metadata-Version: 2.5
Name: quanty-py
Version: 0.5.0
Summary: Self-hosted framework for recording, backtesting, paper and live trading of repeated prediction markets
Project-URL: Repository, https://github.com/kwingram25/quanty
Project-URL: Documentation, https://github.com/kwingram25/quanty/tree/main/docs
Project-URL: Issues, https://github.com/kwingram25/quanty/issues
Project-URL: Changelog, https://github.com/kwingram25/quanty/blob/main/CHANGELOG.md
Author: Keith Ingram
License-Expression: MIT
License-File: LICENSE
Keywords: backtesting,kalshi,paper trading,polymarket,prediction markets,trading
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: alembic>=1.13
Requires-Dist: cryptography>=43
Requires-Dist: fastapi>=0.115
Requires-Dist: httpx>=0.27
Requires-Dist: jinja2>=3.1
Requires-Dist: mcp>=2.3
Requires-Dist: orjson>=3.10
Requires-Dist: pydantic-settings>=2.4
Requires-Dist: pydantic>=2.8
Requires-Dist: python-multipart>=0.0.9
Requires-Dist: sortedcontainers>=2.4
Requires-Dist: sqlalchemy>=2.0
Requires-Dist: structlog>=24
Requires-Dist: tenacity>=9
Requires-Dist: tomlkit>=0.15.2
Requires-Dist: typer>=0.12
Requires-Dist: uvicorn>=0.30
Requires-Dist: websockets>=13
Description-Content-Type: text/markdown

# quanty

A self-hosted framework for recording, backtesting, paper trading and live trading **repeated
prediction markets** on Kalshi and Polymarket US: crypto up/down windows, daily weather highs,
economic releases, any market that recurs on a schedule and settles against a known source.

Any binary contract works: up/down windows, ranges and ladders (a question with several outcomes
is a set of binaries sharing an event), thresholds. See [Writing strategies](https://github.com/kwingram25/quanty/blob/main/docs/strategies.md#any-binary-market).

One strategy file runs unchanged in four modes. Only the broker behind it changes:

| Mode | Data | Orders |
|---|---|---|
| **backtest** | synthetic markets, or your recordings replayed | simulated fills: latency, book depth, queue position |
| **paper** | live feeds | simulated fills |
| **shadow** | live feeds | simulated fills, plus each order checked by the venue |
| **live** | live feeds | real orders, behind several layers of safety stops |

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/kwingram25/quanty/main/docs/images/dashboard-dark.png">
  <img alt="The quanty dashboard during a paper session: strategies with paper badges and halt controls on the left, cumulative realized P&L per strategy with a hover tooltip in the middle, open markets with the market's chance and the strategies' own estimates, and the event feed on the right" src="https://raw.githubusercontent.com/kwingram25/quanty/main/docs/images/dashboard-light.png">
</picture>

**[Live demo](https://quanty-demo.fly.dev/)**: the dashboard on synthetic markets, shared by everyone
viewing it (the controls work; it starts over every few hours).

## Try it

Install the `quanty` command with [uv](https://docs.astral.sh/uv/) (quanty is `quanty-py` on
PyPI; the `quanty` there is an unrelated project):

```sh
uv tool install quanty-py
quanty demo --ui          # backtest four variants on synthetic markets, open the dashboard
quanty demo --live        # or watch them paper trade in real time, with the controls
```

No keys, no setup (and to try it without installing anything: `uvx --from quanty-py quanty demo --ui`).
To start your own project, with a strategy skeleton, configs, API keys and the files to deploy it:

```sh
quanty init my-quanty                     # a few questions; --yes for the defaults
cd my-quanty && quanty list               # in a project, quanty runs the version the project pins
quanty server root@your-server            # a fresh Ubuntu server: Docker, firewall, swap, updates
quanty keys root@your-server --file .env.server   # the server's own API keys, once
quanty deploy root@your-server            # trader + dashboard, restarted on failure
```

[Getting started](https://github.com/kwingram25/quanty/blob/main/docs/getting-started.md) goes step by step from experiments to recording real data,
paper trading, shadow trading and live trading; [Deploying](https://github.com/kwingram25/quanty/blob/main/docs/deploying.md) covers servers.

## What's in it

- **Recording you can trust.** Every venue and feed message is stored exactly as received, with
  receive timestamps, including market discovery. Replays reproduce what a live run saw, in order.
  Per-minute health: gaps, reconnects, parse errors, receive lag p50/p99.
- **Venues.** Kalshi (any series: crypto, weather, economics; books rebuilt from deltas with
  sequence checks; CF Benchmarks indexes) and Polymarket US (repeated markets by slug template).
  Request signing, fee models, order APIs checked against the venues' published specs and real
  orders.
- **A realistic fill model.** Latency in event time, taker fills that walk the book, resting
  orders that wait their turn in the queue, post-only rejects; tunable from optimistic to
  conservative.
- **Risk in the core.** Order size, position, open risk, risk per correlated group, daily loss,
  halts: checked before any broker sees an order.
- **From paper to live, one strategy at a time.** Run many variants on paper (a `grid` in the
  experiment makes one per combination), rank them by what they likely make per trade at worst,
  and switch the ones you pick to shadow, then real money, while the session runs: every
  experiment has sim, shadow and live brokers, so it's a button on the dashboard (or
  `quanty promote --now`) once the live broker's caps are set. Each keeps a paper twin beside it, so live fills can be compared with
  simulated ones on the same markets; every order records whether it was real money, so the two are
  never added together. `quanty reload` starts and retires variants without a restart, and
  restarts restore what each strategy holds.
- **Live trading that stops rather than guesses.** Required size caps, `--arm`, self-disabling on
  repeated rejections or unknown order outcomes, an order journal that cleans up after a crash
  without touching anything else on the account. A fake exchange with fault injection for tests.
- **A dashboard.** P&L over time per strategy, real money and simulated apart; every trade and
  order of a run (filtered, paged, downloadable as CSV); open markets with each strategy's own
  estimate beside the market's; stop losses, the variant ranking (and backtests of new variants from it) and live-vs-twin
  comparison; the project's health checks; feed health, each platform's connection and your balances. Controls for running sessions: halt,
  resume, disarm, kill switch, go live or back to paper, reload, and editing a strategy's params
  while it runs (saved to the file, or brought home from a server with `quanty pull`). Optional
  password login for reaching it over HTTPS.
- **Your strategies stay yours.** They live in your own project (`quanty init` makes one, its own
  private repo), with quanty as a dependency; nothing of yours is ever in the framework. A
  folder named in your user config can share a private strategy library across projects.

## Docs

- [Getting started](https://github.com/kwingram25/quanty/blob/main/docs/getting-started.md): install to live, step by step
- [Writing strategies](https://github.com/kwingram25/quanty/blob/main/docs/strategies.md): hooks, context, orders, signals, testing
- [Architecture](https://github.com/kwingram25/quanty/blob/main/docs/architecture.md): how the pieces fit, and why one file runs everywhere
- [Live trading](https://github.com/kwingram25/quanty/blob/main/docs/live-trading.md): the safety layers, restarts, and what to do before `--arm`
- [Deploying](https://github.com/kwingram25/quanty/blob/main/docs/deploying.md): servers (DigitalOcean, AWS, Fly.io), the dashboard over HTTPS, editing on a server, working with an AI agent
- [Extending](https://github.com/kwingram25/quanty/blob/main/docs/extending.md): your own data feeds, signals and venues, from your project or a package

## Commands

| | |
|---|---|
| `quanty demo` | backtest a strategy on synthetic markets (`--ui` opens the dashboard) |
| `quanty backtest` | run an experiment on synthetic markets, or on recordings with `--data` |
| `quanty record`, `replay`, `feeds` | record venues and feeds; parse recordings back; feed kinds and health |
| `quanty paper`, `live` | run an experiment in real time (`live` needs `--arm`; `--ui` adds the dashboard) |
| `quanty ui` | the dashboard |
| `quanty promote` | move an instance between paper, shadow and live in its experiment file (`--now`: while running) |
| `quanty pull`, `changes` | bring a server's dashboard changes into your experiment files (`--recordings`: its recent recordings too, to backtest on); list what a server holds |
| `quanty reload` | have a running session pick up its experiment file: new variants start, removed ones retire |
| `quanty upgrade` | bring a project onto a newer quanty: its vendored wheel, lock, and the generated files you haven't edited |
| `quanty server` | prepare a fresh Ubuntu/Debian server over SSH: Docker, firewall, swap, updates, optionally Tailscale |
| `quanty init`, `deploy` | create a project; copy it to a Docker server (bringing its dashboard changes home first), check it there and start it |
| `quanty doctor` | check a project before trading: config, keys, clock, venues, leftovers (read-only; also the dashboard's Health page) |
| `quanty list`, `params` | strategies quanty can find, and their parameters |
| `quanty mcp` | the dashboard as tools for an AI agent (Claude Code): summarize, rank, edit params, halt, switch (`--ssh you@server` for a server's) |
| `quanty keys` | put a server's own API keys in place, apart from the code (deploys never send keys) |
| `quanty password` | set the dashboard's login (a salted hash in `.env`) |

## Layout

| | |
|---|---|
| `core/` | events, engine, risk, portfolio, ledger, strategy base class |
| `brokers/` | simulated (with `QueueModel`), shadow and live brokers |
| `feeds/` | transports, Coinbase and Binance adapters, recording, replay, health |
| `venues/` | Kalshi and Polymarket US; order APIs; the fake exchange |
| `extensions.py` | finding feeds, venues and signals in a project's `extensions/` and in installed packages |
| `ui/`, `control.py`, `web/` | the dashboard's API and live stream, the command channel to running sessions, and the React app |
| `signals.py`, `synthetic.py` | derived values rebuilt identically in replay; deterministic synthetic markets |
| `promote.py`, `pull.py`, `sweep.py` | moving strategies between brokers in a file; bringing a server's changes and recordings home; the dashboard's backtests |
| `reconcile.py`, `version.py`, `mcp.py` | a live session's position check on start; the code each run ran; the dashboard as tools for an AI agent |
| `db/` | SQLAlchemy models and Alembic migrations |

## Development

```sh
git clone https://github.com/kwingram25/quanty && cd quanty
uv sync
uv run pytest && uv run ruff check && uv run mypy
pre-commit install   # gitleaks, ruff, private-name guard
```

The dashboard is a React app in `web/` (TypeScript, Vite, Motion). Its build is committed to
`src/quanty/ui/dist`, so using quanty never needs Node; changing the dashboard does:

```sh
cd web && npm ci
npm run dev        # hot reload on :5173, proxying the API of a running `quanty ui` on :8765
npm run build      # before committing: CI checks the committed build matches the source
```

Database tables are SQLAlchemy models in `src/quanty/db/models.py`, migrated automatically when a
file is opened. After changing a model, `uv run alembic revision --autogenerate -m "..."`, review
the file, and run `uv run pytest tests/test_ledger.py`, which fails if models and migrations
differ. `scripts/check_private.py` blocks commits matching a denylist kept outside the repo
(`$QUANTY_DENYLIST`, default `~/.config/quanty/denylist.txt`).

## Use at your own risk

quanty places real orders with real money once you set it up to. It is not financial advice, and
nothing in it (the example strategies, the fill model, the backtests, the variant ranking) promises
that a strategy will make money: simulated results can be better than what live trading gets, and
software, venues and networks fail. You are responsible for what it trades for you, and for
following your venues' rules and the laws where you live. Start on paper, then shadow, then with
caps you'd not mind losing; [Live trading](https://github.com/kwingram25/quanty/blob/main/docs/live-trading.md) explains how. quanty is provided as
is, without warranty of any kind (see the license).

## License

MIT. Changes by version: [CHANGELOG.md](https://github.com/kwingram25/quanty/blob/main/CHANGELOG.md).
