> ## Documentation Index
> Fetch the complete documentation index at: https://docs.luckylobster.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Autonomous Strategies

> Automate your Polymarket trading with server-side strategies

## Overview

Autonomous strategies let your AI agent define trading rules once, then LuckyLobster's server executes them automatically. Instead of your agent making a decision on every heartbeat (which costs tokens and requires the agent to be online), strategies run server-side and trade on your behalf 24/7.

Strategies are **created by your AI agent via the API** and **monitored by you in the dashboard**. You can pause, resume, or cancel any strategy at any time from the dashboard.

## Strategy Types

LuckyLobster supports four strategy types, each designed for a different trading pattern. All can be created by agents via the API or managed from the dashboard:

### Price Alert

**What it does:** Places a single trade when a market's price crosses a threshold you define. Think of it as a conditional order - "buy if the price drops to X" or "sell if the price rises to Y."

**Common use cases:**

* **Stop-loss:** Sell your position if the price drops below a level to limit losses
* **Take-profit:** Sell when the price reaches your target to lock in gains
* **Limit buy:** Buy into a market once the price dips to a level you find attractive

**How it works:**

1. You specify a token, a trigger condition (`PRICE_LTE` or `PRICE_GTE`), and a trigger price
2. The server checks the price every \~10 seconds
3. When the condition is met, it places the order immediately
4. The strategy completes after firing (one-shot)

**Example config:**

```json theme={null}
{
  "type": "PRICE_ALERT",
  "config": {
    "tokenId": "0xabc...",
    "side": "SELL",
    "triggerCondition": "PRICE_LTE",
    "triggerPrice": 0.35,
    "size": 100,
    "orderType": "MARKET"
  },
  "maxBudget": 50
}
```

| Field              | Description                                                                       |
| ------------------ | --------------------------------------------------------------------------------- |
| `tokenId`          | The Polymarket token to monitor (alternative to `marketQuery`)                    |
| `marketQuery`      | Search term to auto-discover markets (e.g., "bitcoin") - alternative to `tokenId` |
| `side`             | `BUY` or `SELL`                                                                   |
| `triggerCondition` | `PRICE_LTE` (at or below) or `PRICE_GTE` (at or above)                            |
| `triggerPrice`     | Price threshold (between 0 and 1)                                                 |
| `size`             | Number of shares to trade                                                         |
| `orderType`        | `MARKET`, `LIMIT`, or `FOK` (default: `MARKET`)                                   |

***

### Recurring Buy

**What it does:** Automatically buys into a market at regular intervals, spreading your investment over time instead of buying all at once. This reduces the impact of short-term price swings.

**Common use cases:**

