# API Keys
Source: https://docs.luckylobster.io/api-keys
How API keys work and how to manage agent access
## Overview
API keys allow AI agents to access your LuckyLobster account programmatically. Each key is tied to a linked agent and has configurable budget limits.
## How API Keys Are Created
API keys are generated automatically through the **device authorization flow** when an AI agent links to your account. There is no manual key creation - the process is:
Your agent calls `POST /api/auth/device` and receives a user code
Visit the link page shown by your agent and enter the code to approve
After approval, the agent receives an `ll_*` API key automatically
```
ll_abc123xyz789defghi456...
```
See the [Skill Reference](/skill) for the complete device authorization flow with code examples.
## Permission Scopes
All linked agents receive the standard set of permissions:
| Scope | Allows | Use Case |
| -------- | ---------------------------------------- | -------------------- |
| `read` | View markets, balance, positions, orders | All agents need this |
| `trade` | Place orders | Trading agents |
| `cancel` | Cancel open orders | Trading agents |
| `redeem` | Redeem settled market winnings | Automated redemption |
## Budget Configuration
### Budget Limits
Configure spending limits for each agent at **Dashboard > Manage Agents** to protect against:
* Bugs in agent logic
* Unexpected market conditions
* Compromised keys
### Budget Settings
| Setting | Description |
| ---------------------- | ---------------------------------------------- |
| **Fixed Limit** | Maximum USDC the agent can spend |
| **Budget Percent** | Percentage of wallet balance the agent can use |
| **Max Position Value** | Cap on total open position value |
The effective budget is the most restrictive of all configured limits and the wallet balance.
### Checking Budget
Agents can check their remaining budget:
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/budget" \
-H "Authorization: Bearer ll_..."
```
## Rate Limits
Default rate limit: **100 requests/minute**
Rate limit headers are included in every response:
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1704067200
```
## Managing Agents
### Viewing Agents
All your linked agents are listed at **Dashboard > Manage Agents** with:
* Name and link date
* API key prefix
* Budget usage
* Strategy count
* Status (active/paused/revoked)
### Pausing Agents
To temporarily disable an agent without revoking its key:
1. Find the agent in your list
2. Click the pause button
3. Select a duration (15 minutes, 30 minutes, 1 hour, 4 hours, or indefinitely)
Paused agents can be resumed at any time.
### Revoking Keys
To permanently revoke an agent's access:
1. Find the agent in your list
2. Click **Revoke**
3. Confirm the action
Revoking is immediate and irreversible. The agent will lose access instantly.
## Best Practices
Each agent gets its own API key through the device flow. This allows
individual budget tracking, selective revocation, and clear audit trails.
Begin with low budget limits and increase as you verify agent behavior.
Use the pause feature to temporarily disable agents without revoking access.
This is useful during maintenance or when you want to stop trading temporarily.
Use environment variables or secure vaults. Never commit keys to repositories.
## API Key Format
```
ll_<64_character_hash>
```
* Prefix: `ll_`
* Hash: 64-character secure random string
# Account
Source: https://docs.luckylobster.io/api-reference/account
Balance, budget, and statistics
## Get Balance
Get raw wallet balance (live from chain).
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/balance" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": {
"usdc": 93.16,
"address": "0x1234...",
"walletType": "proxy"
}
}
```
| Field | Description |
| ------------ | -------------------------------------- |
| `usdc` | USDC balance for trading |
| `walletType` | `proxy` (Polymarket) or `eoa` (direct) |
***
## Get Budget
Get how much you can spend. **Check this before placing orders.**
Budget = min(wallet balance, fixed limit, % of wallet)
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/budget" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": {
"usdc": 46.58,
"limitedBy": "percent",
"wallet": 93.16,
"config": {
"fixedLimit": null,
"budgetPercent": 50,
"maxPositionValue": null,
"used": 0
}
}
}
```
| Field | Description |
| ----------- | ----------------------------------------------------------------------- |
| `usdc` | **What you can spend** (accounts for all limits) |
| `limitedBy` | Why you're capped: `wallet`, `fixed_limit`, `percent`, `position_limit` |
| `wallet` | Raw wallet balance |
| `config` | Your budget settings (configured at Dashboard > Manage Agents) |
***
## Get Stats
Get trading performance statistics.
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/stats" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": {
"totalOrders": 150,
"filledOrders": 142,
"totalVolume": 25000.00,
"realizedPnL": 1250.75,
"unrealizedPnL": 320.50,
"winRate": 62.5,
"avgTradeSize": 166.67
}
}
```
# API Authentication
Source: https://docs.luckylobster.io/api-reference/authentication
Authenticating requests to the LuckyLobster API
## Bearer Token Authentication
All API requests require a Bearer token in the `Authorization` header.
```bash theme={null}
Authorization: Bearer ll_your_api_key_here
```
## Getting an API Key
API keys are generated through the **device authorization flow** when an AI agent links to your account:
1. Agent calls `POST /api/auth/device` and receives a user code
2. You visit the link and approve the connection
3. Agent receives an `ll_*` API key automatically
See the [Skill Reference](/skill) for the complete device flow, or manage linked agents at **Dashboard > Manage Agents**.
## API Key Permissions
All linked agents receive the standard set of permissions:
| Permission | Access Level |
| ---------- | ---------------------------------------- |
| `read` | View markets, balance, positions, orders |
| `trade` | Place orders |
| `cancel` | Cancel open orders |
| `redeem` | Redeem settled market winnings |
## Example Request
```bash cURL theme={null}
curl -X GET "https://luckylobster.io/api/agent/v1/balance" \
-H "Authorization: Bearer ll_abc123..."
```
```python Python theme={null}
import requests
response = requests.get(
"https://luckylobster.io/api/agent/v1/balance",
headers={"Authorization": "Bearer ll_abc123..."}
)
```
```javascript JavaScript theme={null}
const response = await fetch(
"https://luckylobster.io/api/agent/v1/balance",
{
headers: {
"Authorization": "Bearer ll_abc123..."
}
}
);
```
## Authentication Errors
### 401 Unauthorized
```json theme={null}
{
"success": false,
"error": "Unauthorized",
"message": "Invalid or missing API key"
}
```
**Causes:**
* Missing `Authorization` header
* Invalid API key format
* Revoked or expired API key
### 403 Forbidden
```json theme={null}
{
"success": false,
"error": "Forbidden",
"message": "Insufficient permissions for this action"
}
```
**Causes:**
* API key lacks required permission scope
* Budget limit exceeded
## Security Best Practices
Never expose your API key in client-side code, public repositories, or logs.
* Store keys in environment variables or secure vaults
* Link separate agents per use case for individual tracking
* Set appropriate budget limits at **Dashboard > Manage Agents**
* Monitor usage in the dashboard
# Heartbeat
Source: https://docs.luckylobster.io/api-reference/heartbeat
Status check endpoint for trading agents
## Overview
The heartbeat endpoint provides aggregated status information in a single call. Instead of polling multiple endpoints, agents call this periodically to see portfolio changes, pending actions, and budget status.
The heartbeat response includes a suggested `next_check_at` timestamp and `latest_skill_version` for informational purposes. Use these to decide when to check again and whether a skill update is available on ClawHub.
***
## Get Heartbeat
Get current status, action items, portfolio summary, and scheduling info.
**Permission required:** `read`
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/heartbeat?skill_version=9" \
-H "Authorization: Bearer ll_..."
```
**Query Parameters:**
| Parameter | Required | Description |
| --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `skill_version` | optional | Your current skill.md version (from `metadata.openclaw.version`). The response includes `latest_skill_version` so you can compare. |
### Response - Active (OK)
When there are no pending actions:
```json theme={null}
{
"success": true,
"data": {
"status": "OK",
"timestamp": "2026-02-06T14:30:00Z",
"portfolio": {
"openPositions": 3,
"totalValue": 185.50,
"unrealizedPnl": 12.30,
"redeemableCount": 0,
"redeemableValue": 0
},
"orderActivity": {
"openOrders": 1,
"filledSinceLastHeartbeat": 0,
"recentFills": []
},
"budget": {
"available": 46.58,
"limitedBy": "percent",
"walletBalance": 93.16
},
"heartbeat": {
"next_check_at": "2026-02-06T14:31:00Z",
"interval_ms": 60000,
"active_hours": {
"start": "08:00",
"end": "22:00",
"timezone": "America/New_York"
},
"heartbeat_count": 42,
"latest_skill_version": 9
}
}
}
```
### Response - Active (ACTION\_NEEDED)
When actions may need attention, the `actions` array is included:
```json theme={null}
{
"success": true,
"data": {
"status": "ACTION_NEEDED",
"timestamp": "2026-02-06T14:30:00Z",
"actions": [
{
"type": "REDEEM",
"priority": "high",
"summary": "2 position(s) ready to redeem (~$42.50)",
"details": {
"count": 2,
"estimatedValue": 42.50,
"positions": [
{
"conditionId": "0xbc13af0a...",
"title": "Bitcoin Up or Down - February 4",
"outcome": "Down",
"size": 5.0
}
],
"action": "POST /settlements/redeem"
}
},
{
"type": "ORDER_FILLED",
"priority": "medium",
"summary": "1 order(s) filled since last check",
"details": {
"count": 1,
"totalPnl": 3.25,
"fills": [
{
"id": "ord_abc123",
"side": "SELL",
"size": 50,
"filledSize": 50,
"avgFillPrice": 0.65,
"realizedPnl": 3.25,
"marketQuestion": "Bitcoin Up or Down?",
"outcome": "Up",
"filledAt": "2026-02-06T14:28:00Z"
}
]
}
}
],
"portfolio": { "..." : "..." },
"orderActivity": { "..." : "..." },
"budget": { "..." : "..." },
"heartbeat": { "..." : "..." }
}
}
```
### Response - Sleeping
When outside configured active hours:
```json theme={null}
{
"success": true,
"data": {
"status": "SLEEPING",
"timestamp": "2026-02-06T03:00:00Z",
"message": "Outside active hours (08:00-22:00 America/New_York). Suggested next check at next_check_at.",
"heartbeat": {
"next_check_at": "2026-02-06T03:01:00Z",
"interval_ms": 60000,
"active_hours": {
"start": "08:00",
"end": "22:00",
"timezone": "America/New_York"
},
"heartbeat_count": 200,
"latest_skill_version": 9
}
}
}
```
***
## Status Values
| Status | Meaning |
| --------------- | ----------------------------------------------- |
| `OK` | Within active hours, no actions needed |
| `ACTION_NEEDED` | Within active hours, actions may need attention |
| `SLEEPING` | Outside configured active hours |
***
## Action Types
Actions are returned in the `actions` array, sorted by priority.
| Type | Priority | Description |
| -------------------- | -------- | ------------------------------------------------------------------------------------------ |
| `REDEEM` | high | Settled positions ready to redeem. Call `POST /settlements/redeem`. |
| `ORDER_FILLED` | medium | Orders filled since the last heartbeat, with P\&L details. |
| `BUDGET_LOW` | medium | Budget below \$5 or less than 10% of limit remaining. |
| `POSITION_EXPIRING` | low | Open positions in markets closing within 30 minutes. |
| `SEEK_TRADES` | low | Budget available - trading opportunities may exist. |
| `STRATEGY_EXECUTED` | medium | Trades placed by your autonomous strategies. |
| `STRATEGY_ERROR` | high | Strategies auto-paused after consecutive errors. |
| `STRATEGY_COMPLETED` | low | Strategies that finished (budget exhausted or trigger fired). |
| `STRATEGY_PAUSED` | high | Strategy paused by the user from the dashboard. `POST /strategies/{id}/resume` to restart. |
| `STRATEGY_CANCELLED` | high | Strategy cancelled by the user from the dashboard. Create a new strategy if needed. |
***
## Heartbeat Scheduling
Every response (including `SLEEPING`) includes a `heartbeat` object with scheduling information:
| Field | Type | Description |
| ---------------------- | ------------ | ------------------------------------------------------------------------------------------ |
| `next_check_at` | string | ISO 8601 timestamp - suggested time for next check |
| `interval_ms` | int | Heartbeat interval in milliseconds (configured per API key) |
| `active_hours` | object\|null | Configured active hours (`start`, `end`, `timezone`), or null if always active |
| `heartbeat_count` | int | Total heartbeats recorded for this API key |
| `latest_skill_version` | int | Latest skill version available - compare with your version to check for updates on ClawHub |
Use `next_check_at` as a scheduling suggestion. The server computes this based on your API key's configuration.
***
## Response Fields
### `portfolio`
| Field | Type | Description |
| ----------------- | ----- | --------------------------------------- |
| `openPositions` | int | Number of open positions |
| `totalValue` | float | Total value of open positions |
| `unrealizedPnl` | float | Unrealized P\&L across open positions |
| `redeemableCount` | int | Positions ready to redeem |
| `redeemableValue` | float | Estimated value of redeemable positions |
### `orderActivity`
| Field | Type | Description |
| -------------------------- | ----- | ---------------------------------- |
| `openOrders` | int | Number of open/pending orders |
| `filledSinceLastHeartbeat` | int | Orders filled since last heartbeat |
| `recentFills` | array | Details of recently filled orders |
### `budget`
| Field | Type | Description |
| --------------- | ------ | -------------------------------------------------------------------------------- |
| `available` | float | How much you can spend right now |
| `limitedBy` | string | Which constraint is active: `wallet`, `fixed_limit`, `percent`, `position_limit` |
| `walletBalance` | float | Raw wallet USDC balance |
# Markets
Source: https://docs.luckylobster.io/api-reference/markets
Search and get market data
## Search Markets
Search for prediction markets by keyword, tag, or slug.
### Parameters
| Name | Type | Default | Description |
| ------------------ | ------ | ------- | ------------------------------------------------- |
| `q` | string | - | Search query |
| `slug` | string | - | Exact market slug match |
| `tag` | string | - | Category: crypto, politics, sports, entertainment |
| `limit` | int | 10 | Max results (max: 100) |
| `offset` | int | 0 | Pagination offset |
| `sort` | string | volume | volume, liquidity, end\_date, recent |
| `min_volume` | int | 100 | Minimum volume in USD |
| `accepting_orders` | bool | true | Only tradeable markets |
| `ending_soon` | bool | false | Prioritize markets ending within 24h |
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/markets/search?q=bitcoin&sort=volume" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": [
{
"id": "1314069",
"slug": "bitcoin-up-or-down-on-february-3",
"question": "Bitcoin Up or Down on February 3?",
"outcomes": ["Up", "Down"],
"outcomePrices": ["0.65", "0.35"],
"volume": "409100.65",
"liquidity": "39255.13",
"acceptingOrders": true
}
],
"context": {
"topMatch": { "id": "1314069", "question": "..." }
}
}
```
***
## Get Market Details
Get detailed information about a specific market including token IDs for trading.
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/markets/1314069" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": {
"id": "1314069",
"conditionId": "0xf46bf33576e8341821161316705ab2357312f58d58b7d157cb8dca73b656b326",
"question": "Bitcoin Up or Down on February 3?",
"tokens": [
{"tokenId": "36656454529662513...", "outcome": "Up", "price": "0.345"},
{"tokenId": "10609233133841503...", "outcome": "Down", "price": "0.655"}
],
"clobTokenIds": ["36656454529662513...", "10609233133841503..."],
"spreads": [
{"outcome": "Up", "bid": "0.34", "ask": "0.35", "spread": "0.01"}
]
}
}
```
***
## Crypto Markets
Find active crypto up/down markets using deterministic slug-based lookups. This is the most reliable way to find recurring crypto markets - it uses the same approach as the internal market-data-worker.
### Parameters
| Name | Type | Default | Description |
| ---------------- | ------ | ------- | ----------------------------------------------------------------------------- |
| `asset` | string | - | **Required.** btc, eth, sol, xrp, doge, matic (long-form names also accepted) |
| `timeframe` | string | daily | 5m, 15m, 4h, hourly, daily |
| `include_tokens` | bool | true | Include clobTokenIds and live spread data |
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/markets/crypto?asset=btc&timeframe=15m" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": {
"conditionId": "0xabc...",
"slug": "btc-updown-15m-1770129900",
"question": "BTC Up or Down 9:45AM-10:00AM ET?",
"outcomes": ["Up", "Down"],
"outcomePrices": ["0.50", "0.50"],
"endDate": "2026-02-13T15:00:00Z",
"acceptingOrders": true,
"negRisk": false,
"clobTokenIds": ["366564...", "106092..."],
"tokens": [
{"tokenId": "366564...", "outcome": "Up", "price": "0.50", "bid": "0.49", "ask": "0.51"},
{"tokenId": "106092...", "outcome": "Down", "price": "0.50", "bid": "0.49", "ask": "0.51"}
]
},
"meta": {
"asset": "Bitcoin",
"timeframe": "15m",
"searchMethod": "slug"
}
}
```
This endpoint generates deterministic Polymarket slugs for the current time window and fetches them directly - no fuzzy text search. It checks the current window plus the next 2 windows to find the one accepting orders.
***
## Find by Slug
Find a market by its exact Polymarket URL slug.
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/markets/by-slug?slug=btc-updown-15m-1770129900" \
-H "Authorization: Bearer ll_..."
```
***
## Order Book
Get the full order book for a token.
### Parameters
| Name | Type | Description |
| ----------- | ------ | ---------------------------------- |
| `token_id` | string | Token ID (required) |
| `token_ids` | string | Comma-separated for batch (max 20) |
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/orderbook?token_id=36656454529662513..." \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": {
"tokenId": "36656454529662513...",
"bids": [
{"price": "0.65", "size": "1000"},
{"price": "0.64", "size": "500"}
],
"asks": [
{"price": "0.66", "size": "800"}
],
"summary": {
"bestBid": "0.65",
"bestAsk": "0.66",
"spread": "0.01"
}
}
}
```
***
## Prices
Get current prices for tokens.
### Parameters
| Name | Type | Description |
| ----------- | ------ | ------------------------- |
| `token_id` | string | Token ID (required) |
| `token_ids` | string | Comma-separated for batch |
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/prices?token_id=36656454529662513..." \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": {
"tokenId": "36656454529662513...",
"midpoint": "0.655",
"buyPrice": "0.66",
"sellPrice": "0.65",
"lastTradePrice": "0.65"
}
}
```
***
## Spread
Get the bid-ask spread for a token.
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/spread?token_id=36656454529662513..." \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": {
"bid": "0.65",
"ask": "0.66",
"spread": "0.01",
"spreadPercent": "1.52"
}
}
```
***
## Market Data (All-in-One)
Get comprehensive market data in a single request.
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/market-data?token_id=36656454529662513..." \
-H "Authorization: Bearer ll_..."
```
Returns prices, spread, and order book summary combined.
# API Overview
Source: https://docs.luckylobster.io/api-reference/overview
LuckyLobster Agent API v1 reference
## Introduction
The LuckyLobster API enables AI agents and applications to trade on Polymarket prediction markets. All endpoints require API key authentication and respect rate limits and budget constraints.
## Base URL
```
https://luckylobster.io/api/agent/v1
```
## Authentication
All requests require a Bearer token in the `Authorization` header:
```bash theme={null}
Authorization: Bearer ll_your_api_key_here
```
See [Authentication](/authentication) for details on creating and managing API keys.
## Request Format
* **Content-Type**: `application/json` for POST/PUT requests
* **Accept**: `application/json`
```bash theme={null}
curl -X POST "https://luckylobster.io/api/agent/v1/orders" \
-H "Authorization: Bearer ll_..." \
-H "Content-Type: application/json" \
-d '{"tokenId": "...", "side": "BUY", "price": 0.55, "size": 100}'
```
## Response Format
All responses follow a consistent structure:
```json Success theme={null}
{
"success": true,
"data": {
// Endpoint-specific data
},
"agent": {
"id": "api_key_id",
"name": "My Trading Agent"
}
}
```
```json Error theme={null}
{
"success": false,
"error": "Error Type",
"message": "Human-readable error message",
"details": {
// Additional error context
}
}
```
## Rate Limits
Rate limits are configured per API key. Default: 100 requests/minute.
**Headers included in every response:**
| Header | Description |
| ----------------------- | --------------------------------- |
| `X-RateLimit-Limit` | Max requests in current window |
| `X-RateLimit-Remaining` | Requests remaining |
| `X-RateLimit-Reset` | Unix timestamp when window resets |
When rate limited, the API returns `429 Too Many Requests`.
## Budget Enforcement
Orders are validated against your API key's budget limit. If an order would exceed your budget, it returns `403 Forbidden` with budget details:
```json theme={null}
{
"success": false,
"error": "Budget Exceeded",
"message": "Order cost ($55.00) would exceed budget limit",
"budget": {
"limit": 1000,
"used": 950,
"remaining": 50
}
}
```
## Error Codes
| Status | Error | Description |
| ------ | ------------ | ------------------------------------ |
| 400 | Bad Request | Invalid parameters |
| 401 | Unauthorized | Missing or invalid API key |
| 403 | Forbidden | Budget exceeded or permission denied |
| 404 | Not Found | Resource doesn't exist |
| 429 | Rate Limited | Too many requests |
| 500 | Server Error | Internal error |
## Pagination
List endpoints support pagination:
| Parameter | Type | Default | Description |
| --------- | ---- | ------- | ------------------------- |
| `limit` | int | 10-50 | Max results to return |
| `offset` | int | 0 | Number of results to skip |
Response includes pagination info:
```json theme={null}
{
"pagination": {
"limit": 50,
"offset": 0,
"count": 50,
"hasMore": true
}
}
```
## Dry Run Mode
Order endpoints support `dryRun: true` to validate without executing:
```json theme={null}
{
"tokenId": "...",
"side": "BUY",
"price": 0.55,
"size": 100,
"dryRun": true
}
```
Dry run responses include validation details:
```json theme={null}
{
"success": true,
"dryRun": true,
"message": "Order validation passed",
"data": {
"validation": {
"inputsValid": true,
"budgetCheck": { "passed": true },
"walletFound": true
}
}
}
```
## Endpoint Categories
Search and discover prediction markets
Place and manage orders, positions
Aggregated status and action items
Balance, budget, and stats
## SDKs & Libraries
Currently, the LuckyLobster API is accessed directly via HTTP. SDKs for popular languages are coming soon.
For AI agents, point to our skill.md at `https://luckylobster.io/skill.md` for automatic integration.
# Trading
Source: https://docs.luckylobster.io/api-reference/trading
Place orders and manage positions
## Place Order
Place a buy or sell order on a market.
### Request Body
| Field | Type | Required | Description |
| --------- | ------ | -------- | ----------------------------------------- |
| `tokenId` | string | Yes | Token to trade (from market data) |
| `side` | string | Yes | `BUY` or `SELL` |
| `price` | float | Yes | Price between 0.01 and 0.99 |
| `size` | float | Yes | Number of shares |
| `type` | string | No | `LIMIT` (default), `MARKET`, `FOK`, `FAK` |
| `dryRun` | bool | No | Validate without placing |
### Order Types
| Type | Description |
| -------- | --------------------------------------- |
| `LIMIT` | Rests on book until filled or cancelled |
| `MARKET` | Fills immediately at best price |
| `FOK` | Fill or Kill - all or nothing |
| `FAK` | Fill and Kill - take what's available |
### Example
```bash theme={null}
curl -X POST "https://luckylobster.io/api/agent/v1/orders" \
-H "Authorization: Bearer ll_..." \
-H "Content-Type: application/json" \
-d '{
"tokenId": "36656454529662513...",
"side": "BUY",
"price": 0.55,
"size": 50,
"type": "LIMIT"
}'
```
```json Response theme={null}
{
"success": true,
"data": {
"order": {
"id": "ord_abc123",
"polyOrderId": "0x...",
"status": "FILLED",
"side": "BUY",
"price": 0.55,
"size": 50,
"filledSize": 50,
"avgFillPrice": 0.55,
"marketQuestion": "Bitcoin Up or Down?",
"outcome": "Up"
}
}
}
```
### Dry Run
Test order validation without placing:
```bash theme={null}
curl -X POST "https://luckylobster.io/api/agent/v1/orders" \
-H "Authorization: Bearer ll_..." \
-H "Content-Type: application/json" \
-d '{"tokenId": "...", "side": "BUY", "price": 0.55, "size": 50, "dryRun": true}'
```
***
## List Orders
Get your orders with real-time status sync.
### Parameters
| Name | Type | Default | Description |
| -------- | ------ | ------- | ----------------------------------------------------------- |
| `status` | string | - | PENDING, OPEN, FILLED, PARTIALLY\_FILLED, CANCELLED, FAILED |
| `limit` | int | 50 | Max results (max: 100) |
| `offset` | int | 0 | Pagination offset |
| `sync` | bool | true | Sync open orders with Polymarket |
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/orders?status=OPEN" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": [...],
"sync": { "enabled": true, "updated": 2 }
}
```
***
## Get Order
Get details for a specific order with live status.
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/orders/ord_abc123" \
-H "Authorization: Bearer ll_..."
```
***
## Cancel Order
Cancel an open order.
Only orders with status `PENDING`, `OPEN`, or `PARTIALLY_FILLED` can be cancelled.
### Example
```bash theme={null}
curl -X DELETE "https://luckylobster.io/api/agent/v1/orders/ord_abc123" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"message": "Order cancelled successfully",
"data": {
"order": {
"id": "ord_abc123",
"status": "CANCELLED",
"previousStatus": "OPEN"
}
}
}
```
***
## List Positions
Get your current positions from Polymarket.
### Parameters
| Name | Type | Default | Description |
| -------- | ------ | ------- | ------------------------------ |
| `status` | string | open | open, settled, redeemable, all |
| `source` | string | - | Force `clob` for freshest data |
### Example
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/positions" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"data": {
"positions": [
{
"id": "pos_abc123",
"tokenId": "36656454529662513...",
"market": {
"question": "Bitcoin Up or Down on February 3?",
"outcome": "Up"
},
"size": 100.0,
"avgEntryPrice": 0.55,
"currentPrice": 0.62,
"currentValue": 62.00,
"pnl": {
"unrealized": 7.00,
"unrealizedPercent": 12.73
}
}
],
"summary": {
"totalPositions": 1,
"totalUnrealizedPnl": 7.00,
"totalValue": 62.00
}
}
}
```
***
## Close Position
Close an entire position with a single API call.
### Request Body (Optional)
| Field | Type | Default | Description |
| ---------- | ------ | ------- | ----------------------------- |
| `type` | string | MARKET | MARKET, FOK, or LIMIT |
| `slippage` | float | 0.02 | Max slippage for LIMIT orders |
| `dryRun` | bool | false | Preview without executing |
### Example
```bash theme={null}
curl -X POST "https://luckylobster.io/api/agent/v1/positions/pos_abc123/close" \
-H "Authorization: Bearer ll_..."
```
```json Response theme={null}
{
"success": true,
"message": "Position closed successfully",
"data": {
"order": {
"id": "ord_xyz789",
"status": "FILLED",
"side": "SELL",
"filledSize": 100,
"avgFillPrice": 0.65
},
"position": {
"id": "pos_abc123",
"isClosed": true
},
"execution": {
"proceeds": 65.00,
"pnl": 10.00,
"pnlPercent": 18.18
}
}
}
```
***
## Approve Tokens
Approve tokens for trading. Required before selling if you get "allowance" errors.
### Request Body
| Field | Type | Description |
| ------- | ------ | ----------------------------------- |
| `token` | string | `USDC`, `CTF`, `NEG_RISK`, or `all` |
### Example
```bash theme={null}
curl -X POST "https://luckylobster.io/api/agent/v1/wallet/approve" \
-H "Authorization: Bearer ll_..." \
-H "Content-Type: application/json" \
-d '{"token": "CTF"}'
```
If you get "not enough allowance" errors when selling, call this endpoint with `token: "CTF"`.
# Authentication
Source: https://docs.luckylobster.io/authentication
User authentication and API key management
## Overview
LuckyLobster uses two authentication systems:
1. **User Authentication** - For accessing the dashboard (email/password, social login, passkeys)
2. **API Key Authentication** - For agent/programmatic access to the trading API
## User Authentication
### Supported Methods
Traditional email/password with optional 2FA
Google, GitHub, and more
Biometric authentication (Face ID, Touch ID, Windows Hello)
### Two-Factor Authentication (2FA)
We strongly recommend enabling 2FA for additional security:
1. Go to **Dashboard > Settings > Security**
2. Click **Enable 2FA**
3. Scan the QR code with your authenticator app (Google Authenticator, Authy, etc.)
4. Enter the verification code to confirm
Save your 2FA backup codes in a secure location. You'll need them if you lose access to your authenticator app.
## API Key Authentication
### How API Keys Are Created
API keys are generated through the **device authorization flow** when an AI agent links to your account. There is no manual "Create API Key" button - instead:
1. Your AI agent initiates the device flow (`POST /api/auth/device`)
2. You visit the link page and enter the code shown by your agent
3. After you approve, the agent receives an `ll_*` API key automatically
Once linked, you manage your agents and their API keys at **Dashboard > Manage Agents**.
See the [Skill Reference](/skill) for the full device authorization flow, or the [Quickstart](/quickstart) for a step-by-step walkthrough.
### API Key Format
```
ll_abc123xyz789defghi456...
```
* Prefix: `ll_`
* Hash: 64-character secure random string
### Using API Keys
Include your API key in the `Authorization` header:
```bash cURL theme={null}
curl -X GET "https://luckylobster.io/api/agent/v1/balance" \
-H "Authorization: Bearer ll_your_key_here"
```
```python Python theme={null}
import requests
headers = {
"Authorization": "Bearer ll_your_key_here"
}
response = requests.get(
"https://luckylobster.io/api/agent/v1/balance",
headers=headers
)
```
```javascript JavaScript theme={null}
const response = await fetch(
"https://luckylobster.io/api/agent/v1/balance",
{
headers: {
"Authorization": "Bearer ll_your_key_here"
}
}
);
```
### Permission Scopes
All linked agents receive the standard set of permissions:
| Scope | Description | Endpoints |
| -------- | ---------------------- | ------------------------------------------ |
| `read` | Read-only access | Markets, balance, positions, order history |
| `trade` | Place orders | POST /orders |
| `cancel` | Cancel open orders | DELETE /orders |
| `redeem` | Redeem settled markets | POST /settlements/redeem |
### Rate Limiting
API keys are rate limited to protect against abuse:
* **Default**: 100 requests/minute
* **Headers**: Check `X-RateLimit-*` headers in responses
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1704067200
```
When rate limited, you'll receive a `429 Too Many Requests` response:
```json theme={null}
{
"success": false,
"error": "Rate Limited",
"message": "Too many requests. Please wait before retrying.",
"retryAfter": 30
}
```
### Budget Limits
You can configure spending limits for each agent at **Dashboard > Manage Agents**:
| Setting | Description |
| ---------------------- | ---------------------------------------------- |
| **Fixed Limit** | Maximum USDC the agent can spend |
| **Budget Percent** | Percentage of wallet balance the agent can use |
| **Max Position Value** | Cap on total open position value |
Check budget via the API:
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/budget" \
-H "Authorization: Bearer ll_..."
```
Response:
```json theme={null}
{
"success": true,
"data": {
"usdc": 46.58,
"limitedBy": "percent",
"wallet": 93.16,
"config": {
"fixedLimit": null,
"budgetPercent": 50,
"maxPositionValue": null,
"used": 0
}
}
}
```
### Revoking API Keys
To revoke an agent's API key:
1. Go to **Dashboard > Manage Agents**
2. Find the agent you want to revoke
3. Click the **Revoke** button
4. Confirm the action
Revoking a key is immediate and irreversible. Any agents using that key will lose access.
## Security Best Practices
API keys should only be used server-side or in secure agent environments.
Never include them in browser JavaScript, mobile apps, or public repositories.
Each agent gets its own API key through the device flow.
This gives you individual budget tracking and selective revocation.
Start with low budget limits and increase as needed.
This protects against bugs or unexpected agent behavior.
Use the pause feature in Manage Agents to temporarily disable an agent
without revoking its key. You can resume it later.
## Wallet Security
Your Polymarket wallet private key is protected with:
* **AES-256-GCM encryption** at rest
* **Per-wallet unique IV** (initialization vector)
* **Server-side only decryption** during order signing
* **No client-side key exposure**
The encryption key is stored securely in our infrastructure and never exposed in API responses.
## Audit Logging
All sensitive operations are logged:
* Agent linking/revocation
* Order placement
* Wallet operations
* Login attempts
## API Reference
Full API authentication documentation
# Budget Limits
Source: https://docs.luckylobster.io/budget-limits
Control agent spending with budget limits
## Overview
Budget limits are a critical safety feature that cap how much an API key can spend. This protects against bugs, unexpected behavior, and compromised keys.
## How Budget Limits Work
```mermaid theme={null}
flowchart LR
A[Agent Places Order] --> B{Check Budget}
B -->|Order Cost <= Remaining| C[Execute Order]
B -->|Order Cost > Remaining| D[Reject Order]
C --> E[Update Budget Used]
D --> F[Return 403 Error]
```
1. Agent submits an order
2. LuckyLobster calculates order cost: `price × size`
3. Compares against remaining budget
4. If sufficient, executes and updates usage
5. If exceeded, rejects with budget details
## Configuring Budgets
Configure budget limits for each agent at **Dashboard > Manage Agents**.
### Budget Settings
| Setting | Description |
| ---------------------- | ---------------------------------------------- |
| **Fixed Limit** | Maximum USDC the agent can spend |
| **Budget Percent** | Percentage of wallet balance the agent can use |
| **Max Position Value** | Cap on total open position value |
The effective budget is the most restrictive of all configured limits and the wallet balance.
### Example Configurations
| Setup | Use Case |
| ------------------------------ | ----------------------------------- |
| Fixed \$50 | Testing and development |
| 50% of wallet | Moderate risk exposure |
| Fixed $500 + max position $200 | Active trading with position limits |
## Budget Enforcement
### Order Placement
When placing an order, budget is checked:
```json theme={null}
{
"success": false,
"error": "Budget Exceeded",
"message": "Order cost ($55.00) would exceed budget limit",
"budget": {
"limit": 100,
"used": 80,
"remaining": 20,
"activePositionValue": 150,
"maxPositionValue": 500
}
}
```
### What Counts Toward Budget
| Counts | Doesn't Count |
| ----------------------- | ----------------- |
| Order cost at placement | Unrealized gains |
| Filled trade value | Market research |
| Fees | Viewing positions |
## Checking Your Budget
### Via Dashboard
View budget usage at **Dashboard > Manage Agents** for each agent.
### Via API
```bash theme={null}
curl "https://luckylobster.io/api/agent/v1/budget" \
-H "Authorization: Bearer ll_..."
```
Response:
```json theme={null}
{
"success": true,
"data": {
"usdc": 46.58,
"limitedBy": "percent",
"wallet": 93.16,
"config": {
"fixedLimit": null,
"budgetPercent": 50,
"maxPositionValue": null,
"used": 0
}
}
}
```
### How Budget Is Calculated
The `usdc` field is the actual spendable amount, determined by the most restrictive constraint:
```
usdc = min(walletBalance, fixedLimit, walletBalance * budgetPercent/100)
```
The `limitedBy` field tells you which constraint is active: `"wallet"`, `"fixed_limit"`, `"percent"`, or `"position_limit"`.
## Position Limits
In addition to spending budgets, you can configure position limits:
| Setting | Description |
| ----------------------- | ----------------------------------- |
| **Max Position Value** | Maximum value of all open positions |
| **Max Single Position** | Maximum size of any single position |
These prevent concentration risk and limit exposure.
## Best Practices
Begin with a low budget (\$50-100) and increase as you verify agent behavior. It's easier to increase limits than recover from losses.
* Use `daily` for high-frequency strategies that need fresh limits each day
* Use `monthly` for steady strategies with predictable spending
* Use `never` for fixed-allocation strategies
Regularly check budget utilization in the dashboard. If an agent consistently hits limits, it might need adjustment or investigation.
Configure notifications (coming soon) for when budget usage exceeds thresholds like 80%.
## Increasing Limits
To increase an API key's budget:
1. Go to **Dashboard > Manage Agents**
2. Click the budget settings for the agent
3. Update the budget configuration
4. Save changes
Changes take effect immediately. Be sure you want to increase spending capacity before confirming.
## Dry Run Testing
Use `dryRun: true` in orders to test budget validation without spending:
```bash theme={null}
curl -X POST "https://luckylobster.io/api/agent/v1/orders" \
-H "Authorization: Bearer ll_..." \
-H "Content-Type: application/json" \
-d '{
"tokenId": "...",
"side": "BUY",
"price": 0.55,
"size": 100,
"dryRun": true
}'
```
This validates all budget constraints without placing a real order.
# Introduction
Source: https://docs.luckylobster.io/introduction
Trade Polymarket with AI agents using LuckyLobster
## What is LuckyLobster?
LuckyLobster is a secure trading platform that enables AI agents to trade on [Polymarket](https://polymarket.com) on your behalf. Connect your wallet, generate API keys, and let your OpenClaw agents execute prediction market strategies.
Get trading in under 5 minutes
Install the LuckyLobster skill for your agent
Full API documentation for developers
Add LuckyLobster to your agent
## Key Features
Your Polymarket Magic Proxy Safe wallet keys are encrypted with AES-256-GCM. Private keys never leave your account and are only decrypted server-side during order execution.
Native integration with OpenClaw (ClawdBot, MoltBot) and other AI agents. Simply install the skill.md and your agent can start trading.
Set spending limits per API key to control how much your agents can trade. Track P\&L and performance metrics in real-time.
Define trading rules (Price Alert, Recurring Buy, Buy Low Sell High) once and let the server execute them 24/7 - even when your agent is offline. [Learn more](/strategies).
Direct integration with Polymarket's Builder API for fast order execution. Support for LIMIT, MARKET, FOK, and FAK order types.
## How It Works
```mermaid theme={null}
sequenceDiagram
participant Agent as AI Agent
participant LL as LuckyLobster
participant PM as Polymarket
Agent->>LL: 1. Search markets (API key auth)
LL->>PM: Query markets
PM-->>LL: Market data
LL-->>Agent: Markets with tokens
Agent->>LL: 2. Place order
LL->>LL: Validate budget & permissions
LL->>PM: Submit signed order
PM-->>LL: Order confirmation
LL-->>Agent: Order status
```
1. **Sign Up** - Create an account and connect your Polymarket wallet
2. **Install Skill** - Add the LuckyLobster skill to your AI agent
3. **Link Agent** - Your agent uses the device flow to get an API key automatically
4. **Trade** - Your agent searches markets and places orders within budget limits
## Supported Order Types
| Type | Description |
| -------- | ---------------------------------------------------- |
| `LIMIT` | Order remains on book until filled or cancelled |
| `MARKET` | Executes immediately at best available price |
| `FOK` | Fill or Kill - must fill entirely or cancel |
| `FAK` | Fill and Kill - fills what's available, cancels rest |
## Security First
LuckyLobster is built with security as a core principle:
* **Encrypted Keys** - All private keys encrypted at rest with AES-256-GCM
* **Budget Limits** - Hard spending caps per API key
* **Permission Scopes** - Fine-grained control over API key capabilities
* **Rate Limiting** - Protection against abuse
* **Audit Logging** - All actions tracked for accountability
LuckyLobster handles real funds on Polymarket. Always start with small amounts and test thoroughly before deploying with larger budgets.
## Get Help
Join our community for help and updates
Reach out for technical support
# Quickstart
Source: https://docs.luckylobster.io/quickstart
Start trading on Polymarket with your AI agent in 5 minutes
## Prerequisites
Before you begin, make sure you have:
A Polymarket account with a Magic Proxy Safe wallet.
[Sign up at Polymarket](https://polymarket.com) if you don't have one.
USDC deposited into your Polymarket wallet. LuckyLobster trades using funds in your Polymarket account - it does not hold or transfer funds itself.
[How to deposit USDC on Polymarket](https://help.polymarket.com/en/articles/13369887-how-to-deposit).
If using with AI agents, install [ClawdBot](https://openclaw.ai) or another compatible agent.
## Step 1: Create Your Account
1. Go to [luckylobster.io/signup](https://luckylobster.io/signup)
2. Enter your email and create a password
3. Verify your email address
4. Enable 2FA for additional security (recommended)
1. Go to [luckylobster.io/signup](https://luckylobster.io/signup)
2. Click "Continue with Google" or "Continue with GitHub"
3. Authorize the application
1. Go to [luckylobster.io/signup](https://luckylobster.io/signup)
2. Click "Sign up with Passkey"
3. Follow your device's biometric authentication
## Step 2: Connect Your Wallet
After signing in, you need to connect your Polymarket wallet.
You'll need the private key from your Polymarket Magic Safe wallet.
This key is encrypted and stored securely, but handle it with care.
1. Navigate to **Dashboard > Settings > Wallets**
2. Click **Import Wallet**
3. Enter your wallet details:
* **Private Key**: Your Magic Safe EOA private key
* **Proxy Address**: Your Polymarket proxy/Safe address
```bash theme={null}
# Your private key looks like this (keep it secret!)
0x1234567890abcdef...
# Your proxy address looks like this
0xABCD...1234
```
4. Click **Import & Verify**
5. LuckyLobster will verify the wallet and check balances
Your wallet is now connected! You can see your USDC balance.
## Step 3: Link Your AI Agent
API keys are generated automatically when an AI agent links to your account through the device authorization flow.
1. Visit [ClawHub Skills](https://clawhub.com/skills)
2. Search for "LuckyLobster"
3. Click **Install**
4. Your agent will initiate the device flow automatically
5. Approve the link when prompted
Point your agent to the skill file:
```
https://luckylobster.io/skill.md
```
Your agent will read the skill and initiate the device flow:
1. Agent calls `POST /api/auth/device` and shows you a link with a code
2. Visit the link and approve the connection
3. Agent receives its `ll_*` API key automatically
If you're building your own integration:
```bash theme={null}
# 1. Request device code
curl -X POST "https://luckylobster.io/api/auth/device" \
-H "Content-Type: application/json" \
-d '{"agent_name": "My Agent"}'
# Response includes user_code and verification_uri_complete
# 2. Visit the link and approve
# 3. Poll for the API key
curl "https://luckylobster.io/api/auth/device/token?device_code=abc123..."
```
See the [Skill Reference](/skill) for the complete flow.
Once linked, configure your agent's budget at **Dashboard > Manage Agents**.
Start with a small budget limit while testing. You can increase it later
once you're confident in your setup.
## Step 4: Make Your First Trade
Tell your AI agent:
> "Search for Bitcoin prediction markets and buy \$10 of YES on the most liquid one"
The agent will:
1. Search markets using `/markets/search?q=bitcoin`
2. Analyze liquidity and find the best market
3. Place a BUY order via `/orders`
4. Report back with the order status
Test directly with curl:
```bash theme={null}
# Search for markets
curl -X GET "https://luckylobster.io/api/agent/v1/markets/search?q=bitcoin" \
-H "Authorization: Bearer ll_abc123..."
# Check your balance
curl -X GET "https://luckylobster.io/api/agent/v1/balance" \
-H "Authorization: Bearer ll_abc123..."
# Place a test order (dry run)
curl -X POST "https://luckylobster.io/api/agent/v1/orders" \
-H "Authorization: Bearer ll_abc123..." \
-H "Content-Type: application/json" \
-d '{
"tokenId": "TOKEN_ID_HERE",
"side": "BUY",
"price": 0.55,
"size": 10,
"type": "LIMIT",
"dryRun": true
}'
```
## Next Steps
Full skill.md documentation for agents
Complete API documentation
Configure spending controls
Security and auth details
## Troubleshooting
Check your wallet balance at **Dashboard > Settings > Wallets** or via the `/balance` API endpoint.
Make sure you have enough USDC for the order. If you need to add funds, deposit through Polymarket directly - see [How to Deposit](https://help.polymarket.com/en/articles/13369887-how-to-deposit).
Your agent has reached its spending limit. Either:
* Increase the budget limit in **Dashboard > Manage Agents**
* Wait for position values to decrease (if using percentage-based budget)
* Verify the agent's API key hasn't been revoked
* Check if the agent is paused in **Dashboard > Manage Agents**
* Ensure you're using `Bearer` auth: `Authorization: Bearer ll_...`
Market orders should fill quickly. For limit orders:
* Check if your price is competitive using `/orderbook` or `/spread`
* Consider using MARKET or FOK order types for immediate execution
# Skill Reference
Source: https://docs.luckylobster.io/skill
Install the LuckyLobster skill for AI agent integration
## Overview
The LuckyLobster skill enables AI agents (OpenClaw, ClawdBot, MoltBot, etc.) to trade on Polymarket prediction markets. This document describes the skill capabilities and how agents should use them.
One-click installation for compatible agents
Full skill definition file
## Skill File URL
Point your agent to the skill file at:
```
https://luckylobster.io/skill.md
```
The skill file is dynamically generated and includes:
* OpenClaw metadata with emoji and environment requirements
* Device authorization flow for linking agents
* Complete API documentation with examples
* Market data, trading, and settlement endpoints
## Device Authorization Flow
LuckyLobster uses a device code flow for agents to authenticate, similar to how you'd link a TV app to your account.
Agent calls `POST /api/auth/device` with agent name
User opens `https://luckylobster.io/link` and enters the code
Agent polls `GET /api/auth/device/token` until authorized
Agent saves the returned `ll_*` API key for future requests
### Example Flow
```bash theme={null}
# 1. Request device code
curl -X POST "https://luckylobster.io/api/auth/device" \
-H "Content-Type: application/json" \
-d '{"agent_name": "ClawdBot"}'
# Response:
# {
# "device_code": "abc123...",
# "user_code": "ABCD-1234",
# "verification_uri": "https://luckylobster.io/link",
# "expires_in": 900,
# "interval": 5
# }
# 2. Tell user to visit: https://luckylobster.io/link?code=ABCD-1234
# 3. Poll every 5 seconds
curl "https://luckylobster.io/api/auth/device/token?device_code=abc123..."
# Success response:
# {
# "api_key": "ll_abc123...",
# "user_email": "user@example.com",
# "permissions": ["read", "trade", "cancel", "redeem"]
# }
```
## Capabilities
### Market Discovery
| Endpoint | Description |
| ------------------------- | ---------------------------------------------------------------- |
| `GET /markets/search` | Search by keyword, tag, or slug |
| `GET /markets/{id}` | Get market details with token IDs |
| `GET /markets/crypto` | Quick lookup for crypto up/down markets |
| `GET /markets/crypto/all` | All active crypto markets with live prices, oracle data, spreads |
| `GET /markets/by-slug` | Find by exact Polymarket slug |
### Market Data
| Endpoint | Description |
| ------------------ | ------------------------------ |
| `GET /orderbook` | Full order book with bids/asks |
| `GET /prices` | Current bid/ask/mid prices |
| `GET /spread` | Bid-ask spread |
| `GET /market-data` | Comprehensive data in one call |
### Trading
| Endpoint | Description |
| --------------------- | -------------------------- |
| `POST /orders` | Place buy/sell orders |
| `GET /orders` | List orders with live sync |
| `GET /orders/{id}` | Get order status |
| `DELETE /orders/{id}` | Cancel an order |
### Positions & Account
| Endpoint | Description |
| ---------------------------- | ------------------------------ |
| `GET /positions` | Current holdings with P\&L |
| `POST /positions/{id}/close` | Close a position |
| `GET /balance` | Wallet USDC balance |
| `GET /budget` | Spendable amount with limits |
| `GET /stats` | Trading performance statistics |
| `POST /wallet/approve` | Approve tokens for trading |
### Settlements
| Endpoint | Description |
| -------------------------- | -------------------------- |
| `GET /settlements/redeem` | Check redeemable positions |
| `POST /settlements/redeem` | Redeem winning positions |
### Heartbeat
| Endpoint | Description |
| ---------------- | ----------------------------------------------------- |
| `GET /heartbeat` | Aggregated status, actions, portfolio, and scheduling |
### Autonomous Strategies
| Endpoint | Description |
| ------------------------------ | ----------------------------------------------------------------------------------- |
| `POST /strategies` | Create a strategy (PRICE\_ALERT, RECURRING\_BUY, BUY\_LOW\_SELL\_HIGH, COPY\_TRADE) |
| `GET /strategies` | List strategies with execution history |
| `GET /strategies/types` | Get available strategy types and their config schemas |
| `GET /strategies/{id}` | Get strategy details |
| `PATCH /strategies/{id}` | Update strategy config |
| `POST /strategies/{id}/pause` | Pause a strategy |
| `POST /strategies/{id}/resume` | Resume a paused strategy |
| `DELETE /strategies/{id}` | Cancel a strategy |
## Search Tips
For a full snapshot of all active crypto markets with prices, spreads, and oracle data in one call:
```bash theme={null}
GET /markets/crypto/all # All active crypto markets
GET /markets/crypto/all?asset=btc # Just BTC markets
GET /markets/crypto/all?timeframe=15m # Just 15-minute markets
```
For a single crypto market lookup:
```bash theme={null}
GET /markets/crypto?asset=btc&timeframe=15m # Current BTC 15-minute market
GET /markets/crypto?asset=eth&timeframe=hourly # Current ETH hourly market
GET /markets/crypto?asset=xrp&timeframe=daily # Today's XRP daily market
```
For non-crypto markets, text search works well:
* `trump election` → Political markets
* `superbowl winner` → Sports markets
* `oscars` → Entertainment markets
Strategies using `marketQuery` (e.g., "bitcoin", "xrp") also use slug-based discovery automatically for known crypto assets.
## Order Types
| Type | Description |
| -------- | --------------------------------------- |
| `LIMIT` | Rests on book until filled or cancelled |
| `MARKET` | Fills immediately at best price |
| `FOK` | Fill or Kill - all or nothing |
| `FAK` | Fill and Kill - take what's available |
## Permissions
Linked agents receive standard permissions:
| Permission | Access |
| ---------- | ----------------------------------- |
| `read` | Markets, orders, positions, balance |
| `trade` | Place buy/sell orders |
| `cancel` | Cancel open orders |
| `redeem` | Settle winning positions |
## Rate Limits
* Default: **100 requests/minute** per API key
* Headers included: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
## Error Handling
All endpoints return consistent error format:
```json theme={null}
{
"success": false,
"error": "Error Type",
"message": "Human-readable description"
}
```
| Status | Meaning |
| ------ | ------------------------------------------- |
| 401 | Invalid API key |
| 403 | Insufficient permissions or budget exceeded |
| 404 | Resource not found |
| 429 | Rate limit exceeded |
## Example Workflow
```yaml theme={null}
# 1. Get all crypto markets with prices and spreads in one call
GET /markets/crypto/all
# 2. Check available budget
GET /budget
# 3. Place a limit order using tokenId from the snapshot
POST /orders
{
"tokenId": "...",
"side": "BUY",
"price": 0.55,
"size": 50,
"type": "LIMIT"
}
# 4. Monitor order
GET /orders/{orderId}
# 5. Check positions
GET /positions
# 6. When market settles, redeem
POST /settlements/redeem
```
## Next Steps
Detailed endpoint documentation
Get started in 5 minutes
# Autonomous Strategies
Source: https://docs.luckylobster.io/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 |
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.
***
### 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 |
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.
***
### 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 |
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.
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.
## 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**
Always set a `maxBudget` on every strategy. This is your safety net against unexpected market conditions or rapid execution.
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.
## 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
Every strategy should have a budget cap. This prevents runaway spending if market conditions change unexpectedly.
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.
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.
Check the dashboard or heartbeat regularly to verify strategies are executing as expected. The execution log shows every action, skip, and error.
Begin with small budgets and position sizes. Once you're confident the strategy behaves correctly, gradually increase limits.
## 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 |
# Wallets
Source: https://docs.luckylobster.io/wallets
Connect and manage your Polymarket wallet
## Overview
To trade on Polymarket through LuckyLobster, you need to connect your Polymarket Magic Proxy Safe wallet.
## Wallet Types
The recommended wallet type. Uses Polymarket's Magic Proxy for seamless trading.
Gnosis Safe multisig wallet for institutional users.
## Connecting Your Wallet
### Prerequisites
1. A Polymarket account with a deployed wallet
2. Your wallet private key (EOA key from Magic)
3. Your proxy/Safe address
### Step-by-Step
Go to **Dashboard > Settings > Wallets** and click **Import Wallet**
Paste your Magic EOA private key. This is encrypted immediately with AES-256-GCM.
```
0x1234567890abcdef...
```
Never share your private key with anyone. LuckyLobster encrypts it immediately and it's only decrypted server-side during order signing.
Your Polymarket proxy address (starts with `0x`)
```
0xABCD1234...
```
LuckyLobster will verify the wallet and display your balances.
## Finding Your Wallet Details
### From Polymarket
1. Log in to [polymarket.com](https://polymarket.com)
2. Go to **Settings** or click your profile
3. Your proxy address is displayed in the wallet section
### Getting Your Private Key
Your Magic wallet private key can be exported from your Magic account. Be extremely careful with this key.
Your private key gives full control over your wallet. Only enter it on trusted sites and never share it.
## Wallet Security
Your wallet is protected with:
| Security Layer | Description |
| -------------------------- | -------------------------------------------- |
| **AES-256-GCM Encryption** | Private key encrypted at rest |
| **Per-Wallet IV** | Unique initialization vector for each wallet |
| **Server-Side Only** | Keys never sent to browser/client |
| **Secure Key Derivation** | Master key stored in secure environment |
## Wallet Approvals
Before selling tokens, your wallet needs to approve the Polymarket contracts:
* **USDC Approval** - For buying shares
* **CTF Approval** - For selling shares (Conditional Token Framework)
LuckyLobster handles these approvals automatically when needed.
## Troubleshooting
* Verify your proxy address is correct
* Check that you have USDC in your Polymarket wallet. All funding is done through Polymarket directly - see [How to Deposit](https://help.polymarket.com/en/articles/13369887-how-to-deposit)
* Ensure you're connected to Polygon network
* Check the `/balance` endpoint for current balance
* Verify funds are in your proxy wallet, not EOA
* If you need to add funds, deposit through Polymarket directly - see [How to Deposit](https://help.polymarket.com/en/articles/13369887-how-to-deposit)
LuckyLobster auto-approves CTF when needed. If you get approval errors:
* Try the `/wallet/approve` endpoint manually
* Check for pending transactions on PolygonScan
## API Endpoints
Approve tokens for trading via POST /wallet/approve