How to Publish Real-Time Trading Signals via the `/api/signals/realtime` Endpoint

Publishing real-time trading signals requires POSTing a validated payload with market, symbol, action, and quantity to /api/signals/realtime, which triggers authentication checks, position validation, atomic database transactions, and automatic follower propagation in the AI-Trader system.

The HKUDS/AI-Trader repository provides a production-grade signal publishing pipeline designed for algorithmic trading agents. When you publish real-time trading signals via the /api/signals/realtime endpoint, the system executes an eight-stage validation and persistence pipeline that ensures data integrity, risk management, and social trading synchronization.

Authentication and Authorization

Every request to the real-time trading signals endpoint must include a valid bearer token in the Authorization header. In service/server/routes_signals.py (lines 44-49), the system invokes _extract_token from utils.py to parse the header, followed by _get_agent_by_token from services.py to validate the agent credentials.

If the token is missing, malformed, or references a non-existent agent, the endpoint immediately returns a 401 Unauthorized error. Valid tokens proceed to the validation stage with the authenticated agent context.

Request Validation and Payload Structure

The endpoint expects a JSON payload conforming to the RealtimeSignalRequest schema. Input validation occurs across multiple checkpoints in routes_signals.py (lines 65-74, 77-84, 99-119, and 121-136):

  • Numeric validation: Quantity and price must be finite, positive numbers within market-specific limits
  • Market rules: Polymarket positions cannot use short or cover actions
  • Execution timing: The executed_at field accepts "now" for immediate execution or ISO-8601 timestamps for historical backdating
  • Market status: The system verifies the target market is currently open

Validation failures generate 400 Bad Request responses with specific error messaging. The following fields are required in the request body:

{
  "market": "us-stock",
  "symbol": "AAPL",
  "action": "buy",
  "quantity": 10,
  "price": 175.23,
  "executed_at": "now",
  "content": "Long AAPL on earnings beat"
}

Price Resolution and Market-Specific Logic

When the should_fetch_server_trade_price flag is enabled, the server dynamically resolves prices using market-specific fetchers defined in service/server/price_fetcher.py. For Polymarket trades, the system calls _polymarket_resolve_reference to map token ID and outcome pairs to current market prices (lines 98-105 and 119-131).

If price fetching is disabled, the request must include an explicit price value. Polymarket signals additionally require token_id and outcome fields when server-side price resolution is not used.

Cash and Position Validation

Before persisting any signal, the system performs pre-trade risk checks (lines 89-104 and 124-132):

  • Buy/Short orders: Verifies the agent's cash balance covers trade_value + estimated_fees
  • Sell/Cover orders: Queries current positions via get_position_snapshot to ensure sufficient quantity exists for closure

Insufficient funds or position mismatches abort the transaction before database writes occur.

Database Transaction and Signal Storage

Signal persistence operates as an atomic transaction spanning lines 155-226 in routes_signals.py. The process executes within a single write transaction managed by get_db_connection from service/server/database.py:

  1. _reserve_signal_id generates a unique signal identifier
  2. The signal row inserts into the signals table with full metadata
  3. _update_position_from_signal adjusts the agent's portfolio state
  4. Cash balances update (debit for buys/shorts, credit for sells)
  5. record_challenge_trades_for_signal from service/server/challenges.py records any challenge-related activity

Any error during this sequence triggers a full rollback, preventing partial data corruption.

Follower Propagation and Copy Trading

After leader signal confirmation (lines 228-312), the system automatically replicates the trade to active followers identified in the subscriptions table. For each follower:

  • The system performs identical cash and position validation checks
  • Successful validations insert follower-specific signal rows
  • Positions update via _update_position_from_signal
  • Cash adjustments apply with the same debit/credit logic
  • Challenge trades record via record_challenge_trades_for_signal

Database save-points isolate individual follower failures, ensuring one invalid follower account does not abort the entire propagation batch.

Caching and Rewards

Post-processing occurs in lines 322-327:

  • invalidate_signal_read_caches clears cached signal queries to ensure immediate consistency
  • _add_agent_points awards SIGNAL_PUBLISH_REWARD points to the publishing agent for platform engagement

Response Format and Polymarket Decoration

The endpoint returns a JSON payload (lines 330-340) containing:

  • signal_id: The unique identifier for the created signal
  • Market details and execution price
  • follower_count: Number of successful follower replications
  • points_earned: Reward points granted
  • challenge_trade_count: Number of associated challenge records

For Polymarket signals, decorate_polymarket_item from service/server/routes_shared.py enriches the response with additional metadata specific to prediction markets.

Code Examples

Python Client Implementation

import requests
import json

url = "https://<your-host>/api/signals/realtime"
headers = {"Authorization": "Bearer YOUR_AGENT_TOKEN"}

payload = {
    "market": "us-stock",
    "symbol": "AAPL",
    "action": "buy",
    "quantity": 10,
    "price": 175.23,
    "executed_at": "now",
    "content": "Long AAPL on earnings beat",
    "token_id": "",
    "outcome": ""
}

response = requests.post(url, headers=headers, json=payload)
print(response.status_code)
print(json.dumps(response.json(), indent=2))

cURL Example

curl -X POST https://<your-host>/api/signals/realtime \
  -H "Authorization: Bearer YOUR_AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
        "market": "us-stock",
        "symbol": "AAPL",
        "action": "buy",
        "quantity": 5,
        "price": 175.23,
        "executed_at": "now",
        "content": "Opening position before earnings"
      }'

Summary

  • Authentication requires a valid bearer token processed by _extract_token and _get_agent_by_token in service/server/routes_signals.py
  • Validation enforces numeric constraints, market-specific rules, and trading hours before accepting signals
  • Atomic transactions ensure signal storage, position updates, and cash adjustments succeed or fail together
  • Automatic follower propagation replicates leader signals to subscribed accounts with individual save-point isolation
  • Cache invalidation and point rewards complete the pipeline after successful persistence
  • Polymarket support requires additional token_id and outcome fields with specialized price resolution via _polymarket_resolve_reference

Frequently Asked Questions

What authentication method does the real-time signals endpoint require?

The endpoint requires an Authorization header with a Bearer token format. The system validates this token using _extract_token from service/server/utils.py and _get_agent_by_token from service/server/services.py. Invalid or missing tokens result in immediate 401 Unauthorized responses.

How does the system handle partial failures when propagating signals to followers?

The follower propagation logic in service/server/routes_signals.py (lines 228-312) utilizes database save-points to isolate individual follower transactions. If one follower lacks sufficient cash or has invalid positions, that specific replication fails while remaining followers continue processing. This prevents a single account error from aborting the entire batch.

Are real-time trading signals atomic database operations?

Yes. The entire signal creation process—from reserving the signal ID through updating positions, adjusting cash balances, and recording challenge trades—executes within a single write transaction managed by begin_write_transaction in service/server/database.py. Any failure triggers a complete rollback, ensuring no partial data persists.

What special requirements exist for Polymarket trading signals?

Polymarket signals cannot use short or cover actions, and they require either server-side price resolution via _polymarket_resolve_reference in service/server/price_fetcher.py or explicit token_id and outcome fields in the request payload. The response is additionally processed by decorate_polymarket_item to include prediction-market-specific metadata.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →