> For the complete documentation index, see [llms.txt](https://docs.hipersnipe.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hipersnipe.com/architecture/limit-engine.md).

# Limit engine and Trading Shield

## limit\_engine.py

The limit engine is a separate process that watches prices and executes automated trades.

### Responsibilities

1. **WebSocket subscriptions** — AMM pool account changes for tokens with active limits or shields
2. **Price oracle** — Derives token price from pool state; falls back to HTTP metadata when WSS is stale
3. **Limit order execution** — Triggers buy/sell when price crosses user-defined thresholds
4. **Trading Shield** — Executes TP/SL rules per `auto_sell_configs` table
5. **Registry rebuild** — Hot-reloads configs when users enable/disable shields

### Oracle behavior

* Primary: WSS pool events (lowest latency)
* Fallback: HTTP metadata price (`http_metadata` source)
* When fallback is active, execution may be skipped for safety (`Skipped execution due to http_fallback`)

### Metrics

Periodic logs include:

* `WSS Health: N active subs, X events/sec`
* `PERF-STATS: Active Shields, Avg Latency, Max Spike`

## Trading Shield data model

Stored in `auto_sell_configs` (see `db/limits_dao.py`):

| Field             | Description                                       |
| ----------------- | ------------------------------------------------- |
| `is_enabled`      | Shield active for this user+token                 |
| `tp_levels`       | JSON array of `{pct, sell_pct}` take-profit steps |
| `sl_config`       | `{pct, mode}` stop-loss (fixed or trailing)       |
| `reference_price` | Price at arm time for % calculations              |

Shield states in UI:

| State            | Meaning                                      |
| ---------------- | -------------------------------------------- |
| **ACTIVE**       | `is_enabled = true`                          |
| **ARMED (Auto)** | Global auto-arm on; shield not yet enabled   |
| **OFF**          | No shield; button shows `🛡️ TP & SL is OFF` |

## Presigned sell cache

`swap_engine/presigned_sell_cache.py` pre-builds sell transactions so WSS triggers can fire with minimal latency—critical for stop-loss during volatility.

## Limit orders

Limit orders live in `limit_orders` table with:

* Trigger price or price-change %
* Expiry (1h, 6h, 24h, 7d)
* Buy or sell direction
* Token mint and user wallet reference

Ghost-mint cooldown prevents repeated failures on delisted tokens.

## Interaction with PnL

When a shield sell executes, `pnl_tracker.py` records the trade in the user's `trades` JSON. Cycle-based PnL resets when position balance hits dust threshold.

## User-facing entry points

* Token UI → Trading Shield button → `handlers/trading_auto_sell.py`
* `/limits` dashboard → `handlers/trading_limits.py`


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.hipersnipe.com/architecture/limit-engine.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
