nsekit 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,297 +1,297 @@
1
- # nsekit
2
-
3
- Unified broker abstraction for Indian stock markets. Write your trading logic once and run it against Zerodha, Finvasia (Shoonya), Dhan, or a paper trading engine with zero code changes.
4
-
5
- ```
6
- npm install nsekit
7
- ```
8
-
9
- [AI-adding-a-broker.md](docs/AI-adding-a-broker.md) | [adding-a-broker.md](docs/adding-a-broker.md) | [broker-credentials.md](docs/broker-credentials.md)
10
-
11
- | Document | Description |
12
- |----------|-------------|
13
- | [AI-adding-a-broker.md](docs/AI-adding-a-broker.md) | Self-contained prompt for any AI assistant to implement a new broker adapter end to end — from reading API docs to running tests to submitting a PR. |
14
- | [adding-a-broker.md](docs/adding-a-broker.md) | Step-by-step manual guide covering file structure, implementation order, common pitfalls, the 13-checkpoint integration test, and pull request checklist. |
15
- | [broker-credentials.md](docs/broker-credentials.md) | Per-broker credential reference — which fields are required, where to get them, auth flow details, and security notes. |
16
-
17
- ---
18
-
19
- ## Supported Brokers
20
-
21
- | Broker | Auth Flow | WebSocket | Instruments |
22
- |--------|-----------|-----------|-------------|
23
- | Zerodha (Kite Connect) | OAuth + request_token | Binary (KiteTicker) | CSV bulk dump |
24
- | Finvasia (Shoonya) | TOTP + vendor_code (or OAuth) | JSON (NorenWSTP) | Per-exchange ZIPs + SearchScrip API |
25
- | Dhan | client_id + access_token | Binary (Market Feed) | CSV bulk dump + Search API |
26
- | 5paisa | client_code + TOTP + app secrets | Binary (MarketFeed v3) | Per-exchange ScripMaster |
27
- | Paper | Instant (no credentials) | Proxied from live broker | Delegated to data source |
28
-
29
- Before authenticating, review the credential fields each broker requires: [docs/broker-credentials.md](docs/broker-credentials.md).
30
-
31
- ---
32
-
33
- ## Quick Start
34
-
35
- ```typescript
36
- import { createBroker } from 'nsekit';
37
-
38
- const broker = createBroker('finvasia'); // or 'zerodha', 'dhan', 'fivepaisa', 'paper'
39
- await broker.authenticate({ userId: '...', password: '...', totpSecret: '...', apiKey: '...', vendorCode: '...' });
40
- await broker.sync(); // downloads + indexes ~180K instruments
41
-
42
- // Exchange is auto-resolved — no need to specify it
43
- const order = await broker.placeOrder({ tradingSymbol: 'RELIANCE', side: 'BUY', quantity: 1, type: 'LIMIT', product: 'INTRADAY', price: 2400, validity: 'DAY' });
44
- const cancel = await broker.cancelOrder(order.value.orderId);
45
-
46
- // Or provide exchange explicitly
47
- await broker.placeOrder({ tradingSymbol: 'RELIANCE', exchange: 'NSE', side: 'BUY', quantity: 1, type: 'LIMIT', product: 'INTRADAY', price: 2400, validity: 'DAY' });
48
- ```
49
-
50
- See [docs/broker-credentials.md](docs/broker-credentials.md) for which credential fields each broker requires.
51
-
52
- ---
53
-
54
- ## Instrument Master
55
-
56
- Each broker holds its own `InstrumentMaster` internally. Call `broker.sync()` once at startup, then use `broker.resolve()` and `broker.search()` directly. First sync downloads ~180K instruments and indexes them in memory. Every lookup after that is instant.
57
-
58
- ```typescript
59
- import { createBroker } from 'nsekit';
60
-
61
- const broker = createBroker('finvasia');
62
- await broker.authenticate({ /* ... */ });
63
- await broker.sync();
64
- // => { instrumentCount: 184302, source: 'network' }
65
-
66
- // Resolve, search, or trade — all on the broker
67
- const inst = broker.resolve('NIFTY-24000-CE-27FEB26'); // unified nsekit symbol lookup
68
- const results = broker.search('NIFTY', 'NFO', 'CE', 10); // fuzzy search
69
- ```
70
-
71
- ### `broker.has` — Capabilities
72
-
73
- Every broker exposes a `has` object describing what it supports:
74
-
75
- ```typescript
76
- broker.has.searchAPI // true for Finvasia/Dhan, false for Zerodha
77
- broker.has.bulkDump // true for all real brokers, false for paper
78
- broker.has.optionChain // true for Finvasia/Dhan
79
- broker.has.historicalCandles
80
- broker.has.websocket
81
- broker.has.pnlReport // true for paper only
82
- ```
83
-
84
- ### Where instruments are stored
85
-
86
- The first sync downloads instruments from the broker and saves them to disk as JSON. On subsequent startups, `broker.sync()` loads from this cache — no network call, near-instant.
87
-
88
- ```
89
- ./InstrumentDump/ (default location)
90
- finvasia-instruments.json (one file per broker)
91
- zerodha-instruments.json
92
- ```
93
-
94
- Custom path:
95
-
96
- ```typescript
97
- const broker = createBroker('finvasia', {
98
- instrumentFilePath: './data/instruments',
99
- });
100
- ```
101
-
102
- To force a fresh download (skip cache):
103
-
104
- ```typescript
105
- await broker.sync(true);
106
- ```
107
-
108
- ### Optional: Redis
109
-
110
- Pass an ioredis-compatible client for distributed instrument caching. Useful when multiple processes (user bots, strategy bots) need instrument data without each loading 180K entries from disk.
111
-
112
- ```typescript
113
- import Redis from 'ioredis';
114
-
115
- const broker = createBroker('finvasia', { redis: new Redis() });
116
- await broker.authenticate({ /* ... */ });
117
- await broker.sync();
118
- // All instruments now in Redis — any process with the same Redis gets O(1) lookups
119
- ```
120
-
121
- ### Advanced: Standalone InstrumentMaster
122
-
123
- For multi-broker merge scenarios, `InstrumentMaster` still works standalone:
124
-
125
- ```typescript
126
- import { InstrumentMaster } from 'nsekit';
127
-
128
- const imaster = new InstrumentMaster({ redis: new Redis() });
129
- await imaster.syncBroker('zerodha', zerodhaBroker.instruments);
130
- await imaster.syncBroker('finvasia', finvasiaBroker.instruments);
131
- // NIFTY-24000-CE-27FEB26 now has both zerodha and finvasia tokens
132
- ```
133
-
134
- ### Unified nsekit symbol format
135
-
136
- All instruments are indexed using a unified nsekit symbol format, regardless of which broker provided them:
137
-
138
- ```
139
- EQ: TATAMOTORS (just underlying)
140
- FUT: NIFTY-FUT-27FEB26 (underlying-FUT-DDMMMYY)
141
- CE: NIFTY-24000-CE-27FEB26 (underlying-strike-CE-DDMMMYY)
142
- PE: NIFTY-24000-PE-27FEB26 (underlying-strike-PE-DDMMMYY)
143
- ```
144
-
145
- Zerodha's `NIFTY26FEB24000CE` and Finvasia's `NIFTY26FEB26C24000` both resolve to `NFO:NIFTY-24000-CE-27FEB26`. You never need to think about broker-specific symbol formats.
146
-
147
- ```typescript
148
- broker.resolve('TATAMOTORS'); // NSE equity (NSE preferred over BSE)
149
- broker.resolve('BSE:TATAMOTORS'); // explicit exchange
150
- broker.resolve('NIFTY-24000-CE-27FEB26'); // NFO option
151
- broker.resolve('NFO:NIFTY-FUT-27FEB26'); // with exchange prefix
152
- ```
153
-
154
- ---
155
-
156
- ## Architecture
157
-
158
- ### Mapper Pattern
159
-
160
- Each broker has a dedicated mapper module with pure functions that translate between unified types and broker-specific API formats. Mappers have no side effects and no I/O, making them the most testable part of the system.
161
-
162
- ```
163
- brokers/zerodha/
164
- ZerodhaBroker.ts -- Implements IBroker
165
- zerodha-mapper.ts -- Pure translation functions (toOrderParams, fromPosition, fromOrder, ...)
166
- zerodha-auth.ts -- OAuth + request_token flow
167
- zerodha-socket.ts -- KiteTicker WebSocket adapter
168
- zerodha-instruments.ts -- CSV dump streaming + normalize
169
- zerodha-constants.ts -- Bidirectional enum mappings (MIS <-> INTRADAY, etc.)
170
- index.ts -- Barrel exports
171
- ```
172
-
173
- All four brokers follow this identical structure. The constants files handle the mapping differences:
174
-
175
- | Unified | Zerodha | Finvasia | Dhan |
176
- |---------|---------|----------|------|
177
- | `INTRADAY` | `MIS` | `I` | `INTRA` |
178
- | `DELIVERY` | `CNC` | `C` | `CNC` |
179
- | `LIMIT` | `LIMIT` | `LMT` | `LIMIT` |
180
- | `SL` | `SL` | `SL-LMT` | `STOP_LOSS` |
181
- | `BUY` | `BUY` | `B` | `BUY` |
182
-
183
- ### Result Pattern
184
-
185
- All methods return `Result<T>` instead of throwing exceptions. This makes error handling explicit at every call site.
186
-
187
- ```typescript
188
- import { Ok, Err, isOk, isErr, unwrap } from 'nsekit';
189
-
190
- const result = await broker.placeOrder(params);
191
-
192
- if (result.ok) {
193
- console.log('Order placed:', result.value.orderId);
194
- } else {
195
- console.log('Failed:', result.error.message);
196
- }
197
-
198
- // Or unwrap (throws on Err):
199
- const order = unwrap(result);
200
- ```
201
-
202
- ### Instrument Master
203
-
204
- See the [Instrument Master](#instrument-master) section above for full usage. In short: each broker implements `IBrokerInstruments` with `streamDump()` and `normalize()`. The `normalize()` function sets `underlying`, `instrumentType`, `strike`, and `expiry` — `InstrumentMaster` builds unified nsekit symbols automatically and merges entries across brokers.
205
-
206
- ### Paper Broker
207
-
208
- `PaperBroker` implements the full IBroker interface using an in-memory fill engine. Orders are filled against live LTP data from a real broker's tick feed.
209
-
210
- Fill logic per order type:
211
- - MARKET: fill immediately at LTP + slippage
212
- - LIMIT: fill when `ltp <= price` (BUY) or `ltp >= price` (SELL)
213
- - SL: trigger when price crosses trigger, then fill as LIMIT
214
- - SL_M: trigger when price crosses trigger, then fill as MARKET
215
-
216
- Slippage model: `baseSlippage + (quantity / avgDailyVolume) * impactFactor`
217
-
218
- ---
219
-
220
- ## Broker Credentials
221
-
222
- Each broker requires different credential fields for authentication. See [docs/broker-credentials.md](docs/broker-credentials.md) for the full reference on where to obtain each value and how to pass them to `authenticate()`.
223
-
224
- ---
225
-
226
- ## Infrastructure Modules
227
-
228
- ### SessionManager
229
-
230
- Manages authentication lifecycle across multiple brokers with automatic refresh, Redis session persistence, and health monitoring.
231
-
232
- ```typescript
233
- import { SessionManager } from 'nsekit';
234
-
235
- const sm = new SessionManager(redisClient);
236
- await sm.authenticate('finvasia', credentials);
237
- // Sessions are refreshed automatically before expiry
238
- ```
239
-
240
- ### WSManager
241
-
242
- Aggregates tick streams from multiple broker WebSocket connections. Handles reference-counted subscriptions, symbol resolution via InstrumentMaster, and publishes ticks to Redis.
243
-
244
- ```typescript
245
- import { WSManager } from 'nsekit';
246
-
247
- const ws = new WSManager(instrumentMaster, redisClient);
248
- ws.addBroker('finvasia', finvasiaBroker);
249
- ws.subscribe(['NIFTY', 'RELIANCE'], (tick) => {
250
- console.log(tick.tradingSymbol, tick.ltp);
251
- });
252
- ```
253
-
254
- ---
255
-
256
- ## Add a New Broker
257
-
258
- nsekit is designed to make adding new brokers straightforward. Every broker follows the same 7-file structure and implements the same IBroker interface.
259
-
260
- **Manual approach:** Follow [docs/adding-a-broker.md](docs/adding-a-broker.md) for a step-by-step walkthrough covering file structure, implementation order, common pitfalls, and the 13-checkpoint manual test.
261
-
262
- **With an AI assistant (Claude, Cursor, Copilot, GPT, etc.):** Open [docs/AI-adding-a-broker.md](docs/AI-adding-a-broker.md) and paste it as context to your AI. The prompt walks the AI through the entire process — from reading the broker's API docs, to scaffolding all 7 files from skeleton templates, to running the integration test against your real broker account, to committing and submitting a pull request. You just provide your broker credentials in a `.env` file and let the AI handle the rest.
263
-
264
- ---
265
-
266
- ## Project Structure
267
-
268
- ```
269
- nsekit/
270
- src/
271
- brokers/
272
- zerodha/ -- Zerodha Kite Connect adapter (7 files)
273
- finvasia/ -- Finvasia Shoonya adapter (7 files)
274
- dhan/ -- Dhan adapter (7 files)
275
- paper/ -- Paper trading engine (3 files)
276
- errors/ -- Result<T>, BrokerError, typed error classes
277
- instruments/ -- InstrumentMaster (unified instrument index)
278
- interfaces/ -- IBroker contract
279
- session/ -- SessionManager (auth lifecycle)
280
- types/ -- All shared TypeScript types
281
- websocket/ -- WSManager (multi-broker tick aggregation)
282
- index.ts -- Factory function + exports
283
- docs/
284
- adding-a-broker.md
285
- AI-adding-a-broker.md
286
- broker-credentials.md
287
- package.json
288
- tsconfig.json
289
- ```
290
-
291
- ---
292
-
293
- ## Contributing
294
-
295
- See [docs/adding-a-broker.md](docs/adding-a-broker.md) for the implementation guide or [docs/AI-adding-a-broker.md](docs/AI-adding-a-broker.md) to let an AI do it for you.
296
-
297
- nsekit is open source under the MIT license. Contributions, bug reports, and new broker implementations are welcome from anyone.
1
+ # nsekit
2
+
3
+ Unified broker abstraction for Indian stock markets. Write your trading logic once and run it against Zerodha, Finvasia (Shoonya), Dhan, or a paper trading engine with zero code changes.
4
+
5
+ ```
6
+ npm install nsekit
7
+ ```
8
+
9
+ [AI-adding-a-broker.md](docs/AI-adding-a-broker.md) | [adding-a-broker.md](docs/adding-a-broker.md) | [broker-credentials.md](docs/broker-credentials.md)
10
+
11
+ | Document | Description |
12
+ |----------|-------------|
13
+ | [AI-adding-a-broker.md](docs/AI-adding-a-broker.md) | Self-contained prompt for any AI assistant to implement a new broker adapter end to end — from reading API docs to running tests to submitting a PR. |
14
+ | [adding-a-broker.md](docs/adding-a-broker.md) | Step-by-step manual guide covering file structure, implementation order, common pitfalls, the 13-checkpoint integration test, and pull request checklist. |
15
+ | [broker-credentials.md](docs/broker-credentials.md) | Per-broker credential reference — which fields are required, where to get them, auth flow details, and security notes. |
16
+
17
+ ---
18
+
19
+ ## Supported Brokers
20
+
21
+ | Broker | Auth Flow | WebSocket | Instruments |
22
+ |--------|-----------|-----------|-------------|
23
+ | Zerodha (Kite Connect) | OAuth + request_token | Binary (KiteTicker) | CSV bulk dump |
24
+ | Finvasia (Shoonya) | TOTP + vendor_code (or OAuth) | JSON (NorenWSTP) | Per-exchange ZIPs + SearchScrip API |
25
+ | Dhan | client_id + access_token | Binary (Market Feed) | CSV bulk dump + Search API |
26
+ | 5paisa | client_code + TOTP + app secrets | Binary (MarketFeed v3) | Per-exchange ScripMaster |
27
+ | Paper | Instant (no credentials) | Proxied from live broker | Delegated to data source |
28
+
29
+ Before authenticating, review the credential fields each broker requires: [docs/broker-credentials.md](docs/broker-credentials.md).
30
+
31
+ ---
32
+
33
+ ## Quick Start
34
+
35
+ ```typescript
36
+ import { createBroker } from 'nsekit';
37
+
38
+ const broker = createBroker('finvasia'); // or 'zerodha', 'dhan', 'fivepaisa', 'paper'
39
+ await broker.authenticate({ userId: '...', password: '...', totpSecret: '...', apiKey: '...', vendorCode: '...' });
40
+ await broker.sync(); // downloads + indexes ~180K instruments
41
+
42
+ // Exchange is auto-resolved — no need to specify it
43
+ const order = await broker.placeOrder({ tradingSymbol: 'RELIANCE', side: 'BUY', quantity: 1, type: 'LIMIT', product: 'INTRADAY', price: 2400, validity: 'DAY' });
44
+ const cancel = await broker.cancelOrder(order.value.orderId);
45
+
46
+ // Or provide exchange explicitly
47
+ await broker.placeOrder({ tradingSymbol: 'RELIANCE', exchange: 'NSE', side: 'BUY', quantity: 1, type: 'LIMIT', product: 'INTRADAY', price: 2400, validity: 'DAY' });
48
+ ```
49
+
50
+ See [docs/broker-credentials.md](docs/broker-credentials.md) for which credential fields each broker requires.
51
+
52
+ ---
53
+
54
+ ## Instrument Master
55
+
56
+ Each broker holds its own `InstrumentMaster` internally. Call `broker.sync()` once at startup, then use `broker.resolve()` and `broker.search()` directly. First sync downloads ~180K instruments and indexes them in memory. Every lookup after that is instant.
57
+
58
+ ```typescript
59
+ import { createBroker } from 'nsekit';
60
+
61
+ const broker = createBroker('finvasia');
62
+ await broker.authenticate({ /* ... */ });
63
+ await broker.sync();
64
+ // => { instrumentCount: 184302, source: 'network' }
65
+
66
+ // Resolve, search, or trade — all on the broker
67
+ const inst = broker.resolve('NIFTY-24000-CE-27FEB26'); // unified nsekit symbol lookup
68
+ const results = broker.search('NIFTY', 'NFO', 'CE', 10); // fuzzy search
69
+ ```
70
+
71
+ ### `broker.has` — Capabilities
72
+
73
+ Every broker exposes a `has` object describing what it supports:
74
+
75
+ ```typescript
76
+ broker.has.searchAPI // true for Finvasia/Dhan, false for Zerodha
77
+ broker.has.bulkDump // true for all real brokers, false for paper
78
+ broker.has.optionChain // true for Finvasia/Dhan
79
+ broker.has.historicalCandles
80
+ broker.has.websocket
81
+ broker.has.pnlReport // true for paper only
82
+ ```
83
+
84
+ ### Where instruments are stored
85
+
86
+ The first sync downloads instruments from the broker and saves them to disk as JSON. On subsequent startups, `broker.sync()` loads from this cache — no network call, near-instant.
87
+
88
+ ```
89
+ ./InstrumentDump/ (default location)
90
+ finvasia-instruments.json (one file per broker)
91
+ zerodha-instruments.json
92
+ ```
93
+
94
+ Custom path:
95
+
96
+ ```typescript
97
+ const broker = createBroker('finvasia', {
98
+ instrumentFilePath: './data/instruments',
99
+ });
100
+ ```
101
+
102
+ To force a fresh download (skip cache):
103
+
104
+ ```typescript
105
+ await broker.sync(true);
106
+ ```
107
+
108
+ ### Optional: Redis
109
+
110
+ Pass an ioredis-compatible client for distributed instrument caching. Useful when multiple processes (user bots, strategy bots) need instrument data without each loading 180K entries from disk.
111
+
112
+ ```typescript
113
+ import Redis from 'ioredis';
114
+
115
+ const broker = createBroker('finvasia', { redis: new Redis() });
116
+ await broker.authenticate({ /* ... */ });
117
+ await broker.sync();
118
+ // All instruments now in Redis — any process with the same Redis gets O(1) lookups
119
+ ```
120
+
121
+ ### Advanced: Standalone InstrumentMaster
122
+
123
+ For multi-broker merge scenarios, `InstrumentMaster` still works standalone:
124
+
125
+ ```typescript
126
+ import { InstrumentMaster } from 'nsekit';
127
+
128
+ const imaster = new InstrumentMaster({ redis: new Redis() });
129
+ await imaster.syncBroker('zerodha', zerodhaBroker.instruments);
130
+ await imaster.syncBroker('finvasia', finvasiaBroker.instruments);
131
+ // NIFTY-24000-CE-27FEB26 now has both zerodha and finvasia tokens
132
+ ```
133
+
134
+ ### Unified nsekit symbol format
135
+
136
+ All instruments are indexed using a unified nsekit symbol format, regardless of which broker provided them:
137
+
138
+ ```
139
+ EQ: TATAMOTORS (just underlying)
140
+ FUT: NIFTY-FUT-27FEB26 (underlying-FUT-DDMMMYY)
141
+ CE: NIFTY-24000-CE-27FEB26 (underlying-strike-CE-DDMMMYY)
142
+ PE: NIFTY-24000-PE-27FEB26 (underlying-strike-PE-DDMMMYY)
143
+ ```
144
+
145
+ Zerodha's `NIFTY26FEB24000CE` and Finvasia's `NIFTY26FEB26C24000` both resolve to `NFO:NIFTY-24000-CE-27FEB26`. You never need to think about broker-specific symbol formats.
146
+
147
+ ```typescript
148
+ broker.resolve('TATAMOTORS'); // NSE equity (NSE preferred over BSE)
149
+ broker.resolve('BSE:TATAMOTORS'); // explicit exchange
150
+ broker.resolve('NIFTY-24000-CE-27FEB26'); // NFO option
151
+ broker.resolve('NFO:NIFTY-FUT-27FEB26'); // with exchange prefix
152
+ ```
153
+
154
+ ---
155
+
156
+ ## Architecture
157
+
158
+ ### Mapper Pattern
159
+
160
+ Each broker has a dedicated mapper module with pure functions that translate between unified types and broker-specific API formats. Mappers have no side effects and no I/O, making them the most testable part of the system.
161
+
162
+ ```
163
+ brokers/zerodha/
164
+ ZerodhaBroker.ts -- Implements IBroker
165
+ zerodha-mapper.ts -- Pure translation functions (toOrderParams, fromPosition, fromOrder, ...)
166
+ zerodha-auth.ts -- OAuth + request_token flow
167
+ zerodha-socket.ts -- KiteTicker WebSocket adapter
168
+ zerodha-instruments.ts -- CSV dump streaming + normalize
169
+ zerodha-constants.ts -- Bidirectional enum mappings (MIS <-> INTRADAY, etc.)
170
+ index.ts -- Barrel exports
171
+ ```
172
+
173
+ All four brokers follow this identical structure. The constants files handle the mapping differences:
174
+
175
+ | Unified | Zerodha | Finvasia | Dhan |
176
+ |---------|---------|----------|------|
177
+ | `INTRADAY` | `MIS` | `I` | `INTRA` |
178
+ | `DELIVERY` | `CNC` | `C` | `CNC` |
179
+ | `LIMIT` | `LIMIT` | `LMT` | `LIMIT` |
180
+ | `SL` | `SL` | `SL-LMT` | `STOP_LOSS` |
181
+ | `BUY` | `BUY` | `B` | `BUY` |
182
+
183
+ ### Result Pattern
184
+
185
+ All methods return `Result<T>` instead of throwing exceptions. This makes error handling explicit at every call site.
186
+
187
+ ```typescript
188
+ import { Ok, Err, isOk, isErr, unwrap } from 'nsekit';
189
+
190
+ const result = await broker.placeOrder(params);
191
+
192
+ if (result.ok) {
193
+ console.log('Order placed:', result.value.orderId);
194
+ } else {
195
+ console.log('Failed:', result.error.message);
196
+ }
197
+
198
+ // Or unwrap (throws on Err):
199
+ const order = unwrap(result);
200
+ ```
201
+
202
+ ### Instrument Master
203
+
204
+ See the [Instrument Master](#instrument-master) section above for full usage. In short: each broker implements `IBrokerInstruments` with `streamDump()` and `normalize()`. The `normalize()` function sets `underlying`, `instrumentType`, `strike`, and `expiry` — `InstrumentMaster` builds unified nsekit symbols automatically and merges entries across brokers.
205
+
206
+ ### Paper Broker
207
+
208
+ `PaperBroker` implements the full IBroker interface using an in-memory fill engine. Orders are filled against live LTP data from a real broker's tick feed.
209
+
210
+ Fill logic per order type:
211
+ - MARKET: fill immediately at LTP + slippage
212
+ - LIMIT: fill when `ltp <= price` (BUY) or `ltp >= price` (SELL)
213
+ - SL: trigger when price crosses trigger, then fill as LIMIT
214
+ - SL_M: trigger when price crosses trigger, then fill as MARKET
215
+
216
+ Slippage model: `baseSlippage + (quantity / avgDailyVolume) * impactFactor`
217
+
218
+ ---
219
+
220
+ ## Broker Credentials
221
+
222
+ Each broker requires different credential fields for authentication. See [docs/broker-credentials.md](docs/broker-credentials.md) for the full reference on where to obtain each value and how to pass them to `authenticate()`.
223
+
224
+ ---
225
+
226
+ ## Infrastructure Modules
227
+
228
+ ### SessionManager
229
+
230
+ Manages authentication lifecycle across multiple brokers with automatic refresh, Redis session persistence, and health monitoring.
231
+
232
+ ```typescript
233
+ import { SessionManager } from 'nsekit';
234
+
235
+ const sm = new SessionManager(redisClient);
236
+ await sm.authenticate('finvasia', credentials);
237
+ // Sessions are refreshed automatically before expiry
238
+ ```
239
+
240
+ ### WSManager
241
+
242
+ Aggregates tick streams from multiple broker WebSocket connections. Handles reference-counted subscriptions, symbol resolution via InstrumentMaster, and publishes ticks to Redis.
243
+
244
+ ```typescript
245
+ import { WSManager } from 'nsekit';
246
+
247
+ const ws = new WSManager(instrumentMaster, redisClient);
248
+ ws.addBroker('finvasia', finvasiaBroker);
249
+ ws.subscribe(['NIFTY', 'RELIANCE'], (tick) => {
250
+ console.log(tick.tradingSymbol, tick.ltp);
251
+ });
252
+ ```
253
+
254
+ ---
255
+
256
+ ## Add a New Broker
257
+
258
+ nsekit is designed to make adding new brokers straightforward. Every broker follows the same 7-file structure and implements the same IBroker interface.
259
+
260
+ **Manual approach:** Follow [docs/adding-a-broker.md](docs/adding-a-broker.md) for a step-by-step walkthrough covering file structure, implementation order, common pitfalls, and the 13-checkpoint manual test.
261
+
262
+ **With an AI assistant (Claude, Cursor, Copilot, GPT, etc.):** Open [docs/AI-adding-a-broker.md](docs/AI-adding-a-broker.md) and paste it as context to your AI. The prompt walks the AI through the entire process — from reading the broker's API docs, to scaffolding all 7 files from skeleton templates, to running the integration test against your real broker account, to committing and submitting a pull request. You just provide your broker credentials in a `.env` file and let the AI handle the rest.
263
+
264
+ ---
265
+
266
+ ## Project Structure
267
+
268
+ ```
269
+ nsekit/
270
+ src/
271
+ brokers/
272
+ zerodha/ -- Zerodha Kite Connect adapter (7 files)
273
+ finvasia/ -- Finvasia Shoonya adapter (7 files)
274
+ dhan/ -- Dhan adapter (7 files)
275
+ paper/ -- Paper trading engine (3 files)
276
+ errors/ -- Result<T>, BrokerError, typed error classes
277
+ instruments/ -- InstrumentMaster (unified instrument index)
278
+ interfaces/ -- IBroker contract
279
+ session/ -- SessionManager (auth lifecycle)
280
+ types/ -- All shared TypeScript types
281
+ websocket/ -- WSManager (multi-broker tick aggregation)
282
+ index.ts -- Factory function + exports
283
+ docs/
284
+ adding-a-broker.md
285
+ AI-adding-a-broker.md
286
+ broker-credentials.md
287
+ package.json
288
+ tsconfig.json
289
+ ```
290
+
291
+ ---
292
+
293
+ ## Contributing
294
+
295
+ See [docs/adding-a-broker.md](docs/adding-a-broker.md) for the implementation guide or [docs/AI-adding-a-broker.md](docs/AI-adding-a-broker.md) to let an AI do it for you.
296
+
297
+ nsekit is open source under the MIT license. Contributions, bug reports, and new broker implementations are welcome from anyone.
@@ -59,6 +59,11 @@ export declare class FivePaisaBroker implements IBroker {
59
59
  * Supports: "N:C:1660", "N:1660", "1660"
60
60
  */
61
61
  private parseSymbolsToFeedData;
62
+ /** Resolve ExchOrderID from BrokerOrderId via order book lookup.
63
+ * The 5paisa modify/cancel APIs require ExchOrderID, but placeOrder returns
64
+ * BrokerOrderID. If the input already looks like an ExchOrderID (12+ digits),
65
+ * return it directly. */
66
+ private resolveExchOrderId;
62
67
  /** Build the standard 5paisa payload head. */
63
68
  private buildHead;
64
69
  /** Build the standard 5paisa payload body with ClientCode. */
@@ -1 +1 @@
1
- {"version":3,"file":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AAC,CAAC;IAMvE;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAa9B;;;8BAG0B;YACZ,kBAAkB;IAahC,8CAA8C;IAC9C,OAAO,CAAC,SAAS;IAYjB,8DAA8D;IAC9D,OAAO,CAAC,SAAS;IAMjB,kDAAkD;YACpC,IAAI;IA8BlB,OAAO,CAAC,YAAY;CAgBrB"}
@@ -12,7 +12,7 @@ export declare const ROUTES: {
12
12
  readonly TOTP_LOGIN: "https://Openapi.5paisa.com/VendorsAPI/Service1.svc/TOTPLogin";
13
13
  readonly ACCESS_TOKEN: "https://Openapi.5paisa.com/VendorsAPI/Service1.svc/GetAccessToken";
14
14
  readonly MARGIN: "https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V4/Margin";
15
- readonly ORDER_BOOK: "https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V3/OrderBook";
15
+ readonly ORDER_BOOK: "https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V4/OrderBook";
16
16
  readonly HOLDINGS: "https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V3/Holding";
17
17
  readonly POSITIONS: "https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V1/NetPositionNetWise";
18
18
  readonly PLACE_ORDER: "https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V1/PlaceOrderRequest";
@@ -38,6 +38,7 @@ export interface FivePaisaOrderBookEntry {
38
38
  PendingQty: number;
39
39
  TradedQty: number;
40
40
  Rate: number;
41
+ AveragePrice: number;
41
42
  SLTriggerRate: number;
42
43
  WithSL: string;
43
44
  OrderStatus: string;