nsekit 0.1.0 → 0.1.2
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 +227 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
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 | JSON (NorenWSTP) | Per-exchange ZIPs + SearchScrip API |
|
|
25
|
+
| Dhan | client_id + access_token | Binary (Market Feed) | CSV bulk dump + Search API |
|
|
26
|
+
| Paper | Instant (no credentials) | Proxied from live broker | Delegated to data source |
|
|
27
|
+
|
|
28
|
+
Before authenticating, review the credential fields each broker requires: [docs/broker-credentials.md](docs/broker-credentials.md).
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Quick Start
|
|
33
|
+
|
|
34
|
+
```typescript
|
|
35
|
+
import { createBroker } from 'nsekit';
|
|
36
|
+
|
|
37
|
+
// 1. Create a broker instance
|
|
38
|
+
const broker = createBroker('finvasia');
|
|
39
|
+
|
|
40
|
+
// 2. Authenticate
|
|
41
|
+
const auth = await broker.authenticate({
|
|
42
|
+
userId: 'FA12345',
|
|
43
|
+
password: 'your_password',
|
|
44
|
+
totpSecret: 'YOUR_BASE32_SECRET',
|
|
45
|
+
apiKey: 'your_api_secret',
|
|
46
|
+
vendorCode: 'FA12345_U',
|
|
47
|
+
});
|
|
48
|
+
// auth.value => { accessToken: '...', userId: 'FA12345', expiresAt: 1707523199000, ... }
|
|
49
|
+
|
|
50
|
+
// 3. Place an order
|
|
51
|
+
const order = await broker.placeOrder({
|
|
52
|
+
tradingSymbol: 'RELIANCE-EQ',
|
|
53
|
+
exchange: 'NSE',
|
|
54
|
+
side: 'BUY',
|
|
55
|
+
quantity: 1,
|
|
56
|
+
type: 'LIMIT',
|
|
57
|
+
product: 'INTRADAY',
|
|
58
|
+
price: 2400,
|
|
59
|
+
validity: 'DAY',
|
|
60
|
+
});
|
|
61
|
+
// order.value => { orderId: '26020900479551', status: 'PENDING', timestamp: 1707480649000 }
|
|
62
|
+
|
|
63
|
+
// 4. Get positions
|
|
64
|
+
const positions = await broker.getPositions();
|
|
65
|
+
// positions.value => [{ tradingSymbol: 'RELIANCE-EQ', side: 'LONG', quantity: 1, pnl: 12.50, ... }]
|
|
66
|
+
|
|
67
|
+
// 5. Cancel the order
|
|
68
|
+
const cancel = await broker.cancelOrder(order.value.orderId);
|
|
69
|
+
// cancel.value => { orderId: '26020900479551', status: 'CANCELLED' }
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Switch to any other broker by changing a single line:
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
const broker = createBroker('zerodha'); // or 'dhan', 'paper'
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## Architecture
|
|
81
|
+
|
|
82
|
+
### Mapper Pattern
|
|
83
|
+
|
|
84
|
+
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.
|
|
85
|
+
|
|
86
|
+
```
|
|
87
|
+
brokers/zerodha/
|
|
88
|
+
ZerodhaBroker.ts -- Implements IBroker
|
|
89
|
+
zerodha-mapper.ts -- Pure translation functions (toOrderParams, fromPosition, fromOrder, ...)
|
|
90
|
+
zerodha-auth.ts -- OAuth + request_token flow
|
|
91
|
+
zerodha-socket.ts -- KiteTicker WebSocket adapter
|
|
92
|
+
zerodha-instruments.ts -- CSV dump streaming + normalize
|
|
93
|
+
zerodha-constants.ts -- Bidirectional enum mappings (MIS <-> INTRADAY, etc.)
|
|
94
|
+
index.ts -- Barrel exports
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
All four brokers follow this identical structure. The constants files handle the mapping differences:
|
|
98
|
+
|
|
99
|
+
| Unified | Zerodha | Finvasia | Dhan |
|
|
100
|
+
|---------|---------|----------|------|
|
|
101
|
+
| `INTRADAY` | `MIS` | `I` | `INTRA` |
|
|
102
|
+
| `DELIVERY` | `CNC` | `C` | `CNC` |
|
|
103
|
+
| `LIMIT` | `LIMIT` | `LMT` | `LIMIT` |
|
|
104
|
+
| `SL` | `SL` | `SL-LMT` | `STOP_LOSS` |
|
|
105
|
+
| `BUY` | `BUY` | `B` | `BUY` |
|
|
106
|
+
|
|
107
|
+
### Result Pattern
|
|
108
|
+
|
|
109
|
+
All methods return `Result<T>` instead of throwing exceptions. This makes error handling explicit at every call site.
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
import { Ok, Err, isOk, isErr, unwrap } from 'nsekit';
|
|
113
|
+
|
|
114
|
+
const result = await broker.placeOrder(params);
|
|
115
|
+
|
|
116
|
+
if (result.ok) {
|
|
117
|
+
console.log('Order placed:', result.value.orderId);
|
|
118
|
+
} else {
|
|
119
|
+
console.log('Failed:', result.error.message);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Or unwrap (throws on Err):
|
|
123
|
+
const order = unwrap(result);
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Instrument Master
|
|
127
|
+
|
|
128
|
+
The `InstrumentMaster` maintains a normalized lookup table of all tradeable instruments across brokers. Resolution follows a three-tier strategy:
|
|
129
|
+
|
|
130
|
+
1. Redis hot cache (O(1) lookup for recently used instruments)
|
|
131
|
+
2. In-memory index (built from broker dump files)
|
|
132
|
+
3. Broker search API fallback (for brokers that support it)
|
|
133
|
+
|
|
134
|
+
Each broker implements `IBrokerInstruments` with `streamDump()`, `normalize()`, `search()`, and `resolve()` methods.
|
|
135
|
+
|
|
136
|
+
### Paper Broker
|
|
137
|
+
|
|
138
|
+
`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.
|
|
139
|
+
|
|
140
|
+
Fill logic per order type:
|
|
141
|
+
- MARKET: fill immediately at LTP + slippage
|
|
142
|
+
- LIMIT: fill when `ltp <= price` (BUY) or `ltp >= price` (SELL)
|
|
143
|
+
- SL: trigger when price crosses trigger, then fill as LIMIT
|
|
144
|
+
- SL_M: trigger when price crosses trigger, then fill as MARKET
|
|
145
|
+
|
|
146
|
+
Slippage model: `baseSlippage + (quantity / avgDailyVolume) * impactFactor`
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## Broker Credentials
|
|
151
|
+
|
|
152
|
+
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()`.
|
|
153
|
+
|
|
154
|
+
---
|
|
155
|
+
|
|
156
|
+
## Infrastructure Modules
|
|
157
|
+
|
|
158
|
+
### SessionManager
|
|
159
|
+
|
|
160
|
+
Manages authentication lifecycle across multiple brokers with automatic refresh, Redis session persistence, and health monitoring.
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
import { SessionManager } from 'nsekit';
|
|
164
|
+
|
|
165
|
+
const sm = new SessionManager(redisClient);
|
|
166
|
+
await sm.authenticate('finvasia', credentials);
|
|
167
|
+
// Sessions are refreshed automatically before expiry
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### WSManager
|
|
171
|
+
|
|
172
|
+
Aggregates tick streams from multiple broker WebSocket connections. Handles reference-counted subscriptions, symbol resolution via InstrumentMaster, and publishes ticks to Redis.
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
import { WSManager } from 'nsekit';
|
|
176
|
+
|
|
177
|
+
const ws = new WSManager(instrumentMaster, redisClient);
|
|
178
|
+
ws.addBroker('finvasia', finvasiaBroker);
|
|
179
|
+
ws.subscribe(['NIFTY', 'RELIANCE'], (tick) => {
|
|
180
|
+
console.log(tick.tradingSymbol, tick.ltp);
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
## Add a New Broker
|
|
187
|
+
|
|
188
|
+
nsekit is designed to make adding new brokers straightforward. Every broker follows the same 7-file structure and implements the same IBroker interface.
|
|
189
|
+
|
|
190
|
+
**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.
|
|
191
|
+
|
|
192
|
+
**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.
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
## Project Structure
|
|
197
|
+
|
|
198
|
+
```
|
|
199
|
+
nsekit/
|
|
200
|
+
src/
|
|
201
|
+
brokers/
|
|
202
|
+
zerodha/ -- Zerodha Kite Connect adapter (7 files)
|
|
203
|
+
finvasia/ -- Finvasia Shoonya adapter (7 files)
|
|
204
|
+
dhan/ -- Dhan adapter (7 files)
|
|
205
|
+
paper/ -- Paper trading engine (3 files)
|
|
206
|
+
errors/ -- Result<T>, BrokerError, typed error classes
|
|
207
|
+
instruments/ -- InstrumentMaster (unified instrument index)
|
|
208
|
+
interfaces/ -- IBroker contract
|
|
209
|
+
session/ -- SessionManager (auth lifecycle)
|
|
210
|
+
types/ -- All shared TypeScript types
|
|
211
|
+
websocket/ -- WSManager (multi-broker tick aggregation)
|
|
212
|
+
index.ts -- Factory function + exports
|
|
213
|
+
docs/
|
|
214
|
+
adding-a-broker.md
|
|
215
|
+
AI-adding-a-broker.md
|
|
216
|
+
broker-credentials.md
|
|
217
|
+
package.json
|
|
218
|
+
tsconfig.json
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
---
|
|
222
|
+
|
|
223
|
+
## Contributing
|
|
224
|
+
|
|
225
|
+
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.
|
|
226
|
+
|
|
227
|
+
nsekit is open source under the MIT license. Contributions, bug reports, and new broker implementations are welcome from anyone.
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -23764,7 +23764,7 @@ class PaperBroker {
|
|
|
23764
23764
|
}
|
|
23765
23765
|
}
|
|
23766
23766
|
// src/index.ts
|
|
23767
|
-
var VERSION = "0.1.
|
|
23767
|
+
var VERSION = "0.1.2";
|
|
23768
23768
|
function createBroker(brokerId) {
|
|
23769
23769
|
switch (brokerId) {
|
|
23770
23770
|
case "zerodha":
|