Fintech Artificial Intelligence 1 vues

I Built an AI Trading Agent That Reads Twitter Sentiment—Here's How

B
Bright Coding
Auteur
I Built an AI Trading Agent That Reads Twitter Sentiment—Here's How

What if you could predict the next Dogecoin pump before it happened? Not with insider knowledge. Not with complex technical indicators. But by listening to what millions of people are screaming into the social media↗ Bright Coding Blog void.

Here's the brutal truth: retail traders are flying blind. While hedge funds pay thousands for Bloomberg terminals and alternative data feeds, you're refreshing CoinMarketCap and hoping for the best. The sentiment data exists—it's exploding across Twitter, Reddit, and TikTok every second—but nobody's built a bridge between that noise and actionable trading decisions.

Until now.

Meet ai-trading-agent-gemini—an open-source AI trading agent that transforms raw social media sentiment into intelligent BUY/SELL/HOLD signals. Built by developer Danilo Batson, this isn't another toy project. It's a production-ready pipeline combining LunarCrush's social analytics, Google's Gemini AI reasoning, and real-time infrastructure that updates your dashboard live as analysis unfolds.

The secret sauce? A 7-step background workflow that fetches social data, runs AI inference, and streams progress to your browser in real-time. No polling. No page refreshes. Just pure, automated intelligence.

Ready to see how it works? Let's dive deep.


What is ai-trading-agent-gemini?

ai-trading-agent-gemini is an AI-powered trading signal generator that bridges the gap between social media sentiment and financial decision-making. Created by Danilo Batson, this open-source project demonstrates how modern AI integration patterns can solve real-world trading challenges.

At its core, the application performs three critical functions:

  1. Ingests real-time social metrics from LunarCrush's specialized cryptocurrency sentiment API
  2. Processes that data through Google Gemini AI to generate structured trading recommendations with confidence scores
  3. Delivers results through a real-time dashboard powered by Supabase subscriptions and Inngest background jobs

The project sits at the intersection of multiple explosive trends: AI-powered financial analysis, social sentiment trading strategies, and modern full-stack development with Next.js↗ Bright Coding Blog 15. It's trending because it solves a genuinely hard problem—transforming unstructured social noise into structured, actionable intelligence—while demonstrating production-grade patterns that developers can learn from and extend.

What makes this particularly valuable is its educational transparency. Unlike black-box trading bots, every step is visible. You watch the AI think through its reasoning in real-time. You see exactly which social metrics influenced each signal. You control the entire pipeline.

The tech stack reflects serious architectural decisions: Next.js 15 with React Server Components for performance, TypeScript for type safety, Inngest for reliable background processing, Supabase for real-time PostgreSQL↗ Bright Coding Blog, and Tailwind CSS↗ Bright Coding Blog v4 for rapid UI development. This isn't a weekend hack—it's a blueprint for production AI applications.


Key Features That Separate This From Toy Projects

Let's dissect what makes this agent genuinely powerful:

🚀 Real-Time Progress Tracking

Most AI demos feel like black boxes—you click a button and wait, hoping something happens. This agent exposes its entire thought process. A 7-step workflow streams live updates: Initialize Analysis (14%) → Prepare Symbol List (28%) → Fetch Social Data (42%) → AI Signal Generation (57%) → Save to Database (71%) → Generate Summary (85%) → Complete Analysis (100%). Each percentage point represents actual infrastructure work, not fake loading animations.

🧠 AI-Powered Signals with Structured Reasoning

Google Gemini doesn't just spit out "BUY BTC." It generates structured outputs including signal type (BUY/SELL/HOLD), confidence scores (0-100), detailed reasoning explaining the social patterns detected, and underlying metrics that influenced the decision. This audit trail is crucial for trust and iterative improvement.

📊 Unique Social Metrics from LunarCrush

