digdigdig3 0.1.19

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# Fyers Connector - Setup & Usage Guide


Complete implementation of Fyers Securities API v3 for Indian markets.

## Features


- **FREE API Access** - No subscription fees
- **F&O Specialization** - Strong Futures & Options support
- **Multi-Exchange** - NSE, BSE, MCX, NCDEX
- **High Rate Limits** - 100,000 requests/day, 10/sec, 200/min
- **Fast Execution** - Orders execute under 50ms
- **WebSocket Support** - Data, Order, and TBT streams

## Prerequisites


1. Active Fyers trading account
2. Demat account
3. External 2FA TOTP enabled

## Authentication Setup


### Step 1: Create API App


1. Go to https://myapi.fyers.in/dashboard/
2. Click "Create App"
3. Fill in:
   - App Name: `My Trading App`
   - Redirect URI: `https://yourapp.com/callback`
4. Save and note down:
   - `APP_ID` (Client ID): e.g., `ABC123XYZ-100`
   - `APP_SECRET` (Secret Key): e.g., `ABCDEFGH1234567890`

### Step 2: Enable 2FA TOTP


1. Go to https://myaccount.fyers.in/
2. Navigate to "Security" → "External 2FA TOTP"
3. Enable and scan QR code with Google/Microsoft Authenticator
4. **Save the TOTP secret key** for automation

### Step 3: Generate Access Token


#### Option A: Manual (First Time)


```bash
# Set credentials

export FYERS_APP_ID="ABC123XYZ-100"
export FYERS_APP_SECRET="ABCDEFGH1234567890"

# Run the auth helper (create this script)

cargo run --example fyers_auth
```

The script will:
1. Print authorization URL
2. You navigate to it in browser
3. Login with username, password, TOTP code
4. Copy `auth_code` from redirect URL
5. Script exchanges it for `access_token`

#### Option B: Automated (Selenium/Playwright)


Use community tools:
- https://github.com/tkanhe/fyers-api-access-token-v3

### Step 4: Set Environment Variables


```bash
export FYERS_APP_ID="ABC123XYZ-100"
export FYERS_APP_SECRET="ABCDEFGH1234567890"
export FYERS_ACCESS_TOKEN="eyJ0eXAiOiJKV1QiLCJhbGc..."
```

Or create `.env` file:
```env
FYERS_APP_ID=ABC123XYZ-100
FYERS_APP_SECRET=ABCDEFGH1234567890
FYERS_ACCESS_TOKEN=eyJ0eXAiOiJKV1QiLCJhbGc...
```

## Usage Examples


### Basic Setup


```rust
use digdigdig3::stocks::india::fyers::{FyersConnector, FyersAuth};
use digdigdig3::{AccountType, Symbol, OrderSide};

// Create connector from environment variables
let connector = FyersConnector::from_env()?;

// Or with explicit credentials
let auth = FyersAuth::with_token("APP_ID", "APP_SECRET", "ACCESS_TOKEN");
let connector = FyersConnector::new(auth)?;
```

### Market Data


```rust
use digdigdig3::MarketData;

let symbol = Symbol::new("SBIN", "NSE");

// Get current price
let price = connector.get_price(symbol.clone(), AccountType::Spot).await?;
println!("SBIN price: {}", price);

// Get ticker (OHLCV + 24h stats)
let ticker = connector.get_ticker(symbol.clone(), AccountType::Spot).await?;
println!("Open: {}, High: {}, Low: {}, Volume: {}",
    ticker.open, ticker.high, ticker.low, ticker.volume);

// Get orderbook (Level 2)
let orderbook = connector.get_orderbook(symbol.clone(), Some(5), AccountType::Spot).await?;
println!("Best bid: {:?}", orderbook.bids.first());
println!("Best ask: {:?}", orderbook.asks.first());

// Get historical klines
let klines = connector.get_klines(symbol, "5m", Some(100), AccountType::Spot).await?;
for kline in klines.iter().take(5) {
    println!("OHLC: {} {} {} {}", kline.open, kline.high, kline.low, kline.close);
}
```

### Trading


```rust
use digdigdig3::Trading;

let symbol = Symbol::new("SBIN", "NSE");

// Place market order
let order = connector.market_order(
    symbol.clone(),
    OrderSide::Buy,
    100.0, // quantity
    AccountType::Spot
).await?;
println!("Order placed: {}", order.id);

// Place limit order
let order = connector.limit_order(
    symbol.clone(),
    OrderSide::Buy,
    100.0, // quantity
    550.0, // limit price
    AccountType::Spot
).await?;

// Cancel order
let canceled = connector.cancel_order(
    symbol.clone(),
    &order.id,
    AccountType::Spot
).await?;

// Get open orders
let orders = connector.get_open_orders(Some(symbol), AccountType::Spot).await?;
for order in orders {
    println!("{}: {} {} @ {:?}", order.id, order.side, order.symbol, order.price);
}
```

### Account & Positions


```rust
use digdigdig3::{Account, Positions};

// Get balance
let balances = connector.get_balance(None, AccountType::Spot).await?;
for balance in balances {
    println!("{}: Total={}, Free={}, Locked={}",
        balance.asset, balance.total, balance.free, balance.locked);
}

// Get account info
let account_info = connector.get_account_info(AccountType::Spot).await?;
println!("User ID: {}", account_info.user_id);

// Get positions
let positions = connector.get_positions(None, AccountType::Spot).await?;
for pos in positions {
    println!("{} {} @ {} (P&L: {})",
        pos.side, pos.symbol, pos.entry_price, pos.unrealized_pnl);
}
```

### Extended Methods


```rust
// Get holdings (delivery portfolio)
let holdings = connector.get_holdings().await?;

// Get trade book
let trades = connector.get_tradebook().await?;

// Convert position
connector.convert_position(
    "NSE:SBIN-EQ",
    1, // position side
    100.0, // quantity
    "INTRADAY", // from product type
    "CNC" // to product type
).await?;

// Modify order
connector.modify_order(
    &order_id,
    Some(1), // order type (LIMIT)
    Some(551.0), // new limit price
    Some(100) // new quantity
).await?;
```

## Symbol Format


Fyers uses: `EXCHANGE:SYMBOL-SERIES`

### Examples


```rust
// Equity (NSE)
Symbol::new("SBIN", "NSE")        // → NSE:SBIN-EQ

// Equity (BSE)
Symbol::new("SENSEX", "BSE")      // → BSE:SENSEX-EQ

// Futures
Symbol::new("NIFTY24JANFUT", "NSE") // → NSE:NIFTY24JANFUT

// Options
Symbol::new("NIFTY2411921500CE", "NSE") // → NSE:NIFTY2411921500CE

// Commodity
Symbol::new("GOLDM24JANFUT", "MCX") // → MCX:GOLDM24JANFUT
```

## Order Types & Product Types


### Order Types


```rust
// type: 1 = LIMIT
// type: 2 = MARKET
// type: 3 = STOP (stop-loss market)
// type: 4 = STOPLIMIT (stop-loss limit)
```

### Product Types


```rust
"INTRADAY" // Intraday square-off
"CNC"      // Cash and Carry (delivery)
"MARGIN"   // Margin (derivatives only)
"CO"       // Cover Order
"BO"       // Bracket Order
```

### Validity


```rust
"DAY" // Valid till end of day
"IOC" // Immediate or Cancel
```

## Testing


### Run All Tests


```bash
cd zengeld-terminal/crates/connectors/crates/v5
cargo test --lib stocks::india::fyers::tests -- --nocapture
```

### Run Specific Test


```bash
cargo test --lib stocks::india::fyers::tests::test_get_price -- --nocapture
```

### Run Trading Tests (Real Orders!)


```bash
# These are ignored by default - run explicitly

cargo test --lib stocks::india::fyers::tests::test_limit_order_and_cancel -- --ignored --nocapture
```

## Rate Limits


- **10 requests/second**
- **200 requests/minute**
- **100,000 requests/day**

Response headers:
```
X-RateLimit-Limit: 200
X-RateLimit-Remaining: 195
X-RateLimit-Reset: 1640000000
```

## Error Handling


```rust
use digdigdig3::ExchangeError;

match connector.get_price(symbol, AccountType::Spot).await {
    Ok(price) => println!("Price: {}", price),
    Err(ExchangeError::Auth(msg)) => {
        // Token expired - re-authenticate
        eprintln!("Auth error: {}", msg);
    }
    Err(ExchangeError::RateLimit) => {
        // Rate limit hit - wait and retry
        eprintln!("Rate limit exceeded");
    }
    Err(e) => eprintln!("Error: {}", e),
}
```

### Common Error Codes


| Code | Description | Resolution |
|------|-------------|------------|
| 401/-1600 | Authentication failed | Re-authenticate (token expired) |
| 429 | Rate limit exceeded | Wait and retry |
| -100 | Invalid parameters | Check request format |
| -351 | Symbol limit exceeded | Reduce symbol count (WebSocket) |

## Token Expiry


Access tokens expire after trading day (~24 hours).

**No refresh token mechanism** - must re-authenticate daily.

### Auto Re-authentication


```rust
use std::time::Duration;

async fn with_retry<F, T>(mut f: F) -> Result<T, ExchangeError>
where
    F: FnMut() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, ExchangeError>>>>,
{
    match f().await {
        Ok(result) => Ok(result),
        Err(ExchangeError::Auth(_)) => {
            // Re-authenticate
            // let new_token = get_new_access_token().await?;
            // connector.auth.set_access_token(new_token);
            // Retry
            f().await
        }
        Err(e) => Err(e),
    }
}
```

## WebSocket Support


(Coming soon - Phase 6)

Three WebSocket types:
1. **Data WebSocket** - Price updates, orderbook, trades
2. **Order WebSocket** - Order/trade/position updates
3. **TBT WebSocket** - Tick-by-tick binary feed (Protobuf)

## Market Coverage


### Exchanges


- **NSE** - National Stock Exchange (equity, F&O, currency)
- **BSE** - Bombay Stock Exchange (equity)
- **MCX** - Multi Commodity Exchange (commodities)
- **NCDEX** - National Commodity & Derivatives Exchange

### Segments


- **CM** - Capital Market (equity)
- **FO** - Futures & Options (derivatives)
- **CD** - Currency Derivatives
- **COMM** - Commodities

## Notes


1. **FREE API** - No monthly subscription for basic access
2. **Trading account required** - Must have active Fyers account
3. **2FA TOTP mandatory** - Required for API access
4. **Daily re-auth needed** - Tokens expire daily
5. **F&O specialization** - Excellent for derivatives trading
6. **No testnet** - Only production environment available
7. **Fast execution** - Orders execute under 50ms
8. **High limits** - 100k requests/day (10x increase in v3)

## Resources


- **API Dashboard**: https://myapi.fyers.in/dashboard/
- **Documentation**: https://myapi.fyers.in/docsv3
- **Community Forum**: https://fyers.in/community/fyers-api-rha0riqv/
- **Status Page**: https://status.fyers.in/
- **GitHub Samples**: https://github.com/FyersDev/fyers-api-sample-code

## Support


- Email: support@fyers.in
- Community: https://fyers.in/community/
- Support Portal: https://support.fyers.in/

## License


This connector implementation is part of the NEMO trading system. See main project license.