longbridge-terminal
CLAUDE.md1k starsChanged 7 months agoApache-2.0View on GitHub
A Rust-based CLI (longbridge) that wraps every Longbridge OpenAPI endpoint for scripting, AI-agent tool-calling, and daily trading workflows. Also ships a full-screen TUI for interactive market monitoring. Check Cargo.toml / Cargo.lock rather than this list before relying on a version. - State Management: DashMap, Atomic, RwLock - Thread-safe global state - context.rs - Global context management - init_contexts() - Initialize QuoteContext and TradeContext with OAuth token, returns WebSocket receiver - quote() - Get global QuoteContext (for quotes, subscriptions) - quote_cmd()…
- Commits and pushes
Trending
More talk lately.about the whole repository
Who's talking about longbridge/longbridge-terminal
- @orhun.dev“We're trading from /dev/tty0 from now on 💯 📈 longbridge-terminal — A TUI for stock trading & market …”Bluesky · Feb 27, 2026 · 13 likes
- @sungkim.bsky.social“longbridge-terminal — A TUI for stock trading & market monitoring 🌀 Real-time watchlists, candlestick …”Bluesky · Feb 28, 2026 · 10 likes
- gxcsoccer/volta“研究下 longbridge-terminal,看看是否有可以用的地方”GitHub · Mar 24, 2026 · 1 reactions
- A Hacker News story“Longbridge-Terminal: A TUI trading application based on Longbridge OpenAPI”Hacker News · Feb 27, 2026 · 1 points
- sudosubin/agents.nix“agent-skills.github.longbridge.longbridge-terminal: 0.31.0 → 0.31.1”GitHub · Nov 4, 2026
The biggest 5 of 22 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 22
Talked about on GitHub, Bluesky and Hacker News (22 times).
On GitHub · 19
- Mar 24, 2026研究下 longbridge-terminal,看看是否有可以用的地方 — gxcsoccer/volta1 reaction
- Nov 4, 2026agent-skills.github.longbridge.longbridge-terminal: 0.31.0 → 0.31.1 — sudosubin/agents.nix0 reactions
- Oct 26, 2026agent-skills.github.longbridge.longbridge-terminal: 0.30.0 → 0.31.0 — sudosubin/agents.nix0 reactions
- Oct 14, 2026agent-skills.github.longbridge.longbridge-terminal: 0.28.7 → 0.30.0 — sudosubin/agents.nix0 reactions
- Oct 3, 2026agent-skills.github.longbridge.longbridge-terminal: 0-unstable-2026-03-26 → 0.28.7 — sudosubin/agents.nix0 reactions
14 more on GitHub
- Sep 29, 2026agent-skills.github.longbridge.longbridge-terminal: init at 0-unstable-2026-03-26 — sudosubin/agents.nix0 reactions
- Sep 1, 2026[Request]: longbridge — ScoopInstaller/Main0 reactions
- Aug 14, 2026Add Longbridge agent — agentclientprotocol/registry0 reactions
- May 29, 2026feat: add Longbridge Terminal (Finance & Markets) — composio-community/awesome-agent-clis0 reactions
- May 28, 2026Add cask for longbridge-terminal — Homebrew/homebrew-cask0 reactions
- May 28, 2026Add cask for longbridge-terminal — Homebrew/homebrew-cask0 reactions
- May 27, 2026New package: Longbridge.LongbridgeTerminal version 0.22.1 — microsoft/winget-pkgs0 reactions · 3 comments
- May 26, 2026feat: add longbridge-terminal (AI-native financial markets CLI) — rothgar/awesome-tuis0 reactions · 2 comments
- May 26, 2026feat: add longbridge-terminal (AI-native financial markets CLI) — agarrharr/awesome-cli-apps0 reactions
- May 26, 2026feat: add longbridge-terminal (AI-native financial markets CLI) — rust-unofficial/awesome-rust0 reactions
- May 22, 2026feat(optional-skills/finance): add longbridge — live financial markets skill — NousResearch/hermes-agent0 reactions · 1 comment
- May 8, 2026补充 CLI 这个 PR 里面实现这些功能到 MCP 里面 https://github.com/longbridge/longbridge-terminal/pull/185 — longbridge/longbridge-mcp0 reactions
- Apr 10, 2026feat(cli): Add cli full commands docs. — longbridge/developers0 reactions
- Mar 24, 2026Add market_temperature and capital_flow tools via Longbridge OpenAPI — gxcsoccer/volta0 reactions · 1 comment
On Bluesky · 2
- Feb 27, 2026We're trading from /dev/tty0 from now on 💯 📈 longbridge-terminal — A TUI for stock trading & market monitoring 🌀 Real-time watchlists,… — @orhun.dev13 likes and reposts
- Feb 28, 2026longbridge-terminal — A TUI for stock trading & market monitoring 🌀 Real-time watchlists, candlestick charts & multi-market support… — @sungkim.bsky.social10 likes and reposts · 1 reply
On Hacker News · 1
- Feb 27, 2026Longbridge-Terminal: A TUI trading application based on Longbridge OpenAPI1 point
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
13 rules. About 0 are common, 6 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 18
Check Cargo.toml / Cargo.lock rather than this list before relying on a version.
- Very specific: line 125
After any data-layer or CLI output change, verify correctness by comparing the installed release binary against the local build using the …
- Distinctive: line 174
When a change seems to call for a switch:
- Distinctive: line 177
If two behaviors are genuinely both required, stop and ask before adding the option — do not add it and let review decide.
- Distinctive: line 204
IMPORTANT: All code comments and documentation MUST be written in English only.
- Distinctive: line 206
Never: write Chinese or other non-English text in code comments
- Distinctive: line 207
Never: use Chinese strings directly in code
- Very specific: line 208
Use rust-i18n (t! macro) for all user-facing text and messages
- Very specific: line 209
All locale strings should be defined in locales/*.yml files
- Distinctive: line 272
Use a prefix to indicate the area of change.
- Very specific: line 279
Only use tui: when the diff actually modifies TUI files.
- Very specific: line 285
When adding, removing, or modifying any CLI command (in src/cli/), always update all of the following in the same PR:
- Very specific: line 295
If ../skills is not available locally, the repository is https://github.com/longbridge/skills (../developers used to hold a copy of these …
≈ “Common” is an estimate: at least 1 in 5 of the 26,980 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
A Rust-based CLI (longbridge) that wraps every Longbridge OpenAPI endpoint for scripting, AI-agent tool-calling, and daily trading workflows. Also ships a full-screen TUI for interactive market monitoring.
Core Architecture
Tech Stack
- UI Framework: Ratatui (v0.30) - TUI rendering
- Async Runtime: Tokio (v1.33+) - Async I/O
- ECS Framework: Bevy ECS (v0.11) - Entity-Component-System architecture
- Market SDK: longbridge - Longbridge OpenAPI Rust SDK, tracked as a git dependency on
longbridge/openapimain(dependency alias:longbridge-sdk)
Check Cargo.toml / Cargo.lock rather than this list before relying on a version.
- State Management: DashMap, Atomic, RwLock - Thread-safe global state
Key Modules
1. src/auth.rs - Auth utilities
clear_token()- Clear stored OAuth token (logout). Deletes token file used by the SDK.- OAuth and token refresh are handled by the longbridge SDK: use
longbridge::oauth::OAuthBuilderinopenapi::context::init_contexts(). Token is loaded from~/.longbridge/openapi/tokens/<client_id>or browser flow is started; the SDK auto-refreshes the token. - Local callback server: default port
60355(configurable viaOAuthBuilder::callback_port())
2. src/openapi/ - OpenAPI Integration Layer
context.rs- Global context managementinit_contexts()- Initialize QuoteContext and TradeContext with OAuth token, returns WebSocket receiverquote()- Get global QuoteContext (for quotes, subscriptions)quote_cmd()- Same, and fires the/v1/quote/cmdbeacon; use it at WS-backed CLI quote entry pointstrack_quote_cmd()- Fires the beacon alone; HTTP-backed CLI quote entry points call it directlytrade()- Get global TradeContext (for trading operations)- Uses
OnceLockfor global singleton
- One-shot CLI quote commands do not use the WS
QuoteContext: they go throughcli::quote_http::HttpQuoteApi, which POSTs the gateway's/quote/*HTTP shim and reshapes its proto-JSON into the SDK types. Commands without a shim (market temperature, security list, watchlist, subscriptions, …) call the WS context throughquote_cmd(). The TUI andlongbridge servekeep the WSQuoteContext.
3. src/data/ - Data Layer
types.rs- Base type definitionsCounter- Stock identifier (format:700.HK,AAPL.US)TradeStatus,Currency,Market- Enum typesQuoteData,Candlestick,Depth- Market data structures
stock.rs- Stock data structureupdate_from_quote()- Update from longbridge quoteupdate_from_depth()- Update from longbridge depth
stocks.rs- Global stock cache (based onDashMap)STOCKS- Global singleton, providesget(),mget(),insert(),modify()methods
4. src/app.rs - Application Main Loop
- Uses Bevy ECS to manage app state (
AppState) - Handles UI updates via
mpsc::unbounded_channel - Subscribes to index quotes (HSI, DJI, Shanghai Composite, etc.)
- Integrates search, selection, popup components
5. src/system.rs - System Logic and UI Rendering
- Contains rendering logic for pages (Watchlist, Stock, Portfolio, etc.)
- Handles user input and state transitions
6. src/api/ - API Call Layer
search.rs- Stock searchquote.rs- Quote queriesaccount.rs- Account information- Uses
openapi::quote()andopenapi::trade()
7. src/widgets/ and src/views/ - UI Components
Terminal- Terminal managementSearch,LocalSearch- Search componentsCarousel- Carousel componentLoading- Loading animation- Various popups and navigation components
Data Flow
- Authentication:
main.rs→openapi::init_contexts()→longbridge::oauth::OAuthBuilder::build()(loads token from disk or browser flow) →Config::from_oauth(oauth)→ SDK handles token refresh automatically - Initialization:
main.rs→openapi::init_contexts()→ QuoteContext and TradeContext created with config → Get WebSocket receiver - Subscribe Quotes:
app.rs→openapi::quote().subscribe()→ longbridge SDK - Receive Push: WebSocket receiver → Parse
PushEvent→ UpdateSTOCKScache - UI Rendering: Bevy ECS systems → Read
STOCKS→ Ratatui rendering
Development Commands
Build and Run
# Development build
cargo build
# Release build (with LTO and optimizations)
cargo build --release
# Run
cargo runCode Checks
# Clippy check (project uses strict pedantic rules)
cargo clippy
# Format
cargo fmtBefore every git push or gh pr create, always run both and fix all issues:
cargo fmt && cargo clippyVerifying Changes
After any data-layer or CLI output change, verify correctness by comparing the installed release binary against the local build using the same command and --format json:
# Run both and compare — output should be identical (timestamps may differ for live data)
longbridge <command> <args> --format json
cargo run -- <command> <args> --format jsonPick commands that exercise the modified code paths. Common ones:
| Changed area | Verification command |
| Trade direction / trades | longbridge trades 700.HK --format json |
| Kline / AdjustType | longbridge kline 700.HK --format json |
| Quote / calc-index | longbridge calc-index 700.HK --format json |
| Static info | longbridge static 700.HK --format json |
Configuration
Authentication Method: OAuth 2.0 (longbridge SDK)
The application uses the longbridge SDK's built-in OAuth. On first run:
OAuthBuilder::build()loads token from~/.longbridge/openapi/tokens/<client_id>or starts browser authorization- Token is persisted by the SDK; refresh is automatic (no manual expiry check)
No environment variables or manual configuration required!
Requirements:
- Internet connection
- Browser access
- Longbridge account (register at https://open.longbridge.com)
Token storage: ~/.longbridge/openapi/tokens/<client_id> (managed by SDK). Use --logout to clear.
Troubleshooting:
# View detailed OAuth flow logs
RUST_LOG=debug cargo runConvention Over Configuration
Never introduce a new environment variable, CLI flag, or config option without the user's explicit approval. This holds even when the option looks obviously useful, is opt-in, or defaults to today's behavior.
This project follows convention over configuration: choose the behavior that is right and implement only that. A knob is a permanent widening of the contract — it has to be named, documented, tested, and kept working, and every later change has to keep working across all of its states.
When a change seems to call for a switch:
- Pick the behavior that is correct for the common case, implement only it, and say in the PR why that default is the right one.
- If two behaviors are genuinely both required, stop and ask before adding the option — do not add it and let review decide.
Environment variables are the strictest case: they do not appear in --help, cannot be discovered from the CLI surface, and produce configuration only its author knows about. Do not add one.
Code Style
Clippy Rules
Project uses strict clippy::pedantic rules with the following exceptions:
cast_possible_truncationignored_unit_patternsimplicit_hashermissing_errors_doc/missing_panics_docmodule_name_repetitionsmust_use_candidateneedless_pass_by_valuetoo_many_arguments/too_many_lines
Naming Conventions
- Types use UpperCamelCase
- Functions and variables use snake_case
- Constants use SCREAMING_SNAKE_CASE
Language and Localization
IMPORTANT: All code comments and documentation MUST be written in English only.
- Never write Chinese or other non-English text in code comments
- Never use Chinese strings directly in code
- Use
rust-i18n(t!macro) for all user-facing text and messages - All locale strings should be defined in
locales/*.ymlfiles Example:
// Good: English comment let status = t!("TradeStatus.Normal"); // Use i18n for display text // Bad: Chinese comment // let status = "交易中"; // Never hardcode Chinese strings
Longbridge SDK Reference
Documentation
- Rust SDK: https://github.com/longbridge/openapi (we track the
mainbranch, not a crates.io release) - OpenAPI Full Docs: https://open.longbridge.com/llms-full.txt
- Developer Portal: https://open.longbridge.com
Common API Patterns
// Get quotes
let ctx = crate::openapi::quote();
let quotes = ctx.quote(vec!["700.HK", "AAPL.US"]).await?;
// Subscribe to real-time quotes
ctx.subscribe(&symbols, longbridge::quote::SubFlags::QUOTE).await?;
// Query candlesticks
let klines = ctx.candlesticks("AAPL.US", longbridge::quote::Period::Day, 100, None).await?;
// Submit order
let ctx = crate::openapi::trade();
let opts = longbridge::trade::SubmitOrderOptions::new(
"700.HK",
longbridge::trade::OrderType::LO,
longbridge::trade::OrderSide::Buy,
decimal!(500),
longbridge::trade::TimeInForceType::Day,
);
let order = ctx.submit_order(opts).await?;Important Notes
- Rate Limiting: Longbridge OpenAPI rate limits to "no more than 10 calls per second"
- Token Expiration: The SDK automatically refreshes the access token when needed
CN / Global access points: The
.cnand.comendpoints are access points (CDN-style routing), not separate environments — same user data, same token validation, same API responses, and a token issued by one is accepted by the other (device_codeis shared across them too). Do not treat region as a token-refresh issue, and do not rewrite a server response client-side just because it contains the other region's host (averification_uri_completepointing at.cnis valid).The one difference is reach:
.comcan authorize accounts in both data centers, while.cnhas no path to the US data center, so it can only authorize AP accounts (Longbridge SG/HK). This is handled server-side — the.cnlogin page does not offer US accounts — so the CLI needs no detection or fallback for it. Logging in through.comunconditionally is not an option either: China Mainland networks may be unable to reach it.Access point (
.cn/.com) and data center (x-dc-region: ap|us) remain separate concepts; only the latter determines which US-only APIs are available.- Market Support: Supports Hong Kong, US, and China A-share markets
- Testing: Per user instructions, update flow has no test coverage
- Logging: Uses
tracinglibrary, log files configured vialogger::init()
Skills
For Ratatui-specific questions or when working with TUI components, use the rs-ratatui-crate skill.
Commit and PR Title Conventions
Use a prefix to indicate the area of change. The word after the colon must be capitalized.
cli:— changes to CLI commands (src/cli/) or shared infrastructure (src/openapi/,src/region.rs,src/auth.rs, etc.)tui:— changes that touch TUI-specific code (src/tui/app.rs,src/tui/views/,src/tui/widgets/,src/tui/systems/, etc.)ai:— changes to the AI assistant (src/ai/): the chat runtime, answer parsing, Markdown rendering, widgets, session store, settingschore:— other changes that don't fit the above (e.g. docs, formatting, refactors that don't modify behavior)
Only use tui: when the diff actually modifies TUI files. Changes to shared modules that happen to be triggered by a TUI bug should still use cli: or a more specific prefix.
Example: cli: Add statement export command, tui: Fix quit confirmation dialog, ai: Stop linking currency codes as tickers
Keeping Docs in Sync
When adding, removing, or modifying any CLI command (in src/cli/), always update all of the following in the same PR:
README.md— the<!-- COMMANDS_START -->/<!-- COMMANDS_END -->block../skills/skills/longbridge/— all skill files are maintained in theskillsrepo; this repo no longer has its ownskills/directory:SKILL.md— quick reference, if the command is common enough to mentionreferences/cli/overview.md— CLI overview (features, patterns, notable flags)references/python-sdk//references/rust-sdk/— corresponding SDK reference
Skill files should stay high-level. Defer to the CLI's built-in --help for flag details — do not duplicate help text in skill files.
If ../skills is not available locally, the repository is https://github.com/longbridge/skills
(../developers used to hold a copy of these files; it was deleted as a stale duplicate.)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

