### Fundamentals Company Example Source: https://github.com/joaquinbejar/tradier/blob/main/README.md This example demonstrates how to access company fundamentals data using the `Fundamentals` trait. Ensure you have the necessary API credentials and setup. ```Rust use tradier::v1::fundamentals::Fundamentals; #[tokio::main] async fn main() -> Result<(), Box> { let client = tradier::TradierClient::new_from_env(); let company_profile = client.get_company_profile("AAPL").await?; println!("Company Profile: {:#?}", company_profile); let corporate_calendar = client.get_corporate_calendar(None, None).await?; println!("Corporate Calendar: {:#?}", corporate_calendar); let dividend_history = client.get_dividend_history("AAPL").await?; println!("Dividend History: {:#?}", dividend_history); let corporate_actions = client.get_corporate_actions("AAPL").await?; println!("Corporate Actions: {:#?}", corporate_actions); let financial_ratios = client.get_financial_ratios("AAPL").await?; println!("Financial Ratios: {:#?}", financial_ratios); let income_statement = client.get_income_statement("AAPL").await?; println!("Income Statement: {:#?}", income_statement); let balance_sheet = client.get_balance_sheet("AAPL").await?; println!("Balance Sheet: {:#?}", balance_sheet); let cash_flow = client.get_cash_flow("AAPL").await?; println!("Cash Flow: {:#?}", cash_flow); let price_statistics = client.get_price_statistics("AAPL").await?; println!("Price Statistics: {:#?}", price_statistics); Ok(()) } ``` -------------------------------- ### Initialize Tradier Market Session in Rust Source: https://github.com/joaquinbejar/tradier/blob/main/README.md This example demonstrates how to set up the logger, create a configuration, and initialize a MarketSession to interact with the Tradier API. It requires the tokio runtime. ```rust use tradier::config::base::Config; use tradier::utils::logger::setup_logger; use tradier::wssession::market::MarketSession; #[tokio::main] async fn main() -> Result<(), Box> { setup_logger(); let config = Config::new(); let market_session = MarketSession::new(&config).await?; // Use the market_session to interact with the Tradier API Ok(()) } ``` -------------------------------- ### Run Makefile Tasks Source: https://github.com/joaquinbejar/tradier/blob/main/README.md Execute common development tasks such as building, testing, formatting, and linting using the provided Makefile. For example, run tests with `make test`. ```shell make test ``` -------------------------------- ### Retrieve User Profile and Account Data with Blocking Client Source: https://context7.com/joaquinbejar/tradier/llms.txt Utilize the synchronous blocking client for scripts that do not require an async runtime. This example shows fetching user profile, account balances, and positions. ```rust use tradier::Config; use tradier::blocking::{Client, operation::Accounts, operation::User}; fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config)?; // Get user profile let profile = client.get_user_profile()?; println!("User: {:?}", profile.profile.name); // Extract account number from profile let account_number = match &profile.profile.account { tradier::types::OneOrMany::One(account) => &account.account_number, tradier::types::OneOrMany::Many(accounts) => { &accounts.first().expect("at least one account").account_number } }.parse()?; // Get account balances let balances = client.get_account_balances(&account_number)?; println!("Total Equity: {:?}", balances); // Get account positions let positions = client.get_account_positions(&account_number)?; println!("Positions: {:#?}", positions); Ok(()) } ``` -------------------------------- ### Get Option Expirations Source: https://context7.com/joaquinbejar/tradier/llms.txt List all available option expiration dates for a specified symbol. Can include strike prices in the response. ```rust use tradier::Config; use tradier::non_blocking::Client; use tradier::non_blocking::operation::MarketData; use tradier::types::{Symbol, IncludeAllRoots, IncludeStrikes}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config); let symbol: Symbol = "AAPL".parse()?; // Get all available expirations with strike prices let expirations = client.get_option_expirations( &symbol, Some(IncludeAllRoots::new(true)), Some(IncludeStrikes::new(true)), ).await?; println!("Available expirations: {:#?}", expirations); Ok(()) } ``` -------------------------------- ### Stream Market Data via HTTP Chunked Transfer Source: https://github.com/joaquinbejar/tradier/blob/main/README.md This example demonstrates streaming market data over HTTP chunked transfer when WebSockets are not feasible. It reuses the existing REST client's connection pool and handles network and decoding errors gracefully. ```rust,no_run use futures_util::StreamExt; use tradier::non_blocking::Client; use tradier::streaming::http_stream; use tradier::wssession::MarketSession; use tradier::Config; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let rest = Client::new(config.clone()); // Bootstrap a session id the usual way. let session = MarketSession::new(&config).await?; let symbols = ["AAPL".to_string(), "MSFT".to_string()]; let events = http_stream::market_events(&rest, session.get_session_id(), &symbols, None, None, None, None) .await?; futures_util::pin_mut!(events); while let Some(event) = events.next().await { match event { Ok(e) => println!("event: {:?}", e), Err(e) => eprintln!("stream error: {e}"), } } Ok(()) } ``` -------------------------------- ### Get Option Chains with Greeks Source: https://context7.com/joaquinbejar/tradier/llms.txt Retrieve option chain data for a given symbol and expiration date. Optionally include Greeks (delta, gamma, theta, vega) in the response. ```rust use chrono::NaiveDate; use tradier::Config; use tradier::non_blocking::Client; use tradier::non_blocking::operation::MarketData; use tradier::types::{Symbol, Greeks}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config); let symbol: Symbol = "AAPL".parse()?; let expiration = NaiveDate::from_ymd_opt(2024, 6, 21).unwrap(); // Get option chain with Greeks let chains = client.get_option_chains( &symbol, &expiration, Some(Greeks::new(true)), ).await?; println!("Option chains: {:#?}", chains); // Response includes: strike, bid, ask, last, greeks (delta, gamma, theta, vega) Ok(()) } ``` -------------------------------- ### Configure Tradier Client with Environment Variables Source: https://context7.com/joaquinbejar/tradier/llms.txt Configuration is automatically loaded from environment variables. Ensure TRADIER_ACCESS_TOKEN is set. Other variables like TRADIER_CLIENT_ID, TRADIER_REST_BASE_URL, and TRADIER_REST_TIMEOUT can also be configured. ```rust use tradier::Config; // Configuration is loaded automatically from environment variables: // - TRADIER_ACCESS_TOKEN: Your Tradier API access token (required) // - TRADIER_CLIENT_ID: Your client ID // - TRADIER_REST_BASE_URL: API base URL (defaults to production) // - TRADIER_REST_TIMEOUT: Request timeout in seconds (default: 30) // Create config from environment let config = Config::new(); // Or set environment variables in .env file: // TRADIER_ACCESS_TOKEN=your_api_key_here // TRADIER_CLIENT_ID=your_account_id_here // TRADIER_REST_BASE_URL=https://sandbox.tradier.com # For sandbox testing ``` -------------------------------- ### Stream Market Data via WebSocket (Basic) Source: https://context7.com/joaquinbejar/tradier/llms.txt Establishes a WebSocket connection to stream real-time market quotes and trades. Includes automatic reconnection logic in case of connection errors. Ensure the `MarketSessionFilter` is appropriate for the desired data. ```rust use tradier::Config; use tradier::wssession::{MarketSession, MarketSessionFilter, MarketSessionPayload}; use tracing::{info, error}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); loop { match MarketSession::new(&config).await { Ok(market_session) => { info!("Session ID: {}", market_session.get_session_id()); let symbols = ["AAPL".to_string(), "MSFT".to_string()]; let filters = [MarketSessionFilter::QUOTE, MarketSessionFilter::TRADE]; // Build subscription payload let payload = MarketSessionPayload::builder() .symbols(&symbols) .filters(&filters) .session_id(market_session.get_session_id()) .linebreak(true) .valid_only(true) .build(); // Stream events (blocks until connection closes or error) if let Err(e) = market_session.ws_stream(payload).await { error!("Streaming error: {}. Reconnecting...", e); } } Err(e) => { error!("Failed to create session: {}. Retrying...", e); } } tokio::time::sleep(tokio::time::Duration::from_secs(5)).await; } } ``` -------------------------------- ### Build Project with Cargo Source: https://github.com/joaquinbejar/tradier/blob/main/README.md After adding the dependency and setting up credentials, build your Rust project using the cargo build command. ```shell cargo build ``` -------------------------------- ### Set Up Tradier API Credentials Source: https://github.com/joaquinbejar/tradier/blob/main/README.md Configure your Tradier API access token and client ID by creating a .env file in your project's root directory. These credentials are required for authentication. ```dotenv TRADIER_ACCESS_TOKEN=your_api_key_here TRADIER_CLIENT_ID=your_account_id_here ``` -------------------------------- ### Preview Changelog Entries Source: https://github.com/joaquinbejar/tradier/blob/main/README.md Generate a preview of the next changelog entry locally using `git-cliff`. This command helps in visualizing upcoming changes before they are officially released. ```shell git cliff --unreleased ``` -------------------------------- ### Stream Market Data via WebSockets Source: https://github.com/joaquinbejar/tradier/blob/main/README.md Use this snippet to establish a WebSocket connection for streaming real-time market data like quotes and trades. It includes error handling and automatic reconnection logic. ```rust use std::error::Error; use tracing::{error, info}; use tradier::config::base::Config; use tradier::utils::logger::setup_logger; use tradier::wssession::account::AccountSession; use tradier::wssession::market::{MarketSession, MarketSessionFilter, MarketSessionPayload}; #[tokio::main] async fn main() -> Result<(), Box> { setup_logger(); let config = Config::new(); loop { match MarketSession::new(&config).await { Ok(market_session) => { info!( "Market streaming session created with id: {}", market_session.get_session_id() ); let payload = MarketSessionPayload { symbols: vec!["AAPL".to_string(), "MSFT".to_string()], filter: Some(vec![MarketSessionFilter::QUOTE, MarketSessionFilter::TRADE]), session_id: market_session.get_session_id().to_string(), linebreak: Some(true), valid_only: Some(true), advanced_details: None, }; if let Err(e) = market_session.ws_stream(payload).await { error!("Streaming error: {}. Reconnecting...", e); } } Err(e) => { error!( "Failed to create market streaming session: {}. Retrying...", e ); } } tokio::time::sleep(tokio::time::Duration::from_secs(5)).await; } } ``` -------------------------------- ### Account WebSocket Streaming Source: https://context7.com/joaquinbejar/tradier/llms.txt Stream real-time account events such as orders, fills, and positions using WebSockets. Requires an account session. ```rust use futures_util::StreamExt; use tradier::Config; use tradier::wssession::{AccountSession, AccountSessionEvent, AccountSessionPayload}; use tradier::wssession::account_events::AccountEvent; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let session = AccountSession::new(&config).await?; println!("Session ID: {}", session.get_session_id()); println!("WebSocket URL: {}", session.get_websocket_url()); let events = [ AccountSessionEvent::Order, AccountSessionEvent::Fill, AccountSessionEvent::Position, ]; let payload = AccountSessionPayload::builder() .events(&events) .session_id(session.get_session_id()) .build(); let stream = session.event_stream(payload).await?; futures_util::pin_mut!(stream); while let Some(event) = stream.next().await { match event { Ok(AccountEvent::Order(order)) => { println!("Order update: {:?}", order); } Ok(AccountEvent::Fill(fill)) => { println!("Fill: {:?}", fill); } Ok(AccountEvent::Position(position)) => { println!("Position: {:?}", position); } Err(e) => eprintln!("Error: {}", e), _ => {} // Ignore other event types } } Ok(()) } ``` -------------------------------- ### HTTP Streaming Market Events Source: https://context7.com/joaquinbejar/tradier/llms.txt Use HTTP chunked-transfer streaming for market data when WebSockets are blocked. Requires bootstrapping a session ID. ```rust use futures_util::StreamExt; use tradier::Config; use tradier::non_blocking::Client; use tradier::streaming::http_stream; use tradier::wssession::{MarketSession, MarketSessionFilter}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let rest = Client::new(config.clone()); // Bootstrap session ID (same for WebSocket and HTTP streaming) let session = MarketSession::new(&config).await?; let symbols = ["AAPL".to_string(), "MSFT".to_string()]; let filters = [MarketSessionFilter::QUOTE, MarketSessionFilter::TRADE]; // Open HTTP event stream let events = http_stream::market_events( &rest, session.get_session_id(), &symbols, Some(&filters), Some(true), // linebreak Some(true), // valid_only None, // advanced_details ).await?; futures_util::pin_mut!(events); while let Some(event) = events.next().await { match event { Ok(e) => println!("Event: {:?}", e), Err(e) => eprintln!("Error: {}", e), } } Ok(()) } ``` -------------------------------- ### Fetch Real-Time Quotes with Async Client Source: https://context7.com/joaquinbejar/tradier/llms.txt Use the non-blocking (async) client to fetch real-time quotes for multiple symbols. Greeks can be optionally included for options quotes. ```rust use tradier::Config; use tradier::non_blocking::Client; use tradier::non_blocking::operation::MarketData; use tradier::types::{Greeks, Symbol, Symbols}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config); // Create a list of symbols to query let symbols = Symbols::new([ "AAPL".parse::()?, "MSFT".parse::()?, "SPY".parse::()?, ]); // Fetch quotes with Greeks enabled (Greeks apply to option quotes) let response = client.get_quotes(&symbols, Some(Greeks::new(true))).await?; println!("Quotes: {:#?}", response); // Response contains: symbol, description, bid, ask, last, volume, etc. Ok(()) } ``` -------------------------------- ### Account History and Orders Source: https://context7.com/joaquinbejar/tradier/llms.txt Retrieve account transaction history with pagination and filtering by event type, and fetch account orders with tag inclusion options. ```rust use tradier::Config; use tradier::non_blocking::Client; use tradier::non_blocking::operation::Accounts; use tradier::types::{AccountNumber, EventType, Page, Limit, IncludeTags}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config); let account_number: AccountNumber = "VA12345678".parse()?; // Get account history with pagination let history = client.get_account_history( &account_number, Some(Page::new(1)), Some(Limit::new(25)), Some(EventType::Trade), // Options: Trade, Option, Ach, Wire, Dividend, etc. ).await?; println!("History: {:#?}", history); // Get account orders let orders = client.get_account_orders( &account_number, &Page::default(), &Limit::default(), &IncludeTags::from(true), ).await?; println!("Orders: {:#?}", orders); Ok(()) } ``` -------------------------------- ### Stream Market Events with Iterator Pattern Source: https://context7.com/joaquinbejar/tradier/llms.txt Utilizes the async `Stream` interface for granular control over market events like quotes, trades, and summaries. This pattern allows for processing events as they arrive. Ensure the `MarketSessionPayload` is correctly configured. ```rust use futures_util::StreamExt; use tradier::Config; use tradier::wssession::{MarketSession, MarketSessionFilter, MarketSessionPayload}; use tradier::wssession::events::MarketEvent; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let session = MarketSession::new(&config).await?; let symbols = ["SPY".to_string(), "QQQ".to_string()]; let payload = MarketSessionPayload::builder() .symbols(&symbols) .filters(&[MarketSessionFilter::QUOTE, MarketSessionFilter::TRADE]) .session_id(session.get_session_id()) .linebreak(true) .build(); // Get typed event stream let stream = session.event_stream(payload).await?; futures_util::pin_mut!(stream); while let Some(event) = stream.next().await { match event { Ok(MarketEvent::Quote(quote)) => { println!("Quote: {} bid={} ask={}", quote.symbol, quote.bid, quote.ask); } Ok(MarketEvent::Trade(trade)) => { println!("Trade: {} price={} size={}", trade.symbol, trade.price, trade.size); } Ok(MarketEvent::Summary(summary)) => { println!("Summary: {} open={} high={} low={}", summary.symbol, summary.open, summary.high, summary.low); } Err(e) => eprintln!("Stream error: {}", e), _ => {} } } Ok(()) } ``` -------------------------------- ### Search Companies and Symbol Lookup Source: https://context7.com/joaquinbejar/tradier/llms.txt Search for companies by name or look up specific symbols with optional filters for exchanges and security types. ```rust use tradier::Config; use tradier::non_blocking::Client; use tradier::non_blocking::operation::MarketData; use tradier::types::{IndexesFlag, Exchanges, SecurityTypes}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config); // Search for companies by name let search_results = client.search_companies( "apple", Some(IndexesFlag::new(false)), // Exclude index symbols ).await?; println!("Search results: {:#?}", search_results); // Look up specific symbols with filters let exchanges = Exchanges::new(vec!["N".into(), "Q".into()]); // NYSE, NASDAQ let types = SecurityTypes::new(vec!["stock".into(), "etf".into()]); let lookup = client.lookup_symbol( "GOOG", Some(&exchanges), Some(&types), ).await?; println!("Lookup results: {:#?}", lookup); Ok(()) } ``` -------------------------------- ### Time and Sales (Intraday Tick Data) Source: https://context7.com/joaquinbejar/tradier/llms.txt Retrieve intraday time-and-sales data for a given symbol within a specified time range. Supports configurable intervals. ```rust use chrono::{TimeZone, Utc}; use tradier::Config; use tradier::non_blocking::Client; use tradier::non_blocking::operation::MarketData; use tradier::types::{Symbol, TimeSalesInterval, SessionFilter}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config); let symbol: Symbol = "AAPL".parse()?; let start = Utc.with_ymd_and_hms(2024, 1, 15, 14, 30, 0).unwrap(); let end = Utc.with_ymd_and_hms(2024, 1, 15, 21, 0, 0).unwrap(); // Get 5-minute interval time and sales let timesales = client.get_time_and_sales( &symbol, Some(TimeSalesInterval::FiveMinutes), // Options: Tick, 1min, 5min, 15min Some(&start), Some(&end), Some(SessionFilter::All), ).await?; println!("Time and sales: {:#?}", timesales); Ok(()) } ``` -------------------------------- ### Fetch Historical Quotes (OHLCV Bars) with Async Client Source: https://context7.com/joaquinbejar/tradier/llms.txt Retrieve historical price data (OHLCV bars) for a given symbol using the async client. Supports configurable intervals and date ranges. ```rust use chrono::NaiveDate; use tradier::Config; use tradier::non_blocking::Client; use tradier::non_blocking::operation::MarketData; use tradier::types::{Symbol, HistoryInterval, SessionFilter}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config); let symbol: Symbol = "AAPL".parse()?; let start = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(); let end = NaiveDate::from_ymd_opt(2024, 1, 31).unwrap(); // Fetch daily OHLCV bars for January 2024 let history = client.get_historical_quotes( &symbol, Some(HistoryInterval::Daily), // Options: Daily, Weekly, Monthly Some(&start), Some(&end), Some(SessionFilter::Open), // Options: Open, All ).await?; if let Some(bars) = history.history { for day in bars.day.iter() { println!("{}: O={} H={} L={} C={} V={}", day.date, day.open, day.high, day.low, day.close, day.volume); } } Ok(()) } ``` -------------------------------- ### Market Clock and Calendar Source: https://context7.com/joaquinbejar/tradier/llms.txt Check the current market status and retrieve the trading calendar for a specific month and year. Supports delayed or real-time data. ```rust use tradier::Config; use tradier::non_blocking::Client; use tradier::non_blocking::operation::MarketData; use tradier::types::{DelayedFlag, CalendarMonth, CalendarYear}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config); // Get current market clock status let clock = client.get_clock(Some(DelayedFlag::new(false))).await?; println!("Market state: {:?}", clock.clock.state); println!("Next change: {:?}", clock.clock.next_change); // Get market calendar for a specific month let calendar = client.get_calendar( Some(CalendarMonth::new(6).unwrap()), Some(CalendarYear::new(2024)), ).await?; println!("Trading days: {:#?}", calendar); Ok(()) } ``` -------------------------------- ### Add Tradier Dependency to Cargo.toml Source: https://github.com/joaquinbejar/tradier/blob/main/README.md To use the Tradier library, add it as a dependency in your project's Cargo.toml file. Ensure you are using a compatible version. ```toml [dependencies] tradier = "0.1.0" ``` -------------------------------- ### GetAccountBalancesResponseWire Failure Case Source: https://github.com/joaquinbejar/tradier/blob/main/proptest-regressions/client/blocking.txt This snippet represents a failure case for the GetAccountBalancesResponseWire. It is used to re-run a specific scenario that previously caused a failure during testing. ```rust cc 8dc274e24f4743bc68af52f4d5df1b120516513fdcecdc6055eb63c494087b96 # shrinks to response = GetAccountBalancesResponseWire { balances: GetAccountBalancesWire { option_short_value: 0.0, total_equity: 0.0, account_number: "", account_type: Cash, close_pl: 0.0, current_requirement: 0.0, equity: 0.0, long_market_value: 0.0, market_value: 0.0, open_pl: -0.0, option_long_value: 0.0, option_requirement: 0.0, pending_orders_count: 0, short_market_value: 0.0, stock_long_value: 0.0, total_cash: 0.0, uncleared_funds: 0.0, pending_cash: 0.0, margin: MarginWire { fed_call: 0.0, maintenance_call: 0.0, option_buying_power: 0.0, stock_buying_power: 0.0, stock_short_value: 0.0, sweep: 0.0 } } }, ascii_string = " " ``` -------------------------------- ### Fetch Company Fundamentals with Tradier API Source: https://context7.com/joaquinbejar/tradier/llms.txt Retrieves various fundamental data points for specified stock symbols, including company profiles, dividends, financial ratios, statistics, statements, corporate calendars, and actions. Ensure symbols are correctly parsed into the `Symbol` type. ```rust use tradier::Config; use tradier::non_blocking::Client; use tradier::non_blocking::operation::Fundamentals; use tradier::types::Symbol; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new(); let client = Client::new(config); let symbols = ["AAPL".parse::()?, "MSFT".parse::()?]; // Get company profiles let company = client.get_company(&symbols).await?; println!("Company info: {:#?}", company); // Get dividend history let dividends = client.get_dividends(&symbols).await?; println!("Dividends: {:#?}", dividends); // Get financial ratios (P/E, EPS, margins, etc.) let ratios = client.get_ratios(&symbols).await?; println!("Ratios: {:#?}", ratios); // Get price statistics let statistics = client.get_statistics(&symbols).await?; println!("Statistics: {:#?}", statistics); // Get financial statements let financials = client.get_financials(&symbols).await?; println!("Financials: {:#?}", financials); // Get corporate calendars (earnings, IPOs) let calendars = client.get_corporate_calendars(&symbols).await?; println!("Corporate calendars: {:#?}", calendars); // Get corporate actions (splits, mergers) let actions = client.get_corporate_actions(&symbols).await?; println!("Corporate actions: {:#?}", actions); Ok(()) } ``` -------------------------------- ### GetUserProfileResponseWire Failure Case Source: https://github.com/joaquinbejar/tradier/blob/main/proptest-regressions/client/blocking.txt This snippet represents a failure case for the GetUserProfileResponseWire. It is used to re-run a specific scenario that previously caused a failure during testing, particularly related to user profile data. ```rust cc 1a037bbe0fc8610df601ff0eaee7cb94c459deeb8e0827fa945600cf191b63ea # shrinks to response = GetUserProfileResponseWire { profile: UserProfileWire { id: "", name: "", account: [] } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.