* **Steady accumulation:** Gradually build a position in a market you're bullish on
* **Crypto markets:** Use with `marketQuery` to automatically find the current active market (handles Polymarket's expiring 15-min, hourly, and daily crypto markets)
* **Risk reduction:** Avoid buying everything at a single price point

**How it works:**

1. You specify how much to buy and how often (e.g., \$10 every hour)
2. Each interval, the server places a market buy order
3. If using `marketQuery`, the server auto-discovers the currently active market matching your search
4. Continues until `maxTotalAmount` is reached, the strategy budget is exhausted, or you cancel it

**Example config:**

```json theme={null}
{
  "type": "RECURRING_BUY",
  "config": {
    "marketQuery": "bitcoin",
    "outcome": "Yes",
    "amountPerInterval": 10,
    "intervalMs": 3600000,
    "maxTotalAmount": 200,
    "priceLimit": 0.70
  },
  "maxBudget": 200
}
```

| Field               | Description                                                                                                                                                          |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `marketQuery`       | Search term to auto-discover markets (e.g., "bitcoin", "ethereum")                                                                                                   |
| `tokenId`           | Alternative to `marketQuery` - use a fixed token ID                                                                                                                  |
| `outcome`           | `Yes` or `No` - which outcome to buy                                                                                                                                 |
| `amountPerInterval` | USDC to spend per interval                                                                                                                                           |
| `intervalMs`        | Milliseconds between buys (minimum: 60,000 = 1 minute). You can also use the `interval` field with a human-readable string (e.g., `"1h"`, `"30m"`) as an alternative |
| `maxTotalAmount`    | Optional total spending cap for this strategy                                                                                                                        |
| `priceLimit`        | Optional - skip buying if price is above this level                                                                                                                  |

<Tip>
  Use `marketQuery` instead of `tokenId` for crypto markets on Polymarket. Crypto markets expire frequently (every 15 minutes, hourly, or daily) and get replaced with new ones. The auto-discovery feature handles this automatically, always finding the current active market for your search term.
</Tip>

***

### Buy Low Sell High

**What it does:** Automatically buys when the price drops below a floor and sells when it rises above a ceiling, capturing profit from price oscillations within a range.

**Common use cases:**

* **Mean reversion:** Profit from markets that tend to bounce between two price levels
* **Volatility harvesting:** Capture gains from markets with predictable ranges
* **Automated swing trading:** Buy low, sell high, repeat

**How it works:**

1. You define a `buyBelow` floor and a `sellAbove` ceiling
2. When the price drops to or below `buyBelow`, the server buys
3. After buying, it waits for the price to rise to or above `sellAbove`, then sells
4. The cycle repeats until you cancel the strategy or it hits `maxOpenSize`

**Example config:**

```json theme={null}
{
  "type": "BUY_LOW_SELL_HIGH",
  "config": {
    "tokenId": "0xabc...",
    "buyBelow": 0.40,
    "sellAbove": 0.60,
    "sizePerTrade": 50,
    "maxOpenSize": 200
  },
  "maxBudget": 500
}
```

| Field          | Description                                                                       |
| -------------- | --------------------------------------------------------------------------------- |
| `tokenId`      | The Polymarket token to trade (alternative to `marketQuery`)                      |
| `marketQuery`  | Search term to auto-discover markets (e.g., "bitcoin") - alternative to `tokenId` |
| `buyBelow`     | Buy when price drops to or below this level                                       |
| `sellAbove`    | Sell when price rises to or above this level                                      |
| `sizePerTrade` | Number of shares per trade                                                        |
| `maxOpenSize`  | Optional max position size to hold at any time                                    |

<Warning>
  Range strategies work best in markets that oscillate. If a market trends strongly in one direction, the strategy may buy and never get a chance to sell (or vice versa). Always set a `maxBudget` and `maxOpenSize` to limit exposure.
</Warning>

***

### Copy Trading

**What it does:** Monitors another wallet's Polymarket trades on-chain in real-time and automatically mirrors them. Instead of polling Polymarket's REST API, LuckyLobster watches the blockchain directly via Alchemy's WebSocket RPC, detecting trades within \~2 seconds of confirmation on Polygon.

**Common use cases:**

* **Follow top traders:** Copy a successful trader's positions as they execute
* **Mirror a fund:** Replicate the trades of a known wallet systematically
* **Social trading:** Follow a friend's strategy without manual effort

**How it works:**

1. You provide the target wallet address to copy
2. LuckyLobster subscribes to on-chain ERC1155 transfer events on Polymarket's CTF contract, filtered to that wallet
3. When the target buys or sells, the server detects it in \~2 seconds (Polygon block time)
4. A copy order is placed immediately via the CLOB with your configured sizing
5. Each copied trade is logged and deduplicated to prevent double-execution

**Example config - Fixed sizing:**

```json theme={null}
{
  "type": "COPY_TRADE",
  "config": {
    "targetAddress": "0x1234567890abcdef1234567890abcdef12345678",
    "sizingMode": "fixed",
    "fixedAmount": 10,
    "copySells": true,
    "maxPositionSize": 500
  },
  "maxBudget": 500
}
```

**Example config - Proportional sizing:**

```json theme={null}
{
  "type": "COPY_TRADE",
  "config": {
    "targetAddress": "0x1234567890abcdef1234567890abcdef12345678",
    "sizingMode": "proportional",
    "proportionPct": 50,
    "copySells": true,
    "maxPositionSize": 1000
  },
  "maxBudget": 1000
}
```

| Field             | Description                                                                                     |
| ----------------- | ----------------------------------------------------------------------------------------------- |
| `targetAddress`   | Wallet address to copy (must be a valid Ethereum address)                                       |
| `sizingMode`      | `fixed` (spend fixed USDC per trade) or `proportional` (mirror a % of target's size)            |
| `fixedAmount`     | USDC to spend per copy trade (required when `sizingMode` is `fixed`)                            |
| `proportionPct`   | Percentage of target's trade size to copy, 1-100 (required when `sizingMode` is `proportional`) |
| `copySells`       | Whether to copy sell trades too (if `false`, only buys are mirrored)                            |
| `maxPositionSize` | Optional max shares to hold per token (caps how large a copied position can grow)               |
| `tokenFilter`     | Optional array of token IDs - only copy trades for these specific tokens                        |

<Tip>
  Copy trading detects trades on-chain, so there's a small delay (\~2-5 seconds) between the target's trade and your copy. For highly liquid markets this is usually fine, but fast-moving markets may see slight price differences.
</Tip>

<Warning>
  Copy trading cannot copy your own wallet (self-copy prevention). You also cannot see pending/unconfirmed transactions - only confirmed trades are copied. Always set a `maxBudget` to limit your total exposure.
</Warning>

## Strategy Lifecycle

Every strategy goes through these states:

```mermaid theme={null}
stateDiagram-v2
    [*] --> ACTIVE: Created
    ACTIVE --> PAUSED: Manual pause
    ACTIVE --> ERROR: 3 consecutive failures
    ACTIVE --> COMPLETED: Budget exhausted / trigger fired
    ACTIVE --> CANCELLED: Deleted
    PAUSED --> ACTIVE: Resume
    ERROR --> ACTIVE: Resume
    PAUSED --> CANCELLED: Deleted
```

| Status        | Description                                                              |
| ------------- | ------------------------------------------------------------------------ |
| **ACTIVE**    | Running - evaluated every \~10 seconds (or real-time for COPY\_TRADE)    |
| **PAUSED**    | Manually paused by you - not evaluated until resumed                     |
| **ERROR**     | Auto-paused after 3 consecutive execution failures - use Resume to retry |
| **COMPLETED** | Finished - budget exhausted or one-shot trigger has fired                |
| **CANCELLED** | Permanently stopped - cannot be resumed                                  |

## Budget Controls

Each strategy has its own `maxBudget` (in USDC) that limits how much it can spend. This is separate from your API key's overall budget limit - both are enforced.

* The strategy tracks its own `budgetUsed` counter
* Orders that would exceed the budget are rejected
* When `budgetUsed >= maxBudget`, the strategy status changes to **COMPLETED**

<Tip>
  Always set a `maxBudget` on every strategy. This is your safety net against unexpected market conditions or rapid execution.
</Tip>

<Note>
  Strategies created by agents via the API have a **default 24-hour expiry**. After 24 hours, the strategy will automatically be cancelled unless the agent or user extends it. This prevents orphaned strategies from running indefinitely if the agent disconnects.
</Note>

## Managing Strategies

### From the Dashboard

Go to **Dashboard > Strategies** to see all your strategies. From there you can:

* **Pause** an active strategy to temporarily stop execution
* **Resume** a paused or errored strategy
* **Cancel** a strategy to permanently stop it
* View execution history, budget usage, and current config

### From the API

Your AI agent can manage strategies programmatically:

```bash theme={null}
# Create a strategy
POST /api/agent/v1/strategies

# List strategies (with optional filters)
GET /api/agent/v1/strategies?status=ACTIVE&type=RECURRING_BUY

# Get strategy details (includes last 20 executions)
GET /api/agent/v1/strategies/{id}

# Update config or budget
PATCH /api/agent/v1/strategies/{id}

# Pause / Resume / Cancel
POST /api/agent/v1/strategies/{id}/pause
POST /api/agent/v1/strategies/{id}/resume
DELETE /api/agent/v1/strategies/{id}
```

## Best Practices

<AccordionGroup>
  <Accordion icon="shield-check" title="Always set maxBudget">
    Every strategy should have a budget cap. This prevents runaway spending if market conditions change unexpectedly.
  </Accordion>

  <Accordion icon="crosshairs" title="Use Price Alert for stop-loss / take-profit">
    If you have an open position, set up a Price Alert strategy to automatically protect your downside or lock in gains. This way you don't need your agent to be online 24/7.
  </Accordion>

  <Accordion icon="magnifying-glass" title="Use Recurring Buy with marketQuery for crypto">
    Polymarket's crypto markets (BTC, ETH, etc.) expire and get replaced frequently. Using `marketQuery` with auto-discovery means your Recurring Buy strategy seamlessly transitions to the newest active market.
  </Accordion>

  <Accordion icon="chart-line" title="Monitor execution history">
    Check the dashboard or heartbeat regularly to verify strategies are executing as expected. The execution log shows every action, skip, and error.
  </Accordion>

  <Accordion icon="scale-balanced" title="Start small, scale up">
    Begin with small budgets and position sizes. Once you're confident the strategy behaves correctly, gradually increase limits.
  </Accordion>
</AccordionGroup>

## Limits

| Limit                                    | Value                |
| ---------------------------------------- | -------------------- |
| Max active strategies per agent          | 10                   |
| Minimum RECURRING\_BUY interval          | 1 minute (60,000 ms) |
| Evaluation frequency                     | \~10 seconds         |
| Max consecutive errors before auto-pause | 3                    |
