Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions docs_site/authentication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# Authentication

## Auth modes

| Mode | How it works | Broker support |
|------|-------------|----------------|
| `manual` | You provide a fresh access token each trading day | All brokers |
| `auto` | tt-connect logs in automatically (e.g. via TOTP) | Brokers that support it |

## Basic usage

=== "Sync"

```python
from tt_connect import TTConnect

config = {
"api_key": "YOUR_API_KEY",
"access_token": "YOUR_ACCESS_TOKEN",
}

with TTConnect(broker_id, config) as broker:
print(broker.get_profile().name)
```

=== "Async"

```python
import asyncio
from tt_connect import AsyncTTConnect

async def main() -> None:
config = {
"api_key": "YOUR_API_KEY",
"access_token": "YOUR_ACCESS_TOKEN",
}

async with AsyncTTConnect(broker_id, config) as broker:
profile = await broker.get_profile()
print(profile.name)

asyncio.run(main())
```

## Config keys

### Common keys (all brokers)

| Key | Type | Default | Description |
|---|---|---|---|
| `api_key` | `str` | required | Broker app API key |
| `access_token` | `str` | required (manual mode) | Daily session token |
| `on_stale` | `"fail"` or `"warn"` | `"fail"` | Behavior when instrument cache refresh fails |
| `cache_session` | `bool` | `False` | Persist session to disk for reuse within same day |

### Auto mode keys (brokers that support it)

| Key | Type | Description |
|---|---|---|
| `auth_mode` | `"auto"` | Enable automatic login |
| `client_id` | `str` | Broker client code |
| `pin` | `str` | Trading PIN |
| `totp_secret` | `str` | Base32 TOTP secret for 2FA |

??? note "Broker-specific config details"
See [Broker Differences](broker-differences.md) for the exact config keys required by each broker.

## Instrument cache behavior (`on_stale`)

| Value | Meaning |
|---|---|
| `"fail"` | If instrument refresh fails at startup, client init fails (safest for production) |
| `"warn"` | If refresh fails and a cache exists, continue with stale data |

## Environment variables

Keep credentials out of code:

```python
import os
from tt_connect import TTConnect

config = {
"api_key": os.environ["BROKER_API_KEY"],
"access_token": os.environ["BROKER_ACCESS_TOKEN"],
}

with TTConnect(broker_id, config) as broker:
print(broker.get_profile().name)
```

## Session lifecycle

- Client creation triggers login and instrument initialization
- Sessions are valid for the current trading day only

!!! warning "Daily token expiry (SEBI requirement)"
All Indian broker tokens expire at end of day. This is a SEBI mandate. You must re-authenticate each trading day. If your token expires mid-session, API calls raise `AuthenticationError`.

## Good practices

- Keep credentials in environment variables or a secret manager
- Never hardcode tokens in source code
- Always close the client (the `with` statement does this automatically)

## Common mistakes

- Using `auto` auth mode on a broker that only supports `manual`
- Missing required keys for auto mode (e.g. `totp_secret`)
- Using an expired access token
- Mixing environment variables from different brokers
80 changes: 0 additions & 80 deletions docs_site/basics.md

This file was deleted.

111 changes: 82 additions & 29 deletions docs_site/broker-differences.md
Original file line number Diff line number Diff line change
@@ -1,39 +1,92 @@
# Broker Differences

## Why this page matters
API shape is unified, but broker behavior is not always identical.
The tt-connect API is unified, but brokers differ in capabilities and behavior. This page is the single reference for all per-broker specifics.

## Current capability snapshot
## Capability matrix

| Area | Zerodha | AngelOne |
| Capability | Zerodha | AngelOne |
|---|---|---|
| Auth modes | manual | manual, auto |
| Segments | NSE, BSE, NFO, BFO, CDS | NSE, BSE, NFO, CDS, MCX |
| Order types | MARKET, LIMIT, SL, SL_M | MARKET, LIMIT, SL, SL_M |
| Product types | CNC, MIS, NRML | CNC, MIS, NRML |

## Practical difference examples
- Single order fetch may differ by broker behavior/endpoints.
- GTT payload/rules can differ between brokers.
- Market data depth/fields can differ by broker stream mode.

## Recommended approach
- check capability before critical flows
- keep broker-specific fallbacks for edge cases
- test same strategy on each broker separately

## Simple multi-broker pattern
| Auth modes | `manual` | `manual`, `auto` |
| Segments | `NSE`, `BSE`, `NFO`, `BFO`, `CDS` | `NSE`, `BSE`, `NFO`, `CDS`, `MCX` |
| Order types | `MARKET`, `LIMIT`, `SL`, `SL_M` | `MARKET`, `LIMIT`, `SL`, `SL_M` |
| Product types | `CNC`, `MIS`, `NRML` | `CNC`, `MIS`, `NRML` |

## Pre-order validation

These checks run automatically before any network call:

| Check | What is validated |
|---|---|
| Segment | Instrument exchange is supported by broker |
| Order type | Requested order type is allowed |
| Product type | Requested product type is allowed |
| Tradeability | Index instruments are blocked for order placement |

If validation fails, `UnsupportedFeatureError` is raised immediately.

## Operation differences

### Orders

| Operation | Zerodha | AngelOne | Recommendation |
|---|---|---|---|
| `get_order(id)` | Supported | Fetches order book, filters by ID | Use `get_orders()` + filter for portability |
| `get_orders()` | Full order book | Normalized list (empty on null) | Handle empty list safely |
| `cancel_all_orders()` | List + cancel flow | List + cancel flow | Capture both cancelled and failed IDs |
| `tag` kwarg | Sent as `tag` (max 20 chars) | Sent as `uniqueorderid` | Use short tags for compatibility |

### GTT

| Operation | Zerodha | AngelOne | Recommendation |
|---|---|---|---|
| `place_gtt` | 1 or 2 legs | 1 leg only | Keep to single-leg for portability |
| `modify_gtt` | Supported | Supported | Re-fetch rule after modify |
| `cancel_gtt` | Direct cancel | Uses rule details internally | Handle errors, retry only on transient |

### Authentication

| Area | Zerodha | AngelOne | Recommendation |
|---|---|---|---|
| Auth modes | `manual` only | `manual` + `auto` | Check broker support before using `auto` |
| Token lifecycle | External OAuth flow daily | Auto mode supports TOTP login | Use `cache_session` in auto mode |

### Config keys

| Key | Zerodha | AngelOne (manual) | AngelOne (auto) |
|---|---|---|---|
| `api_key` | Required | Required | Required |
| `access_token` | Required | Required | — |
| `auth_mode` | — | `"manual"` | `"auto"` |
| `client_id` | — | — | Required |
| `pin` | — | — | Required |
| `totp_secret` | — | — | Required |
| `on_stale` | Optional | Optional | Optional |
| `cache_session` | Optional | Optional | Optional |

### Market data

| Operation | Zerodha | AngelOne | Recommendation |
|---|---|---|---|
| `get_quotes()` (REST) | Supported | Not supported | Use WebSocket for live quotes across brokers |
| `get_historical()` | Supported | Supported | Same canonical API |
| WebSocket mode | Full mode | Snap-quote mode | Keep tick callbacks tolerant to missing fields |

### WebSocket

| Area | Zerodha | AngelOne | Recommendation |
|---|---|---|---|
| Subscribe mode | Full (OI, depth, timestamps) | Snap-quote (OI, best-5 bid/ask) | Callbacks should handle optional fields |
| Reconnect | Auto + resubscribe | Auto + resubscribe | Keep callbacks idempotent and fast |

## Writing portable code

```python
from tt_connect import TTConnect

def print_profile(broker_name: str, config: dict) -> None:
with TTConnect(broker_name, config) as broker:
p = broker.get_profile()
print(broker_name, p.client_id, p.name)
def run_strategy(broker_id: str, config: dict) -> None:
with TTConnect(broker_id, config) as broker:
profile = broker.get_profile()
print(broker_id, profile.client_id, profile.name)
```

## See also
- [Broker capabilities](reference/capabilities.md)
- [Broker operation notes](reference/operation-notes.md)
- [Enums](reference/enums.md)
- [Exceptions](reference/exceptions.md)
Test the same strategy on each broker separately. Use `UnsupportedFeatureError` handling for operations that may not be available on all brokers.
Loading
Loading