Twitter API Guide for Trading Bots and AI Agents

Twitter API Guide for Trading Bots and AI Agents
Twitter monitoring API endpoints and integration patterns

Twitter monitoring APIs enable trading bots, AI agents, and analytics platforms to process social media intelligence at scale. This guide covers REST endpoints, WebSocket streaming, authentication, and integration patterns for building automated systems using Xanguard's API. Every endpoint shown here is in the public OpenAPI spec.

We'll explore implementations for crypto trading bots, sentiment analysis systems, and social media automation where speed matters. For reference, Xanguard's median tweet detection time is ~200 ms, published live on the speed page.

API Architecture Overview

Xanguard's Twitter monitoring API provides multiple interfaces optimized for different use cases:

This multi-modal approach allows developers to choose the optimal integration method based on their architecture and latency requirements.

Authentication and Security

All API access uses a Bearer API key. B2B keys start with dt_ and are created with /apikey in @B2B_Xanguard_bot.

API Key Management

// Authentication header for all REST requests
Authorization: Bearer dt_your_api_key

What your key controls:

REST API Endpoints

The REST API manages your monitoring list and returns recent data. All responses use the envelope {"ok": true, "data": {...}}.

GET List Monitored Accounts

GET https://api.xanguard.tech/v1/dt/targets

Retrieve all monitored accounts and your plan limit.

{
"ok": true,
"data": {
"targets": [
{
"id": 101,
"screen_name": "example_dev",
"twitter_user_id": "1234567890",
"is_active": true,
"created_at": "2026-09-01T10:30:00Z"
}
],
"count": 1,
"max_handles": 50
}
}

POST Add Account Monitoring

POST https://api.xanguard.tech/v1/dt/targets

Add a new Twitter account to your monitoring list.

// Request payload
{
"handle": "example_dev"
}

// Response { "ok": true, "data": { "handle": "example_dev", "twitter_user_id": "1234567890" } }

GET Recent Tweets

GET https://api.xanguard.tech/v1/dt/tweets/{handle}

Returns the latest tweets we have detected from a handle on your list. Useful for catching up after a reconnect.

// Response (abridged)
{
"ok": true,
"data": {
"tweets": [
{
"tweet_id": "1766123456789012345",
"full_text": "Example tweet text $EXAMPLE",
"created_at": "2026-09-20T16:30:00Z",
"is_reply": false,
"is_quote": false,
"media_urls": [],
"mentions": []
}
],
"count": 1
}
}

Other B2B REST endpoints include profile data and history (/v1/dt/profile/{handle}), and following and followers lists. See the API docs for the full list.

WebSocket Streaming API

Real-time streaming is the fastest way to receive events and suits time-sensitive applications like crypto trading bots. For complete, reconnecting clients, see the Python and Node.js WebSocket tutorials.

Connection and Authentication

// WebSocket connection with authentication (Node.js, "ws" package)
const WebSocket = require('ws');
const ws = new WebSocket('wss://api.xanguard.tech/v1/dt/realtime/ws');
let heartbeat;

// Auth and events both arrive on the message handler (opcode protocol)
ws.on('message', (raw) => {
  const msg = JSON.parse(raw);

  // HELLO (op 10) -> send LOGIN (op 2), then heartbeat (op 1); READY (op 4) follows
  if (msg.op === 10) {
    ws.send(JSON.stringify({ op: 2, d: 'dt_your_api_key' }));
    heartbeat = setInterval(() => ws.send(JSON.stringify({ op: 1 })), msg.d.heartbeat_interval);
    return;
  }

  // EVENT (op 0)
  if (msg.op === 0 && msg.d.event === 'twitter.post.new') {
    processTweetAlert(msg.d);
  }
});

ws.on('close', () => clearInterval(heartbeat));

Stream Message Format

{
  "op": 0,
  "d": {
    "event": "twitter.post.new",
    "event_id": "evt_1766123456789012345",
    "task_info": {
      "handle": "example_dev"
    },
    "data": {
      "id": "1766123456789012345",
      "type": "post",
      "text": "Example tweet text $EXAMPLE",
      "created_at": 1758385510000,
      "author": {
        "handle": "example_dev",
        "name": "Example Dev"
      }
    }
  }
}

The tweet ID is data.id, and a tweet's link is https://x.com/{handle}/status/{id} (the frame carries no url field). An edited tweet arrives again as twitter.post.update with the same event_id, so deduplicate on it.

Other event types on the same connection, depending on your plan, include deleted tweets, profile changes, new followers and follow/unfollow events. How deletions surface is explained in our deleted tweets guide.

Implementing Trading Bot Integration

Here's an example of wiring the stream into a crypto trading bot. Signal logic (which accounts, which words) lives in your code, so you can tune it without changing anything on the Xanguard side:

const WebSocket = require('ws');
const ExchangeAPI = require('./exchange-api');

class TradingBot {
  constructor(apiKey, exchangeCredentials) {
    this.apiKey = apiKey;
    this.exchange = new ExchangeAPI(exchangeCredentials);
    this.tier1 = new Set(['example_kol', 'example_fund', 'example_exchange']);
  }

  start() {
    const ws = new WebSocket('wss://api.xanguard.tech/v1/dt/realtime/ws');

    ws.on('message', async (raw) => {
      const msg = JSON.parse(raw);
      if (msg.op === 10) {
        ws.send(JSON.stringify({ op: 2, d: this.apiKey }));
        setInterval(() => ws.send(JSON.stringify({ op: 1 })), msg.d.heartbeat_interval);
      } else if (msg.op === 0 && msg.d.event === 'twitter.post.new') {
        await this.processTradingSignal(msg.d.data);
      }
    });
  }

  async processTradingSignal(tweet) {
    // Only act on original posts from accounts you trust
    if (tweet.type !== 'post' || !this.tier1.has(tweet.author.handle.toLowerCase())) return;

    // Your own classifier: keywords, an LLM call, or a sentiment model
    const signal = this.classify(tweet.text);
    if (signal) {
      await this.executeTradeSignal(signal);
    }
  }

  async executeTradeSignal(signal) {
    try {
      const { symbol, sentiment, strength } = signal;
      const tradingPair = `${symbol}/USDT`;

      // Position sizing based on signal strength
      const baseAmount = 1000; // $1000 base position
      const positionSize = baseAmount * (strength / 10);

      if (sentiment === 'bullish') {
        await this.exchange.marketBuy(tradingPair, positionSize);
        console.log(`Bought ${symbol}: $${positionSize}`);
      } else if (sentiment === 'bearish') {
        await this.exchange.marketSell(tradingPair, positionSize);
        console.log(`Sold ${symbol}: $${positionSize}`);
      }

    } catch (error) {
      console.error('Trade execution failed:', error);
    }
  }
}

Rate Limits and Best Practices

Understanding rate limits and implementing proper retry logic ensures reliable API usage:

Rate Limit Handling

class RateLimitHandler {
  constructor(apiClient) {
    this.client = apiClient;
    this.retryQueue = [];
  }

  async makeRequest(endpoint, options) {
    try {
      const response = await this.client.request(endpoint, options);
      return response.data;

    } catch (error) {
      if (error.status === 429) {
        // Rate limit exceeded
        const retryAfter = error.headers['retry-after'] || 1;
        console.log(`Rate limited. Retrying after ${retryAfter}s`);

        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        return this.makeRequest(endpoint, options);
      }

      throw error;
    }
  }
}

Error Handling and Monitoring

Production integrations require comprehensive error handling and monitoring:

// Thin REST client with built-in monitoring
class MonitoredXanguardClient {
  constructor(apiKey, options = {}) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.xanguard.tech';
    this.metrics = new MetricsCollector();
    this.alerting = new AlertingSystem(options.alertWebhook);
  }

  async request(endpoint, options = {}) {
    const startTime = Date.now();

    try {
      const res = await fetch(this.baseUrl + endpoint, {
        ...options,
        headers: { Authorization: `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }
      });
      if (!res.ok) throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status, headers: Object.fromEntries(res.headers) });

      this.metrics.recordSuccess(endpoint, Date.now() - startTime);
      return await res.json();

    } catch (error) {
      this.metrics.recordError(endpoint, error);

      // Alert on critical failures
      if (this.isCriticalError(error)) {
        await this.alerting.sendAlert({
          message: `API request failed: ${endpoint}`,
          error: error.message,
          timestamp: new Date().toISOString()
        });
      }

      throw error;
    }
  }

  isCriticalError(error) {
    // 5xx errors, authentication failures, or connection timeouts
    return error.status >= 500 ||
           error.status === 401 ||
           error.code === 'ECONNRESET';
  }
}

Advanced Integration Patterns

Multi-Exchange Arbitrage Bot

Combining tweets from exchange accounts with price data across multiple exchanges. Add the exchanges' X accounts to your target list, then filter on your side:

class ArbitrageBot {
  constructor() {
    this.apiKey = process.env.XANGUARD_API_KEY;
    this.keywords = ['listing', 'will list', 'deposits open'];
    this.exchanges = [
      new BinanceAPI(),
      new CoinbaseAPI(),
      new KrakenAPI()
    ];
  }

  onTweet(tweet) {
    // Called for each twitter.post.new event from the WebSocket stream
    const text = tweet.text.toLowerCase();
    if (this.keywords.some(k => text.includes(k))) {
      return this.executeArbitrage(tweet);
    }
  }

  async executeArbitrage(tweet) {
    const tokens = this.extractTokens(tweet.text);

    for (const token of tokens) {
      const prices = await this.fetchPricesAcrossExchanges(token);
      const opportunity = this.calculateArbitrage(prices);

      if (opportunity.profit > this.minProfitThreshold) {
        await this.executeArbitrageTrade(opportunity);
      }
    }
  }
}

Conclusion: Building Production-Grade Twitter Intelligence

Xanguard's Twitter monitoring API provides the foundation for trading bots, analytics platforms, and AI agents that need real-time social media intelligence. Key takeaways for successful implementation:

B2B plans start at $49/month for 50 accounts, paid in SOL. The combination of real-time Twitter intelligence with proper API integration enables automated systems that can react to market-moving information faster than manual monitoring allows, providing a genuine competitive advantage in fast-moving crypto markets.

Frequently Asked Questions

What is a Twitter/X monitoring API?

A monitoring API provides programmatic access to real-time Twitter/X data through REST endpoints and WebSocket streams. Xanguard's API lets trading bots and AI agents receive new tweets (median detection ~200 ms, published live at xanguard.tech/speed/), profile changes, and follow events.

How do I integrate a Twitter/X monitoring API into my trading bot?

Connect to Xanguard's WebSocket endpoint for real-time streaming and use the REST API to manage your handle list and catch up after a reconnect. Events arrive as structured JSON as soon as they are detected.

What delivery methods does Xanguard's Twitter/X API support?

The B2B API has two: REST for configuration and recent data, and WebSocket for real-time streaming. Signed webhooks and Telegram delivery are part of the consumer Tweet Alerts paid plans.

Can AI agents use the Twitter/X monitoring API?

Yes. Xanguard's API is designed for both trading bots and AI agents. The structured JSON payloads and WebSocket streaming make it straightforward to integrate Twitter/X intelligence into any automated system.

← Back to Blog

Start Building with the API

Get Telegram notifications for new tweets from any X account, in a median of ~200 ms on paid plans. Free for 1 account. Paid plans from $19 a month for 10 accounts.