Documentation

ForexFlow is a self-hosted, AI-powered forex trading platform that connects to your OANDA broker account. It gives you a real-time command center for managing positions, automating trades, and analyzing every decision with AI.

Quick Start

Prerequisites

RequirementVersionNotes
Node.js>= 22Download
pnpm>= 10npm install -g pnpm
OANDA account-Free practice account
Cloudflare account-Optional — for TradingView alerts
Anthropic API key-Optional — for AI features

1. Clone and install

git clone https://github.com/bmarshall511/forexflow.git
cd forexflow
pnpm install

2. Generate Prisma client

pnpm --filter @fxflow/db db:generate

3. Configure environment

# Single root env file — no per-app duplicates
cat > .env.local <<'EOF'
DATABASE_URL=file:../../data/fxflow.db
ENCRYPTION_KEY=
NEXT_PUBLIC_DAEMON_REST_URL=http://localhost:4100
NEXT_PUBLIC_DAEMON_URL=ws://localhost:4100
EOF

# Generate an ENCRYPTION_KEY and paste it in
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Both the daemon and the web app read from this single root .env.local.

4. Initialize and start

mkdir -p data
pnpm --filter @fxflow/db db:migrate
pnpm dev

This starts the web app at http://localhost:3000 and the daemon at http://localhost:4100.


Configuration

Daemon Environment Variables

VariableRequiredDefaultDescription
DATABASE_URLYes-Prisma database URL
ENCRYPTION_KEYYes-64-char hex for AES-256-GCM encryption
CF_WORKER_WS_URLNo-Cloudflare Worker WebSocket URL
CF_WORKER_DAEMON_SECRETNo-Worker auth secret
DAEMON_PORTNo4100HTTP + WebSocket port
DAEMON_TRADE_RECONCILE_INTERVALNo120000OANDA sync interval (ms)
DAEMON_PRICE_THROTTLENo500Price broadcast throttle (ms)

Web App Environment Variables

VariableRequiredDefaultDescription
DATABASE_URLYes-Must match daemon's DATABASE_URL
ENCRYPTION_KEYYes-Must match daemon's ENCRYPTION_KEY
NEXT_PUBLIC_DAEMON_REST_URLYeshttp://localhost:4100Daemon REST API URL
NEXT_PUBLIC_DAEMON_URLYesws://localhost:4100Daemon WebSocket URL

Cloudflare Worker (optional)

  1. Copy apps/cf-worker/.dev.vars.example to .dev.vars
  2. Set WEBHOOK_TOKEN and DAEMON_SECRET
  3. Deploy: pnpm --filter @fxflow/cf-worker deploy
  4. Set matching values in daemon env

AI Features (optional)

AI features require an Anthropic API key. Configure at Settings > AI for per-trade analysis or Settings > AI Trader for autonomous scanning. Keys are encrypted at rest using AES-256-GCM.


Monorepo Layout

apps/
  web/           Next.js 15 App Router — frontend + 50+ API routes
  daemons/       Node.js daemon — 13+ subsystems, port 4100
  cf-worker/     Cloudflare Worker + Durable Objects — webhook relay
  mcp-server/    MCP server — Claude Code integration

packages/
  types/         Shared TypeScript contracts (DTOs, WebSocket messages)
  shared/        Pure utilities (market hours, pip math, zone detection)
  db/            Prisma ORM + SQLite, 22+ models, 24 service files

Import Boundaries (strict)

  • apps/* may import from packages/*
  • apps/web must NOT import from apps/daemons or apps/cf-worker
  • packages/* must NOT import from apps/*
  • Keep runtime-specific code out of packages/shared and packages/types

Signal Flow

TradingView Alerts

TradingView Alert
  → Cloudflare Worker (IP validation, dedup, queuing)
    → Daemon WebSocket
      → SignalProcessor (9 safety checks)
        → OANDA order execution

Trade Finder (Zone Scanner)

Scans all configured pairs across timeframes, detects supply/demand zones, scores them on 7 dimensions, and auto-places limit orders when enabled. Dual-path fill detection: event-driven (instant via transaction stream) + periodic fallback polling.

AI Trader (Autonomous Scanner)

Tier 1: Local TA (14 techniques) → candidates
Tier 2: Claude Haiku fast filter → pass/fail
Tier 3: Claude Sonnet deep decision → execute/hold

Real-Time Patterns

The daemon maintains a single WebSocket connection per client. All state updates flow through this connection using typed message envelopes with 50+ discriminated message types.

  • Price ticks are throttled to 500ms to prevent UI thrashing
  • Optimistic updates for trade actions (close, modify)
  • Exponential backoff reconnection (5s initial, 60s max)
  • REST polling fallback when WebSocket is unavailable

Dashboard

The trading command center. Live account balance, equity, margin, and P&L updating over WebSocket. Open positions with sub-second price updates, activity feed, automation status, AI insights, market calendar, and source performance breakdown.

TradingView Automation

Receive TradingView webhook alerts via a Cloudflare Worker relay. 9 safety checks before execution: kill switch, market hours filter, per-instrument cooldowns, max open positions, daily loss circuit breaker, pair whitelist, duplicate detection, connectivity verification, and conflicting position detection. Full signal audit trail and performance statistics.

Trade Finder

An automated supply/demand zone scanner. Detects zones across multiple timeframes using candle classification (leg/base/neutral). Scores on 7 "Odds Enhancers": strength, time, freshness, trend alignment, curve position, profit zone, and commodity correlation. Auto-places limit orders with calculated SL/TP and dual-path fill detection.

AI Trade Analysis

Every trade analyzed by Claude with rich structured context: candle data across 3 timeframes, RSI/ATR/EMA indicators, historical win rate, live news events, correlated pair analysis. Outputs include trade quality score, win probability, risk assessment, and executable conditions that evaluate on every price tick with sub-millisecond latency.

AI Trader

Autonomous 3-tier analysis pipeline. Tier 1 runs 14 local TA techniques across configured pairs. Tier 2 uses Claude Haiku for fast pass/fail filtering. Tier 3 uses Claude Sonnet for deep multi-timeframe analysis with fundamental data, sentiment, and risk assessment. Operating modes: Manual (review all), Semi-Auto (auto-execute high confidence), and Full Auto (fully autonomous). 4 profiles: Scalper, Intraday, Swing, and News.

Remote Access

Access from any device with zero configuration. pnpm dev auto-starts a Cloudflare Quick Tunnel with a random HTTPS URL. PIN authentication with lockout protection, session management, rate limiting. Installable as a PWA on mobile for a native-like experience.


Development Commands

CommandDescription
pnpm devStart all apps in dev mode
pnpm buildProduction build
pnpm lintESLint across workspaces
pnpm typechecktsc --noEmit across workspaces
pnpm testVitest with coverage
pnpm formatPrettier format
pnpm knipFind unused exports/dependencies