### Install Schwab API Client Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Install the Schwab API client library using npm. ```bash npm install @sudowealth/schwab-api ``` -------------------------------- ### Basic Schwab API Client Setup Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Set up the Schwab API client using `createSchwabAuth` and `createApiClient`. Requires Schwab developer credentials as environment variables. This example uses the OAuth 2.0 Code Flow and demonstrates generating a login URL and exchanging an authorization code for tokens. ```typescript import { createSchwabAuth, createApiClient } from '@sudowealth/schwab-api' // Create the auth manager (Enhanced OAuth client) const auth = createSchwabAuth({ oauthConfig: { clientId: process.env.SCHWAB_CLIENT_ID!, clientSecret: process.env.SCHWAB_CLIENT_SECRET!, redirectUri: 'https://example.com/callback', // Optional: provide persistence callbacks // save: async (tokens) => { ... }, // load: async () => { ... }, }, }) // Generate login URL console.log('Visit:', auth.getAuthorizationUrl().authUrl) // Exchange auth code for tokens (when user returns) const tokens = await auth.exchangeCode('') // Optionally persist tokens here... // Create API client using the auth manager const schwab = createApiClient({ auth }) ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/sudowealth/schwab-api/blob/main/CONTRIBUTING.md Steps to clone the repository locally and install project dependencies using npm. ```bash git clone https://github.com/your-username/schwab-api.git cd schwab-api npm install ``` -------------------------------- ### Install Beta Version of schwab-api Source: https://github.com/sudowealth/schwab-api/blob/main/CONTRIBUTING.md Installs the latest beta version of the schwab-api package using npm. ```bash npm install @sudowealth/schwab-api@beta ``` -------------------------------- ### Get User Preferences Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Retrieves the current user's preferences and settings. ```APIDOC ## Get User Preferences ### Description Retrieves the current user's preferences and settings. ### Method ``` GET ``` ### Endpoint ``` /user/preferences ``` ### Response #### Success Response (200) - **preferences** (object) - An object containing user preferences. ### Request Example ```typescript const preferences = await schwab.trader.userPreference.getUserPreference() ``` ``` -------------------------------- ### Environment Variables for Credentials Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Example of how to store sensitive API credentials using environment variables in a .env file. Never commit this file to version control. ```bash # .env (never commit this file) SCHWAB_CLIENT_ID=your-client-id SCHWAB_CLIENT_SECRET=your-client-secret ENCRYPTION_KEY=your-256-bit-hex-key ``` -------------------------------- ### Get Accounts Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Retrieves a list of all available accounts for the authenticated user. ```APIDOC ## Get Accounts ### Description Retrieves a list of all available accounts for the authenticated user. ### Method ``` GET ``` ### Endpoint ``` /accounts ``` ### Parameters #### Query Parameters - **fields** (string) - Optional - Specifies which fields to include in the response. Example: 'positions'. ### Response #### Success Response (200) - **accounts** (array) - A list of account objects. ### Request Example ```typescript const accounts = await schwab.trader.accounts.getAccounts() ``` ``` -------------------------------- ### Order Management Source: https://context7.com/sudowealth/schwab-api/llms.txt Manage the full order lifecycle: list, place, get, replace, and cancel orders. ```APIDOC ## `schwab.trader.orders.getOrdersByAccount` — Get Orders by Account Retrieve a list of orders for a specific account, with filtering options. ### Parameters #### Path Parameters - **accountNumber** (string) - Required - The hashed account number. #### Query Parameters - **maxResults** (number) - Optional - The maximum number of orders to return. - **fromEnteredTime** (string) - Optional - The start date/time for filtering orders (ISO 8601 format). - **toEnteredTime** (string) - Optional - The end date/time for filtering orders (ISO 8601 format). - **status** (string) - Optional - The status of the orders to filter by (e.g., 'WORKING'). ### Request Example ```typescript const orders = await schwab.trader.orders.getOrdersByAccount({ pathParams: { accountNumber: 'your-account-hash' }, queryParams: { maxResults: 50, fromEnteredTime: '2024-01-01T00:00:00.000Z', toEnteredTime: '2024-12-31T23:59:59.999Z', status: 'WORKING', }, }) orders?.forEach((o) => console.log(`Order ${o.orderId}: ${o.status} - ${o.orderType}`)) ``` ### Response #### Success Response - **orders** (array) - An array of order objects. - **orderId** (string) - The unique identifier for the order. - **status** (string) - The current status of the order. - **orderType** (string) - The type of the order (e.g., 'MARKET', 'LIMIT'). ### Related Endpoints - `schwab.trader.orders.placeOrderForAccount` - `schwab.trader.orders.cancelOrder` - `schwab.trader.orders.replaceOrder` ``` ```APIDOC ## `schwab.trader.orders.placeOrderForAccount` — Place an Order Place a new order for a specified account. ### Parameters #### Path Parameters - **accountNumber** (string) - Required - The hashed account number. #### Request Body - **orderType** (string) - Required - The type of order (e.g., 'MARKET', 'LIMIT'). - **session** (string) - Required - The trading session (e.g., 'NORMAL'). - **duration** (string) - Required - The duration of the order (e.g., 'DAY', 'GOOD_TILL_CANCEL'). - **orderStrategyType** (string) - Required - The type of order strategy (e.g., 'SINGLE'). - **price** (number) - Optional - The limit price for 'LIMIT' orders. - **orderLegCollection** (array) - Required - A collection of order legs. - **instruction** (string) - Required - The instruction for the leg (e.g., 'BUY', 'SELL'). - **quantity** (number) - Required - The quantity of the instrument. - **instrument** (object) - Required - Details of the instrument. - **symbol** (string) - Required - The security symbol. - **assetType** (string) - Required - The type of asset (e.g., 'EQUITY'). ### Request Example ```typescript // Place a market buy order const placed = await schwab.trader.orders.placeOrderForAccount({ pathParams: { accountNumber: 'your-account-hash' }, body: { orderType: 'MARKET', session: 'NORMAL', duration: 'DAY', orderStrategyType: 'SINGLE', orderLegCollection: [ { instruction: 'BUY', quantity: 10, instrument: { symbol: 'AAPL', assetType: 'EQUITY' }, }, ], }, }) // On success, the Location header contains the new order ID (HTTP 201) // Place a limit sell order await schwab.trader.orders.placeOrderForAccount({ pathParams: { accountNumber: 'your-account-hash' }, body: { orderType: 'LIMIT', price: 195.00, session: 'NORMAL', duration: 'GOOD_TILL_CANCEL', orderStrategyType: 'SINGLE', orderLegCollection: [ { instruction: 'SELL', quantity: 5, instrument: { symbol: 'AAPL', assetType: 'EQUITY' } }, ], }, }) ``` ### Response #### Success Response (201 Created) - The `Location` header contains the URL of the newly created order. ### Related Endpoints - `schwab.trader.orders.getOrdersByAccount` - `schwab.trader.orders.cancelOrder` - `schwab.trader.orders.replaceOrder` ``` ```APIDOC ## `schwab.trader.orders.cancelOrder` — Cancel an Order Cancel an existing order. ### Parameters #### Path Parameters - **accountNumber** (string) - Required - The hashed account number. - **orderId** (string) - Required - The ID of the order to cancel. ### Request Example ```typescript await schwab.trader.orders.cancelOrder({ pathParams: { accountNumber: 'your-account-hash', orderId: '123456789' }, }) ``` ### Related Endpoints - `schwab.trader.orders.getOrdersByAccount` - `schwab.trader.orders.placeOrderForAccount` - `schwab.trader.orders.replaceOrder` ``` ```APIDOC ## `schwab.trader.orders.replaceOrder` — Replace an Order Replace an existing order with new details. ### Parameters #### Path Parameters - **accountNumber** (string) - Required - The hashed account number. - **orderId** (string) - Required - The ID of the order to replace. #### Request Body - **orderType** (string) - Required - The type of order (e.g., 'MARKET', 'LIMIT'). - **session** (string) - Required - The trading session (e.g., 'NORMAL'). - **duration** (string) - Required - The duration of the order (e.g., 'DAY', 'GOOD_TILL_CANCEL'). - **orderStrategyType** (string) - Required - The type of order strategy (e.g., 'SINGLE'). - **price** (number) - Optional - The limit price for 'LIMIT' orders. - **orderLegCollection** (array) - Required - A collection of order legs. - **instruction** (string) - Required - The instruction for the leg (e.g., 'BUY', 'SELL'). - **quantity** (number) - Required - The quantity of the instrument. - **instrument** (object) - Required - Details of the instrument. - **symbol** (string) - Required - The security symbol. - **assetType** (string) - Required - The type of asset (e.g., 'EQUITY'). ### Request Example ```typescript await schwab.trader.orders.replaceOrder({ pathParams: { accountNumber: 'your-account-hash', orderId: '123456789' }, body: { orderType: 'LIMIT', price: 190.00, session: 'NORMAL', duration: 'DAY', orderStrategyType: 'SINGLE', orderLegCollection: [ { instruction: 'BUY', quantity: 10, instrument: { symbol: 'AAPL', assetType: 'EQUITY' } }, ], }, }) ``` ### Related Endpoints - `schwab.trader.orders.getOrdersByAccount` - `schwab.trader.orders.placeOrderForAccount` - `schwab.trader.orders.cancelOrder` ``` -------------------------------- ### Get Account Details Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Retrieves detailed information for a specific account, with options to include specific fields. ```APIDOC ## Get Account Details ### Description Retrieves detailed information for a specific account, with options to include specific fields. ### Method ``` GET ``` ### Endpoint ``` /accounts/{accountNumber} ``` ### Parameters #### Path Parameters - **accountNumber** (string) - Required - The unique identifier for the account. #### Query Parameters - **fields** (string) - Optional - Specifies which fields to include in the response. Example: 'positions'. ### Response #### Success Response (200) - **account** (object) - Detailed information about the account. ### Request Example ```typescript const account = await schwab.trader.accounts.getAccountByNumber({ pathParams: { accountNumber: 'your-account-hash' }, queryParams: { fields: 'positions' }, }) ``` ``` -------------------------------- ### Get Orders by Account Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Retrieves a list of orders for a specific account, with options to limit the number of results. ```APIDOC ## Get Orders by Account ### Description Retrieves a list of orders for a specific account, with options to limit the number of results. ### Method ``` GET ``` ### Endpoint ``` /accounts/{accountNumber}/orders ``` ### Parameters #### Path Parameters - **accountNumber** (string) - Required - The unique identifier for the account. #### Query Parameters - **maxResults** (number) - Optional - The maximum number of orders to return. Defaults to 50. ### Response #### Success Response (200) - **orders** (array) - A list of order objects. ### Request Example ```typescript const orders = await schwab.trader.orders.getOrdersByAccount({ pathParams: { accountNumber: 'your-account-hash' }, queryParams: { maxResults: 50 }, }) ``` ``` -------------------------------- ### Create Feature or Fix Branch Source: https://github.com/sudowealth/schwab-api/blob/main/CONTRIBUTING.md Commands to create a new branch for feature development or bug fixes, starting from the latest 'main' branch. ```bash git checkout main git pull upstream main git checkout -b feature/your-feature-name # or git checkout -b fix/issue-description ``` -------------------------------- ### Get User Preferences Source: https://context7.com/sudowealth/schwab-api/llms.txt Fetches user-specific metadata such as account nicknames and display IDs. Accesses the `getUserPreference` method from the `trader.userPreference` module. ```typescript const prefs = await schwab.trader.userPreference.getUserPreference() prefs.accounts?.forEach((acc) => { console.log(`${acc.accountNumber}: "${acc.nickName}" (${acc.displayAcctId})`) }) ``` -------------------------------- ### Handle Schwab API Errors Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Example of how to catch and differentiate between specific Schwab API errors like authentication errors and general API errors. ```typescript import { SchwabApiError, SchwabAuthError } from '@sudowealth/schwab-api' try { await schwab.trader.accounts.getAccounts() } catch (error) { if (error instanceof SchwabAuthError) { if (error.code === 'TOKEN_EXPIRED') { // Handle expired tokens } } else if (error instanceof SchwabApiError) { // Handle API errors console.error('API Error:', error.message) } } ``` -------------------------------- ### Manage Orders with Schwab API Source: https://context7.com/sudowealth/schwab-api/llms.txt Perform full order lifecycle operations including listing, placing, getting, replacing, and canceling orders. All order operations require a hashed account number. Use `getOrdersByAccount` to retrieve open orders. ```typescript // Get open orders for an account const orders = await schwab.trader.orders.getOrdersByAccount({ pathParams: { accountNumber: 'your-account-hash' }, queryParams: { maxResults: 50, fromEnteredTime: '2024-01-01T00:00:00.000Z', toEnteredTime: '2024-12-31T23:59:59.999Z', status: 'WORKING', }, }) orders?.forEach((o) => console.log(`Order ${o.orderId}: ${o.status} - ${o.orderType}`)) ``` ```typescript // Place a market buy order const placed = await schwab.trader.orders.placeOrderForAccount({ pathParams: { accountNumber: 'your-account-hash' }, body: { orderType: 'MARKET', session: 'NORMAL', duration: 'DAY', orderStrategyType: 'SINGLE', orderLegCollection: [ { instruction: 'BUY', quantity: 10, instrument: { symbol: 'AAPL', assetType: 'EQUITY' }, }, ], }, }) // On success, the Location header contains the new order ID (HTTP 201) ``` ```typescript // Place a limit sell order await schwab.trader.orders.placeOrderForAccount({ pathParams: { accountNumber: 'your-account-hash' }, body: { orderType: 'LIMIT', price: 195.00, session: 'NORMAL', duration: 'GOOD_TILL_CANCEL', orderStrategyType: 'SINGLE', orderLegCollection: [ { instruction: 'SELL', quantity: 5, instrument: { symbol: 'AAPL', assetType: 'EQUITY' } }, ], }, }) ``` ```typescript // Cancel an order await schwab.trader.orders.cancelOrder({ pathParams: { accountNumber: 'your-account-hash', orderId: '123456789' }, }) ``` ```typescript // Replace an existing order await schwab.trader.orders.replaceOrder({ pathParams: { accountNumber: 'your-account-hash', orderId: '123456789' }, body: { orderType: 'LIMIT', price: 190.00, session: 'NORMAL', duration: 'DAY', orderStrategyType: 'SINGLE', orderLegCollection: [ { instruction: 'BUY', quantity: 10, instrument: { symbol: 'AAPL', assetType: 'EQUITY' } }, ], }, }) ``` -------------------------------- ### Create Schwab API Client Source: https://github.com/sudowealth/schwab-api/blob/main/CLAUDE.md Initializes the main API client using the authenticated auth manager. ```typescript createApiClient({ auth }) ``` -------------------------------- ### Build and Validate TypeScript Project Source: https://github.com/sudowealth/schwab-api/blob/main/CLAUDE.md Commands for building the project and running code quality checks like formatting, linting, and type checking. ```bash npm run build # Clean and compile TypeScript to dist/ npm run validate # Format, lint, and typecheck npm run lint # Lint with Biome npm run typecheck # TypeScript type checking npm run format # Format with Biome ``` -------------------------------- ### KVTokenStore Source: https://context7.com/sudowealth/schwab-api/llms.txt A pre-built token storage adapter for Cloudflare Workers KV Namespaces, offering key migration and TTL management. ```APIDOC ## `KVTokenStore` — Cloudflare KV Token Persistence Pre-built token storage adapter for Cloudflare Workers KV Namespaces with key migration and TTL management. ```typescript import { KVTokenStore, createSchwabAuth } from '@sudowealth/schwab-api' // In a Cloudflare Worker: export default { async fetch(request: Request, env: Env) { const store = new KVTokenStore(env.OAUTH_KV, { keyPrefix: 'schwab:token:', ttl: 31 * 24 * 60 * 60, // 31 days autoMigrate: true, }) const ids = { clientId: process.env.SCHWAB_CLIENT_ID } const auth = createSchwabAuth({ oauthConfig: { clientId: env.SCHWAB_CLIENT_ID, clientSecret: env.SCHWAB_CLIENT_SECRET, redirectUri: env.REDIRECT_URI, load: () => store.load(ids), save: (tokens) => store.save(ids, tokens), }, }) // Or use createBoundFunctions helper: const { load, save } = store.createBoundFunctions({ clientId: env.SCHWAB_CLIENT_ID }) // Migrate from old key scheme await store.migrate( { clientId: 'old-client-id' }, { schwabUserId: 'user-12345' }, ) } } ``` ``` -------------------------------- ### Run Project Validation Source: https://github.com/sudowealth/schwab-api/blob/main/CONTRIBUTING.md Executes linting, type checking, and formatting to ensure code quality before committing. ```bash npm run validate ``` -------------------------------- ### Get Transactions Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Retrieves transaction history for a specific account within a given date range and for specified types. ```APIDOC ## Get Transactions ### Description Retrieves transaction history for a specific account within a given date range and for specified types. ### Method ``` GET ``` ### Endpoint ``` /accounts/{accountNumber}/transactions ``` ### Parameters #### Path Parameters - **accountNumber** (string) - Required - The unique identifier for the account. #### Query Parameters - **types** (string) - Optional - The type of transactions to retrieve (e.g., 'TRADE'). - **startDate** (string) - Optional - The start date for the transaction history (YYYY-MM-DD). - **endDate** (string) - Optional - The end date for the transaction history (YYYY-MM-DD). ### Response #### Success Response (200) - **transactions** (array) - A list of transaction objects. ### Request Example ```typescript const transactions = await schwab.trader.transactions.getTransactions({ pathParams: { accountNumber: 'your-account-hash' }, queryParams: { types: 'TRADE', startDate: '2024-01-01', endDate: '2024-12-31', }, }) ``` ``` -------------------------------- ### Create Schwab Authentication Manager Source: https://github.com/sudowealth/schwab-api/blob/main/CLAUDE.md Initializes the authentication manager for the Schwab API client. Requires OAuth configuration. ```typescript createSchwabAuth({ oauthConfig: { clientId, clientSecret, redirectUri } }) ``` -------------------------------- ### KVTokenStore for Cloudflare Workers Source: https://context7.com/sudowealth/schwab-api/llms.txt A pre-built token storage adapter for Cloudflare Workers KV Namespaces. Supports key migration and TTL management. Configure with KV namespace, key prefix, TTL, and auto-migration settings. ```typescript import { KVTokenStore, createSchwabAuth } from '@sudowealth/schwab-api' // In a Cloudflare Worker: export default { async fetch(request: Request, env: Env) { const store = new KVTokenStore(env.OAUTH_KV, { keyPrefix: 'schwab:token:', ttl: 31 * 24 * 60 * 60, // 31 days autoMigrate: true, }) const ids = { clientId: process.env.SCHWAB_CLIENT_ID } const auth = createSchwabAuth({ oauthConfig: { clientId: env.SCHWAB_CLIENT_ID, clientSecret: env.SCHWAB_CLIENT_SECRET, redirectUri: env.REDIRECT_URI, load: () => store.load(ids), save: (tokens) => store.save(ids, tokens), }, }) // Or use createBoundFunctions helper: const { load, save } = store.createBoundFunctions({ clientId: env.SCHWAB_CLIENT_ID }) // Migrate from old key scheme await store.migrate( { clientId: 'old-client-id' }, { schwabUserId: 'user-12345' }, ) } } ``` -------------------------------- ### Secure Token Storage with Encryption Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Demonstrates how to securely save and load API tokens using AES-256-GCM encryption. Never store tokens in plain text. Ensure you use a secure key management system in production. ```typescript // ❌ BAD - Insecure plain text storage const insecureStorage = { save: async (tokens) => { await fs.writeFile('tokens.json', JSON.stringify(tokens)) }, load: async () => { const data = await fs.readFile('tokens.json', 'utf-8') return JSON.parse(data) }, } ``` ```typescript // ✅ GOOD - Encrypted storage example import crypto from 'crypto' const secureStorage = { save: async (tokens) => { // Use a secure key management system in production const key = process.env.ENCRYPTION_KEY const iv = crypto.randomBytes(16) const cipher = crypto.createCipheriv( 'aes-256-gcm', Buffer.from(key, 'hex'), iv, ) let encrypted = cipher.update(JSON.stringify(tokens), 'utf8', 'hex') encrypted += cipher.final('hex') const authTag = cipher.getAuthTag() await secureStore.set('tokens', { encrypted, iv: iv.toString('hex'), authTag: authTag.toString('hex'), }) }, load: async () => { const data = await secureStore.get('tokens') if (!data) return null const key = process.env.ENCRYPTION_KEY const decipher = crypto.createDecipheriv( 'aes-256-gcm', Buffer.from(key, 'hex'), Buffer.from(data.iv, 'hex'), ) decipher.setAuthTag(Buffer.from(data.authTag, 'hex')) let decrypted = decipher.update(data.encrypted, 'hex', 'utf8') decrypted += decipher.final('utf8') return JSON.parse(decrypted) }, } ``` -------------------------------- ### Place Order for Account Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Places a new order for a specified account. ```APIDOC ## Place Order for Account ### Description Places a new order for a specified account. ### Method ``` POST ``` ### Endpoint ``` /accounts/{accountNumber}/orders ``` ### Parameters #### Path Parameters - **accountNumber** (string) - Required - The unique identifier for the account. #### Request Body - **orderType** (string) - Required - The type of order (e.g., 'MARKET', 'LIMIT'). - **session** (string) - Required - The trading session (e.g., 'NORMAL'). - **duration** (string) - Required - The duration of the order (e.g., 'DAY', 'GTC'). - **orderStrategyType** (string) - Required - The strategy type for the order (e.g., 'SINGLE'). - **orderLegCollection** (array) - Required - A collection of order legs, each specifying instruction, quantity, and instrument details. - **instruction** (string) - Required - The action to take (e.g., 'BUY', 'SELL'). - **quantity** (number) - Required - The number of shares or units. - **instrument** (object) - Required - Details of the financial instrument. - **symbol** (string) - Required - The trading symbol (e.g., 'AAPL'). - **assetType** (string) - Required - The type of asset (e.g., 'EQUITY'). ### Response #### Success Response (200) - **orderResponse** (object) - Details of the placed order. ### Request Example ```typescript const orderResponse = await schwab.trader.orders.placeOrderForAccount({ pathParams: { accountNumber: 'your-account-hash' }, body: { orderType: 'MARKET', session: 'NORMAL', duration: 'DAY', orderStrategyType: 'SINGLE', orderLegCollection: [ { instruction: 'BUY', quantity: 10, instrument: { symbol: 'AAPL', assetType: 'EQUITY', }, }, ], }, }) ``` ``` -------------------------------- ### Get Schwab Account Data Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Retrieve various trading-related data such as accounts, orders, transactions, and user preferences. Ensure you have authenticated and initialized the Schwab API client. ```typescript // Get accounts const accounts = await schwab.trader.accounts.getAccounts() // Get account details const account = await schwab.trader.accounts.getAccountByNumber({ pathParams: { accountNumber: 'your-account-hash' }, queryParams: { fields: 'positions' }, }) // Get orders const orders = await schwab.trader.orders.getOrdersByAccount({ pathParams: { accountNumber: 'your-account-hash' }, queryParams: { maxResults: 50 }, }) // Place an order const orderResponse = await schwab.trader.orders.placeOrderForAccount({ pathParams: { accountNumber: 'your-account-hash' }, body: { orderType: 'MARKET', session: 'NORMAL', duration: 'DAY', orderStrategyType: 'SINGLE', orderLegCollection: [ { instruction: 'BUY', quantity: 10, instrument: { symbol: 'AAPL', assetType: 'EQUITY', }, }, ], }, }) // Get transactions const transactions = await schwab.trader.transactions.getTransactions({ pathParams: { accountNumber: 'your-account-hash' }, queryParams: { types: 'TRADE', startDate: '2024-01-01', endDate: '2024-12-31', }, }) // Get user preferences const preferences = await schwab.trader.userPreference.getUserPreference() ``` -------------------------------- ### Fetch Options Chain Source: https://context7.com/sudowealth/schwab-api/llms.txt Use `getOptionChain` to fetch option chains with Greeks, open interest, and volume. Filter by contract type, expiration, and strike range. `getOptionExpirationChain` retrieves only expiration dates. ```typescript // Fetch AAPL call options expiring in the next 30 days const chain = await schwab.marketData.options.getOptionChain({ queryParams: { symbol: 'AAPL', contractType: 'CALL', strikeCount: 10, // 5 strikes above and below ATM includeUnderlyingQuote: true, strategy: 'SINGLE', range: 'NTM', // Near-the-money daysToExpiration: 30, expMonth: 'ALL', }, }) console.log(`Underlying: $${chain.underlyingPrice}`) const callMap = chain.callExpDateMap if (callMap) { for (const [expDate, strikesMap] of Object.entries(callMap)) { for (const [strike, contracts] of Object.entries(strikesMap)) { const c = contracts[0] if (c) { console.log(`${expDate} $${strike} Call: bid=${c.bid} ask=${c.ask} delta=${c.delta} OI=${c.openInterest}`) } } } } ``` ```typescript // Get expiration dates only const expirations = await schwab.marketData.options.getOptionExpirationChain({ queryParams: { symbol: 'AAPL' }, }) expirations.expirationList?.forEach((e) => { console.log(`${e.expirationDate} (${e.optionRoots})`) }) ``` -------------------------------- ### createApiClient(options) Source: https://context7.com/sudowealth/schwab-api/llms.txt Factory function to create the top-level SchwabApiClient, which includes `marketData`, `trader`, `schemas`, `auth`, and `errors` namespaces. It accepts an EnhancedTokenManager or authentication configuration and allows customization of middleware for rate limiting and retries. ```APIDOC ## `createApiClient(options)` — API Client Factory Creates the top-level `SchwabApiClient` with `marketData`, `trader`, `schemas`, `auth`, and `errors` namespaces. Accepts an `EnhancedTokenManager` (sync) or an `AuthFactoryConfig`/string token (async). Also accepts `middleware` options to tune rate limiting and retry behavior. ```typescript import { createSchwabAuth, createApiClient } from '@sudowealth/schwab-api' // Sync path: pass an EnhancedTokenManager directly const auth = createSchwabAuth({ oauthConfig: { clientId: process.env.SCHWAB_CLIENT_ID!, clientSecret: process.env.SCHWAB_CLIENT_SECRET!, redirectUri: 'https://myapp.com/callback', load: async () => loadTokensFromStorage(), save: async (t) => saveTokensToStorage(t), }, }) const schwab = createApiClient({ auth, // EnhancedTokenManager → synchronous, returns SchwabApiClient directly middleware: { rateLimit: { maxRequests: 120, windowMs: 60_000 }, retry: { maxAttempts: 3, baseDelayMs: 1000 }, }, config: { environment: 'production', // or 'sandbox' }, }) // Async path: pass AuthFactoryConfig (returns Promise) const schwabAsync = await createApiClient({ auth: { oauthConfig: { clientId: process.env.SCHWAB_CLIENT_ID!, clientSecret: process.env.SCHWAB_CLIENT_SECRET!, redirectUri: 'https://myapp.com/callback', }, }, }) ``` ``` -------------------------------- ### schwab.marketData.options.getOptionChain Source: https://context7.com/sudowealth/schwab-api/llms.txt Fetches option chains with full Greeks, open interest, and volume data. Supports filtering by contract type, expiration, and strike range. ```APIDOC ## `schwab.marketData.options.getOptionChain` — Options Chain ### Description Fetches option chains with full Greeks, open interest, and volume data. Supports filtering by contract type, expiration, and strike range. ### Method GET (inferred from SDK usage) ### Endpoint `/marketdata/options/chain` (inferred from SDK usage) ### Parameters #### Query Parameters - **symbol** (string) - Required - The underlying symbol. - **contractType** (string) - Optional - Type of contract ('CALL' or 'PUT'). - **strikeCount** (number) - Optional - Number of strikes to return above and below the at-the-money strike. - **includeUnderlyingQuote** (boolean) - Optional - Whether to include the underlying quote. - **strategy** (string) - Optional - Trading strategy (e.g., 'SINGLE'). - **range** (string) - Optional - Range for strikes (e.g., 'NTM' for near-the-money). - **daysToExpiration** (number) - Optional - Number of days to expiration. - **expMonth** (string) - Optional - Expiration month ('ALL' or specific month). ### Request Example ```typescript const chain = await schwab.marketData.options.getOptionChain({ queryParams: { symbol: 'AAPL', contractType: 'CALL', strikeCount: 10, includeUnderlyingQuote: true, strategy: 'SINGLE', range: 'NTM', daysToExpiration: 30, expMonth: 'ALL', }, }) ``` ### Response #### Success Response (200) - **underlyingPrice** (number) - The price of the underlying asset. - **callExpDateMap** (object) - A map of expiration dates to strike prices for call options. - **expirationDate** (object) - A map of strike prices to option contracts. - **strike** (array of objects) - An array of option contracts for a given strike. - **bid** (number) - The current bid price. - **ask** (number) - The current ask price. - **delta** (number) - The option's delta. - **openInterest** (number) - The open interest for the option. ### Response Example ```json { "underlyingPrice": 170.50, "callExpDateMap": { "2024-07-19": { "165": [ { "bid": 5.00, "ask": 5.50, "delta": 0.75, "openInterest": 1000 } ] } } } ``` ``` -------------------------------- ### Rebase Branch onto Main Source: https://github.com/sudowealth/schwab-api/blob/main/CONTRIBUTING.md Updates your feature branch with the latest changes from the 'main' branch using rebase. ```bash git checkout main git pull upstream main git checkout your-branch-name git rebase main ``` -------------------------------- ### HMAC Signing and Verification with Schwab API Source: https://context7.com/sudowealth/schwab-api/llms.txt Utilize `createHmacKey`, `signData`, and `verifySignature` for HMAC signing. Ensure the secret key meets the minimum length requirement. Data can be signed and verified using different encodings and hash algorithms. ```typescript import { createHmacKey, signData, verifySignature, toHex, fromHex } from '@sudowealth/schwab-api' // Create a key (validates minimum length and entropy) const key = await createHmacKey('your-secret-key-that-is-at-least-32-characters-long') // Sign data const signature = await signData(key, 'payload-to-sign', { algorithm: 'HMAC', encoding: 'hex', // or 'base64' hash: 'SHA-256', }) // Verify const isValid = await verifySignature(key, signature, 'payload-to-sign') console.log('Valid:', isValid) // true // Hex conversion utilities const buffer = new ArrayBuffer(4) new Uint8Array(buffer).set([0xde, 0xad, 0xbe, 0xef]) console.log(toHex(buffer)) // "deadbeef" const restored = fromHex('deadbeef') ``` -------------------------------- ### createHmacKey / signData / verifySignature — Crypto Utilities Source: https://context7.com/sudowealth/schwab-api/llms.txt Provides low-level cryptographic primitives for HMAC signing, including key creation, data signing, and signature verification. ```APIDOC ## `createHmacKey` / `signData` / `verifySignature` — Crypto Utilities ### Description Low-level cryptographic primitives for HMAC signing used by the cookie store and available for custom use. ### Methods - **createHmacKey**(secret: string) : Promise - **signData**(key: HmacKey, data: string | ArrayBuffer, options?: { algorithm?: 'HMAC', encoding?: 'hex' | 'base64', hash?: 'SHA-1' | 'SHA-256' | 'SHA-512' }) : Promise - **verifySignature**(key: HmacKey, signature: string, data: string | ArrayBuffer) : Promise - **toHex**(data: ArrayBuffer | Uint8Array) : string - **fromHex**(hex: string) : ArrayBuffer ### Parameters #### `createHmacKey` - **secret** (string) - Required - Your secret key that is at least 32 characters long. #### `signData` - **key** (HmacKey) - Required - The HMAC key generated by `createHmacKey`. - **data** (string | ArrayBuffer) - Required - The data to sign. - **options** (object) - Optional - Signing options. - **algorithm** (string) - The signing algorithm, defaults to 'HMAC'. - **encoding** (string) - The encoding for the signature, 'hex' or 'base64'. Defaults to 'hex'. - **hash** (string) - The hash function to use, e.g., 'SHA-256'. Defaults to 'SHA-256'. #### `verifySignature` - **key** (HmacKey) - Required - The HMAC key used for signing. - **signature** (string) - Required - The signature to verify. - **data** (string | ArrayBuffer) - Required - The original data that was signed. #### `toHex` - **data** (ArrayBuffer | Uint8Array) - Required - The data to convert to hex. #### `fromHex` - **hex** (string) - Required - The hex string to convert to an ArrayBuffer. ### Request Example ```typescript import { createHmacKey, signData, verifySignature, toHex, fromHex } from '@sudowealth/schwab-api' // Create a key (validates minimum length and entropy) const key = await createHmacKey('your-secret-key-that-is-at-least-32-characters-long') // Sign data const signature = await signData(key, 'payload-to-sign', { algorithm: 'HMAC', encoding: 'hex', // or 'base64' hash: 'SHA-256', }) // Verify const isValid = await verifySignature(key, signature, 'payload-to-sign') console.log('Valid:', isValid) // true // Hex conversion utilities const buffer = new ArrayBuffer(4) new Uint8Array(buffer).set([0xde, 0xad, 0xbe, 0xef]) console.log(toHex(buffer)) // "deadbeef" const restored = fromHex('deadbeef') ``` ``` -------------------------------- ### createSchwabAuth(config) Source: https://context7.com/sudowealth/schwab-api/llms.txt Factory function to create an EnhancedTokenManager for handling OAuth 2.0 authorization code + PKCE flow. It supports optional save/load callbacks for token persistence. ```APIDOC ## `createSchwabAuth(config)` — OAuth Client Factory Creates an `EnhancedTokenManager` that handles the full OAuth 2.0 authorization code + PKCE flow. Accepts optional `save`/`load` callbacks for token persistence. ```typescript import { createSchwabAuth, SchwabAuthError, AuthErrorCode } from '@sudowealth/schwab-api' const auth = createSchwabAuth({ oauthConfig: { clientId: process.env.SCHWAB_CLIENT_ID!, clientSecret: process.env.SCHWAB_CLIENT_SECRET!, redirectUri: 'https://myapp.com/callback', // Optional: persist tokens across restarts save: async (tokens) => { await db.set('schwab_tokens', JSON.stringify(tokens)) }, load: async () => { const raw = await db.get('schwab_tokens') return raw ? JSON.parse(raw) : null }, }, }) // Step 1: Generate the authorization URL (with PKCE, async) const { authUrl, generatedState } = await auth.getAuthorizationUrl({ scope: ['api', 'offline_access'], }) console.log('Redirect user to:', authUrl) // Step 2: After user authorizes, exchange code for tokens // Pass back the state parameter received in the OAuth callback const tokens = await auth.exchangeCode(authorizationCode, callbackState) console.log('Access token expires at:', new Date(tokens.expiresAt!)) // Step 3: Manually refresh (the client auto-refreshes, but can be forced) try { const refreshed = await auth.refresh(tokens.refreshToken!, { force: true }) console.log('Refreshed:', refreshed.accessToken.substring(0, 8) + '...') } catch (e) { if (e instanceof SchwabAuthError && e.code === AuthErrorCode.TOKEN_EXPIRED) { // Refresh token expired after 7 days — user must re-authenticate const { authUrl } = await auth.getAuthorizationUrl() console.log('Re-auth required:', authUrl) } } ``` ``` -------------------------------- ### EnhancedTokenManager for Low-Level Token Management Source: https://context7.com/sudowealth/schwab-api/llms.txt Instantiate `EnhancedTokenManager` for fine-grained control over token refresh, retry, and event handling. Requires client ID, secret, and redirect URI. Token persistence can be configured via `load` and `save` async functions. ```typescript import { EnhancedTokenManager, TokenPersistenceEvent } from '@sudowealth/schwab-api' const manager = new EnhancedTokenManager({ clientId: process.env.SCHWAB_CLIENT_ID!, clientSecret: process.env.SCHWAB_CLIENT_SECRET!, redirectUri: 'https://myapp.com/callback', // Storage load: async () => loadFromDB(), save: async (t) => saveToDB(t), // Retry config maxRetryAttempts: 5, initialRetryDelayMs: 500, maxRetryDelayMs: 30_000, useExponentialBackoff: true, // Refresh config refreshThresholdMs: 5 * 60 * 1000, // 5 minutes before expiry autoReconnect: true, // Events onTokenEvent: (event, data, meta) => { if (event === TokenPersistenceEvent.TOKEN_SAVED) { console.log('Tokens saved successfully', meta) } if (event === TokenPersistenceEvent.TOKEN_SAVE_FAILED) { console.error('Token save failed!') } }, debug: false, traceOperations: false, }) // Initialize: loads tokens from storage, refreshes if expiring soon const ready = await manager.initialize() console.log('Manager ready:', ready) // Get access token (auto-refreshes if needed) const token = await manager.getAccessToken() // Get full token data const data = await manager.getTokenData() console.log('Expires at:', new Date(data!.expiresAt!)) // Register refresh notification manager.onRefresh((newTokens) => { console.log('Tokens refreshed, new expiry:', new Date(newTokens.expiresAt!)) }) // Generate a comprehensive token report const report = await manager.generateTokenReport() console.log('Validation:', report.tokenValidation) // Force refresh await manager.refreshIfNeeded({ force: true }) // Clear tokens (logout) await manager.clearTokens() ``` -------------------------------- ### Create Schwab API Client Source: https://context7.com/sudowealth/schwab-api/llms.txt Factory function to create the SchwabApiClient. Can accept an EnhancedTokenManager directly for synchronous client creation or an AuthFactoryConfig for asynchronous creation. Allows configuration of middleware for rate limiting and retries, and API environment. ```typescript import { createSchwabAuth, createApiClient } from '@sudowealth/schwab-api' // Sync path: pass an EnhancedTokenManager directly const auth = createSchwabAuth({ oauthConfig: { clientId: process.env.SCHWAB_CLIENT_ID!, clientSecret: process.env.SCHWAB_CLIENT_SECRET!, redirectUri: 'https://myapp.com/callback', load: async () => loadTokensFromStorage(), save: async (t) => saveTokensToStorage(t), }, }) const schwab = createApiClient({ auth, // EnhancedTokenManager → synchronous, returns SchwabApiClient directly middleware: { rateLimit: { maxRequests: 120, windowMs: 60_000 }, retry: { maxAttempts: 3, baseDelayMs: 1000 }, }, config: { environment: 'production', // or 'sandbox' }, }) // Async path: pass AuthFactoryConfig (returns Promise) const schwabAsync = await createApiClient({ auth: { oauthConfig: { clientId: process.env.SCHWAB_CLIENT_ID!, clientSecret: process.env.SCHWAB_CLIENT_SECRET!, redirectUri: 'https://myapp.com/callback', }, }, }) ``` -------------------------------- ### Authentication Client Methods Source: https://github.com/sudowealth/schwab-api/blob/main/README.md Provides methods for managing OAuth authentication, including generating authorization URLs, exchanging codes, and refreshing tokens. ```APIDOC ## Authentication Client Methods ### Description Provides methods for managing OAuth authentication, including generating authorization URLs, exchanging codes, and refreshing tokens. ### Methods - **`getAuthorizationUrl()`**: Generates the URL for initiating the user login and authorization process. - **`exchangeCode(code)`**: Exchanges an authorization code received after user login for access and refresh tokens. - **`refresh(refreshToken)`**: Refreshes an expired access token using a valid refresh token. ### Handling Token Expiration Refresh tokens have a 7-day expiration limit. If a refresh token expires, the `refresh()` method will throw a `SchwabAuthError` with code `TOKEN_EXPIRED`, requiring a full re-authentication flow. ### Example Usage ```typescript try { const newTokens = await auth.refresh(oldRefreshToken) // Update stored tokens } catch (error) { if (error instanceof SchwabAuthError && error.code === 'TOKEN_EXPIRED') { // Redirect user to re-authenticate const { authUrl } = auth.getAuthorizationUrl() window.location.href = authUrl } } ``` ``` -------------------------------- ### Add Upstream Remote Repository Source: https://github.com/sudowealth/schwab-api/blob/main/CONTRIBUTING.md Adds the original schwab-api repository as an upstream remote for fetching updates. ```bash git remote add upstream https://github.com/sudowealth/schwab-api.git ```