# API Reference

### Overview

The AIQuant API provides programmatic access to AI-powered quantitative trading data, analyses, and signals for cryptocurrency markets. This API allows developers, traders, and funds to integrate AIQuant's advanced trading intelligence directly into their applications and systems.

With the AIQuant API, you can access performance reports, trade logs, evaluation results, alpha signals, and trading playbooks across multiple blockchain networks. The API is designed to support a wide range of use cases from simple data retrieval to complex trading strategy implementation.

### Getting Started

#### 1. Create an AIQuant Account

Visit [AIQuant.fun](https://aiquant.fun/) to sign up for an account.&#x20;

#### 2. Launch a Quant

Create and configure your AI-powered trading quant. This will be your primary trading agent that generates signals and evaluations.

#### 3. Select an API Plan

Choose the API plan that best suits your needs:

* **Basic API**: For indie builders and hobbyist developers
* **Growth API**: For scaling products, mid-sized funds, and onchain tools
* **Enterprise API**: For quant funds, trading platforms, and strategic innovators

#### 4. Generate an API Key

See [Authentication](#authentication) section.

#### 5. Start Integrating

Add your API key to the request headers:

```
X-API-Key: your_api_key_here
```

Test your integration with a simple request:

```bash
curl -H "X-API-Key: your_api_key_here" https://api.aiquant.fun/api/trades/stats
```

### Authentication

All API requests must be authenticated using an API key. To make authenticated requests, include your API key in the request header:

```
X-API-Key: your_api_key_here
```

#### Getting Your API Key

API keys are tied to your AIQuant subscription plan. To obtain an API key:

1. Subscribe to one of the API plans (Basic, Growth, or Enterprise)
2. Navigate to the API section in your profile settings
3. Generate a new API key

For security reasons, store your API key securely and do not share it publicly.

### Rate Limits and Quotas

The AIQuant API implements daily request limits based on your subscription plan:

| Plan           | Daily Request Limit | Chain Access     | Primaray Use Case              |
| -------------- | ------------------- | ---------------- | ------------------------------ |
| Basic API      | 100 requests/day    | Up to 1 chain    | Developers & Hobbyists         |
| Growth API     | 500 requests/day    | Up to 2 chains   | Scaling Products               |
| Enterprise API | 5,000 requests/day  | Unlimited chains | Quant Funds & Advanced Traders |

Rate limit information is included in the response headers:

```
X-RateLimit-Limit: [daily limit]
X-RateLimit-Remaining: [remaining requests]
X-RateLimit-Reset: [reset timestamp]
```

When you exceed your daily limit, the API will return a `429 Too Many Requests` response.

### API Plans and Features

AIQuant offers three API subscription plans with different capabilities:

#### Basic API Plan

* Performance reports & trade logs
* Quick evaluation summaries
* Support: Email

#### Growth API Plan

* Everything in Basic, plus:
* Detailed evaluation reports
* Realtime alpha signals
* Basic trading playbook
* Support: Email + Telegram

#### Enterprise API Plan

* Everything in Growth, plus:
* Advanced trading playbook
* AI-powered strategy optimizations
* Support: Email + Telegram + Slack

### Available Endpoints

**Base URL:** [https://api.aiquant.fun](https://api.aiquant.fun/)

All endpoints should be prefixed with this base URL. For example, to access the Trade Statistics endpoint, use: `https://api.aiquant.fun/api/trades/stats`

#### Performance & Trades

* [Trade Statistics](#trade-statistics)
* [Trade History](#trade-history)
* [Trade Details](#trade-details)

#### Evaluation Results

* [Evaluation Results](#latest-evaluation-results)
* [Evaluation Details](#evaluation-details)
* [Evaluation History](#evaluation-history)

#### Alpha Signals

* [Alpha Signals List](#alpha-signals-list)
* [Alpha Signal Details](#alpha-signal-details)

#### Trading Playbook

* [Degen Configuration](#degen-configuration)

#### Strategy Optimization

* [Optimization Dashboard](#optimization-dashboard)
* [Run Analysis](#run-analysis)
* [Apply Recommendation](#apply-recommendation)

***

### Performance & Trades

#### Trade Statistics

<img src="/files/n5lJCXfV5YHBtXqygI8B" alt="" data-size="line"> **Trade Metrics**

**GET** `/api/trades/stats`

Retrieves aggregated metrics for trades, including total trades, volume, and weekly performance changes.

**Query Parameters:**

* `quantId` (integer, optional): Filter metrics by specific quant ID

**Response:**

```json
{
    "metrics": {
        "totalTrades": 20624,
        "totalVolume": 11022415.867949218,
        "tradesWeeklyChange": -18.414533443435175,
        "volumeWeeklyChange": -30.29726971091618
    }
}
```

#### Trade History

<img src="/files/Jfm4KOeSXZchzlU1Ax9U" alt="" data-size="line"> **Trade List**

**GET** `/api/trades`

Retrieves paginated trade history with filtering options.

**Query Parameters:**

* `quantId` (integer, optional): Filter by quant ID
* `page` (integer, optional): Page number for pagination
* `pageSize` (integer, optional): Number of trades per page
* `sortBy` (string, optional): Field to sort by
* `sortOrder` (string, optional): Sort direction (`asc` or `desc`)
* `filterStatus` (string, optional): Filter by trade status
* `search` (string, optional): Search term for tokens
* `startDate` (string, optional): Filter by start date (ISO format)
* `endDate` (string, optional): Filter by end date (ISO format)
* `chain` (string, optional): Filter by blockchain network
* `positionClosed` (string, optional): Filter by position status (`true`, `false`, or `all`)
* `isTrackingEnabled` (string, optional): Filter by tracking status (`true`, `false`, or `all`)
* `tradingMode` (string, optional): Filter by trading mode (`live`, `paper`, or `all`)
* `tradingStatus` (string, optional): Filter by model validation status:

&#x20;   \- `executed` - Shows only trades that were executed after approval (default when not specified)

&#x20;   \- `delayed` - Shows trades currently delayed by model (with active wait timers)

&#x20;   \- `rejected` - Shows trades rejected by model validation

&#x20;   \- `recommended` - Shows trades in recommended status

&#x20;   \- `all` - Shows all trades regardless of model validation status

**Response:**

```json
{
    "trades": [
        {
            "id": "50155",
            "token_id": "54667",
            "token_name": "WE LOVE ASS",
            "token_symbol": "ASS",
            "token_image": "https://ipfs.io/ipfs/QmYqF2cRhTKKUbWjBTuNsXSSNPbzFWtwd9p4ua1xFD2sHv",
            "token_chain": "SOLANA",
            "token_address": "CfgmB9iTWABdYh3CHQQDUGtWy18rMNAEEqyp4GrJpump",
            "open_date": "2025-04-09 03:05:05",
            "close_date": "2025-04-09 03:52:08",
            "duration": "0.78",
            "buy_cost_usd": "$10",
            "sell_revenue_usd": "$10",
            "pnl_usd": "-$0.4",
            "roi": "-4.0%",
            "eth_sol_spent": "0.100000 SOL",
            "eth_sol_received": "0.096180 SOL",
            "tokens_bought": "14771.92610532857",
            "tokens_sold": "14771.92610532857",
            "avg_buy_price_solOrEth": "0.00000677",
            "status": "Closed",
            "result": "Loss",
            "price": "$0.000672",
            "price_change": "+26.53%",
            "volume24h": "$85.42K",
            "quant_name": "Premium Edge",
            "metadata": {
                "llmValidation": {
                  "decision": "DELAY",
                  "waitUntil": "2025-09-03T11:19:24.363Z",
                  "confidence": 85,
                  "validatedAt": "2025-09-03T07:19:24.363Z",
                  "reasoning": {
                    "marketAnalysis": "The overall market regime is neutral, but the DeFi sector is showing significant negative momentum...",
                    "riskAssessment": "The primary risk is poor entry timing...",
                    "technicalEvaluation": "Price is extremely overextended at 98.5% Bollinger Band..."
                  }
                }
            },
            "latest_evaluation": {
                "id": 6807776,
                "type": "TOKEN_BUY",
                "passed": false,
                "ai_score": 35,
                "internal_score": 50,
                "timestamp": "2025-04-09T13:48:09.929Z",
                "summary": "The token shows weak market dynamics with a bearish trend indicated by declining price changes and low buy-to-sell ratios. Community engagement data is missing, which adds uncertainty. Technical analysis reveals mixed signals, with a bearish MACD and moving average, but a strong Fibonacci score suggesting potential support. Overall, the negative indicators outweigh the positives, making it a risky investment. It is not a good time to buy this token.",
                "detection_price": 0.001866992233880762,
                "token_image": "https://ipfs.io/ipfs/QmYqF2cRhTKKUbWjBTuNsXSSNPbzFWtwd9p4ua1xFD2sHv"
            }
        }
    ],
    "summary": {
        "totalTrades": 157,
        "totalVolume": 34816.93969230225,
        "profitableTrades": 84,
        "lossTrades": 73,
        "totalProfit": 3989.0842282990784,
        "totalLoss": 2823.7555181923963,
        "winRate": 53.503184713375795,
        "accountValue": 35982.26840240895,
        "realized": {
            "trades": 150,
            "volume": 32497.442223898477,
            "profitableTrades": 83,
            "lossTrades": 67,
            "profit": 3877.258630608689,
            "loss": 2661.3419094668675,
            "pnl": 1215.9167211418214,
            "roi": 3.7415766839878914,
            "winRate": 55.333333333333336,
            "avgReturn": 8.10611147427881
        },
        "unrealized": {
            "trades": 7,
            "volume": 2319.4974684037825,
            "profitableTrades": 1,
            "lossTrades": 6,
            "profit": 111.8255976903888,
            "loss": 162.41360872552906,
            "pnl": -50.588011035140255,
            "roi": -2.180990137917831,
            "winRate": 14.285714285714285,
            "avgReturn": -7.226858719305751
        }
    },
    "pagination": {
        "total": 157,
        "page": 1,
        "pageSize": 20,
        "totalPages": 8
    }
}
```

#### Trade Details

<img src="/files/DG9RW1zpKRXDVtabF5zC" alt="" data-size="line"> **Trade Information**

**GET** `/api/trades/:id`

Retrieves detailed information about a specific trade.

**Path Parameters:**

* `id` (integer, required): Trade ID

**Response:**

```json
{
    "trade": {
        "id": "50208",
        "token_id": "59181",
        "token_name": "42069COIN",
        "token_symbol": "42069COIN",
        "token_image": "https://ipfs.io/ipfs/QmUzk4cQBHxCBLRH3sPxKWAsFT9CpmjsBndJGPzkEQGbkv",
        "token_chain": "SOLANA",
        "token_address": "5CxtvaR1SskwLxfzHGurx8Enu8bgSTPyWF3YP4sWpump",
        "open_date": "2025-04-09 03:46:23",
        "close_date": "2025-04-09 04:02:50",
        "duration": "0.27",
        "buy_cost_usd": "$10",
        "sell_revenue_usd": "$12",
        "pnl_usd": "$1.5",
        "roi": "+14.4%",
        "eth_sol_spent": "0.100000 SOL",
        "eth_sol_received": "0.113978 SOL",
        "tokens_bought": "23262.21112957615",
        "tokens_sold": "23262.21112957615",
        "avg_buy_price_solOrEth": "0.00000430",
        "status": "Closed",
        "result": "Profit",
        "price": "$0.000435",
        "price_change": "+525.69%",
        "volume24h": "$1.63M",
        "quant_name": "Premium Edge",
        "duration_seconds": 987,
        "buy_cost_usd_raw": 10.31736792095562,
        "sell_revenue_usd_raw": 11.799694276221217,
        "pnl_usd_raw": 1.482326355265597,
        "roi_raw": 14.367291799828537,
        "eth_sol_spent_raw": 0.1,
        "eth_sol_received_raw": 0.1139776250364365,
        "tokens_bought_raw": 23262.21112957615,
        "tokens_sold_raw": 23262.21112957615,
        "avg_buy_price_solOrEth_raw": 0.00000429881748742524,
        "price_raw": 0.0004350409701404734,
        "price_change_raw": 525.6869012910554,
        "volume24h_raw": 1634074.65679551,
        "marketCap": "$435.04K",
        "marketCap_raw": 435038.0329303403,
        "liquidity": "$77.67K",
        "liquidity_raw": 77670.61858872062,
        "transactions": [
            {
                "id": 73467,
                "action": "BUY",
                "txHash": "FAKE-dd00268f-a4ae-4a5c-b7ea-186774914e5e",
                "timestamp": "2025-04-09T03:46:23.238Z",
                "inputToken": "So11111111111111111111111111111111111111112",
                "outputToken": "5CxtvaR1SskwLxfzHGurx8Enu8bgSTPyWF3YP4sWpump",
                "inputAmount": 0.1,
                "outputAmount": 23262.21112957615,
                "inputValueUsd": 10.31736792095562,
                "outputValueUsd": 10.317367920955618,
                "pricePerTokenInUsd": 0.0004435248164280421
            },
            {
                "id": 73491,
                "action": "SELL",
                "txHash": "FAKE-0a0810a0-bfa9-49b5-91cb-5a0b424fa531",
                "timestamp": "2025-04-09T04:02:50.239Z",
                "inputToken": "5CxtvaR1SskwLxfzHGurx8Enu8bgSTPyWF3YP4sWpump",
                "outputToken": "So11111111111111111111111111111111111111112",
                "inputAmount": 23262.21112957615,
                "outputAmount": 0.1139776250364365,
                "inputValueUsd": 11.799694276221219,
                "outputValueUsd": 11.799694276221217,
                "pricePerTokenInUsd": 0.0005072473210089129
            }
        ],
        "latest_evaluation": {
            "id": 6673431,
            "type": "TOKEN_BUY",
            "passed": false,
            "ai_score": 30,
            "internal_score": 55,
            "timestamp": "2025-04-09T07:58:30.921Z",
            "summary": "The token shows significant bearish signals with a high RSI indicating overbought conditions, negative price changes, and a downtrend forecast from AI. Despite some positive community engagement and buy-to-sell ratios, the overall market dynamics and technical indicators suggest a strong sell sentiment. Given the current conditions, it is not a good time to buy this token.",
            "detection_price": 0.00004558404626886283,
            "token_image": "https://ipfs.io/ipfs/QmUzk4cQBHxCBLRH3sPxKWAsFT9CpmjsBndJGPzkEQGbkv"
        }
    }
}
```

### Evaluation Results

#### Evaluation Results

<img src="/files/xERB92h7w6JJKkqQF9mo" alt="" data-size="line"> **Evaluation Results**

**GET** `/api/eval-results`

Retrieves the latest token evaluation results with filtering options.

**Query Parameters:**

* `limit` (integer, optional): Maximum number of results to return
* `offset` (integer, optional): Number of results to skip
* `chain` (string, optional): Filter by blockchain network
* `search` (string, optional): Search term for tokens
* `quantId` (string, optional): Filter by quant ID
* `passed` (string, optional): Filter by pass/fail status
* `uniqueTokensOnly` (string, optional): Return only unique tokens
* `onlyScored` (string, optional): Return only scored evaluations
* `timeTo` (string, optional): End time for results (ISO format)
* `timeFrom` (string, optional): Start time for results (ISO format)
* `evaluationResultType` (string, optional): Filter by evaluation type

**Response:**

```json
{
    "results": [
        {
            "id": 20083701,
            "tokenId": 30938,
            "userQuantId": 4,
            "createdAt": "2025-05-08T08:45:30.837Z",
            "updatedAt": "2025-05-08T08:45:30.837Z",
            "evaluationResultType": "TOKEN_BUY",
            "marketCap": 775354,
            "passed": true,
            "avgScore": 65,
            "aiScore": 65,
            "internalScore": 65,
            "aiAnalysis": "The token exhibits strong technical momentum with high MACD and bullish on-chain prediction, supported by increasing volume and buy-to-sell ratios. Despite some sell volume increases and ranging market regime, the overall technical and AI signals lean positive. The lack of verified community engagement data introduces some uncertainty, but the technical and fundamental indicators suggest a promising entry point. Therefore, it is a GOOD TIME to BUY with medium risk tolerance.",
            "aiPrompt": "...",
            "token": {
                "id": 30938,
                "symbol": "BITCOIN",
                "address": "0x2a06A17CBC6d0032Cac2c6696DA90f29D39a1a29",
                "chainName": "BASE",
                "DataFetcherResponseSnapshots": [...],
                "detectionPrice": 0.06284334598184069,
                "image": "https://dd.dexscreener.com/ds-data/tokens/base/0x2a06a17cbc6d0032cac2c6696da90f29d39a1a29.png?key=9d0df5&size=xl"
            },
            "performance": {
                "tokenId": 30938,
                "entryPriceUsd": 0.039514,
                "roi": 4.21
            }
        }
    ],
    "total": 2
}
```

#### Evaluation Details

<img src="/files/GvoniIF2GCTldjlYSZ12" alt="" data-size="line"> **Evaluation Details**

**GET** `/api/eval-details`

Retrieves detailed information about a specific evaluation.

**Query Parameters:**

* `evaluationId` (string, required): ID of the evaluation

**Response:**

```json
{
    "token": {
        "id": 96941,
        "image": "https://ipfs.io/ipfs/QmefBnQRMLs9CKarKBPWiTXrMZ32A32zDxD7FX9FzTRS1M",
        "name": "Nice Meme",
        "symbol": "NM",
        "address": "5Q4ABNEAyg1MVXwxGAEsVzEHWNxuWZdjnZ1gDHvbaqwQ",
        "priceSnapshot": 0.0009107867837406853,
        "priceChange24h": 201.310559747887,
        "mc": 905975.3320194203,
        "liquidity": 363.5912362391309,
        "volume24h": 2879.724923089009,
        "status": "DORMANT",
        "createdAt": "2025-05-07T21:50:01.083Z",
        "chainName": "SOLANA"
    },
    "userQuant": {
        "id": 4,
        "name": "Premium Edge"
    },
    "evaluationResult": {
        "id": 20142913,
        "passed": false,
        "evaluationResultType": "TOKEN_STATUS",
        "avgScore": 0,
        "internalScore": 0,
        "aiScore": 0,
        "aiAnalysis": "Failed required criteria: Liquidity to Market Cap Ratio",
        "createdAt": "2025-05-08T15:34:49.951Z"
    },
    "evaluationResultDetails": [
        {
            "id": 767283072,
            "passed": null,
            "value": "",
            "threshold": 80,
            "weight": 0,
            "score": null,
            "criteriaScore": null,
            "criteriaId": 65,
            "createdAt": "2025-05-08T15:34:49.951Z",
            "extraInfo": {
                "operator": "V_GTE_T"
            },
            "criteria": {
                "key": "tokenSnifferScore",
                "name": "Token Sniffer Score",
                "shortDescription": "Overall security score based on audit findings.",
                "longDescription": "Aggregates various security factors into a single score, indicating the overall security health of the token."
            },
            "category": {
                "id": 4,
                "name": "Security"
            }
        },
        // ...additional criteria details
    ]
}
```

#### Evaluation History

<img src="/files/s51WKvwTs2u3SYOQhHZ1" alt="" data-size="line"> **Evaluation History**

**GET** `/api/eval-history`

Retrieves the evaluation history for a specific token or evaluation.

**Query Parameters:**

* `evaluationId` (string, required): ID of the evaluation
* `take` (integer, optional): Maximum number of results to return
* `skip` (integer, optional): Number of results to skip
* `excludeTypes` (string, optional): Evaluation type to exclude from results. Valid values are: `TOKEN_STATUS`, `TOKEN_BUY`, or `TOKEN_SELL`

**Response:**

```json
{
    "total": 2,
    "results": [
        {
            "id": 20142913,
            "createdAt": "2025-05-08T15:34:49.951Z",
            "marketCap": 905975.3320194203,
            "evaluationResultType": "TOKEN_STATUS",
            "aiScore": 0,
            "internalScore": 0,
            "price": 0.0009107867837406853,
            "passed": false
        },
        {
            "id": 20138175,
            "createdAt": "2025-05-08T14:34:21.817Z",
            "marketCap": 905975.3320194203,
            "evaluationResultType": "TOKEN_STATUS",
            "aiScore": 0,
            "internalScore": 0,
            "price": 0.0009107867837406853,
            "passed": false
        }
    ]
}
```

### Alpha Signals

#### Alpha Signals List

<img src="/files/fuiVfwSqowgQD0TqFtRg" alt="" data-size="line"> **Alpha Signals**

**GET** `/api/alpha-signals`

Retrieves a list of alpha signals with filtering options.

**Query Parameters:**

* `quantId` (integer, optional): Filter by quant ID
* `limit` (integer, optional): Maximum number of results to return
* `chain` (string, optional): Filter by blockchain network. Valid values are: `SOLANA`, `BASE`, or `BSC`
* `includeTokenDetails` (boolean, optional): Include detailed token information
* `search` (string, optional): Search term for tokens

**Response:**

```json
{
    "signals": [
        {
            "tokenId": 96941,
            "evaluationId": 20142913,
            "token": "Nice Meme",
            "symbol": "NM",
            "image": "https://ipfs.io/ipfs/QmefBnQRMLs9CKarKBPWiTXrMZ32A32zDxD7FX9FzTRS1M",
            "chainName": "SOLANA",
            "price": 0.0009107867837406853,
            "change": 201.310559747887,
            "volume": 2879724.923,
            "analysisProgress": 0,
            "stage": "SCREENING",
            "alert": "Failed required criteria: Liquidity to Market Cap Ratio",
            "updatedAt": "2025-05-08T15:34:49.951Z",
            "entryPriceUsd": null,
            "roi": null,
            "marketCap": 905975.3320194203,
            "liquidity": 363.5912362391309,
            "volume24h": 2879.724923089009,
            "address": "5Q4ABNEAyg1MVXwxGAEsVzEHWNxuWZdjnZ1gDHvbaqwQ",
            "passed": false,
            "evaluationResultType": "TOKEN_STATUS"
        },
        // ...additional signals
    ],
    "byChain": {
        "all": {
            "signals": [...],
            "stats": {
                "total": 12,
                "screening": 12,
                "buy": 0,
                "sell": 0,
                "watch": 0
            }
        },
        "solana": {
            "signals": [...],
            "stats": {...}
        },
        "base": {
            "signals": [...],
            "stats": {...}
        },
        "bsc": {
            "signals": [...],
            "stats": {...}
        }
    }
}
```

#### Alpha Signal Details

<img src="/files/xeD0yBO0ljml0mFQ6yZC" alt="" data-size="line"> **Signal Details**

**GET** `/api/alpha-signals/:tokenId`

Retrieves detailed information about a specific alpha signal.

**Path Parameters:**

* `tokenId` (integer, required): ID of the token

**Query Parameters:**

* `quantId` (integer, optional): ID of the quant

**Response:**

```json
{
    "tokenId": 93953,
    "evaluationId": 20142864,
    "token": "MYX",
    "symbol": "MYX",
    "image": null,
    "address": "0x38b1CD3b470db9A91eD4529297D1a3718f0c0a15",
    "chainName": "BSC",
    "price": 0.00007181090731037781,
    "change": 0,
    "volume": 0.003434320356159834,
    "marketCap": 330330.1736277379,
    "liquidity": 6.128644159233319,
    "stage": "SCREENING",
    "alert": "Failed required...",
    "aiScore": 0,
    "internalScore": 0,
    "aiAnalysis": "Failed required criteria: Min Buy Tx 1h",
    "evaluationResultType": "TOKEN_STATUS",
    "passed": false,
    "updatedAt": "2025-05-08T15:33:09.932Z",
    "entryPriceUsd": null,
    "roi": null,
    "evaluationDetails": []
}
```

### Trading Playbook

#### Degen Configuration

<img src="/files/AUmlDguu717FHhy8OYmU" alt="" data-size="line"> **Trading Playbook Configuration**

**GET** `/api/degen/config`

Retrieves the trading playbook configuration for a quant.

**Query Parameters:**

* `quantId` (integer, required): ID of the quant
* `configGroupId` (string, optional): ID of the configuration group

**Response:**

```json
[
    {
        "marketCap": "DEGEN_CAP",
        "categories": {
            "Security": [
                {
                    "rootKey": "auditRisks",
                    "criteriaName": "Audit Risks",
                    "shortDescription": "Checks multiple security aspects of the contract.",
                    "longDescription": "Conducts a comprehensive audit of the token's contract for security risks, such as disabled minting and burned liquidity tokens.",
                    "isHumanCriteria": true,
                    "configTypes": {
                        "SCANNING": {
                            "thresholds": {
                                "noTime": 1
                            },
                            "weights": {
                                "noTime": 8
                            },
                            "requireds": {
                                "noTime": false
                            },
                            "disableds": {
                                "noTime": false
                            },
                            "extraInfos": {
                                "noTime": {
                                    "options": [
                                        {
                                            "id": 0,
                                            "label": "Any"
                                        },
                                        {
                                            "id": 1,
                                            "label": "No Risks Found Only"
                                        },
                                        {
                                            "id": 2,
                                            "label": "Has Risks Found Only"
                                        }
                                    ]
                                }
                            },
                            "delegates": {
                                "noTime": false
                            },
                            "configIdsByInterval": {
                                "noTime": "3d5feae0-da93-4659-8df7-56562517ca57"
                            },
                            "configKeys": {
                                "noTime": "auditRisks"
                            }
                        }
                    }
                }
            ],
            "Market": [
                // Market criteria configurations
            ],
            "Social": [
                // Social criteria configurations
            ],
            "AI": [
                // AI criteria configurations
            ],
            "Technical Analysis": [
                // Technical Analysis criteria configurations
            ],
            "Onchain": [
                // Onchain criteria configurations
            ]
        }
    }
]
```

**PUT** `/api/degen/config`

Updates the trading playbook configuration for a quant.

**Request Body:**

```json
{
  "quantId": 4,
  "newConfigs": [
    {
      "configId": "3d5feae0-da93-4659-8df7-56562517ca57", 
      "field": "threshold",
      "newValue": 2
    },
    {
      "configId": "9ef798af-3fc1-4d21-97e2-2a07b8fb20d0",
      "field": "threshold",
      "newValue": 75
    },
    {
      "configId": "ee95f248-7bbe-4694-9315-674660e83401",
      "field": "extraInfo",
      "newValue": {
        "range": {
          "max": 2500000,
          "min": 350000
        }
      }
    }
  ]
}
```

**Response:**

```
{
  "success": true,
  "updatedConfigs": [
    {
      "id": "3d5feae0-da93-4659-8df7-56562517ca57",
      "criteriaId": 64,
      "criteriaKey": "auditRisks",
      "threshold": 2,
      "weight": 8,
      "required": false,
      "disabled": false,
      "configType": "SCANNING",
      "extraInfo": {
        "options": [
          {
            "id": 0,
            "label": "Any"
          },
          {
            "id": 1,
            "label": "No Risks Found Only"
          },
          {
            "id": 2,
            "label": "Has Risks Found Only"
          }
        ]
      }
    },
    {
      "id": "9ef798af-3fc1-4d21-97e2-2a07b8fb20d0",
      "criteriaId": 22,
      "criteriaKey": "minBuyTx1h",
      "threshold": 75,
      "weight": 0,
      "required": true,
      "disabled": false,
      "configType": "SCANNING",
      "extraInfo": {
        "operator": "V_GTE_T"
      }
    },
    {
      "id": "ee95f248-7bbe-4694-9315-674660e83401",
      "criteriaId": 20,
      "criteriaKey": "liquidity",
      "threshold": 70000,
      "weight": 8,
      "required": false,
      "disabled": false,
      "configType": "BUYING",
      "extraInfo": {
        "range": {
          "max": 2500000,
          "min": 350000
        }
      }
    }
  ]
}
```

### Strategy Optimization

#### Optimization Dashboard

<img src="/files/ocPuNxXuZ0aB6DJTgwcd" alt="" data-size="line"> **Strategy Dashboard**

**GET** `/api/refine-eval/dashboard`

Retrieves the strategy optimization dashboard with performance metrics and recommendations.

**Query Parameters:**

* `quantId` (integer, optional): ID of the quant

**Response:**

```json
{
    "success": true,
    "data": {
        "overallPerformance": {
            "totalTrades": 343,
            "completedTrades": 336,
            "activeTrades": 7,
            "winningTrades": 219,
            "losingTrades": 117,
            "winRate": 0.6517857142857143,
            "avgProfitWinningTrades": 18.23220626191062,
            "avgLossLosingTrades": -26.49156851917146,
            "totalPnL": 1345.4071517405107
        },
        "recentRecommendations": [
            {
                "id": 45,
                "criteriaId": 54,
                "criteriaKey": "volumeChangePercent24h",
                "criteriaName": "Volume Change Percent 24h",
                "oldThreshold": 60,
                "newThreshold": -61.73595809622495,
                "oldExtraInfo": {
                    "operator": "V_GTE_T"
                },
                "newExtraInfo": {
                    "operator": "V_GTE_T"
                },
                "confidence": 0.95,
                "reasoning": "Profitable trades have higher values (avg: 444475.48) than unprofitable trades (avg: 2095.70). Suggesting a threshold of -61.74 to optimize separation.",
                "applied": true,
                "appliedAt": "2025-03-29T20:49:28.468Z",
                "beforeWinRate": 0,
                "afterWinRate": 0.6260869565217392,
                "tradeDifference": 230,
                "configType": "BUY",
                "isDegenConfig": true,
                "userQuantId": 4,
                "profitableAccuracy": 1,
                "unprofitableAccuracy": 0.08823529411764706,
                "f1Score": 0.6990291262135923,
                "sampleSize": 70,
                "profitableAvg": 444475.4815665149,
                "unprofitableAvg": 2095.697533762305,
                "valueDifferenceRatio": 0.9952850098134183,
                "userFeedback": null,
                "actualImpact": 0.6260869565217392,
                "createdAt": "2025-03-26T22:05:01.363Z",
                "updatedAt": "2025-04-12T20:49:31.076Z"
            }
        ],
        "appliedRecommendations": [
            // List of applied recommendations
        ],
        "historicalTrends": {}
    }
}
```

#### Run Analysis

<img src="/files/31NaePxSBvu8RDZudn68" alt="" data-size="line"> **Analysis Executor**

**POST** `/api/refine-eval/analyze`

Executes a strategy analysis to generate optimization recommendations.

**Request Body:**

* `apply` (string, optional): Whether to automatically apply recommendations (`"true"` or `"false"`)
* `minCompletedTrades` (integer, optional): Minimum number of completed trades required for analysis

**Example Request:**

```
{
  "apply": "false",
  "minCompletedTrades": 50
}
```

**Response:**

```json
{
    "success": true,
    "data": {
        "tradesAnalyzed": 343,
        "recommendationsGenerated": 24,
        "recommendationsApplied": 0
    }
}
```

#### Apply Recommendation

<img src="/files/vwD4iTjo4nvR2Fg5aV3J" alt="" data-size="line"> **Apply Recommendation**

**POST** `/api/refine-eval/recs/:id/apply`

Applies a specific optimization recommendation to the trading strategy.

**Path Parameters:**

* `id` (integer, required): ID of the recommendation to apply

**Response:**

```json
{
    "success": true,
    "data": {
        "id": 45,
        "criteriaId": 54,
        "criteriaKey": "volumeChangePercent24h",
        "criteriaName": "Volume Change Percent 24h",
        "oldThreshold": 60,
        "newThreshold": -61.73595809622495,
        "applied": true,
        "appliedAt": "2025-05-08T16:45:12.468Z",
        "beforeWinRate": 0.602,
        "afterWinRate": 0.684,
        "tradeDifference": -15,
        "actualImpact": 0.082
    }
}
```

### Code Examples

#### JavaScript/Node.js

```javascript
const axios = require('axios');

const API_KEY = 'your_api_key_here';
const BASE_URL = 'https://aiquant.fun/api';

async function getAlphaSignals(chain = 'SOLANA', limit = 10) {
  try {
    const response = await axios.get(`${BASE_URL}/alpha-signals`, {
      headers: {
        'X-API-Key': API_KEY
      },
      params: {
        chain,
        limit,
        includeTokenDetails: true
      }
    });
    
    return response.data;
  } catch (error) {
    console.error('Error fetching alpha signals:', error.response?.data || error.message);
    throw error;
  }
}

// Usage
getAlphaSignals()
  .then(data => console.log(`Found ${data.signals.length} alpha signals`))
  .catch(err => console.error('Failed to fetch alpha signals'));
```

#### Python

```python
import requests

API_KEY = 'your_api_key_here'
BASE_URL = 'https://aiquant.fun/api'

def get_trade_history(quant_id=None, days=7):
    from datetime import datetime, timedelta
    end_date = datetime.now().isoformat()
    start_date = (datetime.now() - timedelta(days=days)).isoformat()
    
    params = {
        'startDate': start_date,
        'endDate': end_date,
        'pageSize': 50,
        'page': 1
    }
    
    if quant_id:
        params['quantId'] = quant_id
        
    headers = {
        'X-API-Key': API_KEY
    }
    
    response = requests.get(f"{BASE_URL}/trades", params=params, headers=headers)
    
    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"API request failed with status {response.status_code}: {response.text}")

# Usage
try:
    trades = get_trade_history(quant_id=4)
    print(f"Retrieved {len(trades['trades'])} trades with win rate: {trades['summary']['winRate']:.2%}")
except Exception as e:
    print(f"Error: {e}")
```

***

For urgent assistance, please contact our developer relations team at <info@starter.xyz>


---

# 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://docs.aiquant.fun/overview/api-reference.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.
