finnhub
A comprehensive Rust client for the Finnhub.io financial data API.
Features
- 🚀 Full async/await support with Tokio
- 📊 Extensive API coverage (103/107 endpoints - 96.3%)
- 🔒 Type-safe request and response models
- ⚡ Built-in rate limiting (30 requests/second)
- 🔄 WebSocket support (minimal implementation, feature-gated)
- 🛡️ Comprehensive error handling
- 📝 Well-organized module structure
- 🎯 Zero-copy deserialization where possible
Installation
Add this to your Cargo.toml:
[]
= "0.2.0"
# For WebSocket support
= { = "0.2.0", = ["websocket"] }
Quick Start
use ;
async
Authentication
The library uses header authentication (X-Finnhub-Token) by default for better security. Both header and URL parameter authentication are supported by Finnhub.
use ;
// Default: Header authentication (more secure)
let client = new;
// Alternative: URL parameter authentication
let config = ClientConfig ;
let client = with_config;
API Coverage
Stock Market Data (52/54 endpoints - 96.3%)
- ✅ Quotes & Prices: Real-time quotes, candles (OHLCV), ⚠️ bid/ask [Premium], ⚠️ tick data [Premium]
- ✅ Company Info: Profile, peers, executives, ⚠️ market cap history [Premium]
- ✅ Fundamentals: Financials, metrics, earnings, dividends
- ✅ Estimates: Price targets, recommendations, earnings estimates
- ⚠️ Alternative Data: ESG scores, patents, visa applications, lobbying [Most require Premium]
- ✅ Insider Data: Transactions, ownership, ⚠️ sentiment [Premium]
- ✅ Market Info: Symbols, market status, holidays
Other Markets
- ✅ ETFs (4/4): Profile, holdings, country/sector exposure
- ⚠️ Forex (4/4): Symbols, candles, rates, exchanges [Premium]
- ⚠️ Crypto (4/4): Exchanges, symbols, candles, profile [Premium]
- ⚠️ Bonds (4/4): Profile, price, tick data, yield curve [Premium]
- ⚠️ Mutual Funds (6/6): Profile, holdings, performance, ESG data [Premium]
- ⚠️ Indices (2/2): Constituents, historical constituents [Premium]
Data & Analytics
- ✅ Economic Data (2/2): Economic indicators and codes
- ✅ News (3/3): Market news, company news, sentiment
- ✅ Calendar (3/3): Earnings, economic events, IPO calendar
- ✅ Technical Analysis (3/3): Pattern recognition, support/resistance, aggregate indicators
Miscellaneous
- ✅ Search & Lookup: Symbol search, country metadata
- ✅ Alternative Data: COVID-19, FDA calendar, airline price index
- ✅ Market Analysis: Sector metrics, press releases, technical indicators
- 🚧 AI Features: AI chat (requires POST support)
Advanced Features
- ⚠️ WebSocket: Basic structure only (not production-ready)
- ✅ Rate Limiting: Automatic 30 req/s limit with flexible strategies
- ✅ Error Handling: Typed errors with context and retry helpers
Examples
Stock Market Data
use ;
// Get financials
let financials = client.stock
.financials
.await?;
// Get insider transactions
let insiders = client.stock.insider_transactions.await?;
// Get price target consensus
let target = client.stock.price_target.await?;
println!;
Alternative Data
Many alternative data endpoints require premium API access:
// Social sentiment (available with basic access)
let sentiment = client.stock
.social_sentiment
.await?;
println!;
println!;
// Premium endpoints (require additional access):
// - ESG scores: client.stock().esg("AAPL")
// - Patent applications: client.stock().uspto_patents("NVDA", from, to)
// - Congressional trading: client.stock().congressional_trading("AAPL", None, None)
// - Lobbying data: client.stock().lobbying("AAPL", from, to)
Calendar Events
// Earnings calendar
let earnings = client.calendar
.earnings
.await?;
println!;
// IPO calendar
let ipos = client.calendar
.ipo
.await?;
println!;
News & Sentiment
use NewsCategory;
// Company news with sentiment
let news = client.news.company_news.await?;
// Market-wide news
let market_news = client.news.market_news.await?;
Technical Analysis
// Support and resistance levels
let levels = client.scanner.support_resistance.await?;
// Aggregate technical indicators
let indicators = client.scanner.aggregate_indicators.await?;
println!;
Search & Discovery
// Symbol search
let results = client.misc.symbol_search.await?;
println!;
// Country information
let countries = client.misc.country.await?;
println!;
// FDA calendar
let fda = client.misc.fda_calendar.await?;
println!;
Project Structure
finnhub/
├── src/
│ ├── client.rs # Main client implementation
│ ├── auth.rs # Authentication handling
│ ├── error.rs # Error types
│ ├── rate_limiter.rs # Rate limiting
│ ├── models/ # Response models
│ │ ├── stock/ # Stock models (14 modules)
│ │ ├── forex.rs # Forex models
│ │ ├── crypto.rs # Crypto models
│ │ └── ... # Other market models
│ └── endpoints/ # API endpoint implementations
│ ├── stock/ # Stock endpoints (14 modules)
│ ├── forex.rs # Forex endpoints
│ └── ... # Other endpoints
└── examples/ # Usage examples
Error Handling
The library provides comprehensive error handling:
use Error;
match client.stock.quote.await
Rate Limiting
The client includes built-in rate limiting to comply with Finnhub's API limits:
// Default: 30 requests/second with burst capacity
let client = new;
// For batch processing: 15-second window (450 request burst)
let mut config = default;
config.rate_limit_strategy = FifteenSecondWindow;
let client = with_config;
// Rate limiting is automatic
for symbol in
Production Best Practices
Retry Logic
This library intentionally does not implement automatic retry logic, allowing applications to implement context-aware retry strategies. The library provides helpers to make this easy:
use ;
use Duration;
use sleep;
async
// Usage
let quote = with_retry.await?;
Caching
Response caching is best implemented at the application layer where you understand data freshness requirements:
use Quote;
use HashMap;
use ;
Error Handling
Always handle specific error types appropriately:
match client.stock.quote.await
Concurrent Requests
When making multiple requests, consider rate limits and use concurrency control:
use ;
let symbols = vec!;
// Process 3 symbols concurrently to stay well under rate limit
let quotes: = iter
.map
.buffer_unordered
.collect
.await;
WebSocket Support (Minimal)
Basic WebSocket structure is implemented but requires significant work:
// Requires 'websocket' feature
use ;
let client = new;
let mut stream = client.connect.await?;
// Subscribe to symbols
stream.subscribe.await?;
// Process messages
match stream.next.await?
See examples/websocket_basic.rs for a complete example.
Note: WebSocket support is minimal and not recommended for production use. It lacks:
- Automatic reconnection
- Heartbeat handling
- Convenient subscription methods
- Proper error recovery
Environment Variables
For examples and tests, you can use environment variables:
# .env file
FINNHUB_API_KEY=your_api_key_here
// In your code
dotenv.ok;
let api_key = var
.expect;
Troubleshooting
Common Issues
- 401 Unauthorized: Check your API key is valid and has appropriate permissions
- 429 Rate Limit: You're exceeding 30 requests/second. The client should handle this automatically
- Empty responses: Some endpoints return empty data outside market hours or for invalid symbols
Debug Logging
Enable debug logging to see request details:
RUST_LOG=finnhub=debug
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. See CLAUDE.md for development guidelines and architecture details.
Development Setup
# Clone the repository
# Run tests (requires API key)
FINNHUB_API_KEY=your_key
# Run specific example
FINNHUB_API_KEY=your_key
# Check formatting and lints
Development
This library was developed with assistance from Claude, Anthropic's AI assistant, using the Claude Code development environment. The AI helped with implementation, documentation, and best practices while maintaining human oversight and decision-making throughout the development process.
License
Licensed under either of:
- MIT license (LICENSE-MIT)
- Apache License, Version 2.0 (LICENSE-APACHE)
at your option.