Skip to content

Hitheshkaranth/OpenTerminalUI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

175 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OpenTerminalUI

OpenTerminalUI logo

The open-source financial terminal for traders, researchers, and quant teams.

Version 0.5.0 Python 3.11 Node 22 FastAPI React 18 TypeScript Vite 6 Docker MIT License

Website | Features | Screenshots | Architecture | Quick Start | Contributing


OpenTerminalUI is a self-hosted, full-stack financial terminal that combines real-time market data, institutional-grade charting, derivatives analytics, portfolio management, and quant research into a single platform. Built with a terminal-style shell interface inspired by Bloomberg and Refinitiv, it delivers professional-grade workflows to anyone with a browser.

Multi-market coverage across NSE, BSE, NYSE, NASDAQ, crypto, commodities, forex, bonds, ETFs, and mutual funds. 70+ technical indicators, multi-panel chart workstations, F&O option chains with live Greeks, backtesting with Model Lab, statistical arbitrage with Pair Trading Lab, portfolio analytics with risk engine, a tool-using AI research agent with multi-agent debate, and an extensible plugin system — all running on your own hardware.

Screenshots

Workspace & Markets

Home Dashboard

Home / Mission Control — market context, AI Market Outlook, portfolio hub, system health, and the full feature launch grid.

Chart Workstation

Multi-panel chart workstation — a 6-chart grid with synchronized crosshairs, 70+ technical indicators, and drawing tools.

Market View

Full-screen market view (AAPL, NASDAQ) — candlestick price action with volume, multi-timeframe, and indicator overlays.

Security Hub (US)

Security Hub for a US name (AAPL) — quotes, fundamentals, price chart, analysis tabs, and the AI Catalyst & Conviction panel.

Security Hub (India)

Security Hub for an Indian name (RELIANCE, NSE) — the same workflow across markets, with India fundamentals and sector context.

Financial Analysis

Financial analysis — income statement, balance sheet, and cash-flow statements with multi-period trends.

F&O Option Chain

Futures & Options (AAPL, US) — live option chain with Greeks, OI build-up, and PCR signals; the same workflow covers NSE F&O.

Commodities

Cross-asset coverage — commodities, forex, crypto, bonds, ETFs, and mutual funds.

Research & Stock Picking

Advanced Screener

Advanced screener with query builder, custom formula engine, composite factor scores, and "why ranked" insights.

Factor Dashboard

Factor Dashboard — multi-factor (Value / Momentum / Quality / Low-Vol) idea lists and ranked picks for US & Indian markets.

News & Sentiment

News & Sentiment with the AI Emotion Indicator powered by a local Gemma model via LM Studio.

Intelligence Timeline

Unified Intelligence Timeline — news, alerts, events, insider activity, earnings, and model signals in one feed.

Portfolio, Risk & Backtesting

Portfolio

Portfolio monitoring — holdings, movement & historical return, risk metrics, and AI Risk Assessment.

Cockpit

Cockpit Priority Stack — a ranked daily brief across portfolio risk, alerts, catalysts, movers, and model signals.

Risk Dashboard

Risk dashboard with statistical risk metrics, factor/exposure heatmaps, and AI Risk Insights powered by Gemma.

Backtesting Lab

Backtesting workspace with strategy presets, execution-profile modeling, performance summary, and AI analysis.

Model Lab

Model Lab — parameter sweeps, walk-forward validation, Monte Carlo robustness, and run leaderboards.

Portfolio Lab

Portfolio Lab — multi-asset portfolio backtests, strategy blends, and correlation analysis.

Watchlist

Watchlists with live quotes, heatmap view, and one-click routing to charts, screener, and backtests.

AI Research Agent

AI Research Agent

The tool-using research agent (Ctrl/Cmd + J) — a screen-aware verdict on AAPL backed by a live snapshot card it fetched itself.

Multi-agent debate

