# Trading and Execution Engine

<figure><img src="/files/NMVqxvUXR3JNiVvtw49j" 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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aiquant.fun/technical-docs/trading-and-execution-engine.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
