Zhiyuan Song
← Home

KLineLens

KLineLens is an open-source K-line structure terminal for intraday and swing trading: multi-timeframe market structure, automatic support/resistance, breakout quality scoring, pre/post-market context, plus a built-in 0DTE options plan state machine and a pluggable strategy framework. Optional GPT-4 / Gemini narratives in English or Chinese.

Repository: github.com/songzhiyuan98/KLineLens

Open-source positioning

For traders and developers, KLineLens stresses data ownership and strategy extensibility.

  • Bring-your-own market data: switch Yahoo Finance, TwelveData, Alpaca, Alpha Vantage, etc. via environment variables; free tiers to start, paid keys when you need reliable volume—no single-vendor lock-in.
  • Code your own strategies: implement modules against a unified strategy interface, register them, and they flow through the terminal UI and API; built-in playbooks and 0DTE are reference implementations—community can add strategies and providers (see CUSTOM_STRATEGY.md, CONTRIBUTING.md).

Why KLineLens

  • Full timeframe stack: 1m/5m intraday through 15m/1h/1d swing; trend / range / chop with confidence.
  • Built-in 0DTE: state-machine-driven same-day options plan at the underlying level—no options-chain quotes required.
  • Pluggable strategies: extend as modules on the same analysis + UI rails.
  • Breakout confirmation: three factors to reduce false breaks—close confirmation, RVOL ≥ 1.8, outcome vs ATR threshold (see engine spec).
  • Optional AI narrative: OpenAI / Google APIs for bilingual commentary.

Core features (summary)

Market structure

Capability Description
Trend Detection Up / down / range + confidence
Auto S/R Zones ATR-based support/resistance with strength
Breakout Quality Multi-factor breakout scoring
Behavior Inference Wyckoff-style: accumulation, distribution, markup probabilities with evidence

Extended hours

Capability Description
Premarket Regime Gap & Go, fill-the-gap, trend continuation, range day, etc.
Key Levels Prior close (YC), premarket high/low (PMH/PML), etc.
Session Awareness Adjust analysis context by session

Languages

Full Chinese UI and AI commentary; English UI and commentary; extend via i18n.

0DTE strategy module (state machine)

Same-day ultra short-dated options planning driven by a state machine; typical path:

WAIT → WATCH → ARMED → ENTER → HOLD → TRIM → EXIT

Output is an underlying-level plan (prices, targets, stops, phases)—usable in MVP without live options-chain feeds.

Hot-swappable data providers

Provider Free tier Volume Setup
Yahoo Finance Relaxed Partial / inconsistent Often no API key
TwelveData ~800 calls/day More reliable Free API key
Alpaca Generous quotas Full Free key
Alpha Vantage ~25 calls/day Full Free key

Suggestion: prove the loop on Yahoo, then switch to TwelveData or similar for better volume-sensitive metrics.

System architecture

MVP uses monorepo + three tiers: Web (Next.js) ↔ API (FastAPI) ↔ Core (pure Python analytics package).

┌─────────────────────────────────────────────┐
│              Next.js Frontend                │
│  Chart · Zones · Strategy · Timeline · AI  │
│  i18n · Settings · Watchlist                 │
└────────────────────┬────────────────────────┘
                     │ REST API + SSE
┌────────────────────▼────────────────────────┐
│              FastAPI Backend                │
│  Analysis Engine (Pure Python call)        │
│  Strategy Layer: Playbook | 0DTE | Custom   │
│  Provider Layer: Yahoo | TwelveData | …    │
└─────────────────────────────────────────────┘

Directory layout (summary)

KLineLens/
├── apps/web/          # Next.js
├── apps/api/          # FastAPI: routes / providers / cache
├── packages/core/     # Pure Python: features, structure, behavior, …
├── docs/
├── infra/             # Docker, etc.
├── MASTER_SPEC.md
└── README.md

Data flow, cache, and state (MVP)

Typical detail-page requests

  1. GET /v1/bars: TTL cache hit skips downstream; miss pulls bars from the provider.
  2. POST /v1/analyze: Core analyze() returns structure/behavior/timeline/playbook reports for the UI panels.

Auto refresh

Frontend re-issues POST /analyze about every 60s; bars may be cached while timeline state compares successive reports server-side to decide whether to emit events.

Storage notes (from architecture doc)

  • Bars: in-process TTL cache in the API (e.g. 60s).
  • Timeline state: MVP in-memory dict (lost on restart); future Redis/DB.
  • Signal evaluations: persisted to apps/api/data/klinelens.db SQLite.
  • Frontend evidence/timeline: localStorage keyed by trading day.

Milestones & MVP acceptance

Phase Contents
M0 Repo bootstrap, web/api/core skeleton, environment wiring
M1 Providers, GET /v1/bars, caching and error handling
M2 Swing, zones, regime, breakout state machine
M3 Behavior probabilities, evidence bundles, stateful timeline, playbook templates
M4 Terminal UI, big search to /t/{ticker}, language setting, 60s refresh
M5 Extended-hours context, 0DTE module, strategy type picker (Playbook / 0DTE)

MVP acceptance checklist

  • Home ticker search navigates to the detail page.
  • 1m candles with zones/signals visible.
  • Behavior probabilities, evidence, timeline, playbook panels visible.
  • Language setting applies globally.
  • docker compose up brings up a working stack.

Pluggable strategies & extensions

Strategy type Description
Playbook Structure-conditioned entries, targets, stops, R:R
0DTE Same-day state-machine plan
Custom Subclass BaseStrategy, implement analyze(snapshot) → StrategySignal, register in settings to appear in UI

Interfaces, state-machine patterns, frontend wiring, and tests live in CUSTOM_STRATEGY.md and ENGINE_SPEC.md.

Quick start (Docker)

Prereq: Docker Desktop installed and running.

git clone https://github.com/songzhiyuan98/KLineLens.git
cd KLineLens
cp .env.example .env
# Edit .env: PROVIDER, API keys, CACHE_TTL, API_PORT, WEB_PORT, etc.

docker compose up -d --build
docker compose ps

Open http://localhost:3000 and enter a ticker (e.g. TSLA, QQQ, SPY).

docker compose down          # stop
git pull && docker compose up -d --build   # update

Local dev (no Docker)

# Terminal 1
cd apps/api && pip install -r requirements.txt
uvicorn src.main:app --reload --port 8000

# Terminal 2
cd apps/web && npm install && npm run dev

Environment variables: docs/CONFIG.md; deployment: docs/DEPLOYMENT.md.

Documentation index (in repo)

Document Contents
ENGINE_SPEC.md Core algorithms
CUSTOM_STRATEGY.md Custom strategy development
API.md REST API
PROVIDER.md Adding data providers
LLM_SPEC.md AI integration
SIM_TRADER_SPEC.md 0DTE state-machine specification

Contributing

PRs welcome: bugs, features, providers, docs, tests, UI, custom strategies. Check Issues first; open a discussion issue for large changes.

  • Branches: feature/…, fix/…, docs/…
  • Commits: Conventional Commits (feat:, fix:, etc.)
  • New provider: implement MarketDataProvider, register factory, update .env.example and docs/PROVIDER.md, add tests
  • Standards: Python type hints + docstrings; explicit TS types; avoid magic numbers; solid errors and tests

Full guide: CONTRIBUTING.md and CLAUDE.md.

Roadmap (public)

  • v0.8 — Extended hours, 0DTE, custom strategies
  • v0.7 — Responsive layout, multilingual
  • v0.6 — Terminal-style UI, AI commentary
  • v1.0 — WebSocket streaming, signal backtests
  • v1.1 — Dark mode, mobile
  • v2.0 — Multi-timeframe linkage, options chain integration

License & disclaimer

License: MIT—personal or commercial use allowed; retain license notices.

For education and information only. The tool applies technical analysis to price/volume data and is not investment advice. Past performance does not guarantee future results. Do your own research and accept trading risk.