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 operationsexecuteSell: Processes token sale operationschargeFee: 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:
Receives trade details including user ID and token information
Retrieves the user record from the database
Creates or updates a
userTokenrecord withEXECUTINGstatusDelegates the actual purchase to the
TraderserviceUpdates the record status to
COMPLETEDorFAILEDbased on the outcome
3. Sell Execution Flow
The sell flow in executeSellJob.ts follows a similar pattern but includes additional logic for:
Validating token ownership
Calculating profits and moonbag retention
Processing the sell transaction
Updating position status
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:
Take Profit (TP): When position value exceeds a configured profit multiple
Stop Loss (SL): When position value drops below a configured percentage
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:
Calculates fee amounts in native chain currency (ETH or SOL)
Handles chain-specific fee collection logic
Executes transactions via Privy (a transaction signing service)
Manages error cases like insufficient balance
Transaction Processing Workflow
Buy Flow
Token passes evaluation, triggering
pushExecuteBuysin the evaluatorBuy messages are queued for affected users
executeBuyJobworker picks up messages and validates user detailsprocessPurchaseexecutes the transaction viaTraderserviceTransaction status is updated in the database
Sell Flow
Triggered by:
Manual user action
Evaluation results (
processSellEvaluations)Position watcher detecting TP/SL conditions
Sell messages are queued for affected users
executeSellJobworker processes the sell operationprocessSellcalculates metrics and executes the transactionFor profitable trades, fee collection is queued
chargeFeeJobcollects platform fees
Error Handling and Resilience
The system implements several error handling mechanisms:
Transaction Status Tracking: All trades maintain
EXECUTINGβCOMPLETED/FAILEDstatus flowWorker Error Events: All workers log detailed error information including job data
Database Transaction Safety: Operations follow a consistent pattern of preparation, execution, and status update
Price Staleness Checks: Position watcher verifies price recency before taking action
Chain-Specific Considerations
The system supports multiple blockchains with chain-specific logic:
Solana:
Uses Solana Web3.js for transaction construction
Manages lamports for transaction fees
Implements SOL-specific balance checks
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:
Buy Settings:
Purchase amount in SOL/ETH
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:
Job status events (active, completed, failed)
Transaction details (prices, amounts, timestamps)
Trading analytics (profit multiples, loss percentages)
Error information with full stack traces
Getting Started for Developers
To work with the trading and execution module, developers should:
Understand the queue processing model in
index.tsReview the job implementation files (
executeBuyJob.ts,executeSellJob.ts, etc.)Study the position watcher logic for automated trading signals
Examine error handling patterns throughout the codebase
Key Technical Workflows
Position Value Calculation
The system maintains accurate position value tracking by:
Tracking all buy and sell transactions in sequence
Calculating running token balance and investment amounts
Determining average cost basis per token
Computing current value, profit multiples, and loss percentages
Dynamic Stop Loss Management
The trailing stop loss system provides sophisticated risk management by:
Recording all-time high price for each position
Supporting variable trailing percentages based on profit levels
Automatically tightening stop loss as profits grow
Triggering sell signals when price drops below trailing threshold
Chain-Specific Transaction Handling
The system handles blockchain differences through:
Chain-specific transaction preparation logic
Appropriate fee calculation and management
Customized address validation and formatting
Blockchain-specific error handling
Fee Collection
Platform fees are processed through a dedicated workflow:
Calculating token-denominated fee amounts
Converting to native chain currency
Creating and signing appropriate transactions
Managing buffer amounts for transaction costs
Handling confirmation and error scenarios
Last updated