Multi-agent debate — an analyst team (fundamental / sentiment / technical) each returns an evidence-backed verdict, which feeds a bull-vs-bear debate and a portfolio-manager decision.

Strategy Lab agent

Strategy Lab — the agent proposes a strategy, backtests it, changes one variable to iterate, then runs out-of-sample validation and reports an honest verdict (here, "not a validated edge" at p = 0.25).

Features

Terminal Shell

  • GO Bar (Ctrl+G) — Bloomberg-style command bar with symbol lookup and route navigation
  • Command Palette (Ctrl+K) — fuzzy search across 25+ functions, tickers, and natural language queries
  • Function Keys (F1-F9) — rapid workspace switching with Bloomberg-style hotkeys
  • Ticker Tape — rolling market pulse with live quotes across exchanges
  • Theme Engine — Terminal Noir (default), classic, and light themes with custom accent support
  • Desktop & Mobile Layouts — responsive design with persistent workspace framing

Charting & Technical Analysis

  • Multi-Panel Workstation — up to 9 synchronized chart panels with crosshair linking
  • 70+ Technical Indicators — SMA, EMA, RSI, MACD, Bollinger Bands, Keltner, Supertrend, ATR, VWAP, OBV, CMF, Stochastic, CCI, ADX, Donchian, and many more
  • Multi-Timeframe — 1m, 2m, 5m, 15m, 30m, 1h, 4h, 1D, 1W, 1M with extended hours toggle
  • Drawing Tools — persistent annotations with templates, save/restore
  • Volume Profile — VPOC + 70% value area overlay
  • Replay Mode — step through historical price action bar by bar
  • Comparison Overlays — multi-symbol normalized or raw price comparison
  • Alternative Charts — Renko, Kagi, Point & Figure, Line Break
  • Chart Export — PNG, SVG, and CSV data export
  • OpenScript — custom indicator scripting with script library

Equity Research & Security Hub

  • 8-Tab Security Analysis — overview, financials, chart, news/sentiment, ownership, estimates, peers, ESG
  • Fundamental Metrics — P/E, P/B, ROE, ROA, dividend yield, earnings growth, debt ratios
  • Earnings Calendar — historical surprises, upcoming events, guidance tracking
  • Shareholding History — promoter/FII/DII/public breakdown with trend visualization
  • Analyst Estimates — consensus tracking, revisions, and target prices
  • Corporate Actions — splits, dividends, rights, bonuses timeline
  • Peer Comparison — relative valuation matrices across comparable companies
  • Insider Trading Monitor — recent insider trades, per-stock insider activity, top buyers/sellers leaderboard, and cluster-buy detection with minimum insider thresholds
  • Trade Journal — trade logging with equity curve, calendar heatmap, and performance statistics

Advanced Screener

  • Query Builder — custom filters with preset formulas and arithmetic operations
  • Custom Formula Engine — write, save, and share custom formulas with server-side evaluation, formula library with descriptions and categories
  • 15+ Visualization Modes — tables with sparklines, sector treemaps, heatmaps, scatter plots, radar charts, box plots, bubble charts, waterfall charts, RRG quadrants, gauge dials, distribution histograms, stacked area, and comparison bars
  • Multi-Market Scanning — NSE, BSE, NYSE, NASDAQ with technical and fundamental overlays
  • Preset Management — save, load, share, and browse community screens
  • Score-Based Ranking — deterministic scoring with stable ordering and explainable setup detection

Insight-Driven Stock Picking

  • Multi-Factor Composite Scoring — cross-sectional, sector-relative Value / Momentum / Quality / Low-Volatility z-scores combined into a weighted composite rank
  • Ranked Idea Lists — top-quintile picks per market and sector for both US (NYSE/NASDAQ) and Indian (NSE/BSE) universes
  • Factor Dashboard — per-symbol factor radar, factor chips, and conviction scoring with a US/India market toggle
  • Catalyst & Conviction Engine — LLM-extracted sentiment and upcoming catalysts from NSE/BSE and SEC filings, surfaced in the Security Hub
  • Point-in-Time Fundamentals — as-reported fundamental history that removes look-ahead bias from factor and fundamental backtests
  • Why-Ranked Explanations — composite scores, factor chips, and plain-language rationale on screener rows, with one-click routing to chart and backtest

