# Welcome

Explore the future of crypto trading with AIQuant.fun—your platform for launching AI-driven agents, achieving gamified goals, and earning rewards.

<figure><img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2F5fD7puh3cEdr1Npb0Tm2%2Faiq-home-new.png?alt=media&amp;token=b484bb09-b69e-475b-a8ea-64941b46249d" alt=""><figcaption></figcaption></figure>

AIQuant.fun is where innovation meets automation, revolutionizing the way you trade cryptocurrencies. By creating your own AI Quant, you can eliminate human emotion from trading, focus on precision, and scale your impact. These autonomous agents operate 24/7, leveraging data-driven insights to execute trades with unmatched speed and efficiency—all while enabling you to gamify your trading experience.

### Getting Started: Your Path to AI Trading

Creating your AI quant is a seamless journey designed to empower traders of all levels:

1. **Choose Your Subscription**
   * Select from tiered plans matching your trading ambitions
   * Access features tailored to your experience level
   * Flexible options for beginners and advanced traders
2. **Customize Your AI Quant**
   * Name your unique trading agent
   * Configure personalized trading parameters
   * Select preferred blockchain network
   * Set strategic preferences like Take Profit, Stop Loss, and Slippage
3. **Deploy and Activate**
   * Instantly launch your AI-powered trading assistant
   * Begin automated trading with just a few clicks
   * Monitor performance and adjust as needed

### How Trading Works: Intelligent, Autonomous, Adaptive

AIQuant.fun provides a powerful, flexible approach to AI-driven crypto trading. Your AI quant is designed to execute trades autonomously, leveraging advanced algorithms to make data-driven decisions. With fully customizable parameters, you can fine-tune your trading strategy to match your specific goals and risk tolerance.

Each paid quant comes with a comprehensive set of tools to optimize your trading:

* Full control over trading parameters
* Advanced risk management capabilities
* Ability to customize evaluation criteria
* Sophisticated trading strategy configuration

Note: Our planned bonding curve feature for free quants, including Core Mode and native tokenization, is scheduled for release later in 2025. Stay tuned for more details about this exciting future enhancement.

### Tokenomics and Ecosystem Economics

At the heart of AIQuant.fun is a carefully designed economic model powered by the $AIQ token. Our innovative approach creates a sustainable, community-driven ecosystem that aligns user incentives with platform growth.

#### $AIQ Token: The Platform's Backbone

The $AIQ token is more than just a cryptocurrency—it's the fundamental driver of the AIQuant.fun ecosystem. Holders gain access to platform features, participate in governance, and contribute to the platform's strategic development. With a unique dual governance model, $AIQ brings together long-term supporters and new ecosystem participants to shape the platform's future.

### Referral Program

Expand your network and boost your rewards. Share AIQuant.fun and earn commissions, provide value to your community, and become an influential part of the AI trading revolution.

### Why Choose AIQuant.fun

* 24/7 Automated Trading
* Advanced AI Algorithms
* Flexible Subscription Options
* Multichain Support
* Gamified Trading Experience
* Community-Driven Innovation
* Built By and For Degens

Join us in reshaping the future of crypto trading—one AI quant at a time.

***

## Table of Contents

{% content-ref url="/pages/HZEocW96jIZ1juAA3gQ4" %}
[Getting Started (.fun!)](/overview/getting-started-.fun)
{% endcontent-ref %}

{% content-ref url="/pages/1SeKyG9oQHs7MqMroxiw" %}
[How it Works](/overview/how-it-works)
{% endcontent-ref %}

{% content-ref url="/pages/gWnBW5I9tvMOc2psqye6" %}
[Tokenomics](/overview/tokenomics)
{% endcontent-ref %}

{% content-ref url="/pages/7235l91c4IDegSJbBeb8" %}
[Refer and Earn](/overview/refer-and-earn)
{% endcontent-ref %}


# Getting Started (.fun!)

Learn the essentials of creating, configuring, and launching a tokenized AI quant, and explore how to scale its success through gamified milestones.

<figure><img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FpCseOvhNDN7sps90sgHs%2F2024-12-31%2000.26.39.gif?alt=media&amp;token=a2728a9e-d28e-46c0-b20e-4c5c94a2d380" alt=""><figcaption></figcaption></figure>

#### **Overview: Why Build a Tokenized AI Quant?**

Creating an AI quant is more than deploying a trading bot. It's about tokenizing your trading strategy, automating decisions, and attracting supporters who believe in your approach. Your AI quant operates with unparalleled precision, emotionless execution, and real-time adaptability. As you grow your quant’s influence, you unlock exciting gamified features while building a scalable, community-driven trading agent.

#### **Step 1: Create Your Tokenized AI Quant**

Every tokenized AI quant starts with your vision. Here’s how to bring it to life:

1. **Name Your Tokenized Quant**\
   Give your tokenized AI quant a unique identity that reflects your trading strategy and personality. This name will also define the token associated with your quant.
2. **Generate or Upload Token Image**\
   Use our built-in AI image generator to create a token image for your quant based on a prompt. Or chose to upload an existing token image from your device.
3. **Create a Token**\
   Alongside your AI quant, a token is minted with a custom name, symbol, description, and image. This token is tied to your quant and used for its trading economy.
4. **Deposit $AIQ for Bonding Curve**\
   To initiate your quant, deposit 2,500 $AIQ tokens. This deposit creates a bonding curve (e.g., TOKEN/AIQ pair), enabling others to buy your quant’s token and participate in its performance.
5. **Hatching Fee**\
   Pay a one-time hatching fee of 0.10 ETH to help cover initialization costs.

<figure><img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FZCN9iZ0yNl5JSLBCPgtV%2F2024-12-31%2000.33.03.gif?alt=media&amp;token=9f4379c8-9dc7-4239-91dc-1b249f576601" alt=""><figcaption></figcaption></figure>

#### **Step 2: Configure Core Mode Settings**

Your AI quant starts in **Core Mode**, which includes pre-configured evaluation criteria. Customize these key settings for precision and flexibility:

1. **Trading Parameters**\
   Set essential parameters, including:
   * **Take Profit (%):** Automatically sell when your target profit is reached.
   * **Stop Loss (%):** Limit potential losses by automatically exiting a trade.
   * **Moonbag (%):** Keep a portion of profits in tokens for future potential.
   * **Slippage (%):** Control acceptable price variance during trades.
   * **Autobuy Amount:** Specify the amount of native chain token (SOL or ETH) for purchasing.
2. **Select Your Trading Chain**\
   Your quant's token will be natively launched on Base. However, you may choose between **Solana,** **BNB Chain, Base, or all chains** for your AI quant’s ***trading*** operations.

<figure><img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FGw0ka6oSkoQPdbRtb1GN%2Fcreate-aiquant2.png?alt=media&amp;token=791b1718-1a56-4b91-8a2a-b9c17bec6bce" alt=""><figcaption></figcaption></figure>

{% hint style="success" %}
**Step 3: Launch and Scale**

With your tokenized AI quant created and configured, it’s time to launch it into the marketplace and begin its journey of growth:

1. **Token Activation and Bonding Curve**\
   Once your quant is live, others can purchase its token via the bonding curve. Token demand fuels liquidity, trading, and community engagement.
2. **Achieve Milestones**
   * **Matrix Breached:** Your quant reaches a **$100K market cap**, gaining special recognition as the most sought-after quant on the platform. It can begin autonomously trading with predefined parameters.
   * **Transcended:** With a **$250K market cap**, your quant unlocks **Degen Mode**, allowing full customization of settings and access to advanced features like posting on Farcaster, Telegram, and Twitter. This stage also allows customization of parameters such as Take Profit, Stop Loss, Moonbag %, Slippage, and trading strategies.
     {% endhint %}


# How it Works

Uncover the mechanics behind AIQuant.fun’s AI-powered agents, token analytics, and performance-driven milestones.

<figure><img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FctfePsucFrZevmJ0TWSf%2FScreen%20Shot%202024-12-31%20at%2012.42.04%20AM.png?alt=media&amp;token=d195ad25-237d-4cf5-a4a1-a27c797952ab" alt=""><figcaption></figcaption></figure>

#### A Technical Deep Dive

AIQuant.fun's underlying infrastructure is built to evaluate, classify, and trade cryptocurrency tokens with precision, leveraging a combination of AI-driven analytics and robust configuration mechanisms. Below, we summarize the core functionality and expand on its technical inner-workings.

**Real-Time Evaluation and Monitoring**

AIQuant.fun uses continuous data feeds to monitor crypto markets and evaluate tokens. Some of our sources include, but are not limited to, DexScreener, BirdEye, and Dune. Its multi-layered architecture ensures high reliability and adaptability:

* **Token Analysis**: As tokens are discovered, they are classified into categories (Active, Dormant, Pending, or Rejected) based on performance across technical, on-chain, and social metrics.
* **Configuration-Driven**: Token evaluation relies on configurable thresholds for multiple parameters, such as liquidity, age, volatility, and sentiment, ensuring flexibility across different market conditions.

**Technical Analysis Metrics**

AIQuant.fun integrates advanced technical indicators to assess market trends and opportunities:

* **RSI**: Measures market momentum, signaling overbought (>70) or oversold (<30) conditions.
* **MACD**: Detects momentum shifts through crossovers between the MACD and signal lines.
* **Bollinger Bands**: Identifies price volatility and potential breakouts.
* **Moving Averages (SMA/EMA)**: Highlights long-term trends, such as bullish signals when price surpasses a 200-day EMA.

These indicators are used with configurable thresholds to trigger buy or sell conditions, ensuring adaptability to market dynamics.

**Onchain and Market Metrics**

AIQuant.fun evaluates tokens with a comprehensive set of configurable onchain metrics:

* **Liquidity**: Ensures sufficient depth in trading pairs to minimize slippage, with thresholds such as $50,000 minimum liquidity.
* **Transaction Activity**: Tracks the ratio of buy to sell volume and total trade count over periods ranging from 30 minutes to 24 hours.
* **Holder Distribution**: Assesses risks by evaluating the concentration among top holders (e.g., maximum 20% for the top 10 wallets).

Market metrics like price volatility and trading volume trends are integrated to detect potential price manipulation or unhealthy token ecosystems.

**Social Sentiment and Community Dynamics**

Social metrics play a key role in understanding market sentiment and token credibility:

* **Sentiment Analysis**: Weighted sentiment scores across platforms (e.g., Telegram, Twitter) highlight overall mood toward a token.
* **Influencer Activity**: Evaluates engagement metrics such as posts and interactions from the top 20 key opinion leaders (KOLs).
* **Community Metrics**: Tracks unique contributors, posts, and trend direction to gauge token popularity and engagement.

**Token Monitoring Framework**

AIQuant.fun employs a rigorous token evaluation framework, leveraging configurations for performance thresholds:

