TheCryptoPulse Docs
Comprehensive technical reference for the TheCryptoPulse platform — covering system architecture, data pipelines, the AI signal engine, all API endpoints, and deployment infrastructure.
What is TheCryptoPulse?
TheCryptoPulse is an AI-powered prediction market intelligence platform that transforms real-time probability data from Polymarket into structured, actionable trading signals for cryptocurrency markets. Rather than manually monitoring hundreds of prediction markets, the platform continuously ingests, normalizes, and interprets market data through a multi-layer processing pipeline, surfacing high-confidence signals to traders.
The platform bridges two distinct information sources: the decentralized prediction markets on Polymarket — where participants bet real capital on the likelihood of future events — and traditional on-chain market data from CoinMarketCap and CoinGecko. By synthesizing prediction probabilities with technical indicators (RSI, MACD) and market sentiment (Fear & Greed Index), TheCryptoPulse delivers a richer analytical context than either source provides alone.
Signal generation is performed by a Groq-hosted LLaMA 3.3 70B model, fine-tuned via prompt engineering to reason over probability time-series, volume patterns, bid-ask spreads, and time-to-resolution dynamics. The result is classified into four signal types — Bullish, Bearish, Contrarian, and Neutral — each accompanied by a confidence score, rationale, key drivers, and risk factors.
System Architecture
The platform is organized into six discrete processing layers. Each layer has a single responsibility and communicates with adjacent layers through typed interfaces. The architecture is designed for horizontal scalability and can be decomposed into independent microservices if traffic demands grow beyond the current serverless model.
Data Layer
Establishes persistent connections to Polymarket's three API surfaces: Gamma API (market metadata, questions, resolution criteria), Data API (historical OHLC price series), and CLOB API (live order book depth and liquidity). CoinMarketCap and CoinGecko supplement with on-chain price and volume data. Crypto markets are isolated using a keyword-matching filter and the Polymarket tag_slug=crypto taxonomy.
Processing Pipeline
An ingestion pipeline normalizes heterogeneous API responses into a unified internal schema. Derived metrics are computed at this layer: 24h probability change, volume-to-open-interest ratio, bid-ask spread in basis points, and time-to-resolution in hours. Data is cached using Next.js fetch with configurable revalidation windows (30s for live feeds, 5m for aggregates). The pipeline enforces a 2MB response ceiling to prevent Next.js fetch cache overflow errors observed with large Polymarket payloads.
Intelligence Layer
The core of the platform. A structured prompt is assembled from the normalized market data and submitted to Groq's inference API (LLaMA 3.3 70B Versatile). The model returns a JSON object containing signal classification, confidence score (0–100), human-readable rationale, key bullish/bearish drivers, and risk factors. The prompt explicitly instructs the model to reason over probability momentum, volume anomalies, and time-to-resolution decay curves before committing to a classification.
Visualization Layer
TradingView Lightweight Charts render probability time-series for individual markets. Recharts provides supplementary sparklines and probability distribution overlays within the signal cards. The Fear & Greed gauge is a custom SVG arc with smooth interpolation between values. All charts are fully SSR-compatible and hydrate on the client without layout shift.
Application Layer
Built on Next.js 15 with the App Router. Server Components fetch and cache data at build time and on-demand, minimizing client-side waterfall requests. Client Components (marked 'use client') handle interactive state: filters, sort order, per-card timeframe selection, and SWR-based live polling. API routes are Edge-compatible and deployed globally on Vercel's infrastructure.
User Layer
OAuth 2.0 integration with GitHub and Google for frictionless onboarding. Email/password registration with bcrypt hashing provides an alternative for users who prefer not to use social login. Session management uses secure HTTP-only cookies. Future iterations will expose watchlists, saved signals, custom alert thresholds, and notification delivery via webhook or email.
Data Sources & Ingestion
TheCryptoPulse pulls from four external data providers, each serving a distinct role in the analytical pipeline. All requests are made server-side from Next.js API routes to avoid exposing API keys to the client.
Polymarket Gamma API
https://gamma-api.polymarket.comPrimary market data source. Provides event metadata, market questions, resolution criteria, outcomes, and current YES/NO probabilities. Markets are fetched with tag_slug=crypto and sorted by volume descending to surface the most actively traded markets.
questionslugoutcomePricesvolumeNumliquidityendDateactivePolymarket CLOB API
https://clob.polymarket.comOrder book data for bid-ask spread analysis. Provides real-time best-bid, best-ask, and mid-price for each outcome token. Used to assess market efficiency and liquidity depth, which informs signal confidence scoring.
bestBidbestAskspreadmidpointCoinMarketCap REST API v3
https://pro-api.coinmarketcap.comOn-chain price and market cap data for major cryptocurrencies. Provides current price in USD, 24h/7d percentage changes, market dominance, and fully diluted valuation. Requires CMC_API_KEY environment variable.
pricepercent_change_24hpercent_change_7dmarket_capvolume_24hCoinGecko Free API
https://api.coingecko.comOHLC time-series data for technical indicator computation. 14-day daily candles are used for RSI (14-period Wilder smoothing method) and MACD (12/26/9 EMA). No API key required for the free tier, though rate limits apply.
openhighlowclosetimestampAlternative.me Fear & Greed
https://api.alternative.me/fngComposite market sentiment index combining volatility, market momentum, social media volume, Bitcoin dominance, and survey data. Used as a macro overlay on all signal cards. Cached with a 5-minute revalidation window.
valuevalue_classificationtimestampProcessing Pipeline
Raw API responses are transformed through a series of pure functions before reaching the UI. The pipeline is synchronous within each API route and designed to fail gracefully — a missing data source returns null for that field rather than throwing, ensuring partial data is still surfaced to the user.
Technical Indicator Computation
RSI and MACD are computed server-side from CoinGecko OHLC candles using the following algorithms:
function computeRSI(closes: number[], period = 14): number {
const changes = closes.slice(1).map((c, i) => c - closes[i])
let avgGain = changes.slice(0, period)
.filter(x => x > 0).reduce((a, b) => a + b, 0) / period
let avgLoss = changes.slice(0, period)
.filter(x => x < 0).map(Math.abs)
.reduce((a, b) => a + b, 0) / period
for (let i = period; i < changes.length; i++) {
const gain = changes[i] > 0 ? changes[i] : 0
const loss = changes[i] < 0 ? Math.abs(changes[i]) : 0
avgGain = (avgGain * (period - 1) + gain) / period
avgLoss = (avgLoss * (period - 1) + loss) / period
}
const rs = avgGain / avgLoss
return Math.round((100 - 100 / (1 + rs)) * 10) / 10
}function ema(data: number[], period: number): number[] {
const k = 2 / (period + 1)
return data.reduce((acc, val, i) => {
acc.push(i === 0 ? val : val * k + acc[i - 1] * (1 - k))
return acc
}, [] as number[])
}
function computeMACD(closes: number[]) {
const ema12 = ema(closes, 12)
const ema26 = ema(closes, 26)
const macdLine = ema12.map((v, i) => v - ema26[i])
const signal = ema(macdLine.slice(26), 9)
const hist = macdLine.slice(26).map(
(v, i) => v - signal[i]
)
return {
value: hist[hist.length - 1],
direction: hist[hist.length - 1] > 0 ? "bullish" : "bearish"
}
}Market Filtering
Polymarket returns events across all categories. The pipeline applies two filters: primary filter uses tag_slug=crypto at the API level, and a secondary keyword scan over question and description fields covers markets that are categorized differently but are thematically crypto-adjacent (e.g. ETF approvals, CFTC rulings).
Response Size Management
Polymarket event responses can exceed 3.6MB when all nested fields are included. Next.js's fetch cache enforces a hard 2MB ceiling, causing application errors if responses are cached with next: { revalidate }. The pipeline applies a slim() transformation that retains only the 20 fields required by the UI, reducing response size by ~85%. The Polymarket route also uses cache: "no-store" instead of revalidate to completely bypass the cache layer.
AI Signal Engine
Signal generation is the platform's core value proposition. The intelligence layer transforms normalized market data into structured trading signals through a combination of prompt engineering and LLM reasoning.
Model Selection
LLaMA 3.3 70B Versatile via Groq's inference API was selected for three reasons: (1) sub-300ms inference latency at 70B parameter scale, (2) strong performance on structured JSON output tasks without fine-tuning, and (3) a free tier sufficient for development workloads. The model is invoked through the Vercel AI SDK using structured output mode (generateObject), which enforces schema compliance at the SDK level.
Prompt Architecture
The system prompt establishes the model's role as a quantitative analyst specializing in prediction market microstructure. The user prompt is constructed programmatically from the normalized market data and includes probability, volume, spread, time-to-resolution, and recent price action. The model is explicitly instructed to reason step-by-step before committing to a signal classification.
System: You are a quantitative analyst specializing in prediction market microstructure. Analyze the provided market data and return a structured trading signal. User: Market: "Will Bitcoin exceed $100,000 by end of Q2 2025?" Current YES probability: 0.63 24h probability change: +0.04 (+6.8%) Volume (24h): $2,847,293 Open interest: $14,221,000 Vol/OI ratio: 0.20 Bid-ask spread: 1.2 bps Time to resolution: 47 days Fear & Greed Index: 72 (Greed) Technical indicators (BTC): RSI(14): 61.4 — Neutral MACD: Bullish crossover (histogram: +0.0023) 24h price change: +3.2% Classify this signal and provide your reasoning.
API Reference
All API routes are implemented as Next.js Route Handlers. They are server-side only and should be consumed from client components via SWR or from other server components via fetch. All responses are JSON.
/api/polymarket/marketsReturns all active crypto prediction markets from Polymarket, filtered by tag and keyword matching. Markets are slimmed to essential fields to stay within the 2MB response boundary.
Parameters
limitnumberdefault: 100Maximum number of markets to return (capped at 150).Response
[
{
"id": "string",
"question": "string",
"slug": "string",
"eventSlug": "string",
"outcomePrices": "string", // JSON-encoded array
"volumeNum": number,
"volume24hr": number,
"liquidity": number,
"endDate": "ISO 8601",
"active": boolean
}
]/api/signals/analysisGenerates AI-powered trading signal analysis for a given Polymarket market using Groq (LLaMA 3). Interprets probability movements, volume patterns, and time-to-resolution to produce bullish, bearish, contrarian, or neutral signals.
Parameters
marketIdstringrequiredPolymarket market slug or ID.questionstringrequiredThe market question text.probabilitynumberrequiredCurrent YES probability (0–1).volumenumber24h volume in USD.Response
{
"signal": "bullish" | "bearish" | "contrarian" | "neutral",
"confidence": number, // 0–100
"rationale": "string",
"keyDrivers": ["string"],
"riskFactors": ["string"],
"timeframe": "string"
}/api/coinmarketcapFetches top cryptocurrencies by market cap from CoinMarketCap. Returns pricing, volume, market cap, and percentage changes. Requires CMC_API_KEY environment variable.
Parameters
limitnumberdefault: 20Number of coins to return.convertstringdefault: USDQuote currency for pricing.Response
{
"data": [
{
"id": number,
"name": "string",
"symbol": "string",
"quote": {
"USD": {
"price": number,
"volume_24h": number,
"percent_change_24h": number,
"market_cap": number
}
}
}
]
}/api/market-data/[coin]Hybrid endpoint that sources current price from CoinMarketCap and OHLC history from CoinGecko to compute RSI (14-period Wilder smoothing) and MACD (12/26/9 EMA). Falls back gracefully when either source is unavailable.
Parameters
coinstring (path)requiredCoinGecko coin ID (e.g. bitcoin, ethereum, solana).Response
{
"currentPrice": number | null,
"priceChange24h": number | null,
"marketCap": number | null,
"volume24h": number | null,
"rsi": number | null,
"rsiLabel": "Overbought" | "Neutral" | "Oversold" | null,
"macd": "bullish" | "bearish" | null,
"macdValue": number | null,
"sentiment": number | null
}/api/fear-greedFetches the current Crypto Fear & Greed Index from Alternative.me. Cached server-side with a 5-minute revalidation window.
Response
{
"value": number, // 0 (Extreme Fear) – 100 (Extreme Greed)
"classification": "string", // Extreme Fear | Fear | Neutral | Greed | Extreme Greed
"timestamp": "ISO 8601"
}Signal Classification
The platform emits four signal types. Each type has a defined set of emission criteria that the AI model is instructed to evaluate before producing a classification.
Bullish
Emitted when the YES probability is trending upward with supporting volume. The AI identifies patterns consistent with increasing market confidence in the predicted outcome.
Emission Criteria
- YES probability increasing over the past 24–72 hours
- Above-average 24h volume relative to open interest
- Order book liquidity weighted toward the YES side
- Positive momentum on recent price action
Bearish
Emitted when the YES probability is declining or when the NO side is accumulating strength. Indicates decreasing market confidence in the predicted outcome resolving YES.
Emission Criteria
- YES probability declining or stagnant while NO volume rises
- Shrinking open interest signalling position exits
- Bid-ask spread widening on the YES side
- High time-to-resolution with low probability
Contrarian
Emitted when market sentiment appears extreme and potentially mispriced relative to available information. High-risk, high-reward setups where the AI detects overcrowding.
Emission Criteria
- YES probability above 85% or below 15% (extreme readings)
- Volume spike inconsistent with fundamentals
- Divergence between prediction market and broader market sentiment
- Approaching resolution date with binary outcome skew
Neutral
Emitted when the AI determines insufficient signal clarity for a directional call. Used to prevent low-confidence outputs from polluting the signal feed.
Emission Criteria
- Probability change within normal variance bounds
- Insufficient volume for a statistically significant read
- Conflicting indicators across data sources
- Market structure too illiquid for reliable analysis
Authentication
TheCryptoPulse supports three authentication methods. All sessions are managed with secure HTTP-only cookies and are not accessible from JavaScript in the browser.
Google OAuth 2.0
One-click sign-in with your Google account. No password required. Tokens are exchanged server-side and never exposed to the client.
GitHub OAuth
Authenticate with your GitHub account. Useful for developers who want to explore the codebase and contribute while maintaining a linked identity.
Email & Password
Traditional registration with email verification. Passwords are hashed with bcrypt (12 rounds) before storage. Never stored in plaintext.
The authentication UI is complete and ready for integration with a database provider (Supabase, Neon, or PlanetScale). OAuth callback handlers and session token logic are stubbed and await database connection configuration in environment variables.
Deployment & Infrastructure
The platform is designed for zero-configuration deployment on Vercel. The following environment variables must be set before the application will function correctly in a production environment.
CMC_API_KEYCoinMarketCap Pro API key. Required for /api/coinmarketcap and the hybrid /api/market-data routes.
RequiredGROQ_API_KEYGroq Cloud API key. Required for AI signal generation at /api/signals/analysis.
RequiredNEXT_PUBLIC_APP_URLThe canonical URL of the deployment. Used for OAuth redirect URIs and internal fetch calls.
RequiredGITHUB_CLIENT_IDGitHub OAuth App client ID. Register at github.com/settings/developers.
OptionalGITHUB_CLIENT_SECRETGitHub OAuth App client secret.
OptionalGOOGLE_CLIENT_IDGoogle Cloud OAuth 2.0 client ID.
OptionalGOOGLE_CLIENT_SECRETGoogle Cloud OAuth 2.0 client secret.
OptionalExternal Integrations
All external integrations and their current status within the platform.
No API key required. Rate limits apply at ~100 req/min.
No API key required. Provides order book depth.
Requires CMC_API_KEY. 10,000 credits/month on free tier.
No API key required. 10–30 req/min depending on endpoint.
No API key required. Updated daily.
Requires GROQ_API_KEY. Generous free tier for development.
Apache 2.0 license. No API key required.
Enabled via @vercel/analytics package.
Requires GitHub OAuth App registration.
Requires Google Cloud Console setup.
Technology Stack
Framework
Styling
Data Fetching
AI
Market Data
Charting
Deployment