# How It Works

PaperMarket is a web app that sits between a trader and live Polymarket data.\
It loads markets and order books from Polymarket and simulates all trades on its own backend without touching real USDC or on chain contracts.

This page describes how the main parts work together from the moment a user signs in to the moment a trade appears in their portfolio.

### Data sources and architecture

PaperMarket has three main pieces

* the browser app built with Next.js
* the backend API routes that run on the server
* the database that stores accounts balances orders trades and positions

Polymarket is used only as a data source.\
The app calls public Polymarket APIs to fetch market metadata order books and historical prices.\
No orders are ever sent back to Polymarket and no on chain actions are performed.

### Loading a market from Polymarket

On the main page a user pastes a link or a slug for a Polymarket market.

When the user submits this value the frontend calls a backend endpoint that

1. parses the link or slug
2. requests the event and market information from the Polymarket API
3. finds the correct market and its YES and NO token identifiers
4. stores basic metadata about this market in the PaperMarket database if it is not there already
5. sends a simplified market object back to the frontend

The frontend then shows the question and basic information for the selected market and prepares to display the live book and chart.

### Live order books and price history

Once a market is selected the app needs live prices to simulate trades.

The backend uses the Polymarket CLOB API to fetch the current order book for each token.\
For every YES and NO token it receives the current bids asks and sizes and passes that data to the frontend.

For historical prices the backend calls the Polymarket history API and builds a simple time series of prices.\
The frontend uses this to render a line chart for the YES token so that a trader can see how the market has moved over time.

In addition the browser opens a websocket connection to the Polymarket subscriptions endpoint.\
Through this connection it subscribes to live updates for the selected tokens.\
When new book or price messages arrive the app updates the book view the mid price and the chart in real time.

### Simulating trades on the server

When a user places a virtual order the work is done on the server.

The frontend sends a request to the PaperMarket trade API with

* side buy or sell
* token YES or NO
* size of the order
* order type market or limit
* limit price when used

The backend then

1. fetches the latest order book for the selected token from the Polymarket CLOB API
2. checks the user virtual cash balance for buys and current position size for sells
3. simulates how much of the order can be matched against the live bids or asks
4. creates an order record in the database with the requested size and type
5. creates one or more trade records that describe the filled part of the order
6. updates the user cash balance and positions according to the trades

For market and limit orders with immediate or cancel behaviour the system tries to fill against the live book once and cancels any remainder.\
For good till cancel limit orders the unfilled part stays open in the database and can be filled later when the user explicitly requests an update or when the book is refreshed for that token.

All of this happens inside PaperMarket.\
Polymarket only provides the live book that is used as a reference for prices and available size.

### Positions and portfolio updates

Every time a new trade is stored the backend recalculates the position for the traded token.

For each user and each token the backend keeps

* the net position size
* the average entry price based on all past trades in that token
* the realized effect of closed trades on the cash balance

The frontend periodically calls a snapshot endpoint that returns the current cash balance all positions all open orders and the full list of trades.\
Using the latest mid price from the live book the frontend computes the current value of each position and the unrealized PnL and shows these numbers in the portfolio and account views.

### Balance top up logic

The virtual cash balance is capped at a fixed starting amount for example ten thousand virtual dollars.

When the user runs down their balance they can press a top up button in the app.\
The backend then sets the cash balance for that user back to the starting amount.

The top up does not touch

* open positions
* open or closed orders
* existing trades
* PnL history

This way a trader can continue testing strategies with fresh virtual funds while still keeping a complete record of how their trading has behaved across multiple sessions.

### What is stored and what is not

PaperMarket stores

* user accounts and authentication data
* current virtual cash balances
* all orders and all trades that were simulated
* open and closed positions
* basic metadata about markets and tokens that users have loaded

PaperMarket does not store

* any wallet addresses
* any real USDC balances
* any private Polymarket data

All interactions with Polymarket use public APIs to read market data and order books.\
All trading logic and all account state remain inside PaperMarket and are completely separated from actual Polymarket accounts and contracts.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://papermarket.gitbook.io/papermarket/get-start/how-it-works.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
