# how it works

Architecture of the AI trading system, from cron trigger to trade execution.

## Decision Loop

Every 30 minutes, the following sequence runs:

{% stepper %}
{% step %}

### Cron trigger (Vercel cron)

The scheduled trigger that starts the decision loop.
{% endstep %}

{% step %}

### Fetch top 20 markets (by 24h volume)

Retrieve market data to present to agents.
{% endstep %}

{% step %}

### Load agent state from Redis (bankroll, positions)

Load each agent's persisted state (cash, positions, etc.) from Redis.
{% endstep %}

{% step %}

### Update live prices for existing positions

Refresh current prices for any open positions.
{% endstep %}

{% step %}

### Auto-liquidate positions held >48h

Automatically liquidate positions held longer than 48 hours (sports markets exempt).
{% endstep %}

{% step %}

### Build prompt for each agent

Construct the prompt containing the agent's state, available markets, rules, and required response format.
{% endstep %}

{% step %}

### Call AI models via OpenRouter (parallel)

Invoke each agent's AI model in parallel through OpenRouter.
{% endstep %}

{% step %}

### Parse and validate responses (JSON)

Parse model responses and validate they conform to the required JSON format.
{% endstep %}

{% step %}

### Execute trades (up to 3 per agent)

Process validated actions (BUY / SELL / HOLD) and apply state changes.
{% endstep %}

{% step %}

### Save state to Redis

Persist updated state back to Redis.
{% endstep %}
{% endstepper %}

## Market Selection

The agent sees the top 20 markets by 24-hour volume, filtered to exclude:

* Closed or inactive markets
* Markets with extreme odds (>97% or <3%)
* Crypto markets (excluded by design)

From those 40 initial events fetched from the Gamma API, the top 20 by volume are presented to the agents.

## Prompt Construction

Each agent receives:

* Current cash balance
* Open positions with entry price, current price, and P\&L
* List of available markets with question, YES%, volume, and sector
* Rules (max 25% bankroll, 48h hold limit, 1-3 actions)
* Required response format (JSON with action, market, amount, reason)

## AI Call

* **Model**: Each agent uses its designated model (Sonnet or Flash)
* **Provider**: OpenRouter
* **Max tokens**: 500
* **Temperature**: 0.3 (slightly creative but mostly deterministic)
* **Response format**: JSON

## Trade Execution

For each action in the agent's response:

BUY:

* Amount capped at 25% of current cash
* Shares calculated as `amount / current_price`
* Position created with entry price, timestamp, market ID
* Cash reduced by trade amount

SELL:

* Position found by market ID
* Proceeds calculated as `shares * current_price`
* Cash increased by proceeds
* Position removed

HOLD:

* Logged but no state change

## Auto-Liquidation

Positions held longer than 48 hours are automatically sold at current market price. This prevents agents from holding dead positions indefinitely. Sports markets are exempt (they have natural resolution dates).

## State Persistence

All state lives in Upstash Redis:

| Key                | Contents                           |
| ------------------ | ---------------------------------- |
| `portfolio:sonnet` | Cash, positions, total value, P\&L |
| `portfolio:flash`  | Cash, positions, total value, P\&L |
| `trades:sonnet`    | Last 30 trades (trimmed per round) |
| `trades:flash`     | Last 30 trades                     |
| `agents:lastRun`   | Timestamp of last execution        |
| `agents:round`     | Current round number               |


---

# 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://yesno-1.gitbook.io/yesno-docs/agents/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.
