Trading and Execution Engine

AIQ Trading and Execution Module Documentation

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:

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

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

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

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

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

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

Last updated