* **Price Change and Volatility**: Configurable thresholds ensure tokens are active and responsive without excessive risk.
* **Age and Security**: Tokens must meet minimum age requirements and pass security audits for mint and freeze functions.
* **DEX Listings**: Ensures a minimum presence on decentralized exchanges for broader accessibility.

This framework categorizes tokens dynamically based on aggregated data, ensuring only high-potential tokens remain Active.

**Risk Management**

AIQuant.fun incorporates risk management mechanisms, such as:

* **Liquidity Checks**: Ensures sufficient liquidity to execute trades without significant slippage.
* **Top Holder Analysis**: Limits exposure to tokens with high centralization risk.
* **Volatility Control**: Avoids excessive price swings by capping maximum allowable volatility levels.
* **Auto Position Sizing:** Dynamically adjust position sizes based on real-time factors.&#x20;

**AI and Predictive Modeling**

AIQuant.fun leverages AI and machine learning models for enhanced decision-making:

* **Predictive Algorithms**: AI-driven models forecast price trends and market sentiment.
* **Dynamic Thresholding**: Adaptive configurations modify thresholds based on market conditions, optimizing decision-making.

AIQuant.fun's system integrates configurable technical, on-chain, and social evaluation metrics into a cohesive framework. By leveraging real-time analytics, predictive AI models, and strict governance, the platform ensures data-driven, risk-managed decision-making for cryptocurrency evaluation and trading. This advanced system positions AIQuant.fun as a reliable and adaptive solution for modern crypto trading challenges.


# Tokenomics

Discover how AIQuant.fun's tokenomics drive sustainability, reward participation, and empower AI quant creators.

AIQuant.fun’s tokenomics system creates a sustainable and incentivized ecosystem, ensuring users and backers benefit from the platform's success. By leveraging $AIQ tokens, bonding curves, and carefully allocated transaction fees, the platform fuels growth, rewards participation, and builds value for AI quants.

<table data-header-hidden><thead><tr><th>Category</th><th width="166">Quantity</th><th width="100">% of Supply</th><th>Details</th></tr></thead><tbody><tr><td><strong>Equity Funding</strong></td><td>30,000,000</td><td>3%</td><td>Initial equity funding with token warrant. 1 month cliff.</td></tr><tr><td><strong>Core Team</strong></td><td>200,000,000</td><td>20%</td><td>1 month cliff, linear vesting over 24 months.</td></tr><tr><td><strong>Advisors</strong></td><td>70,000,000</td><td>7%</td><td>Strategic advisors. 3 month cliff, quarterly vesting over 24 months.</td></tr><tr><td><strong>BUIDL Airdrop</strong></td><td>10,000,000</td><td>1%</td><td>Claim portal for $BUIDL stakers. Claiming links available 7-days after TGE, and expires within 60 days.</td></tr><tr><td><strong>Reserve for Strategic Use</strong></td><td>140,000,000</td><td>14%</td><td>Locked for future listings, partnerships, and expansion.</td></tr><tr><td><strong>Treasury</strong></td><td>450,000,000</td><td>45%</td><td>Entity msig treasury for growth and operations. 6 month cliff, quarterly vesting over 48 months.</td></tr><tr><td><strong>TGE &#x26; Market Liquidity</strong></td><td>30,000,000</td><td>3%</td><td>Initial liquidity to bootstrap DEX trading pools. Market liquidity strategically released at TGE</td></tr><tr><td><strong>LP Rewards</strong></td><td>70,000,000</td><td>7%</td><td>1 month cliff, unlocked per incentive program for LPs (e.g. Aerodrome voting).</td></tr></tbody></table>

#### Token Generation Event

AIQuant Labs, a new subsidiary of Starter Labs, has secured equity funding from experienced crypto investors to boost initial growth and operations. This strategic approach eliminated the need to launch seed, strategic and private token sales. AIQ will be listed directly on DEXs like Uniswap and/or Aerodrome during our TGE in September 2025.

**Initial Market Cap: $500,000**

#### AIQ Airdrop Overview