AI Research Agent

  • Conversational Console — a slide-over agent panel (toggle with Ctrl/Cmd + J) that researches and analyzes stocks on demand
  • Tool-Using Agentic Loop — the agent autonomously calls read-only tools — screener, full stock snapshot, multi-ticker compare, and research-knowledge-base search (RAG) — and reasons over the results
  • Screen-Aware Context — defaults to the stock you currently have open and your selected market, so "tell me about this stock" resolves to the right ticker/exchange without re-typing it
  • Multi-Agent Debate Mode — an analyst team (fundamental / sentiment / technical) feeds a bull-vs-bear debate that a portfolio manager resolves into a BUY / HOLD / SELL decision with a conviction score
  • Strategy Lab (idea → tested result loop) — a bounded, read-only research loop that proposes a strategy, backtests it, changes one variable to iterate toward a target metric, then runs mandatory out-of-sample validation (permutation + multi-window robustness) and reports an honest verdict — refusing to call a curve-fit result an edge. Flag-gated and capped on rounds and wall-clock
  • Beautifully Rendered Output — answers render as styled markdown (headings, tables, lists), stock snapshots as crafted cards (logo, price, valuation/quality/growth metrics), and debates as a phase stepper with bull/bear cards and a decision banner with conviction meter
  • Provider-Flexible — runs against OpenRouter, OpenAI, or a local LM Studio model, with an automatic free-model fallback chain and per-phase model routing
  • MCP Server — the read-only agent tools (screener, snapshot, compare, technicals, backtests, research search) are also exposed over the Model Context Protocol for use by external MCP clients
  • Read-Only & Resilient — the agent never places orders or mutates data, and degrades gracefully on rate limits, empty completions, or unavailable data sources

Futures & Options (F&O)

  • Option Chain — full contract listing with live Greeks (Delta, Gamma, Theta, Vega, Rho)
  • IV Analysis — historical and implied volatility tracking, term structure visualization
  • Strategy Builder — multi-leg construction for spreads, butterflies, straddles, strangles
  • OI Analysis — open interest trends, buildup patterns, strike-level concentration
  • PCR Tracking — put-call ratio monitoring with overbought/oversold signals
  • Heatmaps — IV/volume/OI heatmaps across the strike grid
  • Options Flow — unusual activity scanner with volume/OI ratios, premium tracking, heat scores, and bullish/bearish sentiment classification
  • Futures Analytics — term structure, basis analysis, contract specifications
  • Expiry Calendar — contract schedules with roll suggestions

Portfolio & Risk Management

  • Multi-Portfolio CRUD — holdings management with cost basis and transaction tracking
  • Allocation & Attribution — sector allocation charts, contributor/detractor analysis
  • Benchmark Overlay — compare against indices with relative performance metrics
  • Risk Engine — VaR (95%), CVaR, EWMA volatility, rolling correlation, PCA factor exposures
  • Factor Analytics — multi-factor exposure radar, attribution waterfall, rolling factor history, and factor return comparison across market, size, value, momentum, quality, and low-volatility factors
  • Stress Testing — 6 predefined macro scenarios (GFC 2008, COVID 2020, rate shock, INR depreciation, tech rotation, commodity spike), custom shock builder, Monte Carlo simulation, and historical event replay
  • Correlation Deep Dive — correlation matrix, rolling correlation with regime detection, hierarchical clustering with dendrogram, and cross-asset dependency visualization
  • Tax Lot Manager — cost basis tracking across tax lots
  • Dividend Tracker — income tracking with ex-date calendar
  • Paper Trading — virtual trading engine with realistic order fills, slippage modeling, and TCA analytics

