### Install schwab-py Source: https://github.com/alexgolec/schwab-py/blob/main/README.rst Install the library using pip. This is the first step before using any of its functionalities. ```bash pip install schwab-py ``` -------------------------------- ### Set up virtual environment Source: https://github.com/alexgolec/schwab-py/blob/main/docs/contributing.md Installs and activates a virtual environment for development. This helps isolate project dependencies. ```shell pip install virtualenv virtualenv -v virtualenv source virtualenv/bin/activate ``` -------------------------------- ### Install project development dependencies Source: https://github.com/alexgolec/schwab-py/blob/main/docs/contributing.md Installs all necessary packages for development, including testing and documentation tools. ```shell pip install ".[dev]" ``` -------------------------------- ### Build documentation with Sphinx Source: https://github.com/alexgolec/schwab-py/blob/main/docs/contributing.md Builds the project's documentation using Sphinx. Ensure you have Sphinx installed and configured. ```shell sphinx-build docs/ docs-build ``` -------------------------------- ### Verify schwab-py Installation Source: https://github.com/alexgolec/schwab-py/blob/main/docs/getting-started.md Import the schwab library in Python to confirm that the installation was successful. ```python import schwab ``` -------------------------------- ### Create Asynchronous Client and Fetch Price History Source: https://github.com/alexgolec/schwab-py/blob/main/docs/client.md Set up an asynchronous client by passing `asyncio=True` to `easy_client` for high-performance API interactions. This example demonstrates fetching price history within an asyncio event loop. ```python from schwab.auth import client_from_manual_flow async def main(): c = easy_client( api_key='APIKEY', redirect_uri='https://localhost', token_path='/tmp/token.json', asyncio=True) resp = await c.get_price_history_every_day('AAPL') assert resp.status_code == httpx.codes.OK history = resp.json() if __name__ == '__main__': import asyncio asyncio.run_until_complete(main()) ``` -------------------------------- ### Get schwab-py Version Source: https://github.com/alexgolec/schwab-py/blob/main/docs/help.md Execute this command in a Python shell to retrieve the installed version of schwab-py. Ensure you are using the latest version before seeking help. ```python print(schwab.__version__) ``` -------------------------------- ### Simple Limit Order Spec Source: https://github.com/alexgolec/schwab-py/blob/main/docs/order-builder.md Example of a spec for a limit order to buy shares of MSFT. This is equivalent to schwab.orders.equities.equity_buy_limit(). ```JSON { "session": "NORMAL", "duration": "DAY", "orderType": "LIMIT", "price": "190.90", "orderLegCollection": [ { "instruction": "BUY", "instrument": { "assetType": "EQUITY", "symbol": "MSFT" }, "quantity": 1 } ], "orderStrategyType": "SINGLE" } ``` -------------------------------- ### Sample Message Handler Source: https://github.com/alexgolec/schwab-py/blob/main/docs/streaming.md A basic example of a handler function that can be registered with the stream client to process incoming messages. It prints the received message in a JSON format. ```python import json def sample_handler(msg): print(json.dumps(msg, indent=4)) ``` -------------------------------- ### Get Equity Exchange Information Source: https://github.com/alexgolec/schwab-py/blob/main/docs/streaming.md Use Client.search_instruments to find the exchange for a given equity symbol. This is useful for determining which order book stream to subscribe to. ```python r = c.search_instruments(['GOOG'], projection=c.Instrument.Projection.FUNDAMENTAL) assert r.status_code == httpx.codes.OK, r.raise_for_status() print(r.json()['GOOG']['exchange']) # Outputs NASDAQ ``` -------------------------------- ### Original JSON with Numerical Labels Source: https://github.com/alexgolec/schwab-py/blob/main/docs/streaming.md This is an example of the raw JSON response from the API before relabeling, where data fields are represented by numerical keys. ```json { "service": "CHART_EQUITY", "timestamp": 1715908546054, "command": "SUBS", "content": [{ "seq": 0, "key": "MSFT", "1": 779, "2": 421.65, "3": 421.79, "4": 421.65, "5": 421.755, "6": 26.0, "7": 1715903940000, "8": 19859 }] } ``` -------------------------------- ### Build a Complex OCO Order with OrderBuilder Source: https://github.com/alexgolec/schwab-py/blob/main/docs/order-builder.md Use the OrderBuilder and utility functions to construct a complex order, such as a One-Cancels-Other (OCO) order triggered by a limit order. This example demonstrates chaining methods like `set_order_type`, `clear_price`, and `set_stop_price` for detailed order configuration. ```python from schwab.orders.common import OrderType from schwab.orders.generic import OrderBuilder one_triggers_other( equity_buy_limit('GOOG', 1, 1310), one_cancels_other( equity_sell_limit('GOOG', 1, 1400), equity_sell_limit('GOOG', 1, 1240) .set_order_type(OrderType.STOP_LIMIT) .clear_price() .set_stop_price(1250) )) ``` -------------------------------- ### Relabeled JSON with String Labels Source: https://github.com/alexgolec/schwab-py/blob/main/docs/streaming.md This example shows the same data after the schwab-api library has automatically relabeled the numerical keys to descriptive string labels, making the data easier to understand. ```json { "service": "CHART_EQUITY", "timestamp": 1715908546054, "command": "SUBS", "content": [{ "seq": 0, "key": "MSFT", "SEQUENCE": 779, "OPEN_PRICE": 421.65, "HIGH_PRICE": 421.79, "LOW_PRICE": 421.65, "CLOSE_PRICE": 421.755, "VOLUME": 26.0, "CHART_TIME_MILLIS": 1715903940000, "CHART_DAY": 19859 }] } ``` -------------------------------- ### Complex Standing and OCO Order Spec Source: https://github.com/alexgolec/schwab-py/blob/main/docs/order-builder.md Example of a spec for a standing limit order to buy GOOG, with a one-cancels-other (OCO) order to exit if the price rises or falls. This demonstrates advanced order strategies. ```JSON { "session": "NORMAL", "duration": "GOOD_TILL_CANCEL", "orderType": "LIMIT", "price": "1310.00", "orderLegCollection": [ { "instruction": "BUY", "instrument": { "assetType": "EQUITY", "symbol": "GOOG" }, "quantity": 1 } ], "orderStrategyType": "TRIGGER", "childOrderStrategies": [ { "orderStrategyType": "OCO", "childOrderStrategies": [ { "session": "NORMAL", "duration": "GOOD_TILL_CANCEL", "orderType": "LIMIT", "price": "1400.00", "orderLegCollection": [ { "instruction": "SELL", "instrument": { "assetType": "EQUITY", "symbol": "GOOG" }, "quantity": 1 } ] }, { "session": "NORMAL", "duration": "GOOD_TILL_CANCEL", "orderType": "STOP_LIMIT", "stopPrice": "1250.00", "orderLegCollection": [ { "instruction": "SELL", "instrument": { "assetType": "EQUITY", "symbol": "GOOG" }, "quantity": 1 } ] } ] } ] } ``` -------------------------------- ### Synchronous Client Initialization and Usage Source: https://github.com/alexgolec/schwab-py/blob/main/docs/client.md Demonstrates how to initialize a synchronous HTTP client using `easy_client` and make a call to `get_price_history_every_day`. ```APIDOC ## Synchronous Client Initialization and Usage ### Description This example shows how to create a synchronous client instance using `easy_client` and then use it to fetch historical price data for a given symbol. ### Method `easy_client` (constructor) `get_price_history_every_day` (method) ### Parameters for `easy_client` - **api_key** (string) - Required - Your Schwab API key. - **app_secret** (string) - Required - Your Schwab application secret. - **callback_url** (string) - Required - The callback URL for OAuth2. - **token_path** (string) - Required - Path to store the OAuth2 token. ### Parameters for `get_price_history_every_day` - **symbol** (string) - Required - The stock symbol (e.g., 'AAPL'). ### Request Example (Conceptual) ```python from schwab.auth import client_from_manual_flow c = easy_client( api_key='APIKEY', app_secret='APP_SECRET', callback_url='https://127.0.0.1', token_path='/tmp/token.json') resp = c.get_price_history_every_day('AAPL') ``` ### Response #### Success Response (200) - **resp** (httpx.Response) - The HTTP response object containing the price history data. #### Response Example (Conceptual) ```python assert resp.status_code == httpx.codes.OK history = resp.json() ``` ``` -------------------------------- ### Asynchronous Client Initialization and Usage Source: https://github.com/alexgolec/schwab-py/blob/main/docs/client.md Illustrates how to initialize an asynchronous HTTP client and perform an asynchronous API call. ```APIDOC ## Asynchronous Client Initialization and Usage ### Description This example demonstrates setting up an asynchronous client using the `asyncio=True` flag in `easy_client` and making an `await`able call to `get_price_history_every_day`. ### Method `easy_client` (constructor) `get_price_history_every_day` (method) ### Parameters for `easy_client` - **api_key** (string) - Required - Your Schwab API key. - **redirect_uri** (string) - Required - The redirect URI for OAuth2. - **token_path** (string) - Required - Path to store the OAuth2 token. - **asyncio** (boolean) - Required - Set to `True` to enable asynchronous operations. ### Parameters for `get_price_history_every_day` - **symbol** (string) - Required - The stock symbol (e.g., 'AAPL'). ### Request Example (Conceptual) ```python from schwab.auth import client_from_manual_flow async def main(): c = easy_client( api_key='APIKEY', redirect_uri='https://localhost', token_path='/tmp/token.json', asyncio=True) resp = await c.get_price_history_every_day('AAPL') ``` ### Response #### Success Response (200) - **resp** (httpx.Response) - The HTTP response object containing the price history data. #### Response Example (Conceptual) ```python assert resp.status_code == httpx.codes.OK history = resp.json() ``` ``` -------------------------------- ### Create Synchronous Client and Fetch Price History Source: https://github.com/alexgolec/schwab-py/blob/main/docs/client.md Instantiate a synchronous client using `easy_client` and retrieve daily price history for a given symbol. Ensure you have the necessary API credentials and a valid token path. ```python from schwab.auth import client_from_manual_flow # Follow the instructions on the screen to authenticate your client. c = easy_client( api_key='APIKEY', app_secret='APP_SECRET', callback_url='https://127.0.0.1', token_path='/tmp/token.json') resp = c.get_price_history_every_day('AAPL') assert resp.status_code == httpx.codes.OK history = resp.json() ``` -------------------------------- ### Create an authenticated client using easy_client() Source: https://github.com/alexgolec/schwab-py/blob/main/docs/auth.md Use `easy_client()` to create an authenticated client. This method attempts to load an existing token or initiates an OAuth flow to create a new one. Ensure you have your API key, app secret, and callback URL configured. ```python from schwab.auth import easy_client # Follow the instructions on the screen to authenticate your client. c = easy_client( api_key='APIKEY', app_secret='APP_SECRET', callback_url='https://127.0.0.1', token_path='/tmp/token.json') resp = c.get_price_history_every_day('AAPL') assert resp.status_code == httpx.codes.OK history = resp.json() ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/alexgolec/schwab-py/blob/main/docs/getting-started.md Use these commands to create a virtual environment named 'my-venv' and activate it. Ensure you are in your project directory. ```shell pip install virtualenv virtualenv -v my-venv source my-venv/bin/activate ``` -------------------------------- ### Receive Book Snapshots for GOOG Source: https://github.com/alexgolec/schwab-py/blob/main/docs/streaming.md Demonstrates the end-to-end workflow for receiving real-time market data, specifically book snapshots for a given symbol. Ensure you are logged in and have handlers registered before subscribing. ```python from schwab.auth import easy_client from schwab.client import Client from schwab.streaming import StreamClient import asyncio import json # Assumes you've already created a token. See the authentication page for more # information. client = easy_client( api_key='YOUR_API_KEY', app_secret='YOUR_APP_SECRET', callback_url='https://127.0.0.1', token_path='/path/to/token.json') stream_client = StreamClient(client, account_id=1234567890) async def read_stream(): await stream_client.login() def print_message(message): print(json.dumps(message, indent=4)) # Always add handlers before subscribing because many streams start sending # data immediately after success, and messages with no handlers are dropped. stream_client.add_nasdaq_book_handler(print_message) await stream_client.nasdaq_book_subs(['GOOG']) while True: await stream_client.handle_message() asyncio.run(read_stream()) ``` -------------------------------- ### Fetch Account Hash and Place Order Source: https://github.com/alexgolec/schwab-py/blob/main/docs/client.md This snippet shows how to retrieve account numbers and their corresponding hashes using `get_account_numbers`, and then use an account hash to place a market order for AAPL. ```python import atexit import httpx from selenium import webdriver from schwab.auth import easy_client from schwab.orders.equities import equity_buy_market def make_webdriver(): driver = webdriver.Firefox() atexit.register(lambda: driver.quit()) return driver c = easy_client( token_path='/path/to/token.json', api_key='api-key', app_secret='app-secret', callback_url='https://callback.com', webdriver_func=make_webdriver) resp = c.get_account_numbers() assert resp.status_code == httpx.codes.OK # The response has the following structure. If you have multiple linked # accounts, you'll need to inspect this object to find the hash you want: # [ # { # "accountNumber": "123456789", # "hashValue":"123ABCXYZ" # } #] account_hash = resp.json()[0]['hashValue'] c.place_order(account_hash, equity_buy_market('AAPL', 1)) ``` -------------------------------- ### Place a Limit Buy Order with Custom Duration and Session Source: https://github.com/alexgolec/schwab-py/blob/main/docs/order-templates.md This snippet demonstrates how to place a limit buy order for a specific stock, setting a custom duration to Good Till Cancelled and a seamless session. It requires the 'equity_buy_limit' function and the 'Duration' and 'Session' enums from schwab.orders. ```python from schwab.orders.equities import equity_buy_limit from schwab.orders.common import Duration, Session client = ... # See "Authentication and Client Creation" client.place_order( 1000, # account_id equity_buy_limit('GOOG', 1, 1250.0) .set_duration(Duration.GOOD_TILL_CANCEL) .set_session(Session.SEAMLESS) .build()) ``` -------------------------------- ### Incorrect Composite Order Construction Source: https://github.com/alexgolec/schwab-py/blob/main/docs/order-templates.md Demonstrates the incorrect way to construct a 'first triggers second' composite order by placing constituent orders first. This method leads to errors as both orders are executed independently before the composite logic is applied. ```python order_one = c.place_order(config.account_id, option_buy_to_open_limit(trade_symbol, contracts, safety_ask) .set_duration(Duration.GOOD_TILL_CANCEL) .set_session(Session.NORMAL) .build()) order_two = c.place_order(config.account_id, option_sell_to_close_limit(trade_symbol, half, double) .set_duration(Duration.GOOD_TILL_CANCEL) .set_session(Session.NORMAL) .build()) # THIS IS BAD, DO NOT DO THIS exec_trade = c.place_order(config.account_id, first_triggers_second(order_one, order_two)) ``` -------------------------------- ### Run project tests Source: https://github.com/alexgolec/schwab-py/blob/main/docs/contributing.md Executes the project's test suite to verify code integrity and ensure changes haven't introduced regressions. ```shell make test ``` -------------------------------- ### Generate Schwab Token Script Usage Source: https://github.com/alexgolec/schwab-py/blob/main/docs/auth.md Use this script to fetch a new token and save it to a file. It is useful for generating tokens on one machine and using them on another. Ensure pip's executable locations are in your PATH. ```bash usage: schwab-generate-token.py [-h] --token_file TOKEN_FILE --api_key API_KEY --app_secret APP_SECRET --callback_url CALLBACK_URL [--browser BROWSER] Fetch a new token and write it to a file options: -h, --help show this help message and exit required arguments: --token_file TOKEN_FILE Path to token file. Any existing file will be overwritten --api_key API_KEY --app_secret APP_SECRET --callback_url CALLBACK_URL --browser BROWSER Manually specify a browser in which to start the login flow. See here for available options: https://docs.python.org/3/library/webbrowser.html#webbrowser.register ``` -------------------------------- ### Authenticate and Fetch Historical Price Data Source: https://github.com/alexgolec/schwab-py/blob/main/README.rst Demonstrates how to authenticate with the Charles Schwab API using your credentials and fetch daily historical price data for a given symbol. Ensure your API key, app secret, and callback URL are correctly configured, and the token path is valid. ```python from schwab import auth, client import json api_key = 'YOUR_API_KEY' app_secret = 'YOUR_APP_SECRET' callback_url = 'https://127.0.0.1:8182/' token_path = '/path/to/token.json' c = auth.easy_client(api_key, app_secret, callback_url, token_path) r = c.get_price_history_every_day('AAPL') r.raise_for_status() print(json.dumps(r.json(), indent=4)) ``` -------------------------------- ### Build Option Symbol Source: https://github.com/alexgolec/schwab-py/blob/main/docs/order-templates.md Use the OptionSymbol helper to construct syntactically correct option symbols. This utility does not validate if the symbol represents a traded option. ```python from schwab.orders.options import OptionSymbol symbol = OptionSymbol( 'TSLA', datetime.date(year=2020, month=11, day=20), 'P', '1360').build() ``` -------------------------------- ### Handling API Responses Source: https://github.com/alexgolec/schwab-py/blob/main/docs/client.md This pattern demonstrates how to make an API call, check for success status codes, and extract JSON data from the response. It uses httpx for status checking and raises an exception for non-success responses. ```python r = client.some_endpoint() assert r.status_code == httpx.codes.OK, r.raise_for_status() data = r.json() ``` -------------------------------- ### Generate Order Code from Recent Order Source: https://github.com/alexgolec/schwab-py/blob/main/docs/order-builder.md Use this script to generate schwab-py code for your most recently placed order. Ensure pip's executable locations are in your PATH. ```shell schwab-order-codegen.py --token_file --api_key ``` -------------------------------- ### Upgrade schwab-py Source: https://github.com/alexgolec/schwab-py/blob/main/docs/help.md Use this pip command to upgrade schwab-py to the most recent version. This is recommended before asking for help to ensure you are on the latest stable release. ```bash pip install --upgrade schwab-py ``` -------------------------------- ### Enable Root Logger Debug Logging Source: https://github.com/alexgolec/schwab-py/blob/main/docs/help.md Enable diagnostic logging for the root logger to capture schwab-py's internal activity. This can help in debugging issues by providing detailed operational information. ```python import logging logging.getLogger('').addHandler(logging.StreamHandler()) ``` -------------------------------- ### Enable Bug Report Logging in schwab-py Source: https://github.com/alexgolec/schwab-py/blob/main/docs/help.md Call this method before any other schwab-py operations to enable special functionality for gathering and preparing logs for bug reports. It captures, anonymizes, and dumps logs upon program exit. ```python schwab.debug.enable_bug_report_logging() ``` -------------------------------- ### Extract Order ID from Place Order Response Source: https://github.com/alexgolec/schwab-py/blob/main/docs/util.md Extracts the order ID from the 'Location' header of a successful order placement response. This ID is crucial for monitoring or modifying orders. ```python import httpx # Assume client and order already exist and are valid account_id = ... # Fetched from account_information r = client.place_order(account_hash, order) assert r.status_code == httpx.codes.OK, r.raise_for_status() order_id = Utils(client, account_hash).extract_order_id(r) assert order_id is not None ``` -------------------------------- ### Deactivate virtual environment Source: https://github.com/alexgolec/schwab-py/blob/main/docs/contributing.md Exits the currently active virtual environment in the terminal session. ```shell deactivate ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.