The agent leverages metrics unavailable on standard platforms: AltRank™ (proprietary market + social ranking), Galaxy Score™ (0-100 asset health indicator), creator diversity (unique content creators as anti-manipulation signal), and interaction velocity (engagement momentum). These aren't vanity metrics—they're specifically designed for sentiment-driven trading.

⚡ Background Processing Without UI Blocking

Inngest handles the heavy lifting asynchronously. Users trigger analysis and immediately receive a job ID. The workflow continues server-side while the dashboard subscribes to real-time updates. This pattern scales: add more symbols, more complex AI prompts, or additional data sources without degrading user experience.

💾 Live Database Subscriptions

Supabase's real-time PostgreSQL subscriptions push updates to connected clients instantly. No WebSocket management. No polling loops. The frontend simply subscribes to row-level changes and React re-renders automatically.

🎨 Production-Grade Dashboard

Loading states, error boundaries, progress animations, and responsive design come standard. This is interview-portfolio quality work that demonstrates full-stack competence.

🔔 Optional Discord Alerts

Extend signals beyond the dashboard with webhook notifications for immediate action.


Real-World Use Cases Where This Agent Dominates

Scenario 1: The Meme Coin Squeeze

A celebrity tweets about a obscure token. Within minutes, LunarCrush detects exploding mention volume and creator diversity. The agent's AI recognizes the pattern: rapid social acceleration + low prior engagement = potential pump. It generates a BUY signal with confidence 78%, noting "unusual creator influx suggests organic virality rather than coordinated bot campaign." You enter before the 300% candle.

Scenario 2: The Stealth Bear Trap

Price charts look bullish, but social sentiment is quietly deteriorating. Galaxy Score™ drops from 85 to 62 while interactions plateau. The agent flags SELL with confidence 82%: "Decoupling of price action and social engagement historically precedes corrections." Traditional technical analysts miss this divergence.

Scenario 3: Portfolio Rebalancing Automation

Run the agent hourly across your watchlist. When Bitcoin's AltRank™ improves relative to Ethereum, receive a HOLD→BUY rebalancing signal with confidence-weighted position sizing suggestions. Document the reasoning for tax and compliance records.

Scenario 4: Sentiment Arbitrage Detection

Cross-reference LunarCrush social data with on-chain metrics. When social sentiment is euphoric but exchange inflows spike (smart money distributing), the agent's reasoning captures this contradiction: "Social metrics suggest FOMO; on-chain data suggests distribution. SELL with reduced confidence 65%."


Step-by-Step Installation & Setup Guide

Prerequisites

Before starting, ensure you have:

  • Node.js 18+ installed (node --version to verify)
  • Basic React/TypeScript familiarity
  • 20 minutes for complete setup
  • 5 API keys (detailed below)

Quick Start (5 Minutes for Experienced Developers)

# 1. Clone and install
git clone https://github.com/danilobatson/ai-trading-agent-gemini.git
cd ai-trading-agent-gemini
npm install

# 2. Copy environment template
cp .env.example .env.local

# 3. Add your 5 required API keys (see detailed setup below)
# Edit .env.local with your keys

# 4. Set up database tables via Supabase SQL Editor
# Copy SQL schema from README → paste and run

# 5. Start development servers
npm run dev          # Next.js app → localhost:3000
npm run inngest:dev  # Inngest dev server → localhost:8288

Detailed API Setup

LunarCrush API (Social Data Engine)

# Sign up at lunarcrush.com/signup
# Choose Individual plan for testing, Builder for production
# Generate key at lunarcrush.com/developers/api/authentication

Add to .env.local:

LUNARCRUSH_API_KEY=lc_your_key_here

Critical insight: The Individual plan allows 10 requests/minute, 2,000/day. For multi-symbol analysis, implement delays or upgrade to Builder (100 req/min, 20,000/day).

Google Gemini AI (Signal Generation Brain)

# Visit aistudio.google.com
# Create project → API Keys → Create API Key
# Free tier: 15 requests/minute, 1,500/day