Backtesting & Model Lab

  • 16+ Strategy Templates — SMA/EMA crossover, mean reversion, breakout, RSI, MACD, Bollinger Bands, dual momentum, VWAP reversion, Awesome Oscillator, Heikin-Ashi, Parabolic SAR, Dual Thrust, shooting star reversal, and Bollinger W/M patterns
  • Pair Trading Lab — cointegration screening, hedge-ratio estimation, spread z-score diagnostics, half-life analysis, and mean-reversion trade simulations for statistical arbitrage workflows
  • Intraday & Daily Testing — 1m to monthly resolution with session-aware logic
  • Vectorized Engine — NumPy-based computation for fast large-dataset backtests
  • Realistic Execution — slippage, commission, partial fills, latency, and market impact simulation
  • Result Visualization — equity curves, drawdown charts, monthly return heatmaps, rolling Sharpe, 3D parameter surfaces, Monte Carlo paths, trade analysis
  • Walk-Forward Analysis — out-of-sample validation with sliding windows
  • Parameter Sweep — sensitivity analysis across hyperparameter ranges
  • Experiment Tracking — create, run, compare, and promote models through the Model Lab
  • Model Governance — version tracking with code/data hashing, promotion to paper trading
  • Monte Carlo Robustness — trade/return resampling with confidence cones, terminal-wealth distribution, and probability-of-profit
  • Liquidity-Aware Execution — fixed-bps, volume-weighted, and square-root market-impact slippage models with percent-of-volume caps
  • Strategy Tear-Sheets — standardized HTML reports with equity, drawdown, rolling Sharpe, monthly returns, and benchmark overlay
  • Run Leaderboards — sortable Model Lab / Portfolio Lab run comparison by Sharpe, CAGR, max drawdown, turnover, and stability

Portfolio Lab

  • Multi-Asset Backtesting — portfolio-level backtests with up to 200 assets
  • Weighting Modes — equal weight, volatility target, risk parity, momentum, market cap
  • Strategy Blends — combine up to 10 strategies with weighted sum returns
  • Rebalance Scheduling — weekly, monthly, quarterly, or custom frequency
  • Attribution Analysis — top contributors/detractors, worst drawdowns, rebalance log
  • Correlation Matrices — cross-asset cluster analysis

Cockpit, Workspaces & Intelligence

  • Cockpit Priority Stack — a ranked daily brief across portfolio risk, alerts, catalysts, news shocks, top movers, and model signals
  • Unified Intelligence Timeline — news, alerts, events, insider activity, earnings, corporate actions, model signals, and backtest runs in one chronological feed
  • Exposure Heatmaps — sector, factor, currency, and correlation exposure maps across Home, Cockpit, and Risk
  • Workspace Presets — Trader / Quant / PM / Risk / Ops presets that reconfigure dashboards, panels, and quick links
  • Saved Views — capture and restore page, filters, ticker, tabs, columns, and chart layout across major workflows
  • AI Insight Cards — Gemma-powered insights embedded consistently across Home, Cockpit, Screener, Portfolio, and Security Hub, with graceful offline fallback

Cross-Asset & Macro

  • Commodities — energy, metals, agriculture with futures term structure and seasonal analysis
  • Forex — major pairs, cross rates matrix, central bank monitor (Fed, ECB, BoE, BoJ, RBI, and more)
  • Cryptocurrency — full workspace with markets, movers, sectors, DeFi, derivatives, heatmaps, and correlation
  • ETF Analytics — holdings viewer, flow tracker, multi-ETF overlap analysis
  • Mutual Funds — search, comparison, rolling returns, SIP calculator, category rankings, fund overlap
  • Bonds — fixed income yields, spreads, and duration analytics
  • Yield Curve — interactive US Treasury curve with historical comparison and 2s10s inversion detection
  • Economics — global event calendar with impact coding, macro indicators dashboard
  • Sector Rotation — Relative Rotation Graph (RRG) with 12-week trailing momentum paths

