Metadata-Version: 2.4
Name: upstox-auth-pro
Version: 1.0.2
Summary: Automation library for Upstox login and token management
Author-email: Brijesh Yadav <brijeshyadav30599@gmail.com>
Maintainer-email: GrowthQuantix <brijeshyadav30599@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/growthquantix/upstox-auth-pro
Project-URL: Repository, https://github.com/growthquantix/upstox-auth-pro.git
Project-URL: Issues, https://github.com/growthquantix/upstox-auth-pro/issues
Project-URL: Changelog, https://github.com/growthquantix/upstox-auth-pro/blob/main/CHANGELOG.md
Keywords: upstox,authentication,playwright,totp,oauth
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: playwright>=1.40.0
Requires-Dist: pyotp>=2.9.0
Requires-Dist: requests>=2.31.0
Requires-Dist: pytz
Provides-Extra: dev
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: python-dotenv>=1.0.0; extra == "dev"
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Dynamic: license-file

# Upstox Auth Pro 🚀

[![Semantic Release](https://github.com/growthquantix/upstox-auth-pro/actions/workflows/semantic-release.yml/badge.svg)](https://github.com/growthquantix/upstox-auth-pro/actions/workflows/semantic-release.yml)
[![PyPI version](https://img.shields.io/pypi/v/upstox-auth-pro.svg)](https://pypi.org/project/upstox-auth-pro/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python Versions](https://img.shields.io/pypi/pyversions/upstox-auth-pro.svg)](https://pypi.org/project/upstox-auth-pro/)
[![Downloads](https://pepy.tech/badge/upstox-auth-pro)](https://pepy.tech/project/upstox-auth-pro)

**Upstox Auth Pro** is a high-performance, production-grade Python SDK designed to automate the Upstox OAuth2 login flow. It leverages Playwright for robust browser automation, `pyotp` for seamless 2FA, and a pluggable storage system for secure token management.

---

## 📋 Table of Contents
- [✨ Key Features](#-key-features)
- [🛠️ Requirements](#-requirements)
- [🚀 Installation](#-installation)
- [📖 Quick Start](#-quick-start)
- [💻 CLI Usage](#-cli-usage)
- [⚙️ Configuration (.env)](#-configuration-env)
- [📑 API Reference](#-api-reference)
- [🔍 Troubleshooting](#-troubleshooting--logging)
- [🤝 Contributing](#-contributing)
- [👨‍💻 Maintainer](#-maintainer)

---

## ✨ Key Features

- **Maximum Automation**: Fully automated versioning and publishing using Semantic Release.
- **Robust Browser Engine**: Uses Playwright with advanced stealth configurations to bypass bot detection.
- **Intelligent PIN Entry**: Dynamically handles both single-field and multi-field PIN input interfaces.
- **Auto-Retry Mechanism**: Built-in retry logic with exponential backoff for transient network failures.
- **Smart Token Management**: IST-aware token expiry validation (Upstox tokens expire daily at 3:30 AM IST).
- **Diagnostic Mode**: Automatic screenshots on failure and comprehensive logging for easy debugging.
- **Production Ready**: Clean, type-hinted API and a powerful CLI tool for rapid development.

---

## 🛠️ Requirements

- **Python**: 3.8, 3.9, 3.10, 3.11, or 3.12.
- **Browser**: Chromium (managed automatically via Playwright).
- **Upstox API**: Active App Credentials (API Key, Secret, Redirect URI).

---

## 🚀 Installation

### 1. Install the SDK
```bash
pip install upstox-auth-pro
```

### 2. Install Browser Dependencies
```bash
playwright install chromium
```

---

## 📖 Quick Start

```python
import asyncio
from upstox_auth import FileStorage, UpstoxAuthenticator

async def main():
    # 1. Initialize the authenticator
    auth = UpstoxAuthenticator(
        api_key="YOUR_API_KEY",
        api_secret="YOUR_API_SECRET",
        redirect_uri="https://localhost:8000/callback",
        mobile_no="9876543210",
        pin="123456",
        totp_key="YOUR_TOTP_SECRET",
        storage=FileStorage("tokens/upstox_token.json"), # Auto-creates directories
        headless=True,
        retries=2 # Number of retries on transient failures
    )

    # 2. Get your access token (automatically handles login/expiry/storage)
    try:
        token = await auth.get_access_token()
        print(f"Authenticated! Token: {token[:10]}...")
    except Exception as e:
        print(f"Authentication failed: {e}")

if __name__ == "__main__":
    asyncio.run(main())
```

---

## 💻 CLI Usage

You can also use the SDK directly from your terminal. It automatically loads credentials from a `.env` file.

```bash
# Basic usage (returns token to stdout)
upstox-auth

# Run using python module syntax
python -m upstox_auth

# Debug mode: see the browser while it logs in
upstox-auth --visible

# Force a fresh login (bypass stored token)
upstox-auth --force --storage production_token.json
```

---

## ⚙️ Configuration (.env)

We recommend using a `.env` file for secure credential management:

```ini
UPSTOX_API_KEY=your_api_key_here
UPSTOX_API_SECRET=your_api_secret_here
UPSTOX_REDIRECT_URI=https://localhost:8000/callback
UPSTOX_MOBILE=9876543210
UPSTOX_PIN=123456
UPSTOX_TOTP_KEY=JBSWY3DPEHPK3PXP
```

---

## 📑 API Reference

### `UpstoxAuthenticator`
| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `api_key` | `str` | **Required** | Upstox API Key. |
| `api_secret` | `str` | **Required** | Upstox API Secret. |
| `redirect_uri`| `str` | **Required** | Must match Upstox portal config. |
| `mobile_no` | `str` | **Required** | Registered mobile number. |
| `pin` | `str` | **Required** | 6-digit login PIN. |
| `totp_key` | `str` | **Required** | 2FA Secret Key (not the 6-digit code). |
| `storage` | `BaseStorage` | `MemoryStorage` | Token storage provider. |
| `headless` | `bool` | `True` | Run browser without UI. |
| `retries` | `int` | `2` | Automation retry attempts. |

---

## 🔍 Troubleshooting & Logging

### Verbose Logs
If you encounter issues, enable logging to see the step-by-step automation:
```python
import logging
logging.basicConfig(level=logging.INFO)
```

### Common Failures
- **Zscaler/Firewall**: If you see "Access blocked by network filter", ensure `api.upstox.com` is whitelisted.
- **Selector Timeouts**: On failure, a diagnostic screenshot is saved to `.tmp/error_mobile_selector.png`.
- **Redirect URI Mismatch**: The `redirect_uri` must be **identical** to the one set in your Upstox Developer Portal (including trailing slashes).

---

## 👨‍💻 Maintainer

Developed and maintained by **[Brijesh Yadav](https://github.com/brijeshyadav30599)**.

For any queries, feel free to reach out via:
- **Email**: `brijeshyadav30599@gmail.com`
- **GitHub**: [brijeshyadav30599](https://github.com/brijeshyadav30599)
- **Organization**: [GrowthQuantix](https://github.com/growthquantix)

## ⭐ Show Your Support

If this project helped you automate your trading flow, please give it a **Star** on GitHub! It helps more developers find this tool.

---

*Disclaimer: This is an unofficial library and is not affiliated with Upstox. Use at your own risk.*