Add to .env.local:

GOOGLE_GEMINI_API_KEY=your_gemini_key_here

Supabase (Real-Time Database)

# supabase.com → Start your project
# Name: ai-trading-agent
# Save database password securely
# Region: closest to your users

From Project Overview, copy:

NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key_here

Database Schema Creation

In Supabase SQL Editor, execute:

-- AI Trading Agent Database Schema

-- Stores AI-generated trading signals with full audit trail
CREATE TABLE trading_signals (
  id TEXT PRIMARY KEY,
  symbol TEXT NOT NULL,
  signal TEXT NOT NULL CHECK (signal IN ('BUY', 'SELL', 'HOLD')),
  confidence INTEGER NOT NULL CHECK (confidence >= 0 AND confidence <= 100),
  reasoning TEXT NOT NULL,  -- Human-readable AI explanation
  metrics JSONB NOT NULL,   -- Raw LunarCrush data for verification
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Performance indexes for fast queries
CREATE INDEX idx_trading_signals_symbol ON trading_signals (symbol);
CREATE INDEX idx_trading_signals_created_at ON trading_signals (created_at DESC);
CREATE INDEX idx_trading_signals_signal ON trading_signals (signal);

-- Tracks background job progress for real-time UI
CREATE TABLE analysis_jobs (
  id TEXT PRIMARY KEY,
  status TEXT NOT NULL DEFAULT 'started',
  current_step TEXT DEFAULT 'Initializing...',
  step_message TEXT DEFAULT 'Starting analysis...',
  progress_percentage INTEGER DEFAULT 0,
  event_data JSONB,         -- Flexible metadata for each step
  signals_generated INTEGER DEFAULT 0,
  alerts_generated INTEGER DEFAULT 0,
  duration_ms INTEGER,      -- Total execution time
  started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  completed_at TIMESTAMP WITH TIME ZONE,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Indexes for job monitoring queries
CREATE INDEX idx_analysis_jobs_status ON analysis_jobs (status);
CREATE INDEX analysis_jobs_progress_idx ON analysis_jobs (status, started_at DESC, progress_percentage);

Inngest (Background Workflow Engine)

# inngest.com → Sign up → Create app: ai-trading-agent
# Settings → Keys: copy Event Key and Signing Key

Add to .env.local:

INNGEST_EVENT_KEY=inngest_your_event_key_here
INNGEST_SIGNING_KEY=signkey_your_signing_key_here

Final Environment Verification

Your .env.local must contain exactly:

# LunarCrush API (Required)
LUNARCRUSH_API_KEY=lc_your_key_here

# Google Gemini AI (Required)
GOOGLE_GEMINI_API_KEY=your_gemini_key_here

# Supabase Database (Required)
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key_here

# Inngest Background Jobs (Required)
INNGEST_EVENT_KEY=inngest_your_event_key_here
INNGEST_SIGNING_KEY=signkey_your_signing_key_here

REAL Code Examples From the Repository

Let's examine the actual implementation patterns that make this agent tick.

Example 1: Triggering the Analysis Pipeline

The frontend initiates analysis through a simple API call that returns immediately with a job ID:

// src/app/api/trigger/route.ts
// This endpoint kicks off the background workflow without blocking

import { NextResponse } from 'next/server';
import { inngest } from '@/lib/inngest';
import { createJob } from '@/lib/supabase';

export async function POST() {
  // Generate unique job ID for tracking across the entire pipeline
  const jobId = crypto.randomUUID();
  
  // Create initial job record in Supabase
  // Frontend will subscribe to this row for real-time updates
  await createJob({
    id: jobId,
    status: 'started',
    current_step: 'Initializing...',
    progress_percentage: 0,
  });
  
  // Send event to Inngest—returns immediately, processing happens async
  await inngest.send({
    name: 'trading-agent/signal-analysis',
    data: { jobId },  // Pass consistent ID for database correlation
  });
  
  // Return jobId so frontend can subscribe to progress
  return NextResponse.json({ jobId });
}

Why this pattern matters: The API responds in <50ms regardless of how long analysis takes. The user sees immediate feedback while a complex multi-step workflow runs for 30-45 seconds. This is the difference between "fast" and "feels fast."

Example 2: The 7-Step Inngest Workflow

This is the engine that processes everything asynchronously:

// src/functions/signal-analysis.ts
// Core workflow with step-by-step progress tracking

import { inngest } from '@/lib/inngest';
import { fetchLunarCrushData } from '@/lib/lunarcrush';
import { generateSignalWithGemini } from '@/lib/gemini';
import { saveSignal, updateJobProgress } from '@/lib/supabase';

export const signalAnalysis = inngest.createFunction(
  { id: 'signal-analysis' },
  { event: 'trading-agent/signal-analysis' },
  async ({ event, step }) => {
    const { jobId } = event.data;
    const startTime = Date.now();
    
    // Step 1: Initialize (14%)
    await step.run('initialize-analysis', async () => {
      await updateJobProgress(jobId, {
        progress_percentage: 14,
        current_step: 'Initialize Analysis',
        step_message: 'Setting up analysis environment...',
      });
    });
    
    // Step 2: Prepare symbols (28%)
    const symbols = await step.run('prepare-symbols', async () => {
      await updateJobProgress(jobId, {
        progress_percentage: 28,
        current_step: 'Prepare Symbol List',
        step_message: 'Loading target cryptocurrencies...',
      });
      return ['BTC', 'ETH', 'SOL', 'DOGE', 'ADA']; // Configurable
    });
    
    // Step 3: Fetch social data from LunarCrush (42%)
    const socialData = await step.run('fetch-social-data', async () => {
      await updateJobProgress(jobId, {
        progress_percentage: 42,
        current_step: 'Fetch Social Data',
        step_message: 'Retrieving LunarCrush sentiment metrics...',
      });
      // Batch fetch with rate limit awareness
      return await fetchLunarCrushData(symbols);
    });
    
    // Step 4: AI signal generation (57%)
    const signals = await step.run('generate-signals', async () => {
      await updateJobProgress(jobId, {
        progress_percentage: 57,
        current_step: 'AI Signal Generation',
        step_message: 'Google Gemini analyzing social patterns...',
      });
      // Structured output with reasoning
      return await generateSignalWithGemini(socialData);
    });
    
    // Step 5: Save to database (71%)
    await step.run('save-results', async () => {
      await updateJobProgress(jobId, {
        progress_percentage: 71,
        current_step: 'Save to Database',
        step_message: 'Persisting signals with full audit trail...',
      });
      for (const signal of signals) {
        await saveSignal({ ...signal, jobId });
      }
    });
    
    // Step 6: Generate summary (85%)
    const summary = await step.run('generate-summary', async () => {
      await updateJobProgress(jobId, {
        progress_percentage: 85,
        current_step: 'Generate Summary',
        step_message: 'Creating actionable portfolio insights...',
      });
      return generateSummary(signals);
    });
    
    // Step 7: Complete (100%)
    await step.run('complete-analysis', async () => {
      await updateJobProgress(jobId, {
        progress_percentage: 100,
        status: 'completed',
        current_step: 'Complete Analysis',
        step_message: 'Analysis complete! View signals below.',
        completed_at: new Date().toISOString(),
        duration_ms: Date.now() - startTime,
        signals_generated: signals.length,
      });
    });
    
    return { success: true, signalsGenerated: signals.length };
  }
);

Architectural insight: Each step.run() is automatically retried by Inngest if it fails. If LunarCrush is rate-limiting, the fetch step retries with exponential backoff. If Gemini times out, signal generation retries. The entire workflow is durable—interrupt it at 57%, redeploy, and it resumes exactly where it left off.

Example 3: Real-Time Progress Subscription Hook

The frontend uses this custom hook for live updates:

// src/hooks/useJobProgress.ts
// Supabase real-time subscription for live progress

import { useEffect, useState } from 'react';
import { supabase } from '@/lib/supabase';

interface JobProgress {
  status: string;
  current_step: string;
  step_message: string;
  progress_percentage: number;
  signals_generated: number;
}

export function useJobProgress(jobId: string | null) {
  const [progress, setProgress] = useState<JobProgress | null>(null);
  const [isComplete, setIsComplete] = useState(false);
  
  useEffect(() => {
    if (!jobId) return;
    
    // Fetch initial state
    const fetchInitial = async () => {
      const { data } = await supabase
        .from('analysis_jobs')
        .select('*')
        .eq('id', jobId)
        .single();
      if (data) setProgress(data);
    };
    fetchInitial();
    
    // Subscribe to real-time changes on this specific row
    const subscription = supabase
      .channel(`job-${jobId}`)
      .on(
        'postgres_changes',
        {
          event: 'UPDATE',
          schema: 'public',
          table: 'analysis_jobs',
          filter: `id=eq.${jobId}`,
        },
        (payload) => {
          const updated = payload.new as JobProgress;
          setProgress(updated);
          if (updated.status === 'completed') {
            setIsComplete(true);
            subscription.unsubscribe(); // Clean up when done
          }
        }
      )
      .subscribe();
    
    return () => {
      subscription.unsubscribe();
    };
  }, [jobId]);
  
  return { progress, isComplete };
}

Performance note: This uses zero polling. The database pushes updates through persistent WebSocket connections. Scale to 10,000 concurrent users watching different jobs—Supabase handles the connection management automatically.

Example 4: Gemini Integration with Structured Output

// src/lib/gemini.ts
// Forces AI to return parseable, typed responses

import { GoogleGenerativeAI } from '@google/generative-ai';

const genAI = new GoogleGenerativeAI(process.env.GOOGLE_GEMINI_API_KEY!);

export async function generateSignalWithGemini(socialData: any[]) {
  const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
  
  const prompt = `
    Analyze the following cryptocurrency social sentiment data and generate trading signals.
    
    Data: ${JSON.stringify(socialData)}
    
    For each cryptocurrency, provide:
    - signal: exactly "BUY", "SELL", or "HOLD"
    - confidence: integer 0-100
    - reasoning: 2-3 sentences explaining the social pattern detected
    
    Consider: mention velocity, creator diversity, engagement quality, 
    Galaxy Score trends, and AltRank relative positioning.
    
    Respond in valid JSON format.
  `;
  
  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  
  // Parse structured output with fallback
  try {
    return JSON.parse(text);
  } catch {
    // Fallback regex extraction for robustness
    return extractSignalsFromText(text);
  }
}

Advanced Usage & Best Practices

Production Optimization Strategies

Rate Limit Resilience: LunarCrush's Individual plan (10 req/min) is the bottleneck. Implement:

  • Symbol batching with configurable delays between requests
  • Request queuing with priority weights (major coins first)
  • Cached responses for recently-analyzed assets

AI Cost Control: Gemini free tier handles 15 req/min. For scaling:

  • Cache signal patterns for stable market conditions
  • Trigger full analysis only on significant social metric changes
  • Implement tiered analysis: quick HOLD checks vs. deep BUY/SELL reasoning

Database Performance: The included indexes handle thousands of signals. For millions:

  • Partition trading_signals by created_at (monthly)
  • Implement materialized views for dashboard aggregations
  • Archive completed analysis_jobs after 30 days

Security Hardening: Before production:

  • Enable Supabase Row Level Security (RLS)
  • Restrict Inngest webhook endpoints to known IPs
  • Rotate API keys quarterly
  • Never commit .env.local—use Vercel/Vault secrets

Extending the Agent

Multi-Timeframe Analysis: Run hourly, daily, and weekly workflows. Gemini compares: "Hourly social spike contradicts daily downtrend. Reduced confidence SELL."

On-Chain Integration: Merge LunarCrush data with exchange inflows, whale wallet movements, and derivatives funding rates.

Backtesting Framework: Replay historical social data through current prompts to validate signal accuracy before deploying capital.


Comparison with Alternatives

Feature ai-trading-agent-gemini Traditional Trading Bots Social Sentiment SaaS
Open Source ✅ Full code access ❌ Black box ❌ Proprietary
AI Reasoning ✅ Gemini with explanations ❌ Rule-based only ⚠️ Basic NLP
Real-time Progress ✅ Live step tracking ❌ No visibility ⚠️ Limited
Customizable Full stack↗ Bright Coding Blog control ❌ Vendor-locked ⚠️ API-limited
Cost ✅ Free tier viable 💰 Expensive subscriptions 💰 $100-500/month
Learning Value ✅ Modern patterns ❌ None ⚠️ API usage only
Social Metrics Depth ✅ LunarCrush unique metrics ❌ Price-only ⚠️ Generic sentiment

When to choose this: You want to understand, customize, and extend AI trading infrastructure. You're building skills for AI-native fintech roles.

When to choose alternatives: You need instant deployment with zero configuration and have budget for managed services.


FAQ: Developer Concerns Answered

Q: Is this profitable for live trading? A: This is an educational and research tool, not financial advice. Backtest thoroughly, paper trade for months, and never risk capital you can't afford to lose. The value is in learning production AI integration patterns.

Q: Can I use OpenAI/Claude instead of Gemini? A: Absolutely. Swap src/lib/gemini.ts for any provider supporting structured outputs. The prompt engineering and response parsing patterns transfer directly.

Q: How do I handle LunarCrush rate limits with many symbols? A: Implement request queuing with p-limit or native Inngest step delays. Upgrade to Builder plan ($99/month) for 100 req/min. Consider caching strategies for stable assets.

Q: Is Supabase real-time reliable for production? A: Yes, with caveats. For >1000 concurrent subscribers per channel, implement connection pooling or switch to dedicated WebSocket infrastructure. Most trading dashboards don't need that scale.

Q: Can I deploy this without Inngest? A: Technically yes—use Vercel's background functions or AWS Lambda. You'll lose automatic retries, step-level observability, and durable execution. Inngest's free tier handles significant volume.

Q: What about market manipulation and bot swarms? A: LunarCrush's creator diversity metric helps detect coordinated campaigns. The agent's reasoning explicitly flags: "Low creator diversity + high mention volume = potential manipulation. Reduced confidence."

Q: How do I add traditional technical indicators? A: Extend the metrics JSONB column with RSI, MACD, or order book data. Modify the Gemini prompt to weight technical vs. social signals based on your strategy.


Conclusion: Why This Project Matters

The ai-trading-agent-gemini isn't just a trading tool—it's a masterclass in modern AI application architecture. It demonstrates how to combine multiple specialized services into a coherent, observable, and scalable system.

What you'll learn building with this:

  • Durable execution patterns with Inngest for mission-critical workflows
  • Real-time data architecture without polling overhead
  • Structured AI outputs for reliable automation
  • Type-safe full-stack development with Next.js 15

The financial applications are obvious, but these patterns transfer to healthcare (patient monitoring), logistics (shipment tracking), or any domain needing AI-processed data with live progress visibility.

My take? Fork this repository. Break it. Rebuild it with your own data sources. The skills you develop— orchestrating AI workflows, managing real-time state, building observable systems—are exactly what top engineering teams are hiring for in 2024 and beyond.

⭐ Star the repository to support open-source education. Clone it now and start building your AI-native application today.

The future belongs to developers who can bridge AI capabilities with production infrastructure. This is your starting point.

Commentaires 0

Aucun commentaire pour l'instant. Soyez le premier à réagir !

Laisser un commentaire