Alerts & Breakout Scanner

  • Multi-Condition Alert Builder — compound rules with AND/OR logic, multi-field conditions (price, volume, RSI, MACD, moving averages), and natural-language summary
  • Multi-Channel Delivery — in-app, email, webhook, Slack, and Telegram with per-channel configuration and delivery testing
  • Alert Lifecycle — cooldown periods, expiry dates, max trigger limits, trigger history with deduplication
  • WebSocket Push — real-time desktop notifications on alert trigger
  • Breakout Scanner — automated pattern detection with confidence scoring
  • Alert History — full timeline with delivery status and re-trigger tracking

Operations & Compliance

  • OMS — order management with restricted list enforcement and audit trail
  • Ops Dashboard — feed health monitoring, kill switches, data quality panels
  • Model Governance — model registry, approval workflows, risk limit monitoring
  • Cockpit — executive dashboard aggregating portfolio, signals, risk, and events

News & Sentiment

  • Ticker-Specific News — per-symbol news feed with multi-period filtering, scoped strictly to the selected ticker
  • Sentiment Analysis — bullish/bearish/neutral classification with confidence scores
  • Market-Wide Feed — latest headlines with source attribution and sentiment trends
  • AI Emotion Indicator — per-stock fear/greed gauge powered by a locally hosted Gemma model via LM Studio, surfacing a 0–100 emotion index, dominant emotion (panic → euphoria), emotion mix, and per-article bullish/bearish breakdown
  • Local & Private — LLM sentiment runs entirely on your own machine; gracefully falls back to the lexical/FinBERT engine when LM Studio is offline

Plugin System & Scripting

  • Plugin API — extensible architecture for custom analysis modules
  • Included Plugins — RSI Divergence Scanner, Sector Rotation Monitor, Unusual Volume Detector
  • Python Scripting — sandboxed execution with security-hardened imports
  • OpenScript — chart-based indicator scripting with library and sharing

Real-Time Data

  • Multi-Provider WebSocket — Zerodha Kite (India) and Finnhub (US) real-time ticks
  • Provider Waterfall — automatic failover chain: primary → fallback → error
  • Multi-Level Caching — L1 SQLite + L2 Redis with TTL-based invalidation
  • Candle Aggregation — tick-by-tick to any interval with distributed bar construction
  • Redis Pub/Sub — horizontal scaling for multi-client quote fan-out

Architecture

+---------------------------------------------------+
|                   CLIENT TIER                     |
|   React 18 + TypeScript + Vite + Tailwind CSS    |
|   TanStack Query + Zustand + Lightweight Charts   |
|   Recharts + Three.js + Playwright + Vitest       |
+--------------------------+------------------------+
                           | REST API + WebSocket
+--------------------------+------------------------+
|                   API GATEWAY                     |
|   FastAPI + Uvicorn + JWT Auth + CORS Middleware  |
|   53 Route Modules (Equity, F&O, Backtest, Risk) |
+--------------------------+------------------------+
                           |
+--------------------------+------------------------+
|                  SERVICE LAYER                    |
|   Unified Fetcher + Screener Engine + Model Lab  |
|   Risk Engine + Alert Scheduler + Quote Hub      |
|   Provider Registry + Failover Chain             |
+--------------------------+------------------------+
                           |
+--------------------------+------------------------+
|                 DATA PROVIDERS                    |
|   Zerodha Kite | Finnhub | FMP | Yahoo Finance  |
|   NSEPython (F&O, Corporate Actions)             |
+--------------------------+------------------------+
                           |
+--------------------------+------------------------+
|                  PERSISTENCE                      |
|   SQLite (default) | PostgreSQL 16 (production)  |
|   Redis (cache + pub/sub + sessions)             |
+---------------------------------------------------+

Data Flow