AIQ will airdrop 10 million tokens (1% of supply) to **BUIDL stakers** at a ratio of approximately 1 BUIDL : 0.465 AIQ, rewarding long-term supporters of the ecosystem and bootstrapping our trading community. To fully qualify, you must have BUIDL staked and have also completed the [AIQ Rewards program](https://aiquant.fun/airdrop). The airdrop will be fully unlocked upon issuance, allowing recipients to use their tokens immediately. Airdrop allocation must be claimed in the Starter.xyz pool within 60 days.

**BUIDL Contract Address:**&#x20;

{% embed url="<https://dexscreener.com/base/0xe19D64D5949931A91E46B37604a3Cb4D2cFb0D2c>" %}

**BUIDL Staking Portal:**&#x20;

{% embed url="<https://starter.xyz/staking>" %}

**Hatching Fee: Unlocking Your AI Quant**

To create your AI quant, a one-time Hatching Fee of 0.10 ETH is required. This fee supports the platform’s operational and development costs while providing access to the AI quant ecosystem.

Once paid, the Hatching Fee activates the quant creation process, allowing you to name your quant and configure initial settings. This step establishes your quant as a unique entity in the AIQuant.fun ecosystem.

**Utility for AIQ: Tokenized Quants (Future Release)**

In a future release of AIQuant.fun, we will support the creation of tokenized quants. A description of how this works to increase the utility of AIQ is outlined below.

**Maximum Token Supply**

Every tokenized quant launched on AIQuant.fun will be created with a fixed maximum supply of 1,000,000,000 (1 Billion) tokens. This ensures consistency across all AI quants while providing ample supply for backers, trading, and ecosystem growth.

**Fair Launch Mechanism**

AIQuant.fun adheres to a strictly fair-launch policy, meaning:

* **No Presales or Allocations:** No tokens are pre-allocated or sold before the launch. Every token enters the market through the bonding curve.
* **Equal Opportunity:** All participants—backers, investors, and the general public—can acquire tokens at the same stage, promoting fairness and transparency.

**Bonding Curve Integration**

The bonding curve model governs token distribution, ensuring:

* Tokens are minted dynamically based on user deposits of $AIQ.
* Token price and supply increase in alignment with demand, creating a real-time market-driven valuation.

**Example Workflow**

1. **Creation:** A Morpheus launches their AI quant, selecting a unique name and token symbol (e.g., "QUANT").
2. **Bonding Curve Initiation:** Tokens are minted when backers deposit $AIQ into the bonding curve.
3. **Trading Begins:** As more users buy and trade the token, the bonding curve dynamically adjusts the price, reflecting market activity and demand.

**The Role of $AIQ**

$AIQ is the cornerstone of the AIQuant.fun ecosystem, powering the platform’s tokenomics and governance systems.

* **Quant Creation**:\
  Users deposit $AIQ to create their AI quant. These tokens establish the bonding curve for the Quant’s token ($QUANT/$AIQ pair).
* **Stake to Earn**:\
  Staking AIQ will result in the distribution of USDC rewards based on your tier. Check out the [Stake section in our Earn](https://aiquant.fun/airdrop) page to learn more.

By integrating $AIQ into every facet of the platform, AIQuant.fun aligns user incentives, platform growth, and token value creation in a seamless and scalable manner.


# Refer and Earn

Invite frens to join AIQuant.fun and enjoy tiered rewards, passive income, and exclusive benefits.

<figure><img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FWDjgOYscF49CySvqew3M%2FScreenshot%202024-12-16%20at%202.11.47%E2%80%AFAM.png?alt=media&amp;token=1a513334-4c0a-4235-96f5-b5574a8a736e" alt=""><figcaption></figcaption></figure>

The AIQuant.fun referral program is designed to reward users for helping grow the community. Whether you're inviting your friends, followers, or other crypto enthusiasts, the program offers exciting incentives for both referrers and referees. It’s a simple, fun, and rewarding way to expand your network while benefiting from the platform’s growth.

#### **How It Works**

When you participate in the referral program, you’ll earn rewards every time your referees trade on the platform. Here’s how it all comes together:

1. **Invite Your Network**\
   Share your unique referral link with your friends, followers, or community. Once they sign up using your link, they’ll automatically be linked to your account as referees.
2. **Earn on Trades**\
   Earn a percentage of your referees’ trading fees, creating a stream of passive income. The more active your network, the more you earn.
3. **Tiered Rewards**\
   Your earnings grow as your referral network expands. The referral program offers **tiered rewards** that increase the percentage of fees you earn as you reach new milestones:
   * **Tier 1**: Up to 50 referees — earn 5% of their trading fees.
   * **Tier 2**: 51 to 100 referees — earn 7.5% of their trading fees.
   * **Tier 3**: 100+ referees — earn 10% of their trading fees.
4. **Referee Discounts**\
   Those who sign up through your referral link enjoy discounted trading fees, making their journey into AIQuant.fun even more rewarding.

#### **Benefits**

The referral program isn’t just about earning—it’s about building a thriving community of traders, creators, and investors. Here’s what makes it stand out:

* **Passive Income**\
  As your network grows, so does your earning potential. Every trade made by your referees contributes to your rewards, providing a steady stream of income.
* **Exclusive Features for Top Referrers**\
  Climb the referral leaderboard to unlock special perks. Top referrers gain access to exclusive features, such as priority support, early access to new tools, and special badges that showcase your status as a community leader.
* **Strengthen the Ecosystem**\
  By inviting others to join, you contribute to the growth of the AIQuant.fun ecosystem, fostering innovation and collaboration across the platform.

#### **Leaderboard for Referrers**

Track your progress and compete with other referrers on the **Referral Leaderboard**. This dynamic tool showcases the top referrers, their networks, and the rewards they’ve earned. It’s a great way to see how you stack up and stay motivated to grow your network.


# Partnerships

Join our network to amplify innovation, reach global audiences, and drive success in crypto and AI.

AIQuant.fun invites cutting-edge crypto-based AI projects to partner with us in reshaping the landscape of autonomous trading and tokenized AI. With the backing of **Starter Labs** and the dynamic resources of the **Atlanta Blockchain Center**, we’re building a thriving ecosystem for innovation and community-driven success.

**Why Partner with AIQuant.fun?**

Our platform isn’t just about creating AI agents; it’s about pioneering a new era of tokenized AI innovation. Partnering with AIQuant.fun provides unique opportunities to grow your project, engage with crypto-native audiences, and leverage a platform designed for scalability and collaboration.

**Exclusive Benefits for Partners**

1. **Amplify Your Reach with Starter Labs**\
   Gain access to the extensive reach and expertise of [Starter Labs](https://x.com/starterlabshq), the parent company behind AIQuant.fun. With a proven track record of supporting blockchain innovation and launching successful projects, Starter Labs ensures your partnership achieves maximum visibility and engagement.
2. **Unparalleled IRL Access with** [**Atlanta Blockchain Center**](https://x.com/atlantachain)\
   Atlanta Blockchain Center, the only physical crypto community hub of its kind in the USA, offers unmatched opportunities for real-world collaboration. As a partner, you can:
   * Host community events or meetups.
   * Leverage incubation programs to accelerate your project’s growth.
   * Connect with top-tier crypto communities and innovators in a thriving IRL space.
   * Gain exposure to our extensive IRL community, including 3.4k Instagram followers, 1.8k Twitter followers, and over 2,000 email subscribers.
3. **Direct Access to Crypto Communities**\
   Tap into the vibrant and active crypto ecosystems of the USA. With Atlanta Blockchain Center’s deep-rooted connections, you’ll engage with key stakeholders, crypto enthusiasts, and AI innovators to accelerate awareness and adoption for your project.
4. **Collaborative Growth Opportunities**

   * Partner with AIQuant.fun to co-create initiatives that leverage AI and blockchain for new, scalable solutions.
   * Cross-promote within our platform to engage audiences already interested in AI-driven trading and tokenized economies.

A major objective of AIQuant.fun is to foster a growing user base of traders, developers, and blockchain enthusiasts actively engaged with tokenized AI agents. As a partner, you’ll join a platform designed for collaboration, innovation, and long-term growth. Together, we can accelerate the adoption of decentralized AI trading and redefine what’s possible in the crypto space.

**Integration and Expansion**

Tokenized AI quants are more than just automated trading agents—they're being designed to be programmable assets that can integrate seamlessly into broader ecosystems. Through our robust APIs (still in development), partners can extend the functionality of AI quants into their own platforms, marketplaces, or services. Imagine integrating quants into a decentralized marketplace where users can rent or invest in high-performing agents, or enabling enterprises to customize AI quants for niche use cases like portfolio management or liquidity provision. The possibilities expand further as these agents generate value not only for their creators but also for businesses leveraging their performance to enhance user offerings. By partnering with AIQuant.fun, you unlock a new layer of utility for tokenized AI in the decentralized economy.

**Let’s BUIDL Together**

Ready to take the next step? Partner with AIQuant.fun, Atlanta Blockchain Center, and Starter Labs to connect, collaborate, and innovate. Together, we’ll bring AI-powered crypto trading to the forefront and open new opportunities for your project.

Interested in partnering? Get in touch with one of our Partnership Coordinators below, and let’s create the future of tokenized AI, together.

{% hint style="info" %}
**Partnership Coordinators**

[@sal0x](https://t.me/sal0x)\
[@zee\_bulla](https://t.me/zee_bulla)\
[@LordSeed](https://t.me/LordSeed)
{% endhint %}


# API Reference

Comprehensive API documentation for the AIQuant platform.

### 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FBoUcuE3lpv4dDO5i7jwf%2Fimage.png?alt=media&amp;token=68117db7-c61a-474d-ac27-f5e993ce9715" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FbULfiYfzTlyTR43FvNzw%2Fimage.png?alt=media&amp;token=3270403e-846f-487c-be42-f8672f02ec74" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FZJOhUuG34iqAS88tWtBb%2Fimage.png?alt=media&amp;token=c0b6a1d0-a026-40bc-a049-026ed40a4f47" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FyZt1N0BtQyHl02wwZbvu%2Fimage.png?alt=media&amp;token=82d9d236-ae45-438e-aade-08eb18c48fcf" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2F6LqA0Z4hQl4uwCQleipC%2Fimage.png?alt=media&amp;token=eeb91033-81d1-4607-8091-922f63240a09" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FCyw8XIKiFD8DJ6WK0Ovx%2Fimage.png?alt=media&amp;token=30365416-9e05-497c-84fd-9b24ef96508b" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FpxLfYb2kogbbrBEr1w7g%2Fimage.png?alt=media&amp;token=f8e227f4-fade-4070-af76-4b4ccd598aff" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FFVa0VYmm0uoEkKnpuPg5%2Fimage.png?alt=media&amp;token=00633a22-f198-47f8-9cab-182ed87eace1" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2F6IuuYxn60BIgYSGswJlN%2Fimage.png?alt=media&amp;token=dcb061eb-4d10-476f-873e-ae48ef8d03d1" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2Fc6TxUcW4yVUem2ISGb81%2Fimage.png?alt=media&amp;token=c6ecf505-af9c-44a8-abb1-73e293fd6987" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FQZW5TQKgWggY5ldCPzam%2Fimage.png?alt=media&amp;token=dd3d8ee1-3340-4a6c-9909-5e55031ca1d8" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2F6HTSqon0BnGQnBqst5q3%2Fimage.png?alt=media&amp;token=7b5c1f1b-b22d-4ad1-a30d-257e578d0c7d" 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>


# API Reference Draft

Comprehensive API documentation for the AIQuant platform.

### 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.

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

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

#### Performance & Trades

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

#### Evaluation Results

* [Latest Evaluation Results](#latest-evaluation-results)
* [Evaluation Timeseries](#evaluation-timeseries)
* [Evaluation Count](#evaluation-count)
* [Evaluation Details](#evaluation-details)
* [Evaluation History](#evaluation-history)
* [Token OHLCV Data](#token-ohlcv-data)

#### 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FBoUcuE3lpv4dDO5i7jwf%2Fimage.png?alt=media&amp;token=68117db7-c61a-474d-ac27-f5e993ce9715" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FbULfiYfzTlyTR43FvNzw%2Fimage.png?alt=media&amp;token=3270403e-846f-487c-be42-f8672f02ec74" 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`)

**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",
            "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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FZJOhUuG34iqAS88tWtBb%2Fimage.png?alt=media&amp;token=c0b6a1d0-a026-40bc-a049-026ed40a4f47" 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

#### Latest Evaluation Results

<img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FyZt1N0BtQyHl02wwZbvu%2Fimage.png?alt=media&amp;token=82d9d236-ae45-438e-aade-08eb18c48fcf" 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 Timeseries

<img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FRM8Y7tWq9HGQCRlat4oV%2Fimage.png?alt=media&amp;token=9680c096-d13f-4d27-8e7a-32ad80d3148f" alt="" data-size="line"> **Evaluation Trends**

**GET** `/api/eval-timeseries`

Retrieves evaluation data as a time series.

**Query Parameters:**

* `timeFrom` (string, required): Start time for timeseries (ISO format)
* `timeTo` (string, required): End time for timeseries (ISO format)
* `quantId` (string, optional): Filter by quant ID
* `returnAllQuants` (string, optional): Include all quants in results

**Response:**

```json
{
    "timeseries": [
        {
            "timestamp": "2025-05-08T00:00:00.000Z",
            "evaluations": 342,
            "passed": 127,
            "failed": 215,
            "percentPassed": 37.13
        },
        // ...additional time points
    ]
}
```

#### Evaluation Count

<img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FMwxmxLS7WtZzteQEPJ7t%2Fimage.png?alt=media&amp;token=a82ea3a7-8d80-40b3-b2ed-214bcf5a27f2" alt="" data-size="line"> **Evaluation Counts**

**GET** `/api/eval-count`

Retrieves the count of evaluations over time.

**Query Parameters:**

* `timeFrom` (string, required): Start time (ISO format)
* `timeTo` (string, required): End time (ISO format)
* `quantId` (string, optional): Filter by quant ID
* `returnAllQuants` (string, optional): Include all quants in count

**Response:**

```json
{
    "total": 4387,
    "passed": 1634,
    "failed": 2753,
    "percentPassed": 37.25
}
```

#### Evaluation Details

<img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2F6LqA0Z4hQl4uwCQleipC%2Fimage.png?alt=media&amp;token=eeb91033-81d1-4607-8091-922f63240a09" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FCyw8XIKiFD8DJ6WK0Ovx%2Fimage.png?alt=media&amp;token=30365416-9e05-497c-84fd-9b24ef96508b" 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): Comma-separated list of evaluation types to exclude

**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
        }
    ]
}
```

#### Token OHLCV Data

<img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2Fk7JRXAs2kH2ByDYi0AOC%2Fimage.png?alt=media&amp;token=ae701941-25a5-48f0-82e0-fe52759abf1b" alt="" data-size="line"> **Market Data**

**GET** `/api/eval-ohlcv`

Retrieves open, high, low, close, volume (OHLCV) data for a token.

**Query Parameters:**

* `tokenId` (string, required): ID of the token
* `timeframe` (string, optional): Timeframe for data points (e.g., '1h', '4h', '1d')
* `limit` (integer, optional): Maximum number of data points to return

**Response:**

```json
{
    "ohlcv": [
        {
            "timestamp": 1746628800000,
            "open": 0.00092107,
            "high": 0.00095233,
            "low": 0.00089765,
            "close": 0.00091079,
            "volume": 2879.72
        },
        // ...additional data points
    ]
}
```

### Alpha Signals

#### Alpha Signals List

<img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FpxLfYb2kogbbrBEr1w7g%2Fimage.png?alt=media&amp;token=f8e227f4-fade-4070-af76-4b4ccd598aff" 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
* `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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FFVa0VYmm0uoEkKnpuPg5%2Fimage.png?alt=media&amp;token=00633a22-f198-47f8-9cab-182ed87eace1" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2F6IuuYxn60BIgYSGswJlN%2Fimage.png?alt=media&amp;token=dcb061eb-4d10-476f-873e-ae48ef8d03d1" 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
            ]
        }
    }
]
```

### Strategy Optimization

#### Optimization Dashboard

<img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2Fc6TxUcW4yVUem2ISGb81%2Fimage.png?alt=media&amp;token=c6ecf505-af9c-44a8-abb1-73e293fd6987" 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="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FQZW5TQKgWggY5ldCPzam%2Fimage.png?alt=media&amp;token=dd3d8ee1-3340-4a6c-9909-5e55031ca1d8" alt="" data-size="line"> **Analysis Executor**

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

Executes a strategy analysis to generate optimization recommendations.

**Request Body:**

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

**Response:**

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

#### Apply Recommendation

<img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2F6HTSqon0BnGQnBqst5q3%2Fimage.png?alt=media&amp;token=7b5c1f1b-b22d-4ad1-a30d-257e578d0c7d" 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
    }
}
```

### 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

Once subscribed to an API plan:

1. Navigate to the API section in your profile settings
2. Click "Generate New API Key"
3. Store your API key securely

#### 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://aiquant.fun/api/trades/stats
```

### 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>


# Data Fetcher System

AIQ Data Fetcher - Technical Documentation

<figure><img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2F01IHMYcWmOGLzeviNv6m%2FScreen%20Shot%202025-02-25%20at%2012.04.54%20PM.png?alt=media&amp;token=404fffc6-bc16-4b5f-8b5b-50817576e3fb" alt=""><figcaption></figcaption></figure>

### 1. System Overview

The AIQ Data Fetcher is a robust, asynchronous system designed to collect, analyze, and evaluate cryptocurrency token data from various sources. The system uses a job queue architecture to process tasks in parallel, with dependencies between tasks, enabling efficient data processing and analysis.

The system serves multiple purposes:

* Sourcing new tokens from various platforms (Birdeye, Dexscreener, etc.)
* Fetching token data from multiple APIs
* Analyzing token metrics and social signals
* Evaluating tokens for potential trading opportunities
* Continuously monitoring active tokens

### 2. Core Architecture

#### 2.1 Job Queue System

The data fetcher uses BullMQ, a Redis-based queue system, to manage and process jobs. This allows:

* Parallel processing of independent tasks
* Dependency management between related tasks
* Rate limiting to respect API constraints
* Automatic retries for failed jobs
* Progress tracking for long-running operations

#### 2.2 Key Components

1. **Token Sourcing Jobs**: Discover new tokens from various platforms
2. **Data Fetching Jobs**: Collect relevant data about tokens
3. **Evaluation Jobs**: Analyze the collected data and make decisions
4. **Monitoring Jobs**: Continuously track active tokens for updates

#### 2.3 Data Flow

1. Token sourcing discovers potential tokens
2. Evaluation initialization creates a tree of data fetching jobs
3. Data fetchers collect necessary information
4. Once all data is collected, evaluation jobs analyze the token
5. For promising tokens, monitoring begins to track updates

### 3. Rate Limiting Implementation

The system implements precise rate limiting to respect API constraints while maximizing throughput. In `index.ts`, specific limiters are defined:

```typescript
// Production rate limiters
const birdeyeLimiter = {
  // Birdeye Max: 1500 RPM = 25/s, using 10/s to maintain buffer
  max: 10,
  duration: 1000,
  groupKey: "birdeye",
};

const dexscreenerLimiter = {
  // Dexscreener Max: 300 RPM = 5/s, using 2/s for safety
  max: 2,
  duration: 1000,
  groupKey: "dexscreener",
};

const lunarCrushLimiter = {
  // LunarCrush Max: 100 RPM = 1.66/s, using 1/s to stay within limit
  max: 1,
  duration: 1000,
  groupKey: "lunarCrush",
};

const snifferLimiter = {
  max: 4,
  duration: 1000,
  groupKey: "sniffer",
};

const evalInitLimiter = {
  ...config.evalInitRateLimiter, // Loaded from configuration
  groupKey: "eval-init",
};
```

For development environments, these are replaced with a more conservative limiter:

```typescript
const devLimiter = {
  max: 1,
  duration: 1000,
  groupKey: "dev",
};
```

These limiters are applied to specific worker types when initializing BullMQ workers:

```typescript
workers[queue] = new Worker(queue, tokenDataFetcherJob, {
  ...queueOptions,
  name: `worker-${queue}`,
  concurrency, // Varies by queue type
  limiter, // Appropriate limiter based on API
});
```

### 4. Token Sourcing

The system sources tokens from multiple platforms:

#### 4.1 Birdeye Sources

* **New Listings** (`birdeyeNewListingsScannerJob`): Recently listed tokens
* **Trending Tokens** (`birdeyeTrendingScannerJob`): Popular tokens based on trading activity
* **Token Lists** (`birdeyeTokenListScannerJob`): Comprehensive token lists
* **All Tokens List** (`birdeyeAllTokensListScannerJob`): Extensive token catalog with filtering

#### 4.2 Dexscreener Sources

* **Token Boosts** (`dexscreenerBoostScannerJob`): Tokens featured through paid promotions

#### 4.3 Data Processing Flow

1. Source jobs identify potential tokens
2. The `processTokenSources` function filters and processes these tokens
3. Valid tokens are passed to evaluation jobs

#### 4.4 Token Filtering Logic

The system uses specific filtering criteria in `birdeyeAllTokensListScannerJob.ts`:

```typescript
const isValidToken = (token: TokenInfo, minLastTradeTime: number) => {
  const reasons: any = {};

  if (!token.mc || token.mc < config.allTokensListMinMcap) {
    reasons.low_mcap = true;
  }
  if (!token.v24hUSD || token.v24hUSD < config.allTokensListMin24hVolume) {
    reasons.low_vol = true;
  }
  if (token.liquidity < config.allTokensListMinLiquidity) {
    reasons.low_liq = true;
  }
  if (!token.lastTradeUnixTime || token.lastTradeUnixTime < minLastTradeTime) {
    reasons.old_last_trade_time = true;
  }
  if (
    token.address.toLowerCase().endsWith("pump") &&
    (!token.mc || token.mc < config.minMcapForPumpfunTokens)
  ) {
    reasons.low_mcap_pumpfun = true;
  }

  if (Object.keys(reasons).length > 0) {
    // Log dismissal reason
    return false;
  }

  return true;
};
```

### 5. Token Evaluation Process

#### 5.1 Initialization

The `evaluateTokenInitDataFetchingJob` is the entry point for token evaluation:

1. Retrieves token information from database
2. Checks if market cap is sufficient
3. Creates a dependency tree of data fetching operations
4. Schedules data fetching jobs
5. Sets up a flow to evaluate results once data is collected

**5.1.1 Market Cap Validation Logic**

```typescript
try {
  const marketCap = await checkMarketCap(baseTokenData);
  if (
    marketCap <= config.allTokensListMinMcap && // Configured threshold
    checkConfigType !== ConfigType.SELL // Skip for sell evaluations
  ) {
    await tokenStatusUpdater(token, TokenStatus.BLOCKED);
    return {
      status: "BLOCKED",
      reason: "Token market cap is too low",
    };
  }
} catch (error) {
  // Market cap unavailable logic
  await tokenStatusUpdater(token, TokenStatus.DORMANT);
  const err = error as Error;
  return {
    error: err.message,
    stack: err.stack,
  };
}
```

#### 5.2 Data Fetching

The system fetches various types of data about tokens:

**5.2.1 Technical Data**

* **Overview** (`fetchOverviewJobFn`): Basic token information (price, liquidity, etc.)
* **Security** (`fetchSecurityJobFn`): Security metrics and risk assessment
* **Markets** (`fetchMarketsJobFn`): Trading venues and volume
* **Top Traders** (`fetchTopTradersJobFn`): Information about major traders
* **OHLCV** (`ohlcvJob`): Price candle data for technical analysis

**5.2.2 On-chain Data**

* **Pairs** (`fetchPairsJobFn`): Trading pairs on decentralized exchanges
* **Paid Orders** (`fetchPaidOrdersJobFn`): Orders with paid promotions
* **Token Sniffer** (`tokenSnifferJob`): Security audit information

**5.2.3 Social and AI Analysis**

* **Social** (`tokenDataFetcherSocialJob`): Social media sentiment and activity
* **Narrative** (`fetchNarrativeJob`): AI-driven analysis of token narrative
* **Price Trend Prediction** (`fetchPriceTrendPredictionJob`): AI prediction of price movements

#### 5.3 Core Data Fetching Logic

The core data fetching logic is in `tokenDataFetcherJob`:

```typescript
// Check if existing data is fresh
if (lastDataFetch && !isDataStale(lastDataFetch, maxLastFetchedAtSeconds)) {
  logger.debug(`Skipping data fetch for token - still fresh`);
  return dataFetcherResponseToJobData(lastDataFetch);
}

// Fetch dependencies if needed
const childrenFetchedDataMap: Map<DataFetcherKey, DataFetcherResponse> = new Map();
if (dataFetcher.dependencies) {
  // ... dependency fetching logic ...
}

try {
  // Execute data fetcher
  const fetcherJob = dataFetcherJobs[dataFetcherKey];
  const data = await fetcherJob(job, dataFetcher, childrenFetchedDataMap);
  
  // Handle in-progress state if exists
  // ... in-progress handling ...
  
  // Store result
  const dataFetcherResponse = await DataFetcherResponseRepository.create({
    tokenId,
    key: dataFetcherKey,
    data,
    expiresAt,
    status: DataFetcherResponseStatus.SUCCESS,
  });
  return dataFetcherResponseToJobData(dataFetcherResponse);
} catch (error) {
  // Fallback to previous data if max attempts reached
  if (lastDataFetch && job.attemptsStarted >= dataFetcher.maxAttempts) {
    // ... log error ...
    return dataFetcherResponseToJobData(lastDataFetch);
  }

  // Handle unrecoverable errors
  const isUnrecoverable = error instanceof UnrecoverableError;
  const hasTimedOut = differenceInSeconds(/*...*/) > dataFetcher.maxAttemptsTimeoutSeconds;
  const hasReachedMaxAttempts = job.attemptsStarted >= dataFetcher.maxAttempts;

  if (isUnrecoverable || hasTimedOut || hasReachedMaxAttempts) {
    // ... clean up and log ...
    return; // Return undefined instead of throwing
  }

  throw error; // Only throw for recoverable errors that haven't reached max attempts
}
```

#### 5.4 Evaluation Finalization

Once data is collected, one of these jobs processes the results:

* **Status Evaluation** (`evaluateTokenFetchedDataJob`): General token assessment
* **Buy Evaluation** (`evaluateBuyJob`): Analysis for buying opportunities
* **Sell Evaluation** (`evaluateSellJob`): Analysis for selling opportunities

### 6. Job Conditional Logic Details

#### 6.1 Token Data Fetcher Job

In `tokenDataFetcherJob.ts`, the job implements sophisticated conditional logic:

1. **Fresh Data Check Logic**:

```typescript
if (lastDataFetch && !isDataStale(lastDataFetch, maxLastFetchedAtSeconds)) {
  logger.debug(`Skipping data fetch for token - still fresh`);
  return dataFetcherResponseToJobData(lastDataFetch);
}
```

2. **Error/Retry Fallback Logic**:

```typescript
// Fallback to previous data if max attempts reached
if (lastDataFetch && job.attemptsStarted >= dataFetcher.maxAttempts) {
  Logger.newContext({/*...*/}).error(
    `Max attempts reached, falling back to last data`,
    error as Error
  );
  return dataFetcherResponseToJobData(lastDataFetch);
}

const isUnrecoverable = error instanceof UnrecoverableError;
const hasTimedOut = differenceInSeconds(/*...*/) > dataFetcher.maxAttemptsTimeoutSeconds;
const hasReachedMaxAttempts = job.attemptsStarted >= dataFetcher.maxAttempts;

// Close dangling jobs and return null rather than fail on unrecoverable errors
if (isUnrecoverable || hasTimedOut || hasReachedMaxAttempts) {
  await DataFetcherResponseRepository.failDanglingInProgress(/*...*/);
  dataFetcherMissingDataCounter.add(1, {/*...*/});
  return; // Return undefined instead of throwing
}

throw error; // Only throw for recoverable errors that haven't reached max attempts
```

#### 6.2 Social Data Fetcher Logic

In `dataFetcherSocialJob.ts`, complex conditional logic handles partial data availability:

```typescript
// Return earlier successfully for new tokens, timeouts, or max attempts
// as long as some data was fetched
if (
  (isNewToken || hasTimedOut || hasReachedMaxAttempts) &&
  hasFetchedAnySocialData
) {
  return inProgressResponse.data;
}

// For new tokens, stop retrying after 3 attempts
if (isNewToken && job.attemptsStarted >= 3) {
  throw new UnrecoverableError(
    "Social checks can't run on new tokens - stopping retries after 3 attempts"
  );
}
```

#### 6.3 Narrative Fetcher Error Handling

In `dataFetcherNarrativeJob.ts`:

```typescript
// Only retry parsing errors for the first 3 attempts
if (narrative.error && job.attemptsMade < 3) {
  throw new Error("Fetch narrative job attempt failed");
} else if (narrative.error) {
  logger.error("Fetch narrative job completed with an error");
}

return narrative; // Return possibly error-containing data after max attempts
```

### 7. Dependency Management

The system manages dependencies between data fetching tasks using a directed acyclic graph (DAG). The `copycatProcessor` handles complex dependency patterns:

#### 7.1 Dependency Tree Construction

```typescript
function buildSubtree(taskName: string, visited: Set<string>): TreeNode | null {
  // Prevent circular dependencies
  if (visited.has(taskName)) {
    throw new Error(`Circular dependency detected for task: ${taskName}`);
  }

  const task = jobs.find((t) => t.taskKey === taskName);
  if (!task) return null;

  const newVisited = new Set(visited);
  newVisited.add(taskName);

  // Create children nodes
  const children: TreeNode[] = [];
  for (const dep of task.dependencies) {
    const isCopyCat = usedTasks.has(dep); // Track reused dependencies
    const child = buildSubtree(dep, newVisited);
    if (child) {
      children.push({
        ...child,
        isCopyCat: isCopyCat,
      });
    }
  }

  usedTasks.add(taskName);

  return {
    name: taskName,
    children,
  };
}
```

#### 7.2 CopyCat Job Creation

The algorithm detects reused dependencies and creates "copy cat" jobs to optimize execution:

```typescript
export const createCopyCatJob = (job: FlowChildJob): FlowChildJob => {
  const baseQueueName = job.queueName as keyof typeof Queues;
  const baseJobId = job.opts?.jobId;

  if (!baseJobId) throw new Error("Base Copy Cat job must have a jobId");

  const jobData: CopyCatJob = {
    copyJobId: baseJobId,
    copyJobQueueName: baseQueueName,
  };

  const copyCatJob: FlowChildJob = {
    name: `copy_cat_job_for_${baseJobId}`,
    queueName: Queues.copyCat,
    data: jobData,
    opts: {
      backoff: {
        type: "exponential",
        delay: 1000,
      },
      attempts: 10,
      jobId: `${baseJobId}-copy_cat-${uuid()}`,
    },
  };

  return copyCatJob;
};
```

#### 7.3 CopyCat Processor

The copyCat processor itself monitors the original job and returns its result:

```typescript
export const copycatProcessor = async (job: Job<CopycatJob>) => {
  try {
    const { copyJobId, copyJobQueueName } = job.data;
    // ... validation ...
    
    const copyQueue = queueService.getQueue(copyJobQueueName);
    
    // Polling loop to check original job status
    while (true) {
      const copyJob = await copyQueue.getJob(copyJobId);
      
      if (!copyJob) {
        // ... retry logic ...
      }

      const status = await copyJob.getState();

      if (status === "completed") {
        return copyJob.returnvalue;
      }

      if (status === "failed") {
        throw new Error(`Copy job failed: ${copyJobId}`);
      }

      await new Promise((resolve) => setTimeout(resolve, 3000));
    }
  } catch (error) {
    throw new Error(`Error CopyCat processor: ${error}`);
  }
};
```

### 8. Data Caching and Expiration

The system uses timestamp-based data expiration to optimize API usage:

#### 8.1 Expiration Check

```typescript
const isDataStale = (
  lastDataFetch: DataFetcherResponse,
  maxLastFetchedAtSeconds: number | undefined,
) => {
  const lastFetchedAtSecondsAgo = lastDataFetch?.time
    ? differenceInSeconds(new Date(), lastDataFetch?.time)
    : 0;

  // Check max age constraint if provided
  if (maxLastFetchedAtSeconds) {
    return lastFetchedAtSecondsAgo > maxLastFetchedAtSeconds;
  }

  // Otherwise check expiration time
  return !lastDataFetch.expiresAt || lastDataFetch.expiresAt < new Date();
};
```

#### 8.2 Expiration Configuration

Each data fetcher has its own `expiresInSeconds` configuration in the database, allowing customization per data type. When storing data:

```typescript
const expiresAt = addSeconds(new Date(), dataFetcher.expiresInSeconds);

// Store with expiration timestamp
const dataFetcherResponse = await DataFetcherResponseRepository.create({
  tokenId,
  key: dataFetcherKey,
  data,
  expiresAt,
  status: DataFetcherResponseStatus.SUCCESS,
});
```

### 9. OHLCV Data Collection

The `ohlcvJob.ts` implements a pagination system to handle the API limitations:

```typescript
const PAGE_SIZE = 1000; // Maximum candles per request

while (currentTimeFromSecs < timeToSecs) {
  const { success, data, ...response } = await Birdeye.getOHLCV(
    chainName,
    address,
    "1m",
    currentTimeFromSecs,
    timeToSecs,
  );
  
  // ... data processing ...
  
  // Pagination logic
  if (data.items.length < PAGE_SIZE) {
    // Reached the end of available data
    ohlcvData.lastRetrievedCandleTime = 
      data.items[data.items.length - 1].unixTime;
    await job.updateProgress(100);
    break;
  }
  
  // Report progress
  const progressPercentage = Math.min(
    100,
    Math.floor((totalProcessed / totalExpectedMinutes) * 100),
  );
  await job.updateProgress(progressPercentage);
  
  // Next page - start from the timestamp after the last record
  currentTimeFromSecs = data.items[data.items.length - 1].unixTime + 1;
}
```

### 10. Token Sniffer Integration

The `tokenSnifferJob.ts` uses different implementations based on blockchain:

```typescript
export const tokenSnifferJob = async (
  job: Job<BaseTokenData>,
): Promise<TokenSnifferResponse> => {
  switch (job.data.chainName) {
    case ChainName.SOLANA:
      return processSolSniffer(job);
    case ChainName.BASE:
      return processTokenSniffer(job);
    default:
      throw new UnrecoverableError(
        `TokenSniffer Chain not supported ${job.data.chainName}`,
      );
  }
};
```

Each chain has specific audit logic:

```typescript
// For Base chain
const top10HoldersTotalAmount = result.balances.top_holders.reduce(
  (acc, holder) => acc + holder.balance,
  0,
);
const top10HoldersSupplyPct = result.total_supply
  ? (top10HoldersTotalAmount / result.total_supply) * 100
  : undefined;

const top10HoldersPassed =
  top10HoldersSupplyPct !== undefined && top10HoldersSupplyPct <= 30;
```

### 11. In-Progress Fetching and Recovery

For complex data fetchers like social, the system handles partial data and in-progress states:

```typescript
let inProgressResponse =
  (await DataFetcherResponseRepository.findLastInProgressByKeyAndTokenId(
    DataFetcherKey.SOCIAL,
    job.data.tokenId,
  )) ||
  (await DataFetcherResponseRepository.initInProgressFetching(
    DataFetcherKey.SOCIAL,
    job.data.tokenId,
  ));

const data = inProgressResponse.data as SocialJobData;

// Attempt to fetch missing parts
if (!data.topicResponse) {
  try {
    const topicResponse = await lunarCrush.getLunarCrushTopic(address);
    data.topicResponse = topicResponse;
    // ...
  } catch (error) {
    errors.push(error as Error);
  }
}

// Update in-progress state
inProgressResponse = await DataFetcherResponseRepository.updateData(
  inProgressResponse as any,
);
```

This allows long-running jobs to be resumed if interrupted, and for partial data to be used when complete data cannot be obtained.

### 12. Monitoring and Maintenance

#### 12.1 Re-evaluation

The `reEvaluateTokenJob` periodically checks tokens:

```typescript
// Different token types have different re-evaluation periods
const activeTime = subSeconds(
  new Date(),
  systemConfig.activeTokenMonitorIntervalSeconds,
);
const activeTokens = await TokenRepository.findAllByStatusWithLastEvalRequestedBefore(
  TokenStatus.ACTIVE,
  activeTime,
);

const dormantTime = subSeconds(
  new Date(),
  systemConfig.dormantTokenMonitorIntervalSeconds,
);
const dormantTokens = await TokenRepository.findAllByStatusWithLastEvalRequestedBefore(
  TokenStatus.DORMANT,
  dormantTime,
);

const rejectedTime = subSeconds(
  new Date(),
  systemConfig.rejectedTokenMonitorIntervalSeconds,
);
const rejectedTokens = await TokenRepository.findAllByStatusWithLastEvalRequestedBefore(
  TokenStatus.REJECTED,
  rejectedTime,
);
```

#### 12.2 Token Balance Checking

The re-evaluation process checks if tokens have active holders before sending sell signals:

```typescript
const filterOutTokensWithoutHolders = async (tokens: Token[], logger: Logger) => {
  const holderCountPromises = tokens.map((token) =>
    aiquantApi
      .getActiveHoldersCount(token.id)
      .then(({ holdersCount }) => ({ token, holdersCount, success: true })),
  );

  const results = await Promise.all(holderCountPromises);
  const tokensWithHolders: Token[] = [];

  for (const result of results) {
    const { token, holdersCount, success } = result;
    if (success && holdersCount > 0) {
      tokensWithHolders.push(token);
    }
  }

  return tokensWithHolders;
};
```

#### 12.3 Price Snapshots

The `activePriceSnapshotsJob` maintains current price data:

```typescript
const mapTokensToBatchesGroupedByChain = (
  tokens: Token[],
): Map<ChainName, Token[][]> => {
  const batches = new Map<ChainName, Token[][]>();
  for (const token of tokens) {
    const chainName = token.chainName;
    if (!batches.has(chainName)) {
      batches.set(chainName, [[]]);
    }

    const chainBatches = batches.get(chainName)!;

    const lastBatch = chainBatches[chainBatches.length - 1];
    if (lastBatch.length < BATCH_SIZE) {
      lastBatch.push(token);
    } else {
      chainBatches.push([token]);
    }
  }
  return batches;
};
```

This creates an optimized structure where tokens are first grouped by blockchain, then into batches of appropriate size for the API.

### 13. Worker Configuration

#### 13.1 Concurrency Settings

The system uses different concurrency settings per job type:

```typescript
// Setup Data Fetching Workers
const dataFetchingWorkers = [
  {
    queue: getDataFetchQueueName(DataFetcherKey.NARRATIVE),
    concurrency: 2,
    limiter: defaultLimiter,
  },
  {
    queue: getDataFetchQueueName(DataFetcherKey.PRICE_TREND_PREDICTION),
    concurrency: 2,
    limiter: defaultLimiter,
  },
  // ...
  {
    queue: getDataFetchQueueName(DataFetcherKey.TOKEN_SNIFFER),
    concurrency: 10, // Higher concurrency for token sniffer
    limiter: snifferLimiter,
  },
  // ...
];
```

For evaluation jobs, higher concurrency is used since they're CPU-bound rather than I/O bound:

```typescript
evaluateTokenFetchedData: new Worker(
  Queues.evaluateTokenFetchedData,
  evaluateTokenFetchedDataJob,
  {
    ...queueOptions,
    name: `worker-${Queues.evaluateTokenFetchedData}`,
    concurrency: 100, // High concurrency for CPU-bound evaluation
  },
),
```

#### 13.2 Worker Health Management

Workers monitor their own health and job performance:

```typescript
Object.values(workers).forEach((worker) => {
  const logger = Logger.getInstance().withContext({
    context: worker.name,
  });

  worker.on("completed", (job) => {
    // Log completion and metrics
    bullmqJobsCompletedCounter.add(1, {
      worker: worker.name,
      ...logCtx,
    });
  });
  
  worker.on("failed", (job, error) => {
    // Different logging severity based on attempt count
    if (
      job?.attemptsStarted !== undefined &&
      job?.opts.attempts !== undefined &&
      job?.attemptsStarted < job?.opts.attempts
    ) {
      logger.info(msg, { ...logCtx, err: error });
    } else {
      logger.error(msg, error, logCtx);
    }
    
    // Log metrics
    bullmqJobsFailedCounter.add(1, {
      worker: worker.name,
      failedReason: job?.failedReason,
      ...logCtx.tags,
    });
  });
});
```

#### 13.3 Graceful Shutdown

The system implements graceful shutdown to prevent data loss:

```typescript
process.on("SIGTERM", () => {
  Logger.newContext({ context: "workers" }).info(
    "SIGTERM received, closing workers...",
  );
  Object.values(workers).forEach((worker) => worker.close());
});
```

### 14. Error Metrics Collection

The system tracks error metrics to monitor performance:

```typescript
// Dependency errors
dataFetcherMissingDependenciesCounter.add(1, {
  dataFetcherKey,
  dependency,
  tokenId,
  chainName: job.data.chainName,
  symbol: job.data.symbol,
  address: job.data.address,
});

// General data missing errors
dataFetcherMissingDataCounter.add(1, {
  dataFetcherKey,
  errorType: error instanceof Error ? error.name : "Unknown",
  tokenId,
  chainName: job.data.chainName,
  symbol: job.data.symbol,
  address: job.data.address,
});

// Expired data metrics for priority re-fetching
dataFetcherExpiredEvaluationsCounter.add(expired.length, { ...job.data });
```

### 15. Database Batching

Database operations are batched to optimize performance:

```typescript
const updateTokenPrices = async (tokenPrices: Record<number, number>) => {
  const records = Object.entries(tokenPrices).map(([tokenId, price]) => ({
    tokenId: Number(tokenId),
    price,
  }));

  const chunks = chunkArray(records, DB_BATCH_SIZE);
  for (const batch of chunks) {
    await TokenRepository.updateManyPriceSnapshots(batch);
  }
};
```

### 16. Common Workflows

#### 16.1 New Token Discovery and Evaluation

1. Source jobs discover potential tokens
2. `processTokenSources` filters and processes tokens
3. `evaluateTokenInitDataFetchingJob` initializes evaluation
4. Data fetchers collect necessary information
5. `evaluateTokenFetchedDataJob` makes a decision about the token

#### 16.2 Active Token Monitoring

1. `reEvaluateTokenJob` identifies tokens needing updates
2. Data fetchers refresh stale data
3. Evaluation jobs reassess tokens based on new data
4. `activePriceSnapshotsJob` maintains current price information

#### 16.3 Buy/Sell Signal Generation

1. `evaluateBuyJob` or `evaluateSellJob` analyzes token data
2. Technical and social indicators are considered
3. AI predictions influence the decision
4. A signal is generated if criteria are met

### 17. Integration with External Services

The system integrates with several external APIs:

1. **Birdeye**: For token discovery and market data
2. **Dexscreener**: For DEX data and promotions
3. **LunarCrush**: For social metrics and sentiment
4. **SolSniffer/TokenSniffer**: For security audits
5. **AI Services**: For narrative and price trend prediction

### 18. Conclusion

The AIQ Data Fetcher system is a sophisticated platform for token discovery, analysis, and evaluation. Its job-based architecture allows for efficient, scalable data processing, while its comprehensive data collection and analysis capabilities enable informed trading decisions.

Key strengths of the system include:

* Efficient handling of multiple API integrations with proper rate limiting
* Sophisticated dependency management for complex data workflows
* Robust error handling with appropriate fallbacks and retries
* Comprehensive monitoring and maintenance of active tokens
* Scalable architecture that can be extended to new data sources and blockchains


# Token Evaluations System

AIQ Evaluations and Token Processing System Documentation

<figure><img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2FtvqnUNOe8JukpukriAE1%2FScreen%20Shot%202025-02-25%20at%2012.25.08%20PM.png?alt=media&amp;token=506b0192-a040-4d11-93ac-9d6da13ff020" alt=""><figcaption></figcaption></figure>

This documentation provides a comprehensive overview of how the AIQ system processes, evaluates, and manages cryptocurrency tokens across various stages. The system combines market data analysis, technical indicators, and AI-powered evaluations to provide insights on tokens and generate trading signals.

### System Overview

The AIQ platform follows these main workflows:

1. **Token Discovery and Intake**: Tokens are discovered through monitoring services, user searches, or direct submission
2. **Data Collection**: Multiple data fetchers gather information from various sources
3. **Evaluation Process**: Tokens undergo evaluation against configurable criteria
4. **Scoring and Decision Making**: AI models and rule-based checks determine token quality and trading signals
5. **Token Status Management**: Tokens are categorized based on evaluation results

### Core Evaluation Engine

#### Evaluation Types

The system supports three primary evaluation types:

1. **Status Evaluation** (`ConfigType.STATUS`): Evaluates token quality and viability
2. **Buy Evaluation** (`ConfigType.BUY`): Determines if a token is a good buying opportunity
3. **Sell Evaluation** (`ConfigType.SELL`): Analyzes if a token should be sold

#### Evaluation Entry Points

The main entry point for token evaluation is `evaluateTokenConfig`, which directs to the appropriate evaluation type:

```typescript
export const evaluateTokenConfig = async (
  token: Token,
  cutoffDate: Date,
  checkConfigType: ConfigType,
  userQuantId?: number,
) => {
  switch (checkConfigType) {
    case ConfigType.BUY:
      return evaluateBuy(token, cutoffDate, userQuantId);
    case ConfigType.SELL:
      return evaluateSell(token, cutoffDate);
    case ConfigType.STATUS:
      return evaluateStatus(token, cutoffDate);
    default:
      throw new Error(`Invalid check config type: ${checkConfigType}`);
  }
};
```

Each evaluation type follows a similar pattern but has specific processing logic for the evaluation results.

#### Core Evaluation Logic

The `evaluateTokenWithType` function provides the shared evaluation framework:

1. Sets up logging context
2. Initializes a `TokenDataFetcher` to gather data
3. Ensures required data is available
4. Calculates market cap for token categorization
5. Fetches appropriate evaluation configurations
6. Checks for recent evaluations to avoid redundant processing
7. Processes each pending evaluation configuration
8. Returns statistics on evaluation results

#### Check Processing

For each evaluation configuration, the system:

1. Runs all configured checks against gathered data
2. Calculates an internal score based on weighted results
3. Requests an AI-generated score using LLMs
4. Combines scores to determine the final result
5. Saves evaluation results to the database
6. Processes the results according to the evaluation type

#### Check Result Processing

The `processResults` function is central to the evaluation system:

```typescript
const processResults = async (
  configType: ConfigType,
  results: MergedCheckResult[],
  evalConfig: EvalConfig,
  token: Token,
  dataFetcher: TokenDataFetcher,
  marketCap: number,
  logger: Logger,
): Promise<EvaluationResult> => {
  // Calculate internal score based on weighted results
  // Request AI score from LLM
  // Combine scores
  // Determine pass/fail status
  // Return complete evaluation result
}
```

Key aspects of result processing:

1. **Weight Calculation**: Checks have weighted importance in the overall score
2. **Required Checks**: Some checks are required; failing them fails the entire evaluation
3. **AI Analysis**: The system requests AI-generated analysis for holistic assessment
4. **Score Combination**: Internal and AI scores are averaged for a final score
5. **Threshold Application**: Different thresholds apply based on evaluation type

#### Value Comparison Logic

The `compareValues` function implements the core comparison logic for checks:

```typescript
export function compareValues(
  value: number,
  { extraInfo, threshold, name }: CheckConfig,
): ComparisonResult {
  // Handle value validation
  // Process range-based comparisons
  // Apply specified comparison operator
  // Calculate percentage score
  // Return comparison result
}
```

The system supports several comparison modes:

* Range-based comparisons: Check if value falls within a specified range
* Greater-than-or-equal comparisons: Check if value ≥ threshold
* Less-than-or-equal comparisons: Check if value ≤ threshold

The `getPercScore` function converts raw values to percentage scores (0-100) based on the comparison mode, allowing for nuanced scoring rather than binary pass/fail assessment.

### Post-Evaluation Processing

Each evaluation type has specific result processing:

#### Status Evaluation Processing

For status evaluations:

* If passed, the token is queued for buy evaluation
* For test tokens, processing is limited to a single status approval

#### Buy Evaluation Processing

For buy evaluations:

* If passed, the token is queued for execution and status is set to ACTIVE
* Buy execution messages are sent to applicable users

#### Sell Evaluation Processing

For sell evaluations:

* If passed, sell execution messages are created for applicable users
* Sell reason is recorded as "bad performance evaluation"

### Result Persistence

The `saveResultToHistory` function stores evaluation results:

```typescript
const saveResultToHistory = async (
  configType: ConfigType,
  tokenId: number,
  result: EvaluationResult,
) => {
  // Determine evaluation result type
  // Create database record with all details
  // Track metrics for monitoring
}
```

This function:

1. Maps config type to evaluation result type
2. Creates a database record with full evaluation details
3. Includes check-level results for diagnostics
4. Records metrics for system monitoring

### Key Components

#### 1. Token Discovery and Processing

**New Token Calls (`newTokenCall.ts`)**

This service handles the creation of new tokens and token calls:

```javascript
export const newTokenCall = async (
  newToken: { contractAddress: string; ticker: string; name?: string },
  sourceType: SourceType,
  message?: string,
  sourceId?: number,
): Promise<BaseTokenData> => {
  // Log token discovery
  // Get or create token in database
  // Queue token for evaluation
  // Track metrics
  // Return token data
}
```

The function:

* Accepts token information (address, ticker, optional name)
* Records the source of the token (e.g., USER, BIRDEYE, DEXSCREENER)
* Creates the token record if it doesn't exist
* Queues token for evaluation
* Returns basic token data

**Processing Token Sources (`processTokenSources.ts`)**

This file contains functions for processing tokens from various sources:

* `processTokenSources`: Processes tokens from monitoring services
* `processBoostSources`: Processes tokens from DexScreener boosts

Both functions filter out already processed tokens to avoid duplication, then create new token calls for unique discoveries.

**Token Monitors**

Several monitoring services continuously discover new tokens:

1. **BirdEye Monitor** (`birdeyeMonitor.ts`): Monitors BirdEye API for:
   * New tokens
   * Trending tokens
   * High-liquidity tokens
2. **DexScreener Monitor** (`dexscreenerMonitor.ts`): Monitors DexScreener for:
   * Tokens with active boost campaigns
3. **Twitter Monitor** (`twitterMonitor.ts`): Monitors Twitter for:
   * Token mentions from selected accounts

#### 2. Data Collection and Management

**TokenDataFetcher (`TokenDataFetcher.ts`)**

This class handles fetching and caching data for token evaluation:

```javascript
export class TokenDataFetcher {
  private dataCache: TokenDataTypes = {} as TokenDataTypes;
  
  async init({
    skipOhlcv = false,
  }: { skipOhlcv?: boolean } = {}): Promise<void> {
    // Initialize cache with data from database
    // Fetch OHLCV data if needed
  }
  
  getData<K extends DataKey>(key: K): TokenDataTypes[K] {
    // Get data for specific key with validation
  }
}
```

The class:

* Fetches data from multiple sources (BirdEye, DexScreener, etc.)
* Caches responses to avoid redundant API calls
* Provides typed access to different data categories
* Implements data expiration to ensure freshness

**Candle Aggregation (`candleAggregator.ts`)**

This module processes price candle data for technical analysis:

```javascript
export const getLastHour1mCandlesAndPrior23Hours1hCandles = (
  tokenPrice: TokenPrice[],
) => {
  // Extract last hour of 1-minute candles
  // Aggregate remaining data into hourly candles
  // Sort in ascending time order
  // Return [lastHour1mCandles, prior23Hours1hCandles]
}
```

The function:

* Takes raw price data points
* Extracts the most recent hour as 1-minute candles for detailed analysis
* Aggregates the previous 23 hours as hourly candles
* Returns both arrays in time-ascending order

#### 3. Token Evaluation Process

**Core Evaluators**

The system uses two core evaluator classes:

1. **CoreStatusEvaluator** (`CoreStatusEvaluator.ts`): Base class for evaluating token status
2. **CoreTradeEvaluator** (`CoreTradeEvaluator.ts`): Base class for evaluating buy/sell signals

Both follow a similar pattern:

* Gather required data via `TokenDataFetcher`
* Run configured checks against the data
* Calculate internal score based on check results
* Request AI score via LLM
* Combine scores and determine final result
* Save evaluation results to database

**Token-Specific Evaluators**

Two specialized evaluator classes extend the core evaluators:

1. **TokenStatusEvaluator** (`TokenStatusEvaluator.ts`): Evaluates token quality
2. **TokenTradeEvaluator** (`TokenTradeEvaluator.ts`): Evaluates trading opportunities

Both classes:

* Load appropriate configuration based on market cap category
* Support both core (default) and degen (customized) configurations
* Override configurations based on user preferences
* Apply appropriate checks for each evaluation type

**Check Registry**

The system includes many individual check functions, such as:

* `narrative.ts`: Evaluates token narrative strength
* `priceTrendPrediction.ts`: Predicts price movement direction
* `buyToSellMaxRatio1h.ts`: Checks buy/sell volume ratio
* `liquidity.ts`: Evaluates token liquidity
* `marketRegime.ts`: Determines market conditions
* `priceChangePercent1h.ts`: Checks price change percentage
* `priceDrawdown.ts`: Evaluates price drops from highs

Each check:

* Takes a configuration and a `TokenDataFetcher` instance
* Extracts relevant data points
* Performs calculations
* Returns a `CheckResult` with score, value, and pass/fail status

#### 4. AI-Powered Analyses

The system uses AI models for complex analyses:

**Narrative Analysis (`getNarrative.ts`)**

Evaluates token narratives using LLMs:

```javascript
export const getNarrativeStrength = async (
  token: BaseTokenData,
  description?: string,
): Promise<ModelResult<ParsedScoreResult>> => {
  // Generate prompt
  // Get AI response
  // Parse result
  // Return narrative score and explanation
}
```

The function:

* Creates a prompt describing the token
* Sends the prompt to OpenAI API
* Parses the JSON response
* Returns a score (0-100) and explanation

**AI Prompts (`prompts.ts`)**

Contains prompt templates for AI services:

1. `getNarrativePromptMessages`: Generates prompts for evaluating token narratives
2. `getTokenStatusScorePromptMessages`: Generates prompts for overall token evaluation
3. `getPriceTrendPredictionPromptMessages`: Generates prompts for price trend analysis

Each template:

* Includes detailed system instructions
* Formats token data appropriately
* Provides examples to guide the AI response
* Specifies expected output format

#### 5. Token Status Management

**Token Status Updater (`tokenStatusUpdater.ts`)**

Manages token status transitions:

```javascript
export const tokenStatusUpdater = async (token: Token, status: TokenStatus) => {
  // Reset dormant counter for ACTIVE tokens
  // Increment dormant counter for DORMANT tokens
  // Transition to REJECTED when dormant threshold exceeded
  // Update token status in database
}
```

The function:

* Updates token status based on evaluation results
* Manages dormant counter for inactive tokens
* Automatically rejects tokens after multiple dormant evaluations

**Token Data Services (`tokenData.ts`)**

Provides functions for retrieving token data:

* `getTokenWithEvaluationResult`: Retrieves tokens with their evaluation results
* `getTokensByStatus`: Retrieves tokens filtered by status
* `getPriceSnapshot`: Retrieves token price snapshots
* `sortTokens`: Helper function for consistent token sorting

#### 6. Queue System (`queues.ts`)

The queue system orchestrates asynchronous processing:

```javascript
export class QueueService {
  private queues: Map<string, Queue> = new Map();
  
  // Helper methods for queue management
  
  addEvaluateToken = (data: QueueDefinitions["evaluateTokenInitDataFetching"]["data"]) => {
    // Add token to evaluation queue
  }
  
  // Methods for scheduling and periodic tasks
  
  setupSchedulers = async () => {
    // Set up recurring tasks
  }
}
```

The service:

* Creates and manages Bull MQ queues
* Provides methods for adding jobs to queues
* Sets up schedulers for periodic tasks
* Supports retry logic and error handling

Key queues include:

* `evaluateTokenInitDataFetching`: Initial evaluation of discovered tokens
* `evaluateTokenFetchedData`: Evaluation after data fetching
* `evaluateBuy`: Evaluation for buy signals
* `evaluateSell`: Evaluation for sell signals

#### 7. Token Search (`tokenSearcher.ts`)

Provides search functionality for tokens:

```javascript
export const search = async (
  params: SearchParams,
): Promise<TokenSearchResponse> => {
  // Search token by id, address, or symbol
  // Create new token if needed
  // Fetch token overview data
  // Return token with overview data
}
```

The function:

* Accepts search parameters (id, address, symbol)
* Attempts to find existing token
* Creates new token if not found and source exists
* Fetches overview data for context
* Returns token and overview information

#### 8. WebSockets Subscription Manager (`WebsocketsSubscriptionManager.ts`)

Manages real-time data subscriptions:

```javascript
export class WebsocketsSubscriptionManager {
  // Singleton pattern implementation
  
  async subscribeToTokenPriceFeed(token: BaseTokenData) {
    // Subscribe to token price feed
  }
  
  async unsubscribeFromTokenPriceFeed(token: BaseTokenData) {
    // Unsubscribe from token price feed
  }
}
```

The service:

* Manages WebSocket subscriptions via Redis pub/sub
* Allows subscribing to token price feeds
* Supports unsubscribing when monitoring ends

### Configuration Framework

The system uses a flexible configuration framework:

#### Market Cap Categories

Tokens are categorized by market cap:

* Nanocap: < $100K
* Microcap: < $1M
* Smallcap: < $10M
* Midcap: < $100M
* Largecap: < $1B
* Megacap: > $1B

#### Check Configuration

Each check is configurable with:

* Threshold: Target value to compare against
* Weight: Importance in overall score (0-100)
* Required: Whether failing this check automatically fails evaluation
* Disabled: Whether to skip this check
* Operator: How to compare value against threshold (GTE or LTE)
* Range: Optional min/max range for comparison

#### Core and Degen Modes

Two configuration modes:

* Core Mode: Standard configurations managed by system
* Degen Mode: User-customizable configurations for advanced users

### Key Workflows

#### Token Discovery Workflow:

1. Monitoring service finds new token
2. `newTokenCall` creates/updates token record
3. Token is queued for evaluation
4. Data fetchers gather token information
5. Evaluation determines token status

#### Token Evaluation Workflow:

1. Load appropriate configuration
2. Fetch required data
3. Run checks against data
4. Calculate internal score
5. Request AI score
6. Combine scores and determine result
7. Update token status
8. Save evaluation results

#### Trading Signal Workflow:

1. Token selected for evaluation
2. Technical and market checks performed
3. AI analysis requested for price trend
4. Buy/sell signals generated based on results
5. Signal results saved and potentially acted upon

### Error Handling and Resilience

The system implements several resilience features:

* Queue-based processing with retries
* Data caching to reduce API dependency
* Fallback mechanisms for missing data
* Error tracking and logging
* Special handling for unavailable data errors
* Tolerance for test tokens
* Metrics tracking for monitoring system health

### Database Models

Key database models include:

* `Token`: Core token information
* `TokenPrice`: Historical price data
* `DataFetcherResponse`: Cached responses from data sources
* `EvaluationResult`: Results of token evaluations
* `EvaluationResultDetails`: Detailed check results

### Getting Started for New Developers

1. Understand the core evaluation pipeline in `evaluators/index.ts`:
   * How configurations are loaded
   * How checks are executed
   * How results are processed
   * How AI integration works
2. Explore the check system:
   * How individual checks work
   * How checks are configured
   * How the comparison logic in `compareValues` works
   * How results are aggregated
3. Study the result processing functions:
   * `processStatusEvaluations`
   * `processBuyEvaluations`
   * `processSellEvaluations`
4. Examine how results are persisted:
   * `saveResultToHistory`
   * Metrics tracking

### Advanced Topics

Once familiar with the core system, explore:

1. Custom check development
2. Configuration management
3. AI prompt optimization
4. Performance tuning of data fetchers
5. Enhancing comparison operators and scoring methods

### Conclusion

The AIQ Evaluations and Token Processing system is a sophisticated platform combining market data analysis, technical indicators, and AI-powered evaluations. It provides a flexible, configurable framework for discovering, analyzing, and evaluating cryptocurrency tokens, supporting both automated and user-driven workflows. The system's core strengths lie in its modular check system, configurable evaluation pipeline, and integration of machine learning for holistic assessment.


# Trading and Execution Engine

AIQ Trading and Execution Module Documentation

<figure><img src="https://1436123647-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyWO8QHLE41XNXrJodMxY%2Fuploads%2Fl0HMRl0ntWUka42vkh2Z%2FScreen%20Shot%202025-02-25%20at%2012.58.34%20PM.png?alt=media&amp;token=a7bc5c1f-720c-4d85-b6b3-b567f06d34a6" alt=""><figcaption></figcaption></figure>

The AIQ Trading and Execution Module handles the critical processes of executing buy and sell operations based on token evaluation results. This module serves as the bridge between analytical evaluations and on-chain transactions, managing the full lifecycle of trades from queue processing to blockchain confirmation.

### Core Components

#### 1. Queue Processing System

The system implements a queue-based architecture for executing trades:

```javascript
const workers: Record<string, Worker> = {
  executeSell: new Worker(Queues.executeSell, executeSellJob, {
    ...getQueueOptions(),
    name: `worker-${Queues.executeSell}`,
    concurrency: 10,
  }),
  executeBuy: new Worker(Queues.executeBuy, executeBuyJob, {
    ...getQueueOptions(),
    name: `worker-${Queues.executeBuy}`,
    concurrency: 10,
  }),
  chargeFee: new Worker(Queues.chargeFee, chargeFeeJob, {
    ...getQueueOptions(),
    name: `worker-${Queues.chargeFee}`,
    concurrency: 10,
  }),
};
```

Key queues include:

* `executeBuy`: Processes token purchase operations
* `executeSell`: Processes token sale operations
* `chargeFee`: Handles platform fee collection after successful sales

Each worker has a concurrency limit of 10, allowing multiple trades to be processed simultaneously.

#### 2. Buy Execution Flow

The buy flow is handled by `executeBuyJob.ts`, which:

1. Receives trade details including user ID and token information
2. Retrieves the user record from the database
3. Creates or updates a `userToken` record with `EXECUTING` status
4. Delegates the actual purchase to the `Trader` service
5. Updates the record status to `COMPLETED` or `FAILED` based on the outcome

```javascript
const processPurchase = async (
  user: User,
  token: TokenData,
  logger: Logger,
): Promise<void> => {
  const trader = new Trader();
  
  // Record preparation and status management
  const userToken = await prisma.userToken.upsert(/* ... */);
  
  try {
    // Execute the purchase
    const buyPrice = await trader.buyToken({
      user,
      userToken,
      token,
      buyAmountInSolOrEth,
      checkBalance: false,
    });
    
    // Update status on success
    await prisma.userToken.update({
      where: { id: userToken.id },
      data: { buyStatus: "COMPLETED", highestPriceReached: buyPrice },
    });
  } catch (err: any) {
    // Update status on failure
    await prisma.userToken.update({
      where: { id: userToken.id },
      data: { buyStatus: "FAILED" },
    });
    throw err;
  }
};
```

#### 3. Sell Execution Flow

The sell flow in `executeSellJob.ts` follows a similar pattern but includes additional logic for:

1. Validating token ownership
2. Calculating profits and moonbag retention
3. Processing the sell transaction
4. Updating position status
5. Triggering fee collection when profitable

```javascript
const processSell = async ({
  token,
  holder,
  sellAmount,
  closedWithProfits,
  logger,
}): Promise<void> => {
  const trader = new Trader();

  try {
    const platformFeeAmountInTokens = sellAmount * config.platformFeePerc;
    
    // Execute the sale
    await trader.sellToken({
      user: holder.user,
      token,
      amount: sellAmount,
    });
    
    // Update position status
    await prisma.userToken.update({
      where: { id: holder.id },
      data: {
        positionClosed: true,
        closedWithProfits: closedWithProfits,
      },
    });
    
    // Charge platform fee if profitable
    if (closedWithProfits) {
      await QueueService.getInstance().addChargeFee({
        userId: holder.user.id,
        chainName: token.chainName,
        platformFeeAmountInTokens,
        tokenAddress: token.address,
      });
    }
  } catch (err: any) {
    logger.error(`Failed to process sell.`, err);
    throw err;
  }
};
```

#### 4. Automatic Position Management

The system includes a position watcher (`positionsWatcherJob.ts`) that monitors all active positions and triggers sell operations based on:

1. **Take Profit (TP)**: When position value exceeds a configured profit multiple
2. **Stop Loss (SL)**: When position value drops below a configured percentage
3. **Trailing Stop Loss (TSL)**: Dynamic stop loss that adjusts based on highest achieved price

```javascript
export const checkPositionForTPSL = async (
  position: UserTokenWithTransactions,
  currentTokenPriceInUsd: number,
  logger: Logger,
): Promise<PositionTPSLResult> => {
  // Position value calculation logic...
  
  // Check for stop loss
  if (lossPercentage >= position.user.stopLossPercentage) {
    return { status: "sl", /* other metrics */ };
  }
  
  // Check for trailing stop loss
  if (position.user.trailingStopLossEnabled && 
      profitMultiple >= minProfitMultiple &&
      currentTokenPriceInUsd <= trailingStopLossTarget) {
    return { status: "tsl", /* other metrics */ };
  }
  
  // Check for take profit
  if (profitMultiple >= position.user.takeProfitMultiple) {
    return { status: "tp", /* other metrics */ };
  }
  
  // No triggers hit
  return { /* position metrics */ };
};
```

The trailing stop loss feature supports dynamic adjustment based on profit levels:

```javascript
const getTrailingStopLossPercentage = (
  profitMultiple: number,
  dynamicOffset?: TrailingStopLossConfig | null,
  defaultPercentage: number = 15
): number => {
  if (!dynamicOffset?.offsets?.length) {
    return defaultPercentage;
  }

  // Sort to check highest profit levels first
  const sortedOffsets = [...dynamicOffset.offsets].sort((a, b) => 
    b.profitLevel - a.profitLevel
  );
  
  for (const offset of sortedOffsets) {
    if (profitMultiple >= offset.profitLevel) {
      return offset.percentage;
    }
  }

  return defaultPercentage;
};
```

#### 5. Fee Collection System

After profitable sales, the system charges platform fees through `chargeFeeJob.ts`, which:

1. Calculates fee amounts in native chain currency (ETH or SOL)
2. Handles chain-specific fee collection logic
3. Executes transactions via Privy (a transaction signing service)
4. Manages error cases like insufficient balance

```javascript
export const chargeFeeJob = async (job: Job<ChargeFeeData>) => {
  const { userId, chainName, platformFeeAmountInTokens, tokenAddress } = job.data;
  
  // Calculate fee in native currency
  const platformFeeInEthOrSol = 
    chainName === ChainName.SOLANA
      ? (await getTokenPriceSol({ address: tokenAddress })) * platformFeeAmountInTokens
      : (await getTokenPriceInEth({ address: tokenAddress })) * platformFeeAmountInTokens;
  
  // Execute chain-specific fee collection
  if (chainName === ChainName.SOLANA) {
    await paySolanaFee(/* parameters */);
  } else {
    await payBaseFee(/* parameters */);
  }
};
```

### Transaction Processing Workflow

#### Buy Flow

1. Token passes evaluation, triggering `pushExecuteBuys` in the evaluator
2. Buy messages are queued for affected users
3. `executeBuyJob` worker picks up messages and validates user details
4. `processPurchase` executes the transaction via `Trader` service
5. Transaction status is updated in the database

#### Sell Flow

1. Triggered by:
   * Manual user action
   * Evaluation results (`processSellEvaluations`)
   * Position watcher detecting TP/SL conditions
2. Sell messages are queued for affected users
3. `executeSellJob` worker processes the sell operation
4. `processSell` calculates metrics and executes the transaction
5. For profitable trades, fee collection is queued
6. `chargeFeeJob` collects platform fees

### Error Handling and Resilience

The system implements several error handling mechanisms:

1. **Transaction Status Tracking**: All trades maintain `EXECUTING` → `COMPLETED`/`FAILED` status flow
2. **Worker Error Events**: All workers log detailed error information including job data
3. **Database Transaction Safety**: Operations follow a consistent pattern of preparation, execution, and status update
4. **Price Staleness Checks**: Position watcher verifies price recency before taking action

### Chain-Specific Considerations

The system supports multiple blockchains with chain-specific logic:

1. **Solana**:
   * Uses Solana Web3.js for transaction construction
   * Manages lamports for transaction fees
   * Implements SOL-specific balance checks
2. **Base** (Ethereum L2):
   * Uses ethers.js for transaction handling
   * Calculates gas costs in ETH
   * Manages transaction queue and nonce tracking

### User Settings Integration

Trade execution integrates user preferences for:

1. **Buy Settings**:
   * Purchase amount in SOL/ETH
2. **Sell Settings**:
   * Take profit multiple
   * Stop loss percentage
   * Moonbag retention percentage (amount to keep after TP)
   * Trailing stop loss configuration

### Monitoring and Metrics

The system includes comprehensive logging via the `Logger` service, which captures:

1. Job status events (active, completed, failed)
2. Transaction details (prices, amounts, timestamps)
3. Trading analytics (profit multiples, loss percentages)
4. Error information with full stack traces

### Getting Started for Developers

To work with the trading and execution module, developers should:

1. Understand the queue processing model in `index.ts`
2. Review the job implementation files (`executeBuyJob.ts`, `executeSellJob.ts`, etc.)
3. Study the position watcher logic for automated trading signals
4. Examine error handling patterns throughout the codebase

### Key Technical Workflows

#### Position Value Calculation

The system maintains accurate position value tracking by:

1. Tracking all buy and sell transactions in sequence
2. Calculating running token balance and investment amounts
3. Determining average cost basis per token
4. Computing current value, profit multiples, and loss percentages

#### Dynamic Stop Loss Management

The trailing stop loss system provides sophisticated risk management by:

1. Recording all-time high price for each position
2. Supporting variable trailing percentages based on profit levels
3. Automatically tightening stop loss as profits grow
4. Triggering sell signals when price drops below trailing threshold

#### Chain-Specific Transaction Handling

The system handles blockchain differences through:

1. Chain-specific transaction preparation logic
2. Appropriate fee calculation and management
3. Customized address validation and formatting
4. Blockchain-specific error handling

#### Fee Collection

Platform fees are processed through a dedicated workflow:

1. Calculating token-denominated fee amounts
2. Converting to native chain currency
3. Creating and signing appropriate transactions
4. Managing buffer amounts for transaction costs
5. Handling confirmation and error scenarios


