Expand description
§financial-api-rs
面向同花顺官方金融数据服务的异步 Rust
客户端。当前版本覆盖 llms-full.txt 中已经上线的 59 个 REST 端点,统一完成 API Key
注入、HTTP 传输、响应信封解码和业务错误分类。
安装 crates.io 上的 0.1.1 版本:
cargo add financial-api@0.1.1源码与问题跟踪位于 Choi-Jungwoo/financial-api-rs。
§快速开始
设置上游官方约定的环境变量:
export HITHINK_FINANCE_API_KEY='<your-api-key>'然后创建客户端并调用端点:
use financial_api::{Client, Error, SearchQuery, TickerSearchRequest};
#[tokio::main]
async fn main() -> Result<(), Error> {
let client = Client::from_env()?;
let request = TickerSearchRequest::new(SearchQuery::new("贵州茅台")?);
let response = client.tickers_search(&request).await?;
println!("request_id={}", response.request_id());
println!("{:#?}", response.data());
Ok(())
}也可以显式提供 Key,并配置私有部署或测试服务:
use financial_api::{ApiKey, Client, Error};
use std::time::Duration;
fn client() -> Result<Client, Error> {
Client::builder(ApiKey::new("<your-api-key>")?)
.timeout(Duration::from_secs(20))
.build()
}ApiKey 的调试输出始终脱敏,底层 HTTP Header 也被标记为敏感。不要在业务日志中自行输出
原始凭据。
§响应与错误
所有端点先检查统一业务信封。HTTP 200 但 code != 0 会返回 Error::Business,不会被误当
作成功。BusinessError::kind() 提供认证、权限、未找到、数据未就绪、限流和上游不可用等
恢复类别;原始 code、message 与 request_id 仍可读取。
各端点返回 Response<端点数据类型>,例如标的检索返回 Response<TickerData>。响应
结构使用公开 DTO 表达;上游的 null 使用 Option 保留,数组顺序保持不变,不透明游标
使用 Cursor 原样回传:
use financial_api::{Error, TickerData, Response};
fn consume(response: Response<TickerData>) -> Result<(), Error> {
for ticker in &response.data().item {
println!("{} {}", ticker.thscode, ticker.name);
}
Ok(())
}少数上游本身就是动态对象的字段仍使用 JsonValue,但不会把整个普通端点退化为无类型
JSON。全市场导出接口返回 MarketDumpUrl;其中预签名 URL 包装为 SecretUrl,调试输出
不会泄露签名,只有显式调用 expose() 才能取出。
估值端点的十进制数使用 PreciseDecimal 保留 JSON 源数字,不经过二进制浮点转换;可通过
Display 或 as_number() 读取其无损表示。
§领域类型
Thscode表示带市场后缀的完整标的代码。AShareCode进一步限制为六位数字加.SH、.SZ或.BJ。NaturalDate验证YYYY-MM-DD和真实公历日期。UnixMillis拒绝负时间戳。FinancialRange通过枚举让“最近 N 期”和“起止时间”互斥。- 复权、报告频率、基金类型、排行榜周期、排序字段等有限集合均使用枚举。
无损转换实现 From;可能失败的外部文本转换实现 FromStr 或显式构造函数,避免绕过领域
校验。
§已支持范围
| 分组 | 端点数 | 能力 |
|---|---|---|
| 元信息 | 2 | 标的检索、标的列表 |
| A 股 | 22 | 行情、复权、财报、交易日历、竞价、估值、异动、热榜、龙虎榜、涨跌停 |
| A 股指数 | 4 | 同花顺指数目录、成分股、行情快照、历史日线 |
| 基金 | 28 | 资料、持仓、业绩、持有人、经理、公司、财务、诊断、募集、资讯、行情 |
| 全市场导出 | 3 | 十年日 K、近十日日 K、复权因子下载 URL |
SUPPORTED_ENDPOINTS 提供当前编译版本的完整端点名称和路径,可用于能力展示或兼容性检查。
上游文档中明确标为“敬请期待”的 A 股基础信息、指数基础信息/权重,以及按个股反查同花顺 指数归属不在支持范围内。
§开发与验证
工具链和任务统一由 mise.toml 管理:
mise install
mise run fmt
mise run check
mise run clippy
mise run test
mise run doc
mise run doc-test默认测试只使用本地 mock server,不需要网络、真实账号或 API Key。
§契约与边界
- 具体请求参数、字段和错误语义以完整聚合文档与 API 总览为准。
- 本 crate 不缓存、拼接或改写金融数据,也不承诺上游服务的可用性、完整性、延迟和权限。
null不补零;不透明游标原样回传;自然日不会被解释成交易日。- 本软件及示例不构成投资建议。使用上游服务和数据时仍需遵守适用条款。
§许可证
本仓库软件与文档使用 MIT License。该许可证不授予同花顺服务、数据、商标或 其他上游资产的权利。
Structs§
- AShare
Code - Complete target code restricted to the A-share target universe.
- Adjustment
Factor Item - Adjustment
Factors Data - Corporate-action events for one A-share target.
- Anomaly
Item - ApiKey
- Validated API key stored as a sensitive HTTP header value.
- Auction
Benchmark Data - Auction
Benchmark Item - Auction
Snapshot Data - Auction
Snapshot Item - Balance
Sheet Item - Business
Error - A decoded non-zero business result from the response envelope.
- Cash
Flow Statement Item - Client
- Reusable async API client.
- Client
Builder - Builder for optional client-wide transport configuration.
- Compact
Date - Validated Gregorian natural day encoded on the wire as
YYYYMMDD. - Company
Id - Opaque fund-company identifier discovered from fund profile data.
- Concept
Item - Cursor
- Opaque pagination cursor returned by a cursor-paged endpoint.
- Dragon
Tiger Data - Dragon
Tiger Stock Item - Endpoint
Info - A stable name and path for one supported REST capability.
- Financial
Ability - Financial
Indicator - Financial
Indicators Data - Financial
Report - Financial report identifier in
YYYY-[1-4]form. - Financial
Statement Meta - Fields shared by the three listed-company financial statements.
- Fund
Asset Allocation Item - Fund
Balance Sheet Item - Fund
Company Item - Fund
Diagnostics Item - Fund
Dividend Item - Fund
Dividends Data - Fund
Drawdowns Item - Fund
Financial Indicators Item - Fund
Holder Item - Fund
Holding Item - Fund
Holdings Data - Fund
Income Statement Item - Fund
Indicator History Item - Fund
Industry Allocation Item - Fund
Manager Detail Item - Fund
Manager Experience Item - Fund
Manager Performance Item - Fund
Manager Radar Comparison - One manager-versus-peer radar node aligned by category and horizon.
- Fund
Manager Ref - Fund
Manager Style Item - Fund
Market Historical Data - Fund
Market Snapshot Data - Fund
Market Snapshot Item - Fund
NavItem - Fund
News Data - Fund
News Item - Fund
Offering Item - Fund
Portfolio History Item - Fund
Profile Item - Fund
Rate Info - Fund
Report Date Item - Fund
Returns Item - Fund
TopHolder Item - Fund
TopHolders Data - Fund
Trade Rule - Historical
Data - Historical daily price payload.
- HotMoney
Item - HotStock
History Data - HotStock
History Item - HotStock
Item - HotStock
Trend Item - Income
Statement Item - Index
Catalog Item - Index
Constituent Item - Index
Historical Data - Index historical prices include a fixed
nulladjustment field. - Ladder
Board Caps - Ladder
Boards - Ladder
Data - Ladder
Day - Ladder
Stock - Ladder
Window - Limit
Break Item - Limit
Down Item - Limit
UpItem - Manager
Id - Opaque fund-manager identifier discovered from fund profile data.
- Market
Dump Url - Short-lived market dump download authorization.
- Natural
Date - Validated Gregorian natural day serialized as
YYYY-MM-DD. - Page
- Validated pagination for special-data pools.
- Pagination
- Pool
Data - Precise
Decimal - JSON decimal number whose source digits are preserved without binary-float conversion.
- Price
BarItem - One daily OHLCV bar.
- Price
Snapshot Data - A-share or index price snapshot payload.
- Price
Snapshot Item - One latest-price record.
- Report
Type - Fund disclosure report type discovered from a report-dates endpoint.
- Response
- Successful response after the common business envelope has been checked.
- Search
Query - Non-empty search text used for cross-market target lookup.
- Secret
Url - Short-lived presigned URL whose debug representation is always redacted.
- Shanghai
Date Millis - A natural date represented as its
Asia/Shanghaimidnight Unix milliseconds. - Thscode
- Complete target code including its market suffix.
- Ticker
Item - One normalized target-code record.
- Ticker
List Request - Parameters for browsing the target code table.
- Ticker
Search Request - Parameters for target search and cross-market disambiguation.
- Timestamped
Items - A timestamped endpoint payload whose business records are stored in
item. - Trading
DayItem - Unix
Millis - Non-negative Unix timestamp in milliseconds.
- Validation
Error - A request-domain or client configuration value was invalid.
- Valuation
Item - Valuations
Data
Enums§
- Adjustment
- Historical price adjustment convention.
- Anomaly
Tag - A-share anomaly tag.
- Asset
Type - Normalized leaf asset type.
- Auction
Stage - Auction observation stage.
- Business
Error Kind - Stable recovery category for an upstream non-zero business result.
- Daily
Interval - Fixed daily K-line interval returned by fund historical prices.
- Dragon
Tiger Board - Dragon-tiger list board filter.
- Error
- Failures produced while configuring or calling the API.
- Exchange
- Exchange filter supported by the metadata API.
- Financial
Ability Kind - Fixed financial-analysis ability group.
- Financial
Indicator Id - Financial indicator identifier defined by the upstream contract.
- Financial
Period - Financial statement report frequency.
- Financial
Range - Mutually exclusive recent-period or timestamp-range financial query.
- Fiscal
Period - Fiscal period returned by listed-company financial statements.
- Fund
NavType - Fund NAV series selection.
- Fund
Range - Fund NAV history range.
- Fund
Type - Fund target universe.
- Holder
Merge Scope - Holder record merge policy.
- Holder
Record Scope - Actual disclosure scope returned for a fund-holder record.
- HotList
Period - Ranking aggregation period.
- Index
Tag - Tonghuashun index catalog tag.
- Json
Value - Represents any valid JSON value.
- Limit
Break Sort Field - Sort key for the limit-break pool.
- Limit
Down Sort Field - Sort key for the limit-down pool.
- Limit
UpSort Field - Sort key for the limit-up pool.
- Manager
Performance Range - Fund manager performance range.
- Offering
Status - New fund offering subscription state.
- Portfolio
Asset Type - Asset class used in a disclosed fund portfolio.
- Price
Snapshot Selection - Either explicit targets or a page of the complete A-share universe.
- Rank
Trend - Direction of a hot-list rank change.
- Sort
Direction - Sort direction used by paged special-data pools.
Constants§
- SUPPORTED_
ENDPOINTS - Every currently available REST endpoint in the upstream contract.
Type Aliases§
- Anomaly
Data - Balance
Sheets Data - Cash
Flow Statements Data - Fund
Asset Allocation Data - Fund
Balance Sheets Data - Fund
Company Data - Fund
Diagnostics Data - Fund
Drawdowns Data - Fund
Financial Indicators Data - Fund
Holders Data - Fund
Income Statements Data - Fund
Indicator History Data - Fund
Industry Allocation Data - Fund
Manager Detail Data - Fund
Manager Experience Data - Fund
Manager Performance Data - Fund
Manager Style Data - Fund
NavData - Fund
Offerings Data - Fund
Portfolio History Data - Fund
Profile Data - Fund
Report Dates Data - Fund
Returns Data - HotStock
Data - HotStock
Trend Data - Income
Statements Data - Index
Catalog Data - Index
Constituents Data - Limit
Break Data - Limit
Down Data - Limit
UpData - Ticker
Data - Trading
Days Data