Market data flows through a unified pipeline:

  1. Exchange ticks arrive via WebSocket adapters (Kite, Finnhub)
  2. Quote Hub fans out ticks to connected clients via /api/ws/quotes
  3. Bar Aggregator constructs OHLCV candles at all supported intervals
  4. OHLCV Cache persists bars in SQLite (L1) and Redis (L2)
  5. Unified Fetcher serves chart requests with cache-first, provider-fallback semantics
  6. Chart Engine renders via Lightweight Charts v5 with indicator overlays

Provider Waterfall

Request → L1 Cache (SQLite) → L2 Cache (Redis) → Primary Provider → Fallback Provider → 503
             HIT → return         HIT → return       OK → cache+return    OK → cache+return

System Requirements

Component Minimum Recommended
OS Linux, macOS, Windows 10+ Ubuntu 22.04+ / macOS 13+
CPU 2 cores 4+ cores
RAM 4 GB 8 GB+
Disk 2 GB 10 GB+ (historical data cache)
Display 1280 x 720 1920 x 1080+
Browser Chrome 90+, Firefox 90+, Safari 15+, Edge 90+ Latest Chrome or Firefox

Software Dependencies

Software Version Notes
Docker 20.10+ Required for containerized deployment
Docker Compose v2.0+ Included with Docker Desktop
Python 3.11+ Local development only
Node.js 22+ Local frontend development only
Git 2.30+ For cloning the repository

Quick Start

One command (recommended)

git clone https://github.com/Hitheshkaranth/OpenTerminalUI.git
cd OpenTerminalUI
./install.sh          # macOS / Linux / WSL   (Windows: ./install.ps1)

That's it. The installer detects your host OS (macOS, Linux, WSL, or Windows) and adapts, then:

  • creates a single .env from .env.example,
  • auto-generates strong JWT_SECRET_KEY and CACHE_SIGNING_KEY (no secret errors),
  • auto-generates a unique admin password and seeds an admin account, so there are no login errors on first launch,
  • uses Docker if available, otherwise a local Python + Node setup (auto-detected),
  • launches the app at http://localhost:8000 and prints your login credentials.

Prerequisites: either Docker (Desktop/Engine with the daemon running) or, for the local path, Python 3.11+ and Node 20+. Nothing else to configure.

First login: when the installer finishes it prints something like:

 OpenTerminalUI is ready  ->  http://localhost:8000
   email:    admin@openterminal.local
   password: <generated unique password>

The same credentials are saved in your .env (BOOTSTRAP_ADMIN_EMAIL / BOOTSTRAP_ADMIN_PASSWORD). Change the password after first login. Seeding is skipped automatically once any user exists, so re-running never clobbers data.

Force a mode if you prefer: OTUI_MODE=docker ./install.sh or OTUI_MODE=local ./install.sh.

Stopping / restarting (Docker):

docker compose down        # stop (keeps your data + seeded admin)
docker compose down -v      # stop and wipe the database (fresh start next time)
./install.sh                # start again

Adding API keys (one place, guided)

All keys live in the single repo-root .env. The easiest way to add or update them is the interactive wizard, which shows what each key unlocks:

make keys          # or: ./scripts/setup-keys.sh

All keys are optional — the platform runs on built-in fallback data without them.

Manual alternatives

Docker by hand
cp .env.example .env      # add API keys if you have them
docker compose up --build            # Backend + Frontend + Redis (SQLite)
docker compose --profile postgres up --build   # with PostgreSQL
Local development (hot reload)
# Backend
python3.11 -m venv .venv && source .venv/bin/activate
pip install -r backend/requirements.txt
PYTHONPATH=. uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000

# Frontend (separate terminal)
cd frontend && npm ci && npm run dev
  • Backend API: http://127.0.0.1:8000
  • Frontend dev server: http://127.0.0.1:5173

Environment Variables

The platform runs without API keys using fallback providers. Add keys to unlock full data access:

Variable Purpose
FMP_API_KEY Financial Modeling Prep — US equities, fundamentals, earnings
FINNHUB_API_KEY Finnhub — US real-time WebSocket ticks
KITE_API_KEY Zerodha Kite — India NSE/BSE real-time + historical
KITE_API_SECRET Zerodha Kite secret
KITE_ACCESS_TOKEN Zerodha Kite session token
JWT_SECRET_KEY JWT signing key for authentication (auto-generated by install.sh)
CACHE_SIGNING_KEY Cache integrity signing key (auto-generated by install.sh)
BOOTSTRAP_ADMIN_EMAIL Email for the first-run admin account (default admin@openterminal.local)
BOOTSTRAP_ADMIN_PASSWORD Password for the first-run admin (auto-generated by install.sh; seeding is skipped once any user exists)
DATABASE_URL Database connection (default: SQLite)
REDIS_URL Redis connection for caching and pub/sub
OPENTERMINALUI_CORS_ORIGINS Allowed CORS origins
OPENTERMINALUI_PREFETCH_ENABLED Enable background data prefetch
LM_STUDIO_BASE_URL LM Studio OpenAI-compatible endpoint (default http://localhost:1234/v1; use http://host.docker.internal:1234/v1 from Docker)
LM_STUDIO_MODEL Gemma model id loaded in LM Studio (default google/gemma-4-26b-a4b)
LM_STUDIO_ENABLED Toggle the LLM emotion analysis (default true; falls back to lexical sentiment when off)
OPENROUTER_API_KEY OpenRouter key powering the AI research agent (free :free models work)
AGENT_PROVIDER Agent LLM provider: openrouter | openai | lmstudio (default openrouter)
AGENT_MODEL Primary agent model id (default openai/gpt-oss-20b:free)
AGENT_FALLBACK_MODELS Comma-separated models tried when the primary is rate-limited (429) or unavailable (404)
AGENT_DEBATE_ENABLED Enable multi-agent debate mode in the agent console (default true)

AI News Sentiment with Gemma 4 (LM Studio)

OpenTerminalUI integrates a locally hosted Google Gemma 4 model, served through LM Studio, to power the per-stock AI Emotion Indicator on the News workspace. The model reads recent headlines for a ticker and returns a structured judgement — sentiment, confidence, and a market emotion — which the backend aggregates into a 0–100 fear/greed index, a dominant emotion, an emotion mix, and per-article bullish/bearish signals. All inference runs on your own machine; no news or prompt data leaves your hardware.

How it works

News (DB / Yahoo / Google RSS)
        │
        ▼
backend/services/stock_emotion.py ──▶ backend/services/lm_studio_client.py
   (batch prompt + JSON schema)          (OpenAI-compatible /v1/chat/completions)
        │                                          │
        │                                          ▼
        │                                   LM Studio  ·  Gemma 4
        ▼
GET /api/sentiment/emotion/{ticker}  ──▶  Emotion Indicator (News page)
  • All articles for a ticker are analyzed in a single batched request (large local models are slow — per-article calls would pay the latency N times over).
  • The request uses LM Studio structured output (json_schema) so the model is constrained to valid, parseable JSON.
  • If LM Studio is disabled or unreachable, the feature falls back to the built-in lexical / FinBERT sentiment engine, so the endpoint always returns a result.

Integration procedure

  1. Install LM Studio — download from lmstudio.ai (macOS, Windows, Linux).
  2. Download a Gemma model — in LM Studio's Discover tab, search for and download a Gemma model (e.g. google/gemma-4-26b-a4b, or a smaller Gemma variant for faster responses).
  3. Load the model and start the server — load the model, open the Developer / Local Server tab, and click Start Server. It listens on http://localhost:1234 and exposes the OpenAI-compatible API at /v1.
  4. Note the model id — copy the exact model id shown by LM Studio (visible at http://localhost:1234/v1/models); you will set it as LM_STUDIO_MODEL.
  5. Configure OpenTerminalUI:
    • Local development — add to .env (defaults already point at localhost):
      LM_STUDIO_BASE_URL=http://localhost:1234/v1
      LM_STUDIO_MODEL=google/gemma-4-26b-a4b
      LM_STUDIO_ENABLED=true
    • Docker — the container must reach LM Studio on the host. docker-compose.yml already defaults LM_STUDIO_BASE_URL to http://host.docker.internal:1234/v1 and maps host.docker.internal. Override LM_STUDIO_MODEL via .env if your model id differs.
  6. Restart the backend (or docker compose up -d) so the new settings load.
  7. Verify — open the News workspace, select any ticker, and check the Emotion Indicator badge:
    • Gemma · <model id> — the model is live and analyzing.
    • Lexical fallback — LM Studio was unreachable; the built-in engine was used.

Configuration

Variable Default Purpose
LM_STUDIO_BASE_URL http://localhost:1234/v1 LM Studio OpenAI-compatible endpoint. Use http://host.docker.internal:1234/v1 from Docker.
LM_STUDIO_MODEL google/gemma-4-26b-a4b Model id loaded in LM Studio. Must match exactly.
LM_STUDIO_ENABLED true Master toggle for LLM emotion analysis.
LM_STUDIO_TIMEOUT_SECONDS 240 Per-request timeout for the model call.

These can also be set under app: in config/settings.yaml.

Performance: large models such as gemma-4-26b-a4b are slow on consumer hardware — the first analysis for a ticker can take a minute or more (results are then cached). For a snappier experience, load a smaller Gemma / instruct model in LM Studio and point LM_STUDIO_MODEL at it.

Testing

Backend

PYTHONPATH=. python -m compileall backend
PYTHONPATH=. pytest backend/tests -q --cov=backend --cov-fail-under=45

Frontend

cd frontend
npm run build
npx vitest run

End-to-End

cd frontend
npx playwright install chromium
npm run test:e2e

Gate (all checks)

make gate

Repository Layout

backend/                 FastAPI app, adapters, services, routes, tests
  adapters/              Market data provider adapters
  agent/                 AI research agent: orchestrator, tools, debate roles
  api/routes/            53 route modules (equity, fno, backtest, risk, oms, ...)
  core/                  Unified fetcher, failover, service status
  services/              48 business logic modules
  db/                    SQLAlchemy ORM, migrations, caching
  auth/                  JWT authentication and middleware
  config/                Settings, environment, security
  tests/                 409+ backend tests
frontend/                React + Vite + TypeScript SPA
  src/agent/             AI agent console, SSE client, artifact + markdown UI
  src/pages/             51 page components
  src/components/        UI components, terminal design system
  src/fno/               F&O workspace modules
  src/store/             Zustand state management
  src/__tests__/         234+ unit tests
  tests/e2e/             Playwright E2E specs
plugins/                 Extensible plugin system with examples
docs/                    Wiki, architecture specs, and contributor docs
  site/                  GitHub Pages website
  wiki/                  Getting started, contributing guides
data/                    Local SQLite databases and test fixtures
docker-compose.yml       Container orchestration (backend + Redis + Postgres)
Dockerfile               Multi-stage build (Node builder + Python runtime)
Makefile                 Development commands (setup, test, gate)

Keyboard Shortcuts

Shortcut Action
Ctrl+G GO Bar — symbol lookup and navigation
Ctrl+K Command Palette — fuzzy search across all features
Ctrl+J AI Research Agent — toggle the agent console
F1-F9 Function keys for workspace switching
1-7 Timeframe hotkeys in chart views
Esc Close active panel or dialog

Contributing

We welcome contributions. See CONTRIBUTING.md for the full guide.

  1. Fork the repo and create a branch: feat/your-feature or fix/your-fix
  2. Write tests first (TDD encouraged)
  3. Run make gate to pass all checks
  4. Open a PR with a clear description

License

MIT — free to use, modify, and distribute.

About

OpenTerminalUI — a trading terminal UI for market data, charting, screening, backtesting, and alerts.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors