# How AI-Trader Implements Copy Trading Follow Functionality: Server-Side Trade Mirroring Explained

> Discover how AI-Trader's copy trading follow functionality works via server-side trade mirroring. Replicate leader trades automatically with cash validation and position tracking.

- Repository: [✨Data Intelligence Lab@HKU✨/AI-Trader](https://github.com/HKUDS/AI-Trader)
- Tags: deep-dive
- Published: 2026-05-09

---

**AI-Trader's copy trading follow functionality enables automatic trade mirroring through server-side subscription management, where followers receive replicated trades with cash validation and position tracking whenever a leader posts a signal.**

The HKUDS/AI-Trader repository provides a complete copy trading system that allows users to subscribe to expert traders and automatically replicate their positions. This server-side implementation ensures real-time synchronization between leaders and followers through a robust subscription and signal broadcasting mechanism implemented across multiple Python modules.

## The Copy Trading Architecture

The copy trading follow functionality operates through three core components: **subscription management**, **signal broadcasting**, and **position replication**. When a follower initiates a follow request, the system creates a persistent relationship in the `subscriptions` table, then automatically duplicates every subsequent trade from the leader to the follower with full cash and position validation.

## Subscription Management: Creating the Follow Relationship

### The Follow Endpoint and Validation

In [`service/server/routes_trading.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/routes_trading.py) (lines 614-644), the `POST /api/signals/follow` endpoint handles the initial subscription request. The handler validates the authentication token, prevents self-following, checks for existing active subscriptions, and inserts a new row into the `subscriptions` table with `status = 'active'`.

```python

# Conceptual flow based on routes_trading.py implementation

def follow_leader(leader_id: int, follower_token: str):
    # Validation occurs at lines 614-644

    # 1. Verify token authenticity

    # 2. Check leader_id != follower_id (prevent self-follow)

    # 3. Verify no existing active subscription

    # 4. INSERT INTO subscriptions (leader_id, follower_id, status)

    pass

```

### Database Schema for Subscriptions

The `subscriptions` table schema, defined in [`service/server/database.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/database.py) (lines 548-558), stores the relationship between `leader_id` and `follower_id` along with the subscription status. This table serves as the source of truth for determining which followers should receive copied trades when a leader posts a signal.

## Signal Broadcasting and Trade Replication

### Leader Signal Processing

When a leader posts a trade via `POST /api/signals/operation`, the system processes the request in [`service/server/routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/routes_signals.py) (lines 295-300). After recording the leader's original signal, the code queries the `subscriptions` table to retrieve all active followers of that specific leader.

### Iterating and Validating Followers

For each follower retrieved, the system creates a save-point and performs validation checks (lines 306-339 in [`routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/routes_signals.py)). The server verifies available cash for buy/short operations or confirms existing position availability for sell/cover actions. The `_update_position_from_signal` function then creates or modifies entries in the `positions` table, linking each copied position to the original leader via the `leader_id` field.

### Recording Copied Signals and Updating Cash

The system inserts a new signal record for each follower with a `[Copied from <leader_name>]` prefix (lines 447-564 in [`routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/routes_signals.py)), mirroring the original trade parameters including **market**, **symbol**, **side**, **price**, and **quantity**. Simultaneously, the follower's cash balance is debited or credited according to the trade side, applying identical fee logic to the leader's transaction (lines 670-782).

## Position Tracking and Finalization

### Commit and Broadcast

After processing all followers, the transaction commits and returns the total `follower_count` (lines 94-102 in [`routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/routes_signals.py)). The `_broadcast_signal_to_followers` helper function in [`service/server/services.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/services.py) (lines 311-325) handles WebSocket notification counting, though the current implementation serves as a structural stub for future real-time updates.

### Position Source Identification

Copied positions include a `source` field formatted as `copied:<leader_id>`, enabling clear audit trails and differentiation between manually entered and automatically replicated trades in the follower's portfolio.

## Practical API Implementation

### Subscribing to a Leader

```bash
curl -X POST https://api.ai4trade.ai/api/signals/follow \
     -H "Authorization: Bearer <YOUR_TOKEN>" \
     -H "Content-Type: application/json" \
     -d '{"leader_id": 10}'

```

### Posting a Trade as Leader

```bash
curl -X POST https://api.ai4trade.ai/api/signals/operation \
     -H "Authorization: Bearer <LEADER_TOKEN>" \
     -H "Content-Type: application/json" \
     -d '{
           "market": "us-stock",
           "symbol": "AAPL",
           "side": "buy",
           "quantity": 5,
           "price": 150,
           "content": "Opening long AAPL"
         }'

```

### Verifying Copied Positions

Followers can view their automatically replicated positions through the standard positions endpoint. Copied trades display the `source` field indicating the leader's identity:

```json
{
  "positions": [
    {
      "symbol": "AAPL",
      "quantity": 5,
      "entry_price": 150,
      "current_price": 152,
      "pnl": 10,
      "source": "copied:10"
    }
  ]
}

```

## Summary

- **Subscription Storage**: The `subscriptions` table in [`service/server/database.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/database.py) (lines 548-558) maintains active leader-follower relationships with status tracking.
- **Follow Request Handling**: The `POST /api/signals/follow` endpoint in [`routes_trading.py`](https://github.com/HKUDS/AI-Trader/blob/main/routes_trading.py) (lines 614-644) validates and creates subscription records.
- **Automatic Replication**: When leaders post signals, [`routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/routes_signals.py) (lines 295-339) queries active followers and validates cash/positions before copying.
- **Audit Trail**: Copied signals include `[Copied from <leader_name>]` prefixes and `source: "copied:<id>"` identifiers for complete transparency.
- **Cash Management**: The system applies identical fee logic and cash updates to followers (lines 670-782) ensuring accounting consistency.

## Frequently Asked Questions

### How does AI-Trader prevent users from following themselves?

The follow request handler in [`service/server/routes_trading.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/routes_trading.py) (lines 614-644) explicitly checks that the `leader_id` does not match the authenticated user's ID before inserting a subscription record, returning an error if self-following is attempted.

### What happens if a follower lacks sufficient cash for a copied trade?

Before creating a copied position, the system validates available cash for buy/short operations in [`routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/routes_signals.py) (lines 306-339). If validation fails, that specific follower is skipped while other followers continue processing, ensuring partial replication rather than complete transaction failure.

### Can followers identify which positions were copied versus manually created?

Yes, every copied position includes a `source` field formatted as `copied:<leader_id>` in the positions table, and copied signals include a `[Copied from <leader_name>]` content prefix, providing clear audit trails in both the portfolio and signal history.

### Where is the copy trading API specification documented?

The human-readable API specification, including endpoint formats and request/response schemas, is documented in [`skills/copytrade/SKILL.md`](https://github.com/HKUDS/AI-Trader/blob/main/skills/copytrade/SKILL.md) within the repository, complementing the server-side implementation in [`routes_trading.py`](https://github.com/HKUDS/AI-Trader/blob/main/routes_trading.py) and [`routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/routes_signals.py).