Better Orders

Real-time orderbook visualizer with time-travel and AI insights

Websitegithub
  • 0 Raised
  • 641 Views
  • 0 Judges

Categories

  • Orderbook Visualizer

Gallery

Description

Real-time Kraken orderbook visualizer with time-travel replay and AI-powered market insights.

⚠️ The Problem

Professional traders face a fundamental challenge: orderbooks move faster than human perception. Traditional interfaces display raw numbers that flicker and change dozens of times per second. When a whale enters the market, when liquidity suddenly evaporates, when spreads spike - these critical events happen and vanish in milliseconds. Traders are left asking "what just happened?" with no way to rewind and analyze. Better Orders solves this by making the invisible visible.


✨ Features

📈 Live Orderbook Heatmap

The core visualization transforms Kraken's orderbook data into an intuitive canvas-based heatmap. Rather than parsing columns of numbers, traders see a color-coded depth map where intensity equals volume. Bright cells indicate deep liquidity; dim cells reveal thin order depth. The bid side glows green, asks pulse red. At a glance, you understand market structure that would take minutes to parse from raw data.

The heatmap renders at 60fps using optimized Canvas API calls with proper retina scaling (devicePixelRatio awareness) for crisp visuals on any display. This isn't a chart library wrapper - it's custom rendering built for orderbook visualization.

⚡ Real-time WebSocket Connection

Better Orders connects directly to Kraken's WebSocket API v2 - no intermediary servers, no delayed data feeds. The connection handles the complete orderbook lifecycle:

  • Initial snapshot subscription with full depth
  • Incremental updates applied in real-time
  • CRC32 checksum validation on every update to guarantee data integrity
  • Automatic reconnection with exponential backoff to handle network interruptions gracefully
  • Support for trading pairs: BTC/USD, ETH/USD, SOL/USD, XRP/USD, MATIC/USD, DOGE/USD, and more.

The checksum implementation follows Kraken's exact specification - removing decimals AND leading zeros from prices/quantities before hashing - ensuring the local orderbook state always matches Kraken's authoritative state.

⏮️ Time Travel & Replay

This is the breakthrough feature. Every 500 milliseconds, Better Orders captures a complete orderbook snapshot and persists it to IndexedDB via Dexie.js. This creates a frame-by-frame history of market microstructure.

The timeline interface provides:

  • Scrubber navigation: drag to any point in recorded history
  • Variable playback speed: 0.5x for detailed analysis, up to 8x for rapid review
  • Play/pause controls: stop at any moment to examine the exact orderbook state
  • 24-hour retention: automatic cleanup prevents storage bloat while keeping a full day of history

When that flash crash happened at 3:47 AM? Rewind and watch it unfold. When someone dumped 500 BTC? Scrub back and see exactly how the orderbook absorbed it. Time travel transforms reactive trading into analytical trading.

🔍 Event Detection System

Better Orders doesn't just record data - it understands it. Three detection algorithms run continuously against the orderbook stream:

Whale Order

  • Single order exceeds 15% of total top-10 volume on either side
  • Severity scales with volume ratio (15% = low, 50%+ = critical)

Spread Spike

  • Current spread exceeds 2x the rolling average spread
  • Severity based on spike magnitude above baseline

Liquidity Gap

  • Price gap greater than 50 basis points detected in orderbook depth
  • Severity proportional to gap size

Detected events appear in a real-time feed with timestamps, event type, and severity indicators. Events are also marked on the timeline as visual indicators - making it trivial to jump directly to interesting market moments during replay.

🤖 AI-Powered Market Insights

When significant events occur, optional AI integration provides instant analysis and context. Configure either OpenAI or Anthropic as your provider, and Better Orders will:

  • Generate real-time commentary on detected whale orders
  • Explain potential market implications of spread spikes
  • Provide context for liquidity gaps based on current market conditions
  • Summarize trading sessions with key events highlighted

The AI doesn't just describe what happened - it interprets why it matters. A whale bid appearing during low-volume hours has different implications than one during peak trading. The AI layer transforms raw event detection into actionable intelligence.

💅 Brutalist Design System

The interface follows brutalist design principles - rejecting decorative elements in favor of pure functional clarity:

  • Typography: Geist Mono throughout - monospace fonts belong in trading terminals
  • Color palette: high-contrast black backgrounds with green/red accents for bid/ask
  • Geometry: zero rounded corners - every element has sharp, deliberate edges
  • Spacing: dense information display - no wasted pixels
  • Components: custom brutal-panel, brutal-button, brutal-input, etc. classes

The aesthetic isn't just stylistic choice - it's functional. High contrast improves readability during long sessions. Sharp edges create clear visual boundaries. Monospace fonts align numbers perfectly. Every design decision serves the trader.


🛠️ Tech Stack

Framework -> Next.js 16 with App Router
Server components, API routes, optimal bundling

UI -> React 19 + Tailwind CSS 4
Latest concurrent features, utility-first styling

State -> Zustand
Minimal boilerplate, perfect for real-time updates

Storage -> Dexie.js (IndexedDB)
Handles thousands of snapshots without blocking UI

Charts -> TradingView Lightweight Charts
Industry-standard price visualization

AI -> Vercel AI SDK
Clean abstraction over OpenAI/Anthropic

Runtime -> Bun
Faster installs, faster dev server


🔮 What's Next?

  • Multi-pair comparison: view multiple orderbooks simultaneously
  • Custom event thresholds: let traders define their own detection parameters
  • Export functionality: download recorded sessions for offline analysis
  • Alert system: push notifications when events occur on watched pairs


🙋 Whys?

Building for a hackathon means making some tradeoffs - optimize for demonstration, but architect for evolution. Every choice optimizes for working demo in limited time while leaving clear paths to production system at scale. Here's why I made the choices I did:


Why IndexedDB Instead of a Backend Database?

All orderbook snapshots persist locally in the browser via IndexedDB (using Dexie.js). Why?

  • Zero infrastructure: no database to provision, no servers to maintain, no API latency
  • Instant setup: clone, install, run. Anyone can demo it immediately
  • Works offline: once data is recorded, replay works, even without internet
  • Privacy-first: your trading analysis stays on your machine

Future evolution: the Dexie.js abstraction makes this trivially extensible. Adding cloud sync is a matter of implementing dexie-cloud or a custom sync adapter. The snapshot format is already serialization-ready - push to PostgreSQL, MongoDB, or a time-series database like TimescaleDB. The architecture doesn't change; only the storage backend does.


Why Direct WebSocket Instead of a Backend Proxy?

The browser connects directly to Kraken's WebSocket API v2. Why?

  • True real-time: zero added latency - data goes straight from Kraken to your screen
  • No server costs: no WebSocket relay server to host and scale
  • Simpler debugging: one connection to monitor, not two

Future evolution: a backend proxy would enable features like cross-device sync, authenticated trading features, aggregating data from multiple users, and rate-limit management. The WebSocket client is already abstracted - swap the connection URL and message handlers to point at your own relay.


Why Zustand Instead of Redux or Context API?

Zustand manages orderbook, timeline, and events state. Why?

  • Minimal boilerplate: define a store in 10 lines, not 50
  • No providers needed: import and use - no context wrapper hierarchy
  • Optimized re-renders: selectors prevent unnecessary component updates
  • Real-time friendly: handles high-frequency updates without batching headaches

Future evolution: Zustand scales cleanly. Add middleware for persistence, devtools, or even state sync. The store structure already separates concerns - each could become its own module in a larger app.


Why AI SDK Instead of direct API calls?

AI insights use the Vercel AI SDK with provider abstraction. Why?

  • Provider flexibility: switch between OpenAI and Anthropic with an env variable - demo with whichever API key is available
  • Streaming built-in: real-time text streaming without manual SSE handling
  • Next.js integration: works perfectly with App Router and Server Actions

Future evolution: add more providers (Gemini, local LLMs via Ollama, etc.), implement conversation memory, or fine-tune prompts based on user preferences. The abstraction layer makes this clean.


Why Client-Side Only?

The entire app runs in the browser. No backend beyond Next.js API routes for AI. Why?

  • Deployable anywhere: Vercel, Netlify, or just bun build and serve static files
  • No ops burden: nothing to monitor, no database to back up, no server to crash

Future evolution: adding a backend unlocks multi-user features, historical data aggregation, and authenticated trading. The current architecture is client-complete - a backend would extend, not replace.

Attachments