agentleFS
longbridgelongbridge/longbridge-terminal/CLAUDE.md

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

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 3 mentionsMar 2026: 2 mentionsApr 2026: 1 mentionMay 2026: 9 mentionsJun 2026: 0 mentionsJul 2026: 0 mentionsAug 2026: 1 mentionSep 2026: 2 mentionsOct 2026: 3 mentionsNov 2026: 1 mention
Dec 2025Jun 2026Nov 2026
Mentions a month of the longbridge/longbridge-terminal repository that our weekly crawl found. There is no adoption data for this file yet.

Who's talking about longbridge/longbridge-terminal

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

14 more on GitHub

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
  1. Very specific:

    Check Cargo.toml / Cargo.lock rather than this list before relying on a version.

    line 18
  2. Very specific:

    After any data-layer or CLI output change, verify correctness by comparing the installed release binary against the local build using the …

    line 125
  3. Distinctive:

    When a change seems to call for a switch:

    line 174
  4. Distinctive:

    If two behaviors are genuinely both required, stop and ask before adding the option — do not add it and let review decide.

    line 177
  5. Distinctive:

    IMPORTANT: All code comments and documentation MUST be written in English only.

    line 204
  6. Distinctive:

    Never: write Chinese or other non-English text in code comments

    line 206
  7. Distinctive:

    Never: use Chinese strings directly in code

    line 207
  8. Very specific:

    Use rust-i18n (t! macro) for all user-facing text and messages

    line 208
  9. Very specific:

    All locale strings should be defined in locales/*.yml files

    line 209
  10. Distinctive:

    Use a prefix to indicate the area of change.

    line 272
  11. Very specific:

    Only use tui: when the diff actually modifies TUI files.

    line 279
  12. Very specific:

    When adding, removing, or modifying any CLI command (in src/cli/), always update all of the following in the same PR:

    line 285
  13. Very specific:

    If ../skills is not available locally, the repository is https://github.com/longbridge/skills (../developers used to hold a copy of these …

    line 295

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

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/openapi main (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::OAuthBuilder in openapi::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 via OAuthBuilder::callback_port())

2. src/openapi/ - OpenAPI Integration Layer

  • 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() - Same, and fires the /v1/quote/cmd beacon; use it at WS-backed CLI quote entry points
    • track_quote_cmd() - Fires the beacon alone; HTTP-backed CLI quote entry points call it directly
    • trade() - Get global TradeContext (for trading operations)
    • Uses OnceLock for global singleton
  • One-shot CLI quote commands do not use the WS QuoteContext: they go through cli::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 through quote_cmd(). The TUI and longbridge serve keep the WS QuoteContext.

3. src/data/ - Data Layer

  • types.rs - Base type definitions
    • Counter - Stock identifier (format: 700.HK, AAPL.US)
    • TradeStatus, Currency, Market - Enum types
    • QuoteData, Candlestick, Depth - Market data structures
  • stock.rs - Stock data structure
    • update_from_quote() - Update from longbridge quote
    • update_from_depth() - Update from longbridge depth
  • stocks.rs - Global stock cache (based on DashMap)
    • STOCKS - Global singleton, provides get(), 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 search
  • quote.rs - Quote queries
  • account.rs - Account information
  • Uses openapi::quote() and openapi::trade()

7. src/widgets/ and src/views/ - UI Components

  • Terminal - Terminal management
  • Search, LocalSearch - Search components
  • Carousel - Carousel component
  • Loading - Loading animation
  • Various popups and navigation components

Data Flow

  1. 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
  2. Initialization: main.rs → openapi::init_contexts() → QuoteContext and TradeContext created with config → Get WebSocket receiver
  3. Subscribe Quotes: app.rs → openapi::quote().subscribe() → longbridge SDK
  4. Receive Push: WebSocket receiver → Parse PushEvent → Update STOCKS cache
  5. 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 run

Code Checks

# Clippy check (project uses strict pedantic rules)
cargo clippy

# Format
cargo fmt

Before every git push or gh pr create, always run both and fix all issues:

cargo fmt && cargo clippy

Verifying 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 json

Pick commands that exercise the modified code paths. Common ones:

Changed areaVerification command
Trade direction / tradeslongbridge trades 700.HK --format json
Kline / AdjustTypelongbridge kline 700.HK --format json
Quote / calc-indexlongbridge calc-index 700.HK --format json
Static infolongbridge 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:

  1. OAuthBuilder::build() loads token from ~/.longbridge/openapi/tokens/<client_id> or starts browser authorization
  2. Token is persisted by the SDK; refresh is automatic (no manual expiry check)

No environment variables or manual configuration required!

Requirements:

Token storage: ~/.longbridge/openapi/tokens/<client_id> (managed by SDK). Use --logout to clear.

Troubleshooting:

# View detailed OAuth flow logs
RUST_LOG=debug cargo run

Convention 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:

  1. 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.
  2. 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_truncation
  • ignored_unit_patterns
  • implicit_hasher
  • missing_errors_doc / missing_panics_doc
  • module_name_repetitions
  • must_use_candidate
  • needless_pass_by_value
  • too_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/*.yml files
  • 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

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

  1. Rate Limiting: Longbridge OpenAPI rate limits to "no more than 10 calls per second"
  2. Token Expiration: The SDK automatically refreshes the access token when needed
  3. CN / Global access points: The .cn and .com endpoints 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_code is 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 (a verification_uri_complete pointing at .cn is valid).

    The one difference is reach: .com can authorize accounts in both data centers, while .cn has no path to the US data center, so it can only authorize AP accounts (Longbridge SG/HK). This is handled server-side — the .cn login page does not offer US accounts — so the CLI needs no detection or fallback for it. Logging in through .com unconditionally 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.

  4. Market Support: Supports Hong Kong, US, and China A-share markets
  5. Testing: Per user instructions, update flow has no test coverage
  6. Logging: Uses tracing library, log files configured via logger::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, settings
  • chore: — 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:

  1. README.md — the <!-- COMMANDS_START --> / <!-- COMMANDS_END --> block
  2. ../skills/skills/longbridge/ — all skill files are maintained in the skills repo; this repo no longer has its own skills/ directory:
    • SKILL.md — quick reference, if the command is common enough to mention
    • references/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.)

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.