{"id":30290338,"url":"https://github.com/elkingarcia11/charles-schwab-authentication-module","last_synced_at":"2025-09-15T03:09:57.259Z","repository":{"id":296739373,"uuid":"994318641","full_name":"elkingarcia11/charles-schwab-authentication-module","owner":"elkingarcia11","description":"A Python module for handling Charles Schwab API authentication with fresh token generation every time and automatic Google Cloud Storage integration.","archived":false,"fork":false,"pushed_at":"2025-07-18T16:33:31.000Z","size":30,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-18T20:52:19.510Z","etag":null,"topics":["api-integration","base64","class-based","environment-variables","error-handling","file-persistence","google-cloud-storage","json","oauth2","requests","schwab","token-management","url-encoding"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/elkingarcia11.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-01T17:27:21.000Z","updated_at":"2025-07-18T16:33:34.000Z","dependencies_parsed_at":"2025-06-02T03:47:36.452Z","dependency_job_id":"63dfeae2-3958-4bf0-a6e0-241fb703c755","html_url":"https://github.com/elkingarcia11/charles-schwab-authentication-module","commit_stats":null,"previous_names":["elkingarcia11/schwab_api_authenticator","elkingarcia11/schwab-api-authenticator","elkingarcia11/charles-schwab-authentication-module"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/elkingarcia11/charles-schwab-authentication-module","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elkingarcia11%2Fcharles-schwab-authentication-module","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elkingarcia11%2Fcharles-schwab-authentication-module/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elkingarcia11%2Fcharles-schwab-authentication-module/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elkingarcia11%2Fcharles-schwab-authentication-module/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/elkingarcia11","download_url":"https://codeload.github.com/elkingarcia11/charles-schwab-authentication-module/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elkingarcia11%2Fcharles-schwab-authentication-module/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270781393,"owners_count":24643820,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-16T02:00:11.002Z","response_time":91,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-integration","base64","class-based","environment-variables","error-handling","file-persistence","google-cloud-storage","json","oauth2","requests","schwab","token-management","url-encoding"],"created_at":"2025-08-16T23:12:38.729Z","updated_at":"2025-08-16T23:12:39.357Z","avatar_url":"https://github.com/elkingarcia11.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Charles Schwab Authentication Module\n\nA comprehensive Python module for handling Charles Schwab API authentication with OAuth 2.0 flow, automatic token management, and Google Cloud Storage integration.\n\n## Features\n\n- 🔐 **OAuth 2.0 Authentication**: Complete implementation of Schwab API OAuth flow\n- 🔄 **Flexible Token Management**: Support for both fresh authentication and GCS-stored refresh tokens\n- 💾 **Token Persistence**: Saves refresh tokens locally and to Google Cloud Storage\n- ☁️ **Cloud Storage Integration**: Automatic token backup and retrieval from GCS\n- 🛡️ **Robust Error Handling**: Comprehensive error handling for all authentication scenarios\n- 🎯 **Easy Integration**: Simple class-based design for seamless integration into larger projects\n- ⚡ **Dual Mode Operation**: Fresh authentication or GCS-based token refresh\n- 🔧 **Modular Architecture**: Separate GCS module for cloud storage operations\n\n## Prerequisites\n\n- Python 3.8+\n- Charles Schwab Developer Account\n- Registered Schwab API Application\n- Google Cloud Storage Account (for cloud token storage)\n\n## Installation\n\n1. **Clone the repository with submodules:**\n\n   ```bash\n   git clone --recursive \u003crepository-url\u003e\n   cd charles-schwab-authentication-module\n   ```\n\n2. **Create and activate a virtual environment:**\n\n   ```bash\n   # Create virtual environment\n   python -m venv venv\n\n   # Activate virtual environment\n   # On macOS/Linux:\n   source venv/bin/activate\n\n   # On Windows:\n   venv\\Scripts\\activate\n   ```\n\n3. **Install required dependencies:**\n\n   ```bash\n   # Ensure pip is up to date\n   pip install --upgrade pip\n\n   # Install dependencies\n   pip install -r requirements.txt\n   ```\n\n4. **Initialize submodules:**\n   ```bash\n   git submodule update --init --recursive\n   ```\n\n## Setup\n\n### 1. Get Schwab API Credentials\n\n1. Visit the [Charles Schwab Developer Portal](https://developer.schwab.com/)\n2. Create a developer account\n3. Register a new application\n4. Note your App Key and App Secret\n5. Set your redirect URI to `https://127.0.0.1`\n\n### 2. Set up Google Cloud Storage\n\n1. Create a Google Cloud Storage bucket for token storage\n2. Set up a service account with Storage Object Admin permissions\n3. Download the service account key (JSON format)\n4. Configure the `GOOGLE_APPLICATION_CREDENTIALS` environment variable\n\n### 3. Configure Environment Variables\n\nCreate a `.env` file with your credentials:\n\n```env\nSCHWAB_APP_KEY=your_schwab_app_key\nSCHWAB_APP_SECRET=your_schwab_app_secret\nGCS_BUCKET_NAME=your_gcs_bucket_name\nGOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account-key.json\n```\n\n## Usage\n\n### Method 1: Fresh Authentication (Interactive)\n\nRun the script to authenticate locally and upload refresh token to GCS:\n\n```bash\n# Authenticate locally and upload refresh token to GCS\npython schwab_auth.py --authenticate\n# or simply (default behavior)\npython schwab_auth.py\n```\n\nThis will:\n\n1. Prompt you to visit the authorization URL\n2. Ask you to paste the redirect URL after authorization\n3. Generate fresh access and refresh tokens\n4. Display the access token for use in your applications\n5. **Automatically upload the refresh token to Google Cloud Storage**\n\n### Method 2: GCS-Based Token Refresh (Automated)\n\nGet a new access token using the refresh token stored in Google Cloud Storage:\n\n```bash\npython schwab_auth.py --get-access-token\n```\n\nThis will:\n\n1. Download the refresh token from Google Cloud Storage (if not present locally)\n2. Use the refresh token to get a new access token\n3. Display the access token without requiring user interaction\n4. Perfect for automated scripts and services\n\n### Expected Output\n\nWhen you run the program, you'll see:\n\n```\n=== GETTING FRESH TOKENS ===\nGetting new Schwab tokens...\n\n1. Visit this URL: https://api.schwabapi.com/v1/oauth/authorize?client_id=...\n2. Log in and authorize the app\n3. You'll be redirected to a URL that looks like:\n   https://127.0.0.1/?code=LONG_CODE_HERE\u0026session=...\n4. Copy the ENTIRE redirect URL\n\nPaste the full redirect URL here: [YOU PASTE THE URL HERE]\nExtracted code: ABC123...\nTokens obtained successfully!\nAccess Token: eyJ0eXAiOiJKV1QiLCJ...\nRefresh Token: eyJ0eXAiOiJKV1QiLCJ...\nRefresh token saved to schwab_refresh_token.txt\nFile schwab_refresh_token.txt uploaded to schwab_refresh_token.txt.\n✅ Tokens obtained and uploaded to GCS successfully!\n```\n\n## API Reference\n\n### SchwabAuth Class\n\n#### `__init__()`\n\nInitializes the authenticator with credentials from environment variables.\n\n**Environment Variables Required:**\n\n- `SCHWAB_APP_KEY`: Your Schwab application key\n- `SCHWAB_APP_SECRET`: Your Schwab application secret\n- `GCS_BUCKET_NAME`: Your Google Cloud Storage bucket name (optional)\n- `GOOGLE_APPLICATION_CREDENTIALS`: Path to your GCS service account key file (optional)\n\n#### `get_valid_access_token(use_gcs_refresh_token=False)`\n\nMain method to get a valid access token.\n\n**Parameters:**\n\n- `use_gcs_refresh_token` (bool): If True, attempts to use GCS-stored refresh token first\n\n**Returns:**\n\n- `str`: Valid access token, or None if authentication fails\n\n**Example:**\n\n```python\nauth = SchwabAuth()\n\n# Fresh authentication (interactive)\naccess_token = auth.get_valid_access_token()\n\n# Use GCS refresh token (automated)\naccess_token = auth.get_valid_access_token(use_gcs_refresh_token=True)\n```\n\n#### `automated_token_management()`\n\nHandles the complete fresh token generation workflow.\n\n**Returns:**\n\n- `str`: Refresh token, or None if authentication fails\n\n**Example:**\n\n```python\nauth = SchwabAuth()\nrefresh_token = auth.automated_token_management()\n```\n\n#### `refresh_access_token(refresh_token, app_key, app_secret)`\n\nRefreshes access token using refresh token.\n\n**Parameters:**\n\n- `refresh_token` (str): The refresh token to use\n- `app_key` (str): Your Schwab application key\n- `app_secret` (str): Your Schwab application secret\n\n**Returns:**\n\n- `str`: New access token, or None if refresh fails\n\n#### `save_refresh_token(refresh_token)`\n\nSaves refresh token to local file.\n\n**Parameters:**\n\n- `refresh_token` (str): The refresh token to save\n\n#### `load_refresh_token()`\n\nLoads refresh token from local file.\n\n**Returns:**\n\n- `str`: Refresh token if found, None otherwise\n\n#### `upload_refresh_token_to_gcs()`\n\nUploads the local refresh token file to Google Cloud Storage.\n\n#### `download_refresh_token_from_gcs()`\n\nDownloads refresh token from Google Cloud Storage to local file.\n\n**Returns:**\n\n- `str`: Refresh token if download successful, None otherwise\n\n## Integration Examples\n\n### Basic Integration\n\n```python\nfrom schwab_auth import SchwabAuth\n\n# Initialize the authenticator\nauth = SchwabAuth()\n\n# Get access token (automatically uses GCS if available)\naccess_token = auth.get_valid_access_token(use_gcs_refresh_token=True)\n\n# Use the token for API calls\nheaders = {\n    'Authorization': f'Bearer {access_token}',\n    'Content-Type': 'application/json'\n}\n\n# Make API requests\nimport requests\nresponse = requests.get('https://api.schwabapi.com/v1/accounts', headers=headers)\n```\n\n### Integration with Streaming Client\n\n```python\nfrom schwab_auth import SchwabAuth\n\n# In your streaming client\nauth = SchwabAuth()\naccess_token = auth.get_valid_access_token(use_gcs_refresh_token=True)\n\n# Use token for WebSocket authentication\nstreaming_client.login_with_token(access_token)\n```\n\n### Automated Script Integration\n\n```python\nfrom schwab_auth import SchwabAuth\nimport time\n\ndef get_schwab_data():\n    auth = SchwabAuth()\n\n    # Try GCS first, fall back to fresh auth if needed\n    access_token = auth.get_valid_access_token(use_gcs_refresh_token=True)\n\n    if not access_token:\n        print(\"GCS token failed, getting fresh authentication...\")\n        access_token = auth.get_valid_access_token(use_gcs_refresh_token=False)\n\n    return access_token\n\n# Use in automated scripts\naccess_token = get_schwab_data()\n```\n\n## File Structure\n\n```\ncharles-schwab-authentication-module/\n├── schwab_auth.py                    # Main authentication class\n├── schwab_refresh_token.txt          # Stored refresh token (auto-generated)\n├── .env                              # Environment variables (you create this)\n├── requirements.txt                  # Python dependencies\n├── README.md                         # This file\n├── .gitmodules                       # Git submodule configuration\n└── gcs-python-module/                # Google Cloud Storage module\n    ├── gcs_client.py                 # GCS client class\n    ├── requirements.txt              # GCS module dependencies\n    ├── README.md                     # GCS module documentation\n    └── tests/                        # GCS module tests\n        ├── integration_test.py\n        └── README.md\n```\n\n## Environment Variables\n\n| Variable                         | Description                               | Required | Default |\n| -------------------------------- | ----------------------------------------- | -------- | ------- |\n| `SCHWAB_APP_KEY`                 | Your Schwab application key               | Yes      | -       |\n| `SCHWAB_APP_SECRET`              | Your Schwab application secret            | Yes      | -       |\n| `GCS_BUCKET_NAME`                | Your Google Cloud Storage bucket name     | No       | -       |\n| `GOOGLE_APPLICATION_CREDENTIALS` | Path to your GCS service account key file | No       | -       |\n\n## Error Handling\n\nThe module includes comprehensive error handling for:\n\n- Missing environment variables\n- API request failures\n- Invalid authorization codes\n- Token refresh failures\n- File I/O errors\n- Google Cloud Storage operation failures\n- Network connectivity issues\n- Authentication flow interruptions\n\n## Security Notes\n\n- **Never commit your `.env` file** to version control\n- **Keep your App Key and App Secret secure**\n- **The refresh token file contains sensitive data** - protect it accordingly\n- **Use HTTPS in production environments**\n- **Store your Google Cloud service account key securely**\n- **Consider using Google Cloud Secret Manager** for production deployments\n- **Rotate credentials regularly** for enhanced security\n\n## Troubleshooting\n\n### Common Issues\n\n1. **\"No valid refresh token available\"**\n\n   - **Solution**: Run the program again to get fresh tokens\n   - **Check**: Ensure GCS bucket exists and is accessible\n\n2. **\"Error getting tokens\"**\n\n   - **Check**: Your App Key and App Secret are correct\n   - **Verify**: Redirect URI matches your app configuration\n   - **Ensure**: Authorization code is complete and unmodified\n\n3. **\"Failed to get access token\"**\n\n   - **Try**: Running the program again to get fresh tokens\n   - **Check**: Internet connection and API credentials\n   - **Verify**: Refresh token hasn't expired\n\n4. **Google Cloud Storage Errors**\n\n   - **Verify**: Service account has correct permissions\n   - **Check**: Bucket name is correct and exists\n   - **Ensure**: Service account key file path is correct\n   - **Test**: GCS connectivity and bucket access\n\n5. **Virtual Environment Issues**\n\n   - **Ensure**: Virtual environment is activated before installing dependencies\n   - **Fix**: Use `venv\\Scripts\\activate` on Windows instead of `source venv/bin/activate`\n   - **Reinstall**: `pip install -r requirements.txt` if packages aren't found\n\n6. **Git Submodule Issues**\n   - **Initialize**: `git submodule init \u0026\u0026 git submodule update`\n   - **Recursive**: `git submodule update --init --recursive`\n   - **Verify**: `gcs-python-module/` directory exists and contains `gcs_client.py`\n\n### Debug Mode\n\nFor debugging, you can add print statements or modify the error messages in the class methods:\n\n```python\n# Enable debug output\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\n# Or add debug prints\nauth = SchwabAuth()\nprint(f\"App Key: {auth.APP_KEY[:10]}...\")\nprint(f\"GCS Bucket: {auth.GCS_BUCKET_NAME}\")\n```\n\n## Google Cloud Storage Module\n\nThe project includes a comprehensive Google Cloud Storage module (`gcs-python-module/`) that provides:\n\n- **Service Account Authentication**: Secure authentication using service account keys\n- **Comprehensive Operations**: Upload, download, list, delete, and manage files and buckets\n- **Error Handling**: Robust error handling with detailed logging\n- **Type Hints**: Full type annotation support for better development experience\n- **Testing**: Integration tests for all GCS operations\n\nSee the [gcs-python-module/README.md](gcs-python-module/README.md) for detailed documentation on the GCS client functionality.\n\n## Testing\n\nRun tests with pytest:\n\n```bash\npytest tests/\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Add tests if applicable\n5. Submit a pull request\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Disclaimer\n\nThis tool is for educational and development purposes. Always follow Charles Schwab's API terms of service and rate limiting guidelines. The tool is not intended for production trading without proper testing and validation.\n\n## Support\n\nFor issues related to:\n\n- **Schwab API**: Contact Charles Schwab Developer Support\n- **Google Cloud Storage**: Check the [GCS module documentation](gcs-python-module/README.md)\n- **This Tool**: Open an issue in this repository\n- **Integration**: Check the parent project documentation\n\n## Changelog\n\n### v2.1.0\n\n- **Enhanced GCS Integration**: Improved token management with fallback options\n- **Better Error Handling**: More comprehensive error scenarios and recovery\n- **Updated Documentation**: Comprehensive README with integration examples\n- **Python 3.8+ Support**: Updated minimum Python version requirement\n\n### v2.0.0\n\n- **Added Google Cloud Storage Integration**: Automatic token upload to GCS\n- **Modular Architecture**: Separated GCS functionality into dedicated module\n- **Enhanced Security**: Cloud-based token backup and storage\n- **Comprehensive GCS Client**: Full GCS operations support\n- **Updated Dependencies**: Added Google Cloud Storage requirements\n\n### v1.0.0\n\n- **Initial Release**: Class-based architecture\n- **Fresh Token Generation**: Always gets fresh tokens on every run\n- **Token Persistence**: Saves refresh tokens for reference\n- **Comprehensive Error Handling**: Robust error handling for API calls\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felkingarcia11%2Fcharles-schwab-authentication-module","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Felkingarcia11%2Fcharles-schwab-authentication-module","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felkingarcia11%2Fcharles-schwab-authentication-module/lists"}