Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Repository Guidelines

## Project Structure & Module Organization

PaperDrill is a Bun/TypeScript monorepo without a root `package.json`. Each package owns its dependencies and `bun.lock`:

- `backend/`: Express REST/WebSocket API and Prisma schema/migrations.
- `engine/`: in-memory order matching and snapshot persistence.
- `worker/`: Redis stream persistence, candles, and tickers.
- `bot/`: optional market-making clients.
- `frontend/`: React 19/Tailwind 4 SPA; static assets live in `frontend/public/`.
- `docs/`: Mintlify documentation source and site configuration.
- `tests/integration/`: black-box cross-service tests.
- `benchmarks/`: HTTP, matching, and WebSocket performance scenarios.

Keep unit tests in `backend/tests/` or `engine/tests/`. Public documentation belongs in `docs/`.

## Build, Test, and Development Commands

Run `bun install` inside an individual package after changing its dependencies. Common root commands are:

- `make up`: start dependencies, migrate/seed the database, and launch backend, engine, and worker.
- `make build`: build the main development containers.
- `make logs SERVICE=backend`: follow service logs.
- `make test-unit`: run backend and engine Bun tests with `.env.test`.
- `make test-integration`: exercise the disposable test stack.
- `make bench`: run the benchmark suite.
- `make down`: stop the development stack.

For frontend-only work, use `cd frontend && bun run dev` or `bun run build`.
For documentation work, run `mint dev`, `mint validate`, and `mint broken-links` from `docs/`.

## Coding Style & Naming Conventions

Follow existing TypeScript style: tabs, double quotes, semicolons, ESM imports, and trailing commas in multiline constructs. Use `camelCase` for variables/functions, `PascalCase` for components and types, and established kebab-case filenames (for example, `decimal-input.tsx`). No repository-wide formatter or linter is configured, so match adjacent code.

## Testing Guidelines

Tests use `bun:test` and `.test.ts` filenames. Add unit coverage for local logic and integration coverage for cross-service behavior. There is no stated coverage threshold; regressions should include a test that fails without the fix. Run both test commands before submitting service-wide changes.

## Commit & Pull Request Guidelines

Use Conventional Commit prefixes: `feat:`, `fix:`, `docs:`, `ci:`, or a scope such as `fix(bot):`. Keep commits focused. Pull requests should explain the change, identify affected services, link issues, list verification commands, and include screenshots for visible frontend work. Call out migrations, environment changes, or snapshot compatibility concerns.

## Security & Configuration

Never commit `.env.dev`, `.env.prod`, generated Prisma clients, engine snapshots, build output, or secrets. Do not add fallback production credentials. Preserve the established API error envelope and use `bigintReplacer` for BigInt values crossing JSON or Redis boundaries.
15 changes: 8 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<div align="center">
<h1>PaperDrill</h1>
<p><strong>The exchange built for developers, not spectators.</strong></p>
<p><strong>Competitive trading, powered by a real matching engine.</strong></p>

<p>
<img alt="Release v1.0.0" src="https://img.shields.io/badge/release-v1.1.0-6d5dfc">
Expand All @@ -11,30 +11,31 @@

<p>
<a href="https://paperdrill.dev">Platform</a> ·
<a href="https://paperdrill.dev/docs">API documentation</a> ·
<a href="https://docs.paperdrill.dev">API documentation</a> ·
<a href="https://api.paperdrill.dev">API</a>
</p>
</div>

PaperDrill is a live paper-trading exchange simulator with a real matching engine and order book. Trade through the web interface or connect a bot through the API—no KYC and no real funds at risk.
PaperDrill is a competitive trading platform built around credit markets, a real matching engine, and a public leaderboard. Trade through the web interface or connect a bot through the API, build a measurable record, and compete without risking capital.

## Features

- **Live matching engine** — price-time priority matching rather than mocked fills.
- **Real-time market data** — order book, trades, tickers, and updating candles over WebSocket.
- **Persistent accounts** — simulated balances, open orders, order history, and trade history.
- **Public leaderboard** — compare simulated portfolio performance with other traders.
- **Persistent accounts** — credit balances, open orders, order history, and trade history.
- **Public leaderboard** — compare portfolio performance with other traders.
- **Scoped API keys** — programmable account access and order management.
- **Bot-friendly API** — REST trading endpoints and public WebSocket feeds.
- **Daily simulated credit** — idempotent recurring credit with an adjustable PnL baseline.
- **Daily credit** — idempotent recurring credit with an adjustable PnL baseline.

## Architecture

![PaperDrill architecture](/assets/architecture.png)

| Service | Responsibility |
| ---------- | --------------------------------------------------------------------------- |
| `frontend` | React SPA for markets, trading, account management, docs, and leaderboard |
| `frontend` | React SPA for markets, trading, account management, and leaderboard |
| `docs` | Mintlify site for product guides and API documentation |
| `backend` | Express REST/WebSocket API, authentication, validation, and market metadata |
| `engine` | In-memory balances, order books, matching, and periodic snapshots |
| `worker` | Persists orders/fills and derives candles and tickers |
Expand Down
7 changes: 7 additions & 0 deletions docs/.mintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Mintlify automatically ignores these files and directories:
# .git, .github, .claude, .agents, .idea, node_modules,
# README.md, LICENSE.md, CHANGELOG.md, CONTRIBUTING.md

# Draft content
drafts/
*.draft.mdx
32 changes: 32 additions & 0 deletions docs/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# PaperDrill documentation guidelines

## Project scope

- This directory is the source of truth for PaperDrill's public documentation.
- The site is built and hosted with Mintlify.
- Pages use MDX with YAML frontmatter. Site configuration lives in `docs.json`.
- Run `mint dev` from this directory to preview the site at `http://localhost:3000`.

## Writing style

- Use active voice and address the reader as “you”.
- Keep sentences concise and headings in sentence case.
- Use “simulated funds,” not “fake money” or “real funds.”
- Use “API key” and “WebSocket” consistently.
- Format commands, paths, fields, and enum values as code.
- State required API-key scopes next to protected endpoints.

## Accuracy

- Verify public REST routes against `backend/src` before changing endpoint documentation.
- Verify WebSocket channels and payloads against the backend and worker implementations.
- Represent prices, quantities, balances, and other decimal API values as strings.
- Never document internal admin endpoints, credentials, infrastructure secrets, or production topology.
- Do not describe planned competitions or challenges as available until they are released.

## Links

- Use relative links for pages inside this documentation site.
- Use absolute `https://paperdrill.dev` links for the platform and dashboard.
- Use `https://api.paperdrill.dev/v1` as the REST base URL.
- Use `wss://api.paperdrill.dev` as the public WebSocket URL.
28 changes: 28 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# PaperDrill documentation

This directory contains the Mintlify documentation site for PaperDrill.

## Local development

Install the Mintlify CLI, then start the documentation server from this directory:

```bash
npm install --global mint
mint dev
```

The local preview is available at `http://localhost:3000`.

## Validation

Run these checks before publishing documentation changes:

```bash
mint validate
mint broken-links
mint a11y
```

`openapi.yaml` is the public contract for developer-facing REST endpoints. Keep request fields, response schemas, authentication requirements, scopes, and examples aligned with `backend/src`.

Mintlify deploys from the `/docs` monorepo path. Production should use `docs.paperdrill.dev`.
61 changes: 61 additions & 0 deletions docs/account.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
---
title: "Track balances and portfolio"
description: "Read available funds, locked balances, portfolio performance, and private fills."
---

Account endpoints use API-key authentication. Balances and portfolio values are decimal strings so clients do not lose precision.

## Understand balances

`GET /balances` requires `ACCOUNT_READ`. Add `?asset=USD` when you need only one asset.

```bash
curl https://api.paperdrill.dev/v1/balances \
--header "x-api-key: $PAPERDRILL_API_KEY"
```

```json
{
"USD": { "available": "9748.50", "locked": "251.50" },
"SOL": { "available": "2.00", "locked": "0.00" }
}
```

- `available` can be used for a new order.
- `locked` is reserved by open orders.
- Cancelling an order releases its unfilled reservation.
- Fills move value between assets and can change both fields.

Always refresh balances after order activity instead of calculating the authoritative balance only on the client.

## Track portfolio performance

`GET /portfolio` requires `ACCOUNT_READ`. It values positions in the platform quote asset and compares current equity with the account's PnL baseline.

```bash
curl https://api.paperdrill.dev/v1/portfolio \
--header "x-api-key: $PAPERDRILL_API_KEY"
```

| Field | Meaning |
| -------------------- | ------------------------------------------------ |
| `equity` | Current portfolio value |
| `baselineEquity` | Value used as the PnL starting point |
| `pnl` / `pnlPercent` | Change from the baseline |
| `baselineAt` | Time at which the baseline was recorded |
| `asOf` | Oldest market-price timestamp used for valuation |
| `partial` | `true` when a position could not be fully priced |
| `positions` | Per-asset balances, mark price, and value |

Treat `partial: true` as an incomplete valuation. Do not present it as the value of the entire portfolio without a warning.

## Reconcile with private trades

Use `GET /trades` with the `ORDER_READ` scope to retrieve your fills newest first. Each record identifies your side, maker status, and related order.

```bash
curl "https://api.paperdrill.dev/v1/trades?limit=100" \
--header "x-api-key: $PAPERDRILL_API_KEY"
```

Use order history for intent and status, private trades for executions, and balances for the current authoritative funds.
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# Errors and rate limits
---
title: "Errors and rate limits"
description: "Handle API errors, validation failures, safe retries, and rate limits."
---

All API errors use the same JSON envelope. Save `requestId` when reporting an issue, it identifies the matching server log.
All API errors use the same JSON envelope. Save `requestId` when reporting an issue because it identifies the matching server log.

```json
{
Expand All @@ -17,17 +20,17 @@ All API errors use the same JSON envelope. Save `requestId` when reporting an is

## Common status codes

| Status | Common codes | What to do |
| ------ | -------------------------------------------------------- | ---------------------------------------------- |
| `400` | `VALIDATION_ERROR`, `MALFORMED_JSON` | Correct the request shape, value, or precision |
| `401` | `AUTHENTICATION_REQUIRED`, `INVALID_API_KEY` | Add or replace the API key |
| `403` | `FORBIDDEN` | Add the required scope or use another key |
| `404` | `MARKET_NOT_FOUND`, `ORDER_NOT_FOUND` | Check the supplied identifier |
| `409` | `ORDER_NOT_CANCELLABLE` | Refresh the order before retrying |
| `422` | `INSUFFICIENT_BALANCE`, `NO_LIQUIDITY`, `ORDER_REJECTED` | Adjust the order or wait for liquidity |
| `429` | `RATE_LIMITED` | Wait for the current window to reset |
| `503` | `SERVICE_UNAVAILABLE`, `PORTFOLIO_UNAVAILABLE` | Retry with exponential backoff |
| `504` | `ENGINE_TIMEOUT` | Check order history before retrying |
| Status | Common codes | What to do |
| ------ | -------------------------------------------------------------------- | ---------------------------------------------- |
| `400` | `VALIDATION_ERROR`, `MALFORMED_JSON` | Correct the request shape, value, or precision |
| `401` | `AUTHENTICATION_REQUIRED`, `INVALID_API_KEY` | Add or replace the API key |
| `403` | `FORBIDDEN`, `EMAIL_NOT_VERIFIED` | Add the required scope or verify the account |
| `404` | `MARKET_NOT_FOUND`, `ORDER_NOT_FOUND`, `ASSET_NOT_FOUND` | Check the supplied identifier |
| `409` | `ORDER_NOT_CANCELLABLE` | Refresh the order before retrying |
| `422` | `INSUFFICIENT_BALANCE`, `NO_LIQUIDITY`, `ORDER_REJECTED` | Adjust the order or wait for liquidity |
| `429` | `RATE_LIMITED` | Wait for the current window to reset |
| `503` | `SERVICE_UNAVAILABLE`, `ENGINE_UNAVAILABLE`, `PORTFOLIO_UNAVAILABLE` | Retry with exponential backoff |
| `504` | `ENGINE_TIMEOUT` | Check order history before retrying |

## API-key rate limits

Expand All @@ -45,5 +48,7 @@ For sustained usage above these limits, contact [support@paperdrill.dev](mailto:
## Retry safely

- Retry read requests after `429`, `503`, or `504` with exponential backoff and jitter.
- Do not blindly retry order creation after a timeout; check order history first to avoid duplicates.
- Do not blindly retry order creation after a timeout. Check order history first to avoid duplicates.
- Order cancellation is safe to retry after a network failure, but a filled order can no longer be cancelled.

Use the generated **API reference** to see the errors associated with a specific endpoint. See [API overview](/api-reference/overview) for shared data and retry conventions.
34 changes: 34 additions & 0 deletions docs/api-reference/overview.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
title: "API overview"
description: "Connect to PaperDrill and follow the conventions shared by every API endpoint."
---

The REST API lets you read public market data and manage credit-funded orders with a scoped API key. Use the generated endpoint pages for complete request fields, response schemas, and interactive examples.

## Connect

| Interface | URL |
| --------- | ------------------------------- |
| REST API | `https://api.paperdrill.dev/v1` |
| WebSocket | `wss://api.paperdrill.dev` |

Public market-data endpoints do not require authentication. Protected endpoints expect your complete API key in the `x-api-key` header.

## Conventions

| Topic | Convention |
| -------------- | -------------------------------------------------------------------------------------- |
| Decimal values | Prices, quantities, balances, and volumes are strings such as `"125.50"` |
| Symbols | Use the exact underscore-delimited value returned by `GET /markets`, such as `SOL_USD` |
| Precision | Read `pricePrecision` and `qtyPrecision` before constructing an order |
| Timestamps | Responses use either ISO 8601 strings or Unix milliseconds as documented per field |
| Pagination | Order history uses one-based `page` and `limit` parameters |
| Request IDs | Save the `X-Request-Id` header when reporting a problem |

Keep decimal values as strings until you can process them with decimal or scaled-integer arithmetic.

## Retry safely

Retry read requests after `429`, `503`, or `504` with exponential backoff and jitter. Do not blindly retry order creation after a timeout because the API does not accept an idempotency key; inspect order history first.

See [Errors and rate limits](/api-reference/errors-and-limits) for recovery guidance, or choose an endpoint for its full contract.
73 changes: 73 additions & 0 deletions docs/authentication.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
title: "Authentication"
description: "Authenticate API requests with scoped PaperDrill API keys."
---

Programmable access to protected PaperDrill endpoints uses scoped API keys. Public market-data endpoints do not require authentication.

## Create an API key

Verify your email, sign in to PaperDrill, and open [API keys](https://paperdrill.dev/settings/api-keys). Create a separate key for each integration and grant only the permissions it needs.

Copy the complete key when it appears. PaperDrill shows it only once.

## Store the key

Keep the key in a server-side environment variable or secret manager:

```bash
export PAPERDRILL_API_KEY="pdk_your_key_here"
```

Never commit the value to source control or embed it in browser or mobile code. Revoke and replace a key immediately if it may have been exposed.

## Send the key

Pass the complete value in the `x-api-key` header:

<CodeGroup>
```bash cURL
curl https://api.paperdrill.dev/v1/orders/open \
--header "x-api-key: $PAPERDRILL_API_KEY"
```

```js JavaScript
const response = await fetch("https://api.paperdrill.dev/v1/orders/open", {
headers: { "x-api-key": process.env.PAPERDRILL_API_KEY },
});
```

```python Python
import os
import requests

response = requests.get(
"https://api.paperdrill.dev/v1/orders/open",
headers={"x-api-key": os.environ["PAPERDRILL_API_KEY"]},
timeout=10,
)
```

</CodeGroup>

Do not use `Authorization: Bearer`, prepend another prefix, or remove the key's existing `pdk_` prefix.

## Permissions

| Scope | Allows |
| -------------- | --------------------------------------- |
| `ACCOUNT_READ` | Read balances and portfolio performance |
| `ORDER_READ` | Read orders and private trade history |
| `ORDER_CREATE` | Place limit and market orders |
| `ORDER_CANCEL` | Cancel open orders |

Creating and cancelling orders requires a verified account. Read-only order and account endpoints still enforce their listed API-key scope.

## Authentication errors

- `401 AUTHENTICATION_REQUIRED` means no usable credential was supplied.
- `401 INVALID_API_KEY` means the key is malformed, revoked, or incorrect.
- `403 FORBIDDEN` means the key lacks the required scope.
- `403 EMAIL_NOT_VERIFIED` means the account must be verified before the requested mutation.

See [Errors and rate limits](/api-reference/errors-and-limits) for the shared error envelope and retry guidance.
Loading
Loading