- OKX交易自动化 (okx-auto-position, okx-crypto, okx-exchange) - 交易信号处理 (signal-confirmation-templates, trading-signal-aggregator) - 量化因子挖掘 (quant-factor-mining) - 长桥集成 (longbridge-cli, longbridge-python-sdk) - 六合彩分析 (lottery-hk) - 股息投资 (dividend-investing, dividend-scanner) - 日内交易 (intraday-trading) - 同花顺 (tonghuashun)
18 KiB
name, description
| name | description |
|---|---|
| longbridge-cli | LongPort OpenAPI CLI for market data, account management, orders, and trading/dividend analysis workflows. |
LongBridge CLI (longbridge)
A specialized skill for interacting with the LongPort OpenAPI via the longbridge CLI. This skill handles market data (quotes, candlesticks), account info, and order management.
Transport Options
LongPort can be accessed three ways — choose the one that fits:
| Transport | When to use |
|---|---|
CLI (longbridge) |
Quick terminal queries, simple scripts (this skill) |
Python SDK (longport) |
Complex analysis, automated trading, batch workflows (see longbridge-python-sdk skill) |
| MCP (native Hermes) | AI-agent-first access — tools auto-discover in Hermes (see references/longport-mcp-integration.md) |
For the MCP transport, LongPort uses a two-endpoint architecture: an auth endpoint (/agent) to exchange an auth code for a Bearer token, then the main MCP service at https://mcp.longport.cn. Full flow documented in the reference below.
Usage
All commands should be run with the appropriate environment variables (LONGBRIDGE_APP_KEY, LONGBRIDGE_APP_SECRET, LONGBRIDGE_ACCESS_TOKEN) loaded.
Common Commands
- Quotes:
longbridge quote --json <SYMBOLS>(Get real-time quotes) - Candlesticks:
longbridge candlesticks --json <SYMBOLS>(Get OHLC data) - Account:
longbridge balance --jsonorlongbridge positions --json - Orders:
longbridge orders --json(Today's orders) orlongbridge buy/sell --json <SYMBOLS> <QUANTITY>
Order Placement (做T / Active Trading)
CLI order commands require --price for limit orders and -y to skip interactive confirmation (essential for automation):
# Limit buy
longbridge buy RGTI.US --qty 30 --price 18.50 -y
# Limit sell
longbridge sell RGTI.US --qty 30 --price 20.50 -y
# Check pending orders
longbridge orders --json
# Cancel all orders (or specific ones)
longbridge cancel <ORDER_ID>
Pitfall: longbridge buy/sell without -y hangs in interactive mode. Always use -y in scripts/cron.
T-Trading (做T) Analysis Workflow
做T = buying/selling around an existing position to lower cost basis. Requires high-volatility stocks with 10%+ daily swings.
- Fetch multi-timeframe data via Python SDK (5min, 30min, daily candlesticks)
- Calculate technical indicators: SMA(5/10/20), ATR(14) for volatility, recent support/resistance from highs/lows
- Identify key levels: buy zone (support), sell zone (resistance), breakout/breakdown thresholds
- Deploy monitoring script as cron job (every 10-15 min during market hours)
- Auto-place limit orders when price hits key levels, notify user via chat
Technical analysis snippet (run via execute_code):
from longport import openapi
cfg = openapi.Config.from_env()
ctx = openapi.QuoteContext(config=cfg)
candles = ctx.candlesticks("SYMBOL.US", openapi.Period.Day, 20, openapi.AdjustType.NoAdjust)
closes = [float(c.close) for c in candles]
highs = [float(c.high) for c in candles]
lows = [float(c.low) for c in candles]
sma5 = sum(closes[-5:]) / 5
atr = sum(max(highs[i]-lows[i], abs(highs[i]-closes[i-1]), abs(lows[i]-closes[i-1])) for i in range(-14, 0)) / 14
support = min(lows[-5:])
resistance = max(highs[-5:])
Sell Order Workflow (做T卖出)
When user wants to place a sell order for an existing position:
- Query actual position first —
trade_ctx.stock_positions(), getquantity,cost_price,available_quantity. NEVER guess or use memory. - Fetch candlesticks — 30-day daily for resistance levels, 5-min for intraday context.
- Calculate technical levels — SMA(5/10/20), support/resistance from high/low clusters, psychological round numbers ($20, $21, etc.).
- Present options table — conservative / recommended / aggressive, with projected P&L based on ACTUAL cost basis.
- Ask urgency — "这周要成交吗?" determines how aggressive the price should be. Patient = closer to resistance; urgent = closer to current price.
- Place order — Use
execute_code+ Python SDK,submit_orderwithTimeInForceType.GoodTilCanceledandOutsideRTH.AnyTime. - Report order ID — Always return the order_id so user can track/cancel.
Price selection heuristic (not in a hurry):
- Conservative: next psychological round number above current price
- Recommended: SMA10 or recent consolidation zone midpoint
- Aggressive: SMA20 or prior support-turned-resistance
For intraday margin trading with actionable entry/exit/position sizing, see references/intraday-margin-trading.md.\nFor token refresh automation, see ~/.hermes/scripts/update_longbridge_token.sh — auto-updates all token locations and verifies.\nFor semi-automatic order placement with price monitoring, see references/semi-auto-trading.md.
For VWAP + multi-indicator T-trading panel (scoring system, cron-based auto-orders), see references/vwap-t-trading-panel.md.
For DCA position filtering by dividend yield threshold, see references/dca-yield-filter.md.
Market Analysis Workflows
Watchlist Query (via Python SDK)
The CLI does not support watchlist queries directly. Use longbridge-python-sdk skill instead, or use the execute_code pattern in references/execute-code-pattern.py which reliably loads LONGPORT_* env vars:
from longport import openapi
cfg = openapi.Config.from_env()
ctx = openapi.QuoteContext(config=cfg)
resp = ctx.watchlist() # Returns all groups with securities
Dividend/Yield Analysis
When looking for income-generating assets:
- Identify Target: Determine if the user wants monthly, quarterly, or annual payouts.
- Filter by Stability: Prioritize assets with high stability scores (e.g., Dividend Aristocrats/Kings).
- Group and Sort: Group by frequency (Monthly vs Quarterly) and sort by stability, then yield.
- Contextualize: Provide a clear table or list with enough context (Ticker, Name, Yield, Stability).
Key dividend stocks by frequency:
- Monthly: O (Realty Income), MAIN (Main Street Capital)
- Quarterly: KO (Coca-Cola), PG (Procter & Gamble), and most S&P 500 dividend payers
Market Trend & Professional Analysis
- Identify Asset Class: Stocks or Crypto.
- Select Toolset:
- Stocks: Use
stock-analysisorstock-analysis-agent(Yahoo Finance data) - Crypto/professional trading: Use
longbridgeCLI (this skill) orlongbridge-python-sdk
- Stocks: Use
- Execute Analysis: Run the appropriate tool for real-time or historical data.
- Synthesize: Summarize into actionable insights.
Pitfalls (Analysis-Specific)
- Yield vs. Growth: High yield alone doesn't guarantee returns; always check stability/growth potential.
- Frequency Confusion: Distinguish between monthly and quarterly payouts to match user cash-flow needs.
- Data Source Routing: Stocks →
stock-analysis(Yahoo Finance). Professional trading →longbridge.
Pitfalls
- NEVER fabricate trading data (critical): When asked about positions, costs, prices, or orders, you MUST query the actual data from LongBridge API FIRST before doing any calculations. Do NOT guess, assume, or use stale data from memory/user profile. The user will catch fabricated numbers and lose trust. Always:
trade_ctx.stock_positions()→ get realquantity,cost_price,available_quantity→ then calculate. This applies to cost basis calculations, P&L projections, and sell order sizing. One extra API call is infinitely better than a wrong number. - Missing Symbols: Most quote/candlestick commands require one or more symbols.
- JSON Output: Always use the
--jsonflag for machine-readable data. - Environment Variables: Ensure
.envor shell exports are active before running commands. - Command Syntax: Note that
longbridgeuses a sub-command structure (e.g.,longbridge <command> [OPTIONS] <args>). - Token Expiration (401004):
LONGBRIDGE_ACCESS_TOKENis a dynamic, time-sensitive token stored in bashrc (or.env). It expires and causes401004: token invaliderrors. Fix (preferred): runbash ~/.hermes/scripts/update_longbridge_token.sh NEW_TOKEN— it auto-updates all locations (bashrc, .env, hermes envs) and verifies both CLI and Python SDK. Seereferences/token-refresh.mdfor full workflow. Never rely on a stale cached token. - Freshly-generated token still gets 401004: If a new token (just copied from App) gets 401004, first decode the JWT to verify
expis in the future andakmatches the configured APP_KEY (seereferences/token-refresh.md→ "JWT Verification"). If the JWT is valid but API rejects it, either: (a) wait 30s and retry (propagation delay), (b) re-generate from App (first generation sometimes doesn't register), or (c) try from Web console at https://open.longportapp.com/ (different token type). Do NOT assume the token is wrong — the JWT structure is verifiable independently of the API. - Command Name: The npm-installed CLI is
longbridge(notlonbh,longport, etc.). Verify withnpm list -g | grep longbridge. - Env Var Loading: Variables in bashrc are not visible to child processes via
env | grep. Alwayssource ~/.bashrcin the same shell session before running commands. - Validate Token Before Batch: Before running multi-ticker queries (especially dividend/quote batch calls), run a single-ticker sanity check first:
longbridge quote --json AAPL. A 401004 on a 15-ticker batch wastes time diagnosing which tickers are the problem vs. the token being expired. - 401004 Diagnostic Protocol: When hitting 401004, first distinguish between these scenarios:
- Terminal output shows
...→ That's the tool's secret masking. Verify withpython3 -c "open('/home/openclaw/.bashrc').read().split('LONGBRIDGE_ACCESS_TOKEN=')[1].split()[0]" | wc -c. If length ~1053, the token is intact. - Token was never saved → All files have literal
...placeholders. Ask user to re-generate. - Token expired → error 401003. Run
bash ~/.hermes/scripts/update_longbridge_token.sh NEW_TOKEN. - Fresh token gets 401004 → See pitfall "Freshly-generated token still gets 401004" above. Do NOT iterate through config files one by one — run the script which handles all locations in one call.
- Terminal output shows
- CLI Installation Path: The
longbridgeCLI is installed viauv tool installat~/.local/bin/longbridge. It is NOT in$PATHby default in all sessions. Use the full path~/.local/bin/longbridgeor addexport PATH="$HOME/.local/bin:$PATH"to bashrc. Verify withwhich longbridge || ls ~/.local/bin/longbridge. - CLI Token Masking (Critical - Use Python SDK Instead): The terminal tool's secret-redaction layer masks/truncates environment variable values containing tokens. This causes the
longbridgeCLI to get corrupted tokens → 401004 (token invalid) or 403201 (signature invalid) errors. The Python SDK always works becauseexecute_codescripts read bashrc viaopen()and setos.environprogrammatically, bypassing the terminal layer. Rule: For any order/trade/position operation, always useexecute_code+ Python SDK, neverterminal+ CLI. Quote commands may work via CLI but orders will fail. - "..." in terminal output ≠ placeholder (critical trap): The terminal tool masks secrets in both display AND environment variables. When you run
grep LONGBRIDGE_ACCESS_TOKEN ~/.bashrc, the output showsm_eyJh...jb-keven when the actual file has a complete 1053-char JWT. This is the tool's secret-redaction layer, NOT file corruption. Never conclude a token is truncated from terminal grep output alone. To verify the file truly has a complete token:Trust the user when they say "变量没有占位符" — they can see the file without masking.python3 -c " with open('/home/openclaw/.bashrc') as f: for line in f: if 'LONGBRIDGE_ACCESS_TOKEN' in line and 'export' in line: tk = line.strip().split('=', 1)[1] print(f'Token length: {len(tk)}') # Should be ~1053 " - Signature Invalid (403201): Distinct from 401004 (token expired). Error
403201: signature invalidmeans theLONGBRIDGE_APP_SECRET(orLONGPORT_APP_SECRET) value is wrong, corrupted, or truncated — NOT that the token expired. This commonly happens because of the terminal secret masking above. Fix: use Python SDK instead. - HK stock symbols: Use
.HKsuffix (e.g.,0823.HK,0778.HK). The CLI accepts both0823.HKandHK.0823formats. - Python SDK Env Var Prefix Mismatch: The CLI uses
LONGBRIDGE_*env vars, but the Python SDK (longport) readsLONGPORT_*. When using Python, you must manually map the bashrc vars:os.environ["LONGPORT_APP_KEY"] = config.get("LONGBRIDGE_APP_KEY", "")etc. Seereferences/python-sdk.md. buy/sellrequires-yflag: Without-y, the CLI prompts for confirmation interactively and hangs in scripts/cron. Alwayslongbridge buy SYM --qty N --price P -y.- Read-only mode by default (LONGBRIDGE_TRADE_ENABLED): The CLI defaults to read-only mode.
buy,sell, andcancelcommands fail with当前为只读模式,下单/撤单操作已禁用unlessLONGBRIDGE_TRADE_ENABLED=trueis set. This env var must be exported in~/.bashrcalongside the otherLONGBRIDGE_*vars. Without it, even valid tokens reject order commands. Fix:echo 'export LONGBRIDGE_TRADE_ENABLED=true' >> ~/.bashrcthensource ~/.bashrc. - Python SDK
submit_orderAPI quirks: The enum isopenapi.TimeInForceType(NOTTimeInForce). The function signature issubmit_order(symbol, order_type, side, submitted_quantity, time_in_force, submitted_price=None, ...)— notetime_in_forceis a required positional arg before the optionalsubmitted_price. Correct call:
# Enums reference:
# openapi.OutsideRTH: .AnyTime (pre+regular+post), .Overnight, .RTHOnly, .Unknown
# openapi.TimeInForceType: .Day, .GoodTilCanceled, .GoodTilDate, .Unknown
# openapi.OrderType: .LO (limit), .MO (market), .ELO (enhanced limit), .ALO, .AO, .SLO, etc.
# openapi.OrderSide: .Buy, .Sell, .Unknown
resp = trade_ctx.submit_order(
symbol="RGTI.US",
order_type=openapi.OrderType.LO,
side=openapi.OrderSide.Sell,
submitted_quantity=15,
time_in_force=openapi.TimeInForceType.GoodTilCanceled, # GTC = persists until filled/canceled
submitted_price=21.00,
outside_rth=openapi.OutsideRTH.AnyTime, # pre-market + regular + after-hours
)
SecurityQuoteattributes vary: US quotes fromNasdaq Basicmay lackturnover_rate,amplitudeetc. that HK LV1 provides. Wrap attribute access in try/except or hasattr. Nochange_rateattribute: Calculate change manually:(float(q.last_done) - float(q.prev_close)) / float(q.prev_close) * 100. Available attributes:symbol,last_done,prev_close,open,high,low,timestamp.- Period enum uses underscores:
Period.Min_5notPeriod.Min5. Full list:Min_1,Min_2,Min_3,Min_5,Min_10,Min_15,Min_20,Min_30,Min_45,Min_60,Min_120,Min_180,Min_240,Day,Week,Month,Quarter,Year. - AccountBalance attributes: Has
buy_power,total_cash,net_assets,max_finance_amount,remaining_finance_amount,risk_level,margin_call. NOavailable_cashorfree— usebuy_powerfor available buying power. Confirmed HK LV1 attributes (2026-06-25):high,last_done,low,open,overnight_quote,post_market_quote,pre_market_quote,prev_close,symbol,timestamp. NOchange_rate— compute manually:(last_done - prev_close) / prev_close * 100. Periodenum format: UsePeriod.Min_5(underscore), NOTPeriod.Min5. Full list:Min_1,Min_2,Min_3,Min_5,Min_10,Min_15,Min_20,Min_30,Min_45,Min_60,Min_120,Min_180,Min_240,Day,Week,Month,Quarter,Year.SecurityQuoteattributes vary: US quotes fromNasdaq Basicmay lackturnover_rate,amplitudeetc. that HK LV1 provides. Wrap attribute access in try/except or hasattr.- Position fields:
available_quantity(settled, sellable) vsquantity(total incl unsettled). For T-trading sell, checkavailable_quantityfirst. - Prefer
execute_codeoverterminalfor Python SDK: Theexecute_codesandbox can accessLONGPORT_*vars from the host environment, makingConfig.from_env()work reliably. In contrast,terminal+source ~/.bashrcfrequently fails because env vars get masked/truncated by the terminal tool's secret-redaction layer, producing 403201 or 401004 errors. Workflow: for single-call quick data, useexecute_codewith inline Python +Config.from_env(). For CLI commands, useterminalwithsource ~/.bashrc && longbridge .... - China Mainland Geo-Block (Error 602315): LongPort API blocks trading from mainland China IPs. Error:
"Due to Mainland China regulatory requirements, you are currently located in Mainland China and cannot perform this action."(code 602315). Read-only operations (quotes, positions) may still work. Fix: Use WireGuard VPN via overseas VPS. On-demand scripts (wg-trade,wg-on/off/status) route only trading traffic through VPN. Full setup inlongbridge-python-sdkskill'sreferences/wireguard-proxy-setup.md. - Period enum names: LongPort Python SDK uses
Period.Min_5(notPeriod.Min5),Period.Min_10,Period.Min_15, etc. Always use underscore format. - ONLY CLOSE YOUR OWN POSITIONS (critical): Automated trading systems MUST only close positions that were opened by the same system. Track opened positions in a JSON file (e.g.,
entries.json) withorder_id,shares,entry_price. On close, verifyorder_idexists before executing. Never close user's manual positions. User explicitly stated: "只有你开仓的的你才能平,不是你开的你不能操作".