### Quick Start Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md A quick guide to get started with the Public API Python SDK. ```APIDOC ## Quick Start ```python from public_api_sdk import PublicApiClient, PublicApiClientConfiguration from public_api_sdk.auth_config import ApiKeyAuthConfig # Initialize the client client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="INSERT_API_SECRET_KEY"), config=PublicApiClientConfiguration( default_account_number="INSERT_ACCOUNT_NUMBER" ) ) # Get accounts accounts = client.get_accounts() # Get a quote from public_api_sdk import OrderInstrument, InstrumentType quotes = client.get_quotes([ OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY) ]) ``` ``` -------------------------------- ### Set up and Install Public API Python SDK Locally Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Instructions for setting up and installing the Public API Python SDK locally. This involves creating a virtual environment, activating it, and installing the package using pip. Development installation options are also provided. ```bash # Create a virtual environment $ python3 -m venv .venv # Activate the virtual environment $ source .venv/bin/activate # Install the package $ pip install . # Install in editable mode $ pip install -e . # Install with development dependencies $ pip install -e ".[dev]" ``` -------------------------------- ### Run Python SDK Examples Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Instructions on how to run example Python scripts for the Public API SDK. This requires setting up API credentials in a `.env` file. The examples demonstrate various functionalities of the SDK. ```bash # Run an example script $ python example.py ``` -------------------------------- ### Install Public API Python SDK using pip Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Install the Public API Python SDK package from PyPI using pip. This is the standard method for installing Python packages. Ensure you have pip installed and updated. ```bash # Install from PyPI $ pip install publicdotcom-py ``` -------------------------------- ### Installation Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Instructions for installing the Public API Python SDK. ```APIDOC ## Installation ### From PyPI ```bash $ pip install publicdotcom-py ``` ### Run locally ```bash $ python3 -m venv .venv $ source .venv/bin/activate $ pip install . $ pip install -e . $ pip install -e ".[dev]" $ # run example $ python example.py ``` ### Run tests ```bash $ pytest ``` ### Run examples To run example Python files, add your `API_SECRET_KEY` and `DEFAULT_ACCOUNT_NUMBER` to the `.env.example` file and rename it to `.env`. ``` -------------------------------- ### Get Option Expirations (Python) Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Retrieves all available option expiration dates for a specified underlying security. It requires API key authentication and an account number. The response includes a list of expiration dates, and the example shows how to print the first 10 dates. ```python from public_api_sdk import ( PublicApiClient, PublicApiClientConfiguration, OptionExpirationsRequest, OrderInstrument, InstrumentType ) from public_api_sdk.auth_config import ApiKeyAuthConfig client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration(default_account_number="ACCT123456") ) try: # Request option expirations expirations_request = OptionExpirationsRequest( instrument=OrderInstrument( symbol="AAPL", type=InstrumentType.EQUITY ) ) expirations_response = client.get_option_expirations(expirations_request) # Display available expiration dates print(f"Available option expirations for AAPL:") print(f"Total: {len(expirations_response.expirations)} dates\n") for i, expiration in enumerate(expirations_response.expirations[:10]): print(f"{i+1}. {expiration.strftime('%Y-%m-%d')}") if len(expirations_response.expirations) > 10: print(f"... and {len(expirations_response.expirations) - 10} more dates") except Exception as e: print(f"Error retrieving expirations: {e}") finally: client.close() ``` -------------------------------- ### Get Portfolio Information using PublicApiClient Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Retrieves a detailed portfolio snapshot including positions, equity values, buying power, and open orders. Requires API key authentication and an account number. Outputs a summary of the portfolio and its components. ```python from public_api_sdk import PublicApiClient, PublicApiClientConfiguration from public_api_sdk.auth_config import ApiKeyAuthConfig client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration(default_account_number="ACCT123456") ) try: # Get portfolio (account_id optional if default is set) portfolio = client.get_portfolio() # Display portfolio summary print("Portfolio Summary:") print(f" Total Equity: ${portfolio.equity:,.2f}") print(f" Cash: ${portfolio.cash:,.2f}") print(f" Buying Power: ${portfolio.buying_power:,.2f}") # Display positions if portfolio.positions: print(f"\nPositions ({len(portfolio.positions)}):") for position in portfolio.positions: print(f" {position.instrument.symbol}: {position.quantity} shares") print(f" Current Value: ${position.market_value:,.2f}") print(f" Cost Basis: ${position.cost_basis:,.2f}") # Display open orders if portfolio.open_orders: print(f"\nOpen Orders ({len(portfolio.open_orders)}):") for order in portfolio.open_orders: print(f" {order.instrument.symbol}: {order.side.value} {order.quantity}") print(f" Status: {order.status.value}") except Exception as e: print(f"Error retrieving portfolio: {e}") finally: client.close() ``` -------------------------------- ### Get Instrument Details Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Get detailed information about a specific instrument. This includes trading status, fractional trading availability, and option trading details. ```APIDOC ## GET /instruments/{symbol} ### Description Get detailed information about a specific instrument. ### Method GET ### Endpoint /instruments/{symbol} ### Parameters #### Path Parameters - **symbol** (string) - Required - The symbol of the instrument. - **instrument_type** (InstrumentType) - Required - The type of the instrument (e.g., EQUITY, OPTION). ### Request Example ```python instrument = client.get_instrument( symbol="AAPL", instrument_type=InstrumentType.EQUITY ) ``` ### Response #### Success Response (200) - **instrument** (Instrument) - Detailed information about the instrument. - **symbol** (string) - The instrument's symbol. - **type** (InstrumentType) - The type of the instrument. - **trading** (Trading) - Indicates if the instrument is currently tradable. - **fractional_trading** (bool) - Whether fractional shares are supported. - **option_trading** (bool) - Whether options trading is supported for this instrument. - **option_spread_trading** (bool) - Whether options spread trading is supported. #### Response Example ```json { "instrument": {"symbol": "AAPL", "type": "EQUITY"}, "trading": "BUY_AND_SELL", "fractional_trading": true, "option_trading": true, "option_spread_trading": true } ``` ``` -------------------------------- ### Subscribe to Order Status Updates (Python) Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Monitors order status changes in real-time using a synchronous callback function. This example demonstrates placing an order, subscribing to its updates, processing various order statuses (FILLED, CANCELLED, REJECTED), and then unsubscribing. Requires the 'public_api_sdk' library. ```python import uuid import time from decimal import Decimal from public_api_sdk import ( PublicApiClient, PublicApiClientConfiguration, OrderRequest, OrderInstrument, InstrumentType, OrderSide, OrderType, TimeInForce, OrderExpirationRequest, OrderStatus, OrderUpdate, OrderSubscriptionConfig ) from public_api_sdk.auth_config import ApiKeyAuthConfig client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration(default_account_number="ACCT123456") ) try: # Define callback function for order updates def on_order_update(update: OrderUpdate): print(f"Order Update: {update.order_id}") print(f" Status: {update.old_status} -> {update.new_status}") print(f" Time: {update.timestamp}") if update.new_status == OrderStatus.FILLED: print(f" Order filled! Average price: ${update.order.average_price}") elif update.new_status == OrderStatus.CANCELLED: print(" Order cancelled") elif update.new_status == OrderStatus.REJECTED: print(f" Order rejected: {update.order.reject_reason}") # Place order order_request = OrderRequest( order_id=str(uuid.uuid4()), instrument=OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), order_side=OrderSide.BUY, order_type=OrderType.LIMIT, expiration=OrderExpirationRequest(time_in_force=TimeInForce.DAY), quantity=Decimal("5"), limit_price=Decimal("225.00") ) new_order = client.place_order(order_request) print(f"Order placed: {new_order.order_id}") # Subscribe to order status updates subscription_id = new_order.subscribe_updates( callback=on_order_update, config=OrderSubscriptionConfig( polling_frequency_seconds=2.0, retry_on_error=True, max_retries=3, exponential_backoff=True ) ) print(f"Subscribed to updates (ID: {subscription_id})") # Monitor for 10 seconds time.sleep(10) # Cancel order new_order.cancel() print("Cancellation submitted") # Wait a bit more to see the cancellation update time.sleep(3) # Unsubscribe from updates new_order.unsubscribe() print("Unsubscribed from order updates") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Get Account Information with Python SDK Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Retrieves all accounts associated with the authenticated user. It filters for a brokerage account and prints its ID and type. Ensure the API key is valid and the client is properly initialized and closed. ```python from public_api_sdk import PublicApiClient, PublicApiClientConfiguration, AccountType from public_api_sdk.auth_config import ApiKeyAuthConfig client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration() ) try: # Get all accounts accounts_response = client.get_accounts() # Find brokerage account brokerage_account = next( (account for account in accounts_response.accounts if account.account_type == AccountType.BROKERAGE), None ) if brokerage_account: print(f"Account ID: {brokerage_account.account_id}") print(f"Account Type: {brokerage_account.account_type.value}") else: print("No brokerage account found") except Exception as e: print(f"Error retrieving accounts: {e}") finally: client.close() ``` -------------------------------- ### Get Portfolio Snapshot using Python SDK Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Retrieves a snapshot of the account portfolio, including positions, equity, and buying power, using the `get_portfolio` method. The `account_id` is optional if a default account is configured in the client. ```python portfolio = client.get_portfolio(account_id="YOUR_ACCOUNT_NUMBER") # account_id optional if default set print(f"Total equity: {portfolio.equity}") print(f"Buying power: {portfolio.buying_power}") ``` -------------------------------- ### Get Option Chain for Specific Expiration Date Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Retrieves the complete option chain for a given stock symbol and expiration date, including both call and put options. It first fetches available expiration dates and then uses the earliest one to get the option chain details. Requires `public_api_sdk` and authentication credentials. ```python from datetime import datetime from public_api_sdk import ( PublicApiClient, PublicApiClientConfiguration, OptionChainRequest, OptionExpirationsRequest, OrderInstrument, InstrumentType ) from public_api_sdk.auth_config import ApiKeyAuthConfig client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration(default_account_number="ACCT123456") ) try: instrument = OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY) # Get expirations first expirations = client.get_option_expirations( OptionExpirationsRequest(instrument=instrument) ) # Get option chain for first expiration option_chain_request = OptionChainRequest( instrument=instrument, expiration_date=expirations.expirations[0] ) option_chain = client.get_option_chain(option_chain_request) print(f"Option Chain for AAPL expiring {expirations.expirations[0].strftime('%Y-%m-%d')}:\n") # Display calls if option_chain.calls: print(f"CALLS ({len(option_chain.calls)}):") for call in option_chain.calls[:5]: print(f" {call.symbol}") print(f" Strike: ${call.strike_price}") print(f" Bid: ${call.bid} x {call.bid_size}") print(f" Ask: ${call.ask} x {call.ask_size}") # Display puts if option_chain.puts: print(f"\nPUTS ({len(option_chain.puts)}):") for put in option_chain.puts[:5]: print(f" {put.symbol}") print(f" Strike: ${put.strike_price}") print(f" Bid: ${put.bid} x {put.bid_size}") print(f" Ask: ${put.ask} x {put.ask_size}") except Exception as e: print(f"Error retrieving option chain: {e}") finally: client.close() ``` -------------------------------- ### Get All Instruments Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Retrieve all available trading instruments with optional filtering by type and trading status. This is useful for discovering available assets. ```APIDOC ## GET /instruments ### Description Retrieve all available trading instruments with optional filtering. ### Method GET ### Endpoint /instruments ### Parameters #### Query Parameters - **type_filter** (list of InstrumentType) - Optional - Filters instruments by type (e.g., EQUITY, OPTION). - **trading_filter** (list of Trading) - Optional - Filters instruments by their trading status (e.g., BUY, SELL, BUY_AND_SELL). ### Request Example ```python from public_api_sdk import InstrumentsRequest, InstrumentType, Trading instruments = client.get_all_instruments( InstrumentsRequest( type_filter=[InstrumentType.EQUITY], trading_filter=[Trading.BUY_AND_SELL], ) ) ``` ### Response #### Success Response (200) - **instruments** (list of Instrument) - A list of available instruments matching the filters. #### Response Example ```json [ { "symbol": "AAPL", "type": "EQUITY", "trading": "BUY_AND_SELL", "fractional_trading": true, "option_trading": true, "option_spread_trading": true } // ... more instruments ] ``` ``` -------------------------------- ### Get Real-Time Quotes for Multiple Instruments (Python) Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Retrieves real-time market quotes for a list of specified instruments. Requires a list of OrderInstrument objects as input and returns a list of quote objects. ```python from public_api_sdk import OrderInstrument, InstrumentType quotes = client.get_quotes([ OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), OrderInstrument(symbol="GOOGL", type=InstrumentType.EQUITY) ]) for quote in quotes: print(f"{quote.instrument.symbol}: ${quote.last}") ``` -------------------------------- ### Get All Trading Instruments (Python) Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Retrieves a comprehensive list of all available trading instruments. Supports filtering by instrument type and trading status (e.g., BUY_AND_SELL). Returns a list of instrument objects. ```python from public_api_sdk import InstrumentsRequest, InstrumentType, Trading instruments = client.get_all_instruments( InstrumentsRequest( type_filter=[InstrumentType.EQUITY], trading_filter=[Trading.BUY_AND_SELL], ) ) ``` -------------------------------- ### Get Instrument Details using PublicApiClient Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Fetches comprehensive details about a specific trading instrument, including its symbol, type, and trading capabilities like fractional and options trading. Requires authentication and instrument identification. Outputs detailed instrument information. ```python from public_api_sdk import ( PublicApiClient, PublicApiClientConfiguration, InstrumentType ) from public_api_sdk.auth_config import ApiKeyAuthConfig client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration() ) try: # Get detailed instrument information instrument = client.get_instrument( symbol="AAPL", instrument_type=InstrumentType.EQUITY ) # Display instrument details print(f"Instrument: {instrument.instrument.symbol}") print(f"Type: {instrument.instrument.type.value}") print(f"\nTrading Capabilities:") print(f" Trading: {instrument.trading.value if instrument.trading else 'N/A'}") print(f" Fractional Trading: {instrument.fractional_trading.value if instrument.fractional_trading else 'N/A'}") print(f" Option Trading: {instrument.option_trading.value if instrument.option_trading else 'N/A'}") print(f" Option Spread Trading: {instrument.option_spread_trading.value if instrument.option_spread_trading else 'N/A'}") except Exception as e: print(f"Error retrieving instrument: {e}") finally: client.close() ``` -------------------------------- ### Get Instrument Details (Python) Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Fetches detailed information for a single trading instrument, such as an equity. Requires the instrument's symbol and type. Returns an instrument object with various trading-related attributes. ```python from public_api_sdk import InstrumentType instrument = client.get_instrument( symbol="AAPL", instrument_type=InstrumentType.EQUITY ) print(f"Symbol: {instrument.instrument.symbol}") print(f"Type: {instrument.instrument.type}") print(f"Trading: {instrument.trading}") print(f"Fractional Trading: {instrument.fractional_trading}") print(f"Option Trading: {instrument.option_trading}") print(f"Option Spread Trading: {instrument.option_spread_trading}") ``` -------------------------------- ### Get Public API Accounts using Python SDK Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Shows how to retrieve all accounts associated with the authenticated user using the `get_accounts` method of the `PublicApiClient`. The response contains a list of accounts, each with an ID and type. ```python accounts_response = client.get_accounts() for account in accounts_response.accounts: print(f"Account ID: {account.account_id}, Type: {account.account_type}") ``` -------------------------------- ### Subscribe to Order Updates with Async Callback (Python) Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Utilizes an asynchronous callback function for non-blocking order status processing, suitable for complex event-driven workflows. This example shows placing an order and subscribing with an async function, demonstrating how to handle updates without blocking the main execution thread. Requires 'public_api_sdk' and 'asyncio'. ```python import asyncio import time from decimal import Decimal from public_api_sdk import ( PublicApiClient, PublicApiClientConfiguration, OrderRequest, OrderInstrument, InstrumentType, OrderSide, OrderType, TimeInForce, OrderExpirationRequest, OrderStatus, OrderUpdate, OrderSubscriptionConfig ) from public_api_sdk.auth_config import ApiKeyAuthConfig client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration(default_account_number="ACCT123456") ) try: # Define async callback function async def on_order_update_async(update: OrderUpdate): # Perform async processing await asyncio.sleep(0.1) print(f"Async Update: Order {update.order_id} is now {update.new_status}") if update.new_status == OrderStatus.FILLED: # Trigger other async operations print(f"Processing fill at ${update.order.average_price}") # Place order order_request = OrderRequest( order_id=str(uuid.uuid4()), instrument=OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), order_side=OrderSide.BUY, order_type=OrderType.LIMIT, expiration=OrderExpirationRequest(time_in_force=TimeInForce.DAY), quantity=Decimal("5"), limit_price=Decimal("220.00") ) new_order = client.place_order(order_request) print(f"Order placed: {new_order.order_id}") # Subscribe with async callback (automatically detected) subscription_id = new_order.subscribe_updates( callback=on_order_update_async, config=OrderSubscriptionConfig(polling_frequency_seconds=1.5) ) print(f"Subscribed with async callback (ID: {subscription_id})") # Monitor for 5 seconds time.sleep(5) # Cancel and wait for confirmation new_order.cancel() print("Cancelling order...") time.sleep(3) new_order.unsubscribe() except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Use Default Account for Portfolio and Quotes Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Shows how to leverage the `default_account_number` configuration to make API calls for portfolio and quotes without explicitly specifying the `account_id`. The example also demonstrates overriding the default account when necessary. ```python from public_api_sdk import OrderInstrument, InstrumentType config = PublicApiClientConfiguration( default_account_number="INSERT_ACCOUNT_NUMBER" ) client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="INSERT_API_SECRET_KEY"), config=config ) instruments = [ OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), OrderInstrument(symbol="MSFT", type=InstrumentType.EQUITY) ] # No need to specify account_id portfolio = client.get_portfolio() # Uses default account number quotes = client.get_quotes(instruments) # Uses default account number # You can still override with a specific account other_portfolio = client.get_portfolio(account_id="DIFFERENT123") # Uses "DIFFERENT123" ``` -------------------------------- ### Get Option Expiration Dates (Python) Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Fetches a list of available option expiration dates for a given underlying equity. Requires an OrderInstrument for the underlying and returns an OptionExpirations object containing a list of dates. ```python from public_api_sdk import OptionExpirationsRequest, OrderInstrument, InstrumentType expirations = client.get_option_expirations( OptionExpirationsRequest( instrument=OrderInstrument( symbol="AAPL", type=InstrumentType.EQUITY ) ) ) print(f"Available expirations: {expirations.expirations}") ``` -------------------------------- ### Get Market Quotes using Python SDK Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Demonstrates how to fetch market quotes for specific instruments using the `get_quotes` method. This requires defining `OrderInstrument` objects with the symbol and type of the instrument. The `account_id` is optional if a default is configured. ```python from public_api_sdk import OrderInstrument, InstrumentType instruments = [ OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY) ] quotes = client.get_quotes(instruments) ``` -------------------------------- ### Initialize Public API Client Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Initializes the Public API client with authentication credentials and optional configuration. It requires an API secret key and can optionally set a default account number. The client should be closed after use. ```python from public_api_sdk import PublicApiClient, PublicApiClientConfiguration from public_api_sdk.auth_config import ApiKeyAuthConfig # Basic initialization client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration( default_account_number="ACCT123456" ) ) # Use the client try: accounts = client.get_accounts() print(f"Found {len(accounts.accounts)} accounts") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Search All Instruments with Python Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Retrieves all available trading instruments, with options to filter by type (e.g., EQUITY) and trading capabilities (e.g., BUY_AND_SELL). It demonstrates how to initialize the client, build a request, fetch instruments, and display basic details. This function requires API credentials and account information. ```python from public_api_sdk import ( PublicApiClient, PublicApiClientConfiguration, InstrumentsRequest, InstrumentType, Trading ) from public_api_sdk.auth_config import ApiKeyAuthConfig client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration(default_account_number="ACCT123456") ) try: # Filter for buyable equities instruments_request = InstrumentsRequest( type_filter=[InstrumentType.EQUITY], trading_filter=[Trading.BUY_AND_SELL], fractional_trading_filter=None, option_trading_filter=None ) # Get filtered instruments instruments_response = client.get_all_instruments(instruments_request) print(f"Found {len(instruments_response.instruments)} tradeable equities") # Display first 10 instruments for i, instrument in enumerate(instruments_response.instruments[:10]): print(f"{i+1}. {instrument.instrument.symbol} - {instrument.instrument.type.value}") except Exception as e: print(f"Error retrieving instruments: {e}") finally: client.close() ``` -------------------------------- ### Get Option Greeks Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Get Greeks (Delta, Gamma, Vega, Theta) for a specific option contract using its OSI symbol. This helps in understanding option risk. ```APIDOC ## GET /options/greeks ### Description Get Greeks for a specific option contract (OSI format). ### Method GET ### Endpoint /options/greeks ### Parameters #### Query Parameters - **osi_option_symbol** (string) - Required - The OSI symbol of the option contract. ### Request Example ```python greeks = client.get_option_greeks( osi_option_symbol="AAPL260116C00270000" ) ``` ### Response #### Success Response (200) - **delta** (float) - The option's Delta. - **gamma** (float) - The option's Gamma. - **vega** (float) - The option's Vega. - **theta** (float) - The option's Theta. #### Response Example ```json { "delta": 0.65, "gamma": 0.05, "vega": 0.10, "theta": -0.02 } ``` ``` -------------------------------- ### Client Configuration Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Details on configuring the PublicApiClient with authentication and default account settings. ```APIDOC ## API Reference ### Client Configuration The `PublicApiClient` is initialized with an API secret key and optional configuration. ```python from public_api_sdk import PublicApiClient, PublicApiClientConfiguration from public_api_sdk.auth_config import ApiKeyAuthConfig config = PublicApiClientConfiguration( default_account_number="INSERT_ACCOUNT_NUMBER", # Optional default account ) client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="INSERT_API_SECRET_KEY"), config=config ) ``` #### Default Account Number The `default_account_number` configuration simplifies API calls by automatically using the specified account ID when no `account_id` is provided. ```python # With default_account_number configured from public_api_sdk import OrderInstrument, InstrumentType config = PublicApiClientConfiguration( default_account_number="INSERT_ACCOUNT_NUMBER" ) client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="INSERT_API_SECRET_KEY"), config=config ) instruments = [ OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), OrderInstrument(symbol="MSFT", type=InstrumentType.EQUITY) ] # No need to specify account_id portfolio = client.get_portfolio() # Uses default account number quotes = client.get_quotes(instruments) # Uses default account number # You can still override with a specific account other_portfolio = client.get_portfolio(account_id="DIFFERENT123") # Uses "DIFFERENT123" ``` ```python # Without default_account_number config = PublicApiClientConfiguration() client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="INSERT_API_SECRET_KEY"), config=config ) # Must specify account_id for each call portfolio = client.get_portfolio(account_id="INSERT_ACCOUNT_NUMBER") # Required quotes = client.get_quotes(instruments, account_id="INSERT_ACCOUNT_NUMBER") # Required ``` This is useful for single-account usage to reduce code repetition. ``` -------------------------------- ### Get Quotes Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Retrieve real-time quotes for multiple instruments. This endpoint is useful for monitoring the latest prices of various assets. ```APIDOC ## GET /quotes ### Description Retrieve real-time quotes for multiple instruments. ### Method GET ### Endpoint /quotes ### Parameters #### Query Parameters - **instruments** (list of OrderInstrument) - Required - A list of instruments for which to retrieve quotes. ### Request Example ```python from public_api_sdk import OrderInstrument, InstrumentType quotes = client.get_quotes([ OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), OrderInstrument(symbol="GOOGL", type=InstrumentType.EQUITY) ]) ``` ### Response #### Success Response (200) - **quote** (Quote) - Details for a specific instrument quote. - **instrument** (OrderInstrument) - The instrument for which the quote is provided. - **last** (float) - The last traded price. #### Response Example ```json [ { "instrument": {"symbol": "AAPL", "type": "EQUITY"}, "last": 170.00 }, { "instrument": {"symbol": "GOOGL", "type": "EQUITY"}, "last": 2800.00 } ] ``` ``` -------------------------------- ### Initialize Public API Python Client Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Demonstrates how to initialize the `PublicApiClient` with API credentials and optional configuration. The client is used for interacting with the Public Trading API. It requires an API secret key and can optionally use a default account number. ```python from public_api_sdk import PublicApiClient, PublicApiClientConfiguration from public_api_sdk.auth_config import ApiKeyAuthConfig # Initialize the client with API key and default account number client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="INSERT_API_SECRET_KEY"), config=PublicApiClientConfiguration( default_account_number="INSERT_ACCOUNT_NUMBER" ) ) ``` -------------------------------- ### Get Option Expirations Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Retrieve available option expiration dates for an underlying instrument. This is a prerequisite for fetching option chains. ```APIDOC ## GET /options/expirations ### Description Retrieve available option expiration dates for an underlying instrument. ### Method GET ### Endpoint /options/expirations ### Parameters #### Query Parameters - **instrument** (OrderInstrument) - Required - The underlying instrument for which to get expirations. ### Request Example ```python from public_api_sdk import OptionExpirationsRequest, OrderInstrument, InstrumentType expirations = client.get_option_expirations( OptionExpirationsRequest( instrument=OrderInstrument( symbol="AAPL", type=InstrumentType.EQUITY ) ) ) ``` ### Response #### Success Response (200) - **expirations** (list of string) - A list of available expiration dates in YYYY-MM-DD format. #### Response Example ```json { "expirations": ["2024-12-20", "2025-01-17", "2025-02-21"] } ``` ``` -------------------------------- ### Get Order Status Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Retrieve the status and details of a specific order. Use this endpoint to track the execution of your placed orders. ```APIDOC ## GET /orders/{order_id} ### Description Retrieve the status and details of a specific order. ### Method GET ### Endpoint /orders/{order_id} ### Parameters #### Path Parameters - **order_id** (string) - Required - The unique identifier of the order to retrieve. #### Query Parameters - **account_id** (string) - Optional - The account ID for which to retrieve the order. If not provided, the default account will be used. ### Response #### Success Response (200) - **status** (string) - The current status of the order (e.g., "FILLED", "PENDING", "CANCELLED"). - Other order details might be included. #### Response Example ```json { "order_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "status": "FILLED", "filled_quantity": 10, "average_price": 227.50 } ``` ``` -------------------------------- ### Equity Order Preflight Calculation (Python) Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Calculates the estimated commission, fees, and order value before placing an equity order. Requires details like instrument, side, type, quantity, and limit price. Returns a PreflightResponse object. ```python from public_api_sdk import PreflightRequest, OrderSide, OrderType, TimeInForce, OrderInstrument, InstrumentType, OrderExpirationRequest from decimal import Decimal preflight_request = PreflightRequest( instrument=OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), order_side=OrderSide.BUY, order_type=OrderType.LIMIT, expiration=OrderExpirationRequest(time_in_force=TimeInForce.DAY), quantity=10, limit_price=Decimal("227.50") ) preflight_response = client.perform_preflight_calculation(preflight_request) print(f"Estimated commission: ${preflight_response.estimated_commission}") print(f"Order value: ${preflight_response.order_value}") ``` -------------------------------- ### Place Single-Leg Order (Python) Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Submits a buy or sell order for equities or options with comprehensive parameters such as order ID, instrument details, side, type, quantity, and limit price. It also includes functionality to retrieve the order status and cancel the order if it's still open. Requires API key authentication and an account number. ```python import uuid from decimal import Decimal from public_api_sdk import ( PublicApiClient, PublicApiClientConfiguration, OrderRequest, OrderInstrument, InstrumentType, OrderSide, OrderType, TimeInForce, OrderExpirationRequest, OrderStatus ) from public_api_sdk.auth_config import ApiKeyAuthConfig client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration(default_account_number="ACCT123456") ) try: # Create order request with unique ID order_request = OrderRequest( order_id=str(uuid.uuid4()), instrument=OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), order_side=OrderSide.BUY, order_type=OrderType.LIMIT, expiration=OrderExpirationRequest(time_in_force=TimeInForce.DAY), quantity=Decimal("10"), limit_price=Decimal("227.50") ) # Place the order new_order = client.place_order(order_request) print(f"Order placed successfully!") print(f"Order ID: {new_order.order_id}") # Get order status (after brief delay) import time time.sleep(1) order_details = client.get_order(order_id=new_order.order_id) print(f"\nOrder Status: {order_details.status.value}") print(f"Order Type: {order_details.type.value}") print(f"Side: {order_details.side.value}") print(f"Quantity: {order_details.quantity}") print(f"Limit Price: ${order_details.limit_price}") # Cancel order if still open if order_details.status in [OrderStatus.NEW, OrderStatus.PARTIALLY_FILLED]: client.cancel_order(order_id=new_order.order_id) print("\nOrder cancellation submitted") except Exception as e: print(f"Error placing order: {e}") finally: client.close() ``` -------------------------------- ### Configure and Subscribe to Price Changes Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Demonstrates how to create a custom subscription configuration with specific polling and retry settings, and then use it to subscribe to price changes for instruments. This is useful for creating custom real-time data feeds. ```python config = SubscriptionConfig( polling_frequency_seconds=1.0, # poll every second retry_on_error=True, # retry on API errors max_retries=5, # maximum retry attempts exponential_backoff=True # use exponential backoff for retries ) subscription_id = client.subscribe_to_price_changes( instruments=instruments, callback=on_price_change, config=config ) ``` -------------------------------- ### Get Option Chain Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Retrieve the option chain for a specific expiration date and underlying instrument. This provides details for all call and put options. ```APIDOC ## GET /options/chain ### Description Retrieve the option chain for a specific expiration date. ### Method GET ### Endpoint /options/chain ### Parameters #### Query Parameters - **instrument** (OrderInstrument) - Required - The underlying instrument. - **expiration_date** (string) - Required - The expiration date in YYYY-MM-DD format. ### Request Example ```python from public_api_sdk import OptionChainRequest, InstrumentType # Assuming 'expirations' is a list obtained from get_option_expirations option_chain = client.get_option_chain( OptionChainRequest( instrument=OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), expiration_date=expirations.expirations[0] # Using the first available expiration ) ) ``` ### Response #### Success Response (200) - **option_chain** (OptionChain) - The option chain data. - **calls** (list of Option) - List of call options. - **puts** (list of Option) - List of put options. #### Response Example ```json { "calls": [ { "strike": 170.0, "symbol": "AAPL241220C00170000", "last_price": 5.50, "bid_price": 5.40, "ask_price": 5.60, "volume": 1000, "open_interest": 5000 } // ... more call options ], "puts": [ { "strike": 170.0, "symbol": "AAPL241220P00170000", "last_price": 3.20, "bid_price": 3.10, "ask_price": 3.30, "volume": 800, "open_interest": 4500 } // ... more put options ] } ``` ``` -------------------------------- ### Equity Preflight Calculation Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Calculate estimated costs and potential impact before placing an equity order. This provides a preview of order details like commission and total value. ```APIDOC ## POST /preflight/equity ### Description Calculate estimated costs and impact before placing an equity order. ### Method POST ### Endpoint /preflight/equity ### Parameters #### Request Body - **instrument** (OrderInstrument) - Required - Details of the equity instrument. - **order_side** (OrderSide) - Required - BUY or SELL. - **order_type** (OrderType) - Required - Type of order (e.g., MARKET, LIMIT). - **expiration** (OrderExpirationRequest) - Required - Expiration details for the order. - **quantity** (int) - Required - Number of shares to trade. - **limit_price** (Decimal) - Optional - The limit price if order_type is LIMIT. ### Request Example ```python from public_api_sdk import PreflightRequest, OrderSide, OrderType, TimeInForce, OrderInstrument, InstrumentType from public_api_sdk import OrderExpirationRequest from decimal import Decimal preflight_request = PreflightRequest( instrument=OrderInstrument(symbol="AAPL", type=InstrumentType.EQUITY), order_side=OrderSide.BUY, order_type=OrderType.LIMIT, expiration=OrderExpirationRequest(time_in_force=TimeInForce.DAY), quantity=10, limit_price=Decimal("227.50") ) preflight_response = client.perform_preflight_calculation(preflight_request) ``` ### Response #### Success Response (200) - **estimated_commission** (float) - The estimated commission for the order. - **order_value** (float) - The total value of the order. #### Response Example ```json { "estimated_commission": 0.00, "order_value": 2275.00 } ``` ``` -------------------------------- ### Place Single-Leg Order Source: https://github.com/publicdotcom/publicdotcom-py/blob/main/README.md Submit a single-leg equity or option order. This endpoint is used for placing individual buy or sell orders for a specific instrument. ```APIDOC ## POST /orders ### Description Submit a single-leg equity or option order. ### Method POST ### Endpoint /orders ### Parameters #### Request Body - **order_id** (string) - Required - Unique identifier for the order. - **instrument** (object) - Required - Details of the financial instrument. - **symbol** (string) - Required - The trading symbol of the instrument (e.g., "AAPL"). - **type** (string) - Required - The type of instrument (e.g., "EQUITY", "OPTION"). - **order_side** (string) - Required - The side of the order (e.g., "BUY", "SELL"). - **order_type** (string) - Required - The type of order (e.g., "LIMIT", "MARKET"). - **expiration** (object) - Required - Order expiration details. - **time_in_force** (string) - Required - The duration the order remains active (e.g., "DAY", "GTD"). - **quantity** (integer) - Required - The number of shares or contracts to trade. - **limit_price** (number) - Optional - The limit price for limit orders. ### Request Example ```json { "order_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "instrument": { "symbol": "AAPL", "type": "EQUITY" }, "order_side": "BUY", "order_type": "LIMIT", "expiration": { "time_in_force": "DAY" }, "quantity": 10, "limit_price": 227.50 } ``` ### Response #### Success Response (200) - **order_id** (string) - The ID of the placed order. #### Response Example ```json { "order_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Python Async Price Change Subscription with Callbacks Source: https://context7.com/publicdotcom/publicdotcom-py/llms.txt Subscribes to price changes using an asynchronous callback for non-blocking operations. It processes price updates, calculates percentage changes, and alerts on significant movements. Requires the public-api-sdk library. Handles order instruments for equities like SPY and QQQ. ```python import asyncio from decimal import Decimal from public_api_sdk import ( PublicApiClient, PublicApiClientConfiguration, OrderInstrument, InstrumentType, PriceChange, SubscriptionConfig ) from public_api_sdk.auth_config import ApiKeyAuthConfig async def main(): client = PublicApiClient( ApiKeyAuthConfig(api_secret_key="your_api_secret_key"), config=PublicApiClientConfiguration(default_account_number="ACCT123456") ) try: # Track price history price_history = {} # Async callback with complex logic async def on_price_change_async(price_change: PriceChange): symbol = price_change.instrument.symbol new_price = price_change.new_quote.last # Track prices if symbol not in price_history: price_history[symbol] = [] price_history[symbol].append(new_price) # Calculate percentage change if price_change.old_quote and price_change.old_quote.last: old_price = price_change.old_quote.last pct_change = ((new_price - old_price) / old_price) * 100 # Alert on significant changes if abs(pct_change) > 1: print(f"ALERT: {symbol} moved {pct_change:.2f}%!") print(f"{symbol}: ${new_price:.2f}") # Simulate async processing await asyncio.sleep(0.1) # Subscribe with async callback instruments = [ OrderInstrument(symbol="SPY", type=InstrumentType.EQUITY), OrderInstrument(symbol="QQQ", type=InstrumentType.EQUITY) ] subscription_id = client.price_stream.subscribe( instruments=instruments, callback=on_price_change_async, # Async callback automatically detected config=SubscriptionConfig( polling_frequency_seconds=1.0, retry_on_error=True, max_retries=5, exponential_backoff=True ) ) print(f"Started async subscription: {subscription_id}\n") # Monitor for 30 seconds await asyncio.sleep(30) client.price_stream.unsubscribe(subscription_id) print("\nStopped subscription") except Exception as e: print(f"Error: {e}") finally: client.close() # Run async example asyncio.run(main()) ```