### Install firstrade package Source: https://github.com/maxxrk/firstrade-api/blob/main/README.md Use pip to install the library from PyPI. ```bash pip install firstrade ``` -------------------------------- ### Login with TOTP-based MFA Source: https://context7.com/maxxrk/firstrade-api/llms.txt Authenticate with Firstrade using TOTP-based MFA. Recommended for automation. Requires a TOTP secret key from your Firstrade 2FA setup. ```python from firstrade import account # Login with TOTP-based MFA (recommended for automation) ft_session = account.FTSession( username="your_username", password="your_password", mfa_secret="YOUR_TOTP_SECRET_KEY", # From Firstrade 2FA setup save_session=True, # Persist session cookies to file profile_path="./cookies" # Optional: custom cookie storage path ) need_code = ft_session.login() ``` -------------------------------- ### Get Stock Quote Information Source: https://context7.com/maxxrk/firstrade-api/llms.txt Retrieves detailed quote information for a given stock symbol. Access attributes like last price, bid/ask, volume, and more. ```python quote = symbols.SymbolQuote( ft_session=ft_session, account=ft_accounts.account_numbers[0], symbol="INTC" ) # Access quote attributes print(f"Symbol: {quote.symbol}") # INTC print(f"Company: {quote.company_name}") # Intel Corporation print(f"Last Price: ${quote.last}") # 35.50 print(f"Bid: ${quote.bid} x {quote.bid_size}") # $35.48 x 500 print(f"Ask: ${quote.ask} x {quote.ask_size}") # $35.52 x 300 print(f"Day High: ${quote.high}") # 36.00 print(f"Day Low: ${quote.low}") # 35.20 print(f"Volume: {quote.volume}") # 15000000 print(f"Change: {quote.change}") # +0.25 print(f"Exchange: {quote.exchange}") # NASDAQ print(f"Quote Time: {quote.quote_time}") # 2024-01-15 14:30:00 print(f"Is ETF: {quote.is_etf}") # False print(f"Fractional Trading: {quote.is_fractional}") # True print(f"Has Options: {quote.has_option}") # Y ``` -------------------------------- ### Handle API Errors with Exceptions Source: https://context7.com/maxxrk/firstrade-api/llms.txt Demonstrates how to catch specific exceptions for login, account data, and quote retrieval errors. Ensure proper initialization of session and account objects before attempting API calls. ```python from firstrade import account, symbols from firstrade.exceptions import ( LoginError, LoginRequestError, LoginResponseError, QuoteRequestError, QuoteResponseError, AccountResponseError ) try: ft_session = account.FTSession( username="user", password="wrong_password", mfa_secret="secret" ) ft_session.login() except LoginRequestError as e: print(f"HTTP error during login: {e.status_code}") except LoginResponseError as e: print(f"Login failed: {e.message}") except LoginError as e: print(f"MFA configuration error: {e}") try: ft_accounts = account.FTAccountData(ft_session) except AccountResponseError as e: print(f"Failed to get account data: {e.message}") try: quote = symbols.SymbolQuote(ft_session, account_num, "INVALID") except QuoteRequestError as e: print(f"HTTP error getting quote: {e.status_code}") except QuoteResponseError as e: print(f"Quote failed for {e.symbol}: {e.message}") ``` -------------------------------- ### Place Stock Orders Source: https://context7.com/maxxrk/firstrade-api/llms.txt Handles stock order placement, supporting various order types (market, limit, stop), durations, and fractional shares. Includes preview functionality. ```python from firstrade import account, order ft_session = account.FTSession(username="user", password="pass", mfa_secret="secret") ft_session.login() ft_accounts = account.FTAccountData(ft_session) ft_order = order.Order(ft_session) # Preview a limit buy order (dry run) preview = ft_order.place_order( account=ft_accounts.account_numbers[0], symbol="INTC", price_type=order.PriceType.LIMIT, order_type=order.OrderType.BUY, duration=order.Duration.DAY, quantity=10, price=35.00, dry_run=True # Preview only, don't execute ) print(f"Order preview: {preview}") # Execute a market buy order result = ft_order.place_order( account=ft_accounts.account_numbers[0], symbol="AAPL", price_type=order.PriceType.MARKET, order_type=order.OrderType.BUY, duration=order.Duration.DAY, quantity=5, dry_run=False # Execute the order ) print(f"Order ID: {result['result']['order_id']}") print(f"Order State: {result['result']['state']}") # Place a fractional/notional order (buy $100 worth of stock) fractional_order = ft_order.place_order( account=ft_accounts.account_numbers[0], symbol="GOOGL", price_type=order.PriceType.MARKET, order_type=order.OrderType.BUY, duration=order.Duration.DAY, price=100.00, # Dollar amount when notional=True notional=True, dry_run=False ) # Place a stop-limit sell order stop_limit = ft_order.place_order( account=ft_accounts.account_numbers[0], symbol="INTC", price_type=order.PriceType.STOP_LIMIT, order_type=order.OrderType.SELL, duration=order.Duration.GT90, # Good for 90 days quantity=10, price=33.00, # Limit price stop_price=34.00, # Stop trigger price dry_run=False ) # Order types: BUY, SELL, SELL_SHORT, BUY_TO_COVER # Price types: MARKET, LIMIT, STOP, STOP_LIMIT, TRAILING_STOP_DOLLAR, TRAILING_STOP_PERCENT # Durations: DAY, DAY_EXT (8AM-8PM), OVERNIGHT (8PM-4AM), GT90 (good till 90 days) # Instructions: NONE, AON (all or none), OPG (at open), CLO (at close) ``` -------------------------------- ### Retrieve Account Balances Source: https://context7.com/maxxrk/firstrade-api/llms.txt Fetch account balances, including a quick overview and detailed information for specific accounts. Supports filtering by keywords. ```python from firstrade import account import json # Initialize session (see authentication above) ft_session = account.FTSession(username="user", password="pass", mfa_secret="secret") ft_session.login() # Get account data - automatically fetches all linked accounts ft_accounts = account.FTAccountData(ft_session) # Access account numbers print(f"Account numbers: {ft_accounts.account_numbers}") # Output: ['12345678', '87654321'] # Access account balances (quick overview) print(f"Account balances: {ft_accounts.account_balances}") # Output: {'12345678': '50000.00', '87654321': '25000.00'} # Get detailed balance information for an account balances = ft_accounts.get_account_balances(ft_accounts.account_numbers[0]) print(json.dumps(balances, indent=2)) # Output includes: cash_balance, buying_power, margin_balance, equity, etc. # Get filtered balance overview (convenience method) overview = ft_accounts.get_balance_overview( account=ft_accounts.account_numbers[0], keywords=["cash", "buying", "equity", "value"] # Optional filter ) print(overview) # Output: {'cash.available': 10000.00, 'buying_power.stock': 20000.00, ...} # Access user info print(f"User info: {ft_accounts.user_info}") ``` -------------------------------- ### Login with PIN-based MFA Source: https://context7.com/maxxrk/firstrade-api/llms.txt Authenticate with Firstrade using a PIN-based MFA method. This method is suitable for interactive logins. ```python from firstrade import account # Login with PIN-based MFA ft_session = account.FTSession( username="your_username", password="your_password", pin="123456" ) ft_session.login() ``` -------------------------------- ### Access Option Chains and Quotes Source: https://context7.com/maxxrk/firstrade-api/llms.txt Retrieves option chain data, expiration dates, and Greeks for a given symbol. Requires an initialized FTSession and OptionQuote handler. Use `place_option_order` to simulate or execute trades. ```python from firstrade import account, symbols, order import json ft_session = account.FTSession(username="user", password="pass", mfa_secret="secret") ft_session.login() ft_accounts = account.FTAccountData(ft_session) # Initialize option quote handler option_handler = symbols.OptionQuote(ft_session, "INTC") # Get available expiration dates print("Available expiration dates:") for exp in option_handler.option_dates["items"]: print(f" {exp['exp_date']} - {exp['day_left']} days left ({exp['exp_type']})") # Get option chain for a specific expiration exp_date = option_handler.option_dates["items"][0]["exp_date"] option_chain = option_handler.get_option_quote("INTC", exp_date) print(json.dumps(option_chain["items"][:2], indent=2)) # Get Greeks for options greeks = option_handler.get_greek_options("INTC", exp_date) print(json.dumps(greeks["chains"][:2], indent=2)) ``` ```python # Place an option order ft_order = order.Order(ft_session) option_symbol = option_chain["items"][0]["opt_symbol"] # e.g., "INTC240216C00035000" option_result = ft_order.place_option_order( account=ft_accounts.account_numbers[0], option_symbol=option_symbol, order_type=order.OrderType.BUY_OPTION, price_type=order.PriceType.LIMIT, duration=order.Duration.DAY, price=0.50, contracts=1, dry_run=True # Preview order ) print(f"Option order preview: {json.dumps(option_result, indent=2)}") ``` -------------------------------- ### Retrieve Stock Quotes Source: https://context7.com/maxxrk/firstrade-api/llms.txt Fetch real-time quote data for stock symbols, including bid/ask prices, volume, and basic company information. ```python from firstrade import account, symbols ft_session = account.FTSession(username="user", password="pass", mfa_secret="secret") ft_session.login() ft_accounts = account.FTAccountData(ft_session) ``` -------------------------------- ### Manage Session Tokens Source: https://context7.com/maxxrk/firstrade-api/llms.txt Obtain current session tokens for external storage and restore a session from saved tokens. Also includes functionality to delete saved session cookies. ```python # Get current session tokens for external storage tokens = ft_session.get_tokens() # Returns: {'access-token': '...', 'ftat': '...', 'sid': '...', 'cookies': {...}} # Restore session from saved tokens new_session = account.FTSession() new_session.build_session_from_tokens(tokens) # Delete saved session cookies ft_session.delete_cookies() ``` -------------------------------- ### Retrieve Account Positions Source: https://context7.com/maxxrk/firstrade-api/llms.txt Fetch details of currently held stock and options positions for a specified account. Includes market value and quantity. ```python from firstrade import account import json ft_session = account.FTSession(username="user", password="pass", mfa_secret="secret") ft_session.login() ft_accounts = account.FTAccountData(ft_session) # Get all positions for an account positions = ft_accounts.get_positions(account=ft_accounts.account_numbers[0]) print(json.dumps(positions, indent=2)) # Output: # { # "items": [ # {"symbol": "AAPL", "quantity": "10", "market_value": "1750.00", ...}, # {"symbol": "INTC", "quantity": "50", "market_value": "1250.00", ...} # ] # } # Iterate through positions for position in positions["items"]: print(f"{position['quantity']} shares of {position['symbol']} @ ${position['market_value']}") ``` -------------------------------- ### Manage Orders Source: https://context7.com/maxxrk/firstrade-api/llms.txt Retrieve the status of all orders for an account and cancel pending orders. Displays order details in a JSON format. ```python from firstrade import account import json ft_session = account.FTSession(username="user", password="pass", mfa_secret="secret") ft_session.login() ft_accounts = account.FTAccountData(ft_session) # Get all orders for an account orders = ft_accounts.get_orders(account=ft_accounts.account_numbers[0]) print(json.dumps(orders, indent=2)) # Output: # { # "items": [ # {"order_id": "123456", "symbol": "INTC", "quantity": "10", "state": "Open", ...}, # {"order_id": "123457", "symbol": "AAPL", "quantity": "5", "state": "Filled", ...} # ] # } ``` -------------------------------- ### Login with Email/Phone OTP Source: https://context7.com/maxxrk/firstrade-api/llms.txt Authenticate with Firstrade using email or phone OTP. Requires manual entry of the code sent to your device. Session cookies can be persisted. ```python from firstrade import account # Login with email/phone OTP (requires manual code entry) ft_session = account.FTSession( username="your_username", password="your_password", email="user@example.com", # Or use phone="1234567890" save_session=True ) need_code = ft_session.login() if need_code: code = input("Enter the code sent to your email/phone: ") ft_session.login_two(code) ``` -------------------------------- ### Retrieve OHLC Chart Data Source: https://context7.com/maxxrk/firstrade-api/llms.txt Fetches Open-High-Low-Close candlestick data for a symbol over specified time ranges. Useful for charting and technical analysis. ```python from firstrade import account, symbols ft_session = account.FTSession(username="user", password="pass", mfa_secret="secret") ft_session.login() # Get OHLC data for different time ranges # Available ranges: "24h", "1d", "1w", "1m", "1y" ohlc = symbols.SymbolOHLC( ft_session=ft_session, symbol="INTC", range_="1y" # One year of data ) # Access parsed candle data # Format: (timestamp_ms, open, high, low, close, volume) print(f"Total candles: {len(ohlc.candles)}") print(f"First candle: {ohlc.candles[0]}") # Output: (1704067200000, 35.10, 35.50, 34.90, 35.25, 12500000) # Iterate through candles for timestamp, open_price, high, low, close, volume in ohlc.candles[:5]: print(f"Time: {timestamp}, O: {open_price}, H: {high}, L: {low}, C: {close}, Vol: {volume}") # Access raw data print(f"Raw OHLC: {ohlc.ohlc_raw[:2]}") print(f"Raw Volume: {ohlc.vol_raw[:2]}") print(f"Start of day timestamp: {ohlc.start_of_day}") ``` -------------------------------- ### Retrieve Account Transaction History Source: https://context7.com/maxxrk/firstrade-api/llms.txt Fetches transaction history for a specified account. Supports year-to-date and custom date ranges. Ensure you have a valid FTSession and FTAccountData object initialized. ```python from firstrade import account import json ft_session = account.FTSession(username="user", password="pass", mfa_secret="secret") ft_session.login() ft_accounts = account.FTAccountData(ft_session) # Get year-to-date history history = ft_accounts.get_account_history( account=ft_accounts.account_numbers[0], date_range="ytd" ) # Get history for custom date range history = ft_accounts.get_account_history( account=ft_accounts.account_numbers[0], date_range="cust", custom_range=["2024-01-01", "2024-03-31"] ) print(json.dumps(history, indent=2)) ``` ```python # Iterate through transactions for txn in history["items"]: print(f"{txn['report_date']}: {txn['symbol']} - ${txn['amount']}") ``` -------------------------------- ### Cancel a Pending Order Source: https://context7.com/maxxrk/firstrade-api/llms.txt Use this function to cancel an order that has not yet been executed. It requires the order ID as input and returns the cancellation status. ```python order_id = "123456" cancel_result = ft_accounts.cancel_order(order_id) if cancel_result["result"]["result"] == "success": print(f"Order {order_id} cancelled successfully") else: print(f"Failed to cancel order: {cancel_result}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.