@fullstackcraftllc/floe 0.0.2 → 0.0.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 +23 -1
- package/dist/client/FloeClient.d.ts +64 -5
- package/dist/client/FloeClient.js +134 -5
- package/dist/client/brokers/SchwabClient.d.ts +2 -0
- package/dist/client/brokers/SchwabClient.js +6 -0
- package/dist/client/brokers/TastyTradeClient.d.ts +384 -0
- package/dist/client/brokers/TastyTradeClient.js +1081 -0
- package/dist/client/brokers/TradierClient.d.ts +233 -1
- package/dist/client/brokers/TradierClient.js +435 -0
- package/dist/impliedpdf/index.d.ts +148 -0
- package/dist/impliedpdf/index.js +277 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +8 -1
- package/dist/utils/occ.d.ts +1 -1
- package/dist/utils/occ.js +5 -4
- package/dist/volatility/index.d.ts +1 -1
- package/dist/volatility/index.js +1 -1
- package/package.json +2 -1
|
@@ -48,6 +48,21 @@ class TradierClient {
|
|
|
48
48
|
this.tickerCache = new Map();
|
|
49
49
|
/** Cached option data (for merging quote and trade events) */
|
|
50
50
|
this.optionCache = new Map();
|
|
51
|
+
/**
|
|
52
|
+
* Base open interest from REST API - used as t=0 reference for live OI calculation
|
|
53
|
+
* Key: OCC symbol, Value: open interest at start of day / time of fetch
|
|
54
|
+
*/
|
|
55
|
+
this.baseOpenInterest = new Map();
|
|
56
|
+
/**
|
|
57
|
+
* Cumulative estimated OI change from intraday trades
|
|
58
|
+
* Key: OCC symbol, Value: net estimated change (positive = more contracts opened)
|
|
59
|
+
*/
|
|
60
|
+
this.cumulativeOIChange = new Map();
|
|
61
|
+
/**
|
|
62
|
+
* History of intraday trades with aggressor classification
|
|
63
|
+
* Key: OCC symbol, Value: array of trades
|
|
64
|
+
*/
|
|
65
|
+
this.intradayTrades = new Map();
|
|
51
66
|
/** Event listeners */
|
|
52
67
|
this.eventListeners = new Map();
|
|
53
68
|
/** Reconnection attempt counter */
|
|
@@ -64,6 +79,7 @@ class TradierClient {
|
|
|
64
79
|
// Initialize event listener maps
|
|
65
80
|
this.eventListeners.set('tickerUpdate', new Set());
|
|
66
81
|
this.eventListeners.set('optionUpdate', new Set());
|
|
82
|
+
this.eventListeners.set('optionTrade', new Set());
|
|
67
83
|
this.eventListeners.set('connected', new Set());
|
|
68
84
|
this.eventListeners.set('disconnected', new Set());
|
|
69
85
|
this.eventListeners.set('error', new Set());
|
|
@@ -138,6 +154,165 @@ class TradierClient {
|
|
|
138
154
|
isConnected() {
|
|
139
155
|
return this.connected;
|
|
140
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Fetches options chain data from Tradier REST API.
|
|
159
|
+
*
|
|
160
|
+
* @param symbol - Underlying symbol (e.g., 'QQQ')
|
|
161
|
+
* @param expiration - Expiration date in YYYY-MM-DD format
|
|
162
|
+
* @param greeks - Whether to include Greeks data (default: true)
|
|
163
|
+
* @returns Array of option chain items, or empty array on failure
|
|
164
|
+
*/
|
|
165
|
+
async fetchOptionsChain(symbol, expiration, greeks = true) {
|
|
166
|
+
try {
|
|
167
|
+
const params = new URLSearchParams({
|
|
168
|
+
symbol,
|
|
169
|
+
expiration,
|
|
170
|
+
greeks: String(greeks),
|
|
171
|
+
});
|
|
172
|
+
const url = `${this.apiBaseUrl}/markets/options/chains?${params.toString()}`;
|
|
173
|
+
const response = await fetch(url, {
|
|
174
|
+
method: 'GET',
|
|
175
|
+
headers: {
|
|
176
|
+
'Authorization': `Bearer ${this.authKey}`,
|
|
177
|
+
'Accept': 'application/json',
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
// log raw response for debugging
|
|
181
|
+
const rawResponse = await response.clone().text();
|
|
182
|
+
console.log('Raw options chain response:', rawResponse);
|
|
183
|
+
if (!response.ok) {
|
|
184
|
+
this.emit('error', new Error(`Failed to fetch options chain: ${response.statusText}`));
|
|
185
|
+
return [];
|
|
186
|
+
}
|
|
187
|
+
const data = await response.json();
|
|
188
|
+
if (!data.options || !data.options.option) {
|
|
189
|
+
return [];
|
|
190
|
+
}
|
|
191
|
+
// Handle case where API returns single object instead of array
|
|
192
|
+
const options = Array.isArray(data.options.option)
|
|
193
|
+
? data.options.option
|
|
194
|
+
: [data.options.option];
|
|
195
|
+
return options;
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
this.emit('error', error instanceof Error ? error : new Error(String(error)));
|
|
199
|
+
return [];
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Fetches open interest and other static data for subscribed options via REST API.
|
|
204
|
+
* Call this after subscribing to options to populate open interest.
|
|
205
|
+
*
|
|
206
|
+
* @param occSymbols - Array of OCC option symbols to fetch data for
|
|
207
|
+
* @returns Promise that resolves when all data is fetched
|
|
208
|
+
*
|
|
209
|
+
* @remarks
|
|
210
|
+
* Open interest is only available via the REST API, not streaming.
|
|
211
|
+
* This method groups options by underlying and expiration to minimize API calls.
|
|
212
|
+
*/
|
|
213
|
+
async fetchOpenInterest(occSymbols) {
|
|
214
|
+
// Group symbols by underlying and expiration to minimize API calls
|
|
215
|
+
const groups = new Map();
|
|
216
|
+
for (const occSymbol of occSymbols) {
|
|
217
|
+
try {
|
|
218
|
+
const parsed = (0, occ_1.parseOCCSymbol)(occSymbol);
|
|
219
|
+
const key = `${parsed.symbol}:${parsed.expiration.toISOString().split('T')[0]}`;
|
|
220
|
+
if (!groups.has(key)) {
|
|
221
|
+
groups.set(key, new Set());
|
|
222
|
+
}
|
|
223
|
+
groups.get(key).add(occSymbol);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
// Skip invalid OCC symbols
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
// Fetch chains for each underlying/expiration combination
|
|
231
|
+
const fetchPromises = Array.from(groups.entries()).map(async ([key, symbols]) => {
|
|
232
|
+
const [underlying, expiration] = key.split(':');
|
|
233
|
+
const chain = await this.fetchOptionsChain(underlying, expiration);
|
|
234
|
+
// Update cache with open interest data
|
|
235
|
+
for (const item of chain) {
|
|
236
|
+
// Tradier returns symbols in the same format we use (compact OCC)
|
|
237
|
+
if (symbols.has(item.symbol)) {
|
|
238
|
+
// Store base open interest for live OI calculation (t=0 reference)
|
|
239
|
+
this.baseOpenInterest.set(item.symbol, item.open_interest);
|
|
240
|
+
// Initialize cumulative OI change if not already set
|
|
241
|
+
if (!this.cumulativeOIChange.has(item.symbol)) {
|
|
242
|
+
this.cumulativeOIChange.set(item.symbol, 0);
|
|
243
|
+
}
|
|
244
|
+
const existing = this.optionCache.get(item.symbol);
|
|
245
|
+
if (existing) {
|
|
246
|
+
// Update existing cache entry with REST data
|
|
247
|
+
existing.openInterest = item.open_interest;
|
|
248
|
+
existing.liveOpenInterest = this.calculateLiveOpenInterest(item.symbol);
|
|
249
|
+
existing.volume = item.volume;
|
|
250
|
+
existing.impliedVolatility = item.greeks?.mid_iv ?? existing.impliedVolatility;
|
|
251
|
+
// Also update bid/ask if not yet populated
|
|
252
|
+
if (existing.bid === 0 && item.bid > 0) {
|
|
253
|
+
existing.bid = item.bid;
|
|
254
|
+
existing.bidSize = item.bidsize;
|
|
255
|
+
}
|
|
256
|
+
if (existing.ask === 0 && item.ask > 0) {
|
|
257
|
+
existing.ask = item.ask;
|
|
258
|
+
existing.askSize = item.asksize;
|
|
259
|
+
}
|
|
260
|
+
if (existing.last === 0 && item.last !== null) {
|
|
261
|
+
existing.last = item.last;
|
|
262
|
+
}
|
|
263
|
+
if (existing.mark === 0) {
|
|
264
|
+
existing.mark = (item.bid + item.ask) / 2;
|
|
265
|
+
}
|
|
266
|
+
this.optionCache.set(item.symbol, existing);
|
|
267
|
+
this.emit('optionUpdate', existing);
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
// Create new cache entry from REST data
|
|
271
|
+
const parsedSymbol = (0, occ_1.parseOCCSymbol)(item.symbol);
|
|
272
|
+
const option = {
|
|
273
|
+
occSymbol: item.symbol,
|
|
274
|
+
underlying: item.underlying,
|
|
275
|
+
strike: item.strike,
|
|
276
|
+
expiration: item.expiration_date,
|
|
277
|
+
expirationTimestamp: parsedSymbol.expiration.getTime(),
|
|
278
|
+
optionType: item.option_type,
|
|
279
|
+
bid: item.bid,
|
|
280
|
+
bidSize: item.bidsize,
|
|
281
|
+
ask: item.ask,
|
|
282
|
+
askSize: item.asksize,
|
|
283
|
+
mark: (item.bid + item.ask) / 2,
|
|
284
|
+
last: item.last ?? 0,
|
|
285
|
+
volume: item.volume,
|
|
286
|
+
openInterest: item.open_interest,
|
|
287
|
+
liveOpenInterest: this.calculateLiveOpenInterest(item.symbol),
|
|
288
|
+
impliedVolatility: item.greeks?.mid_iv ?? 0,
|
|
289
|
+
timestamp: Date.now(),
|
|
290
|
+
};
|
|
291
|
+
this.optionCache.set(item.symbol, option);
|
|
292
|
+
this.emit('optionUpdate', option);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
await Promise.all(fetchPromises);
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Returns the cached option data for a symbol.
|
|
301
|
+
*
|
|
302
|
+
* @param occSymbol - OCC option symbol
|
|
303
|
+
* @returns Cached option data or undefined
|
|
304
|
+
*/
|
|
305
|
+
getOption(occSymbol) {
|
|
306
|
+
return this.optionCache.get(occSymbol);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Returns all cached options.
|
|
310
|
+
*
|
|
311
|
+
* @returns Map of OCC symbols to option data
|
|
312
|
+
*/
|
|
313
|
+
getAllOptions() {
|
|
314
|
+
return new Map(this.optionCache);
|
|
315
|
+
}
|
|
141
316
|
/**
|
|
142
317
|
* Registers an event listener.
|
|
143
318
|
*
|
|
@@ -256,6 +431,10 @@ class TradierClient {
|
|
|
256
431
|
else if (event.type === 'trade') {
|
|
257
432
|
this.handleTradeEvent(event);
|
|
258
433
|
}
|
|
434
|
+
else if (event.type === 'timesale') {
|
|
435
|
+
this.handleTimesaleEvent(event);
|
|
436
|
+
}
|
|
437
|
+
// 'summary' events don't have data we need for NormalizedTicker/Option
|
|
259
438
|
}
|
|
260
439
|
catch (error) {
|
|
261
440
|
// Ignore parse errors for heartbeat/status messages
|
|
@@ -289,6 +468,21 @@ class TradierClient {
|
|
|
289
468
|
this.updateTickerFromTrade(symbol, event, timestamp);
|
|
290
469
|
}
|
|
291
470
|
}
|
|
471
|
+
/**
|
|
472
|
+
* Handles timesale events (trade with bid/ask at time of sale).
|
|
473
|
+
* This is particularly useful for options where quote events may be sparse.
|
|
474
|
+
*/
|
|
475
|
+
handleTimesaleEvent(event) {
|
|
476
|
+
const { symbol } = event;
|
|
477
|
+
const timestamp = parseInt(event.date, 10) || Date.now();
|
|
478
|
+
const isOption = this.isOptionSymbol(symbol);
|
|
479
|
+
if (isOption) {
|
|
480
|
+
this.updateOptionFromTimesale(symbol, event, timestamp);
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
this.updateTickerFromTimesale(symbol, event, timestamp);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
292
486
|
/**
|
|
293
487
|
* Updates ticker data from a quote event.
|
|
294
488
|
*/
|
|
@@ -401,6 +595,247 @@ class TradierClient {
|
|
|
401
595
|
this.optionCache.set(occSymbol, option);
|
|
402
596
|
this.emit('optionUpdate', option);
|
|
403
597
|
}
|
|
598
|
+
/**
|
|
599
|
+
* Updates ticker data from a timesale event.
|
|
600
|
+
* Timesale events include bid/ask at the time of the trade.
|
|
601
|
+
*/
|
|
602
|
+
updateTickerFromTimesale(symbol, event, timestamp) {
|
|
603
|
+
const existing = this.tickerCache.get(symbol);
|
|
604
|
+
const bid = parseFloat(event.bid);
|
|
605
|
+
const ask = parseFloat(event.ask);
|
|
606
|
+
const last = parseFloat(event.last);
|
|
607
|
+
const size = parseInt(event.size, 10);
|
|
608
|
+
const ticker = {
|
|
609
|
+
symbol,
|
|
610
|
+
spot: (bid + ask) / 2,
|
|
611
|
+
bid,
|
|
612
|
+
bidSize: existing?.bidSize ?? 0, // timesale doesn't include bid/ask size
|
|
613
|
+
ask,
|
|
614
|
+
askSize: existing?.askSize ?? 0,
|
|
615
|
+
last,
|
|
616
|
+
volume: (existing?.volume ?? 0) + size, // Accumulate volume
|
|
617
|
+
timestamp,
|
|
618
|
+
};
|
|
619
|
+
this.tickerCache.set(symbol, ticker);
|
|
620
|
+
this.emit('tickerUpdate', ticker);
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Updates option data from a timesale event.
|
|
624
|
+
* Timesale events include bid/ask at the time of the trade, enabling aggressor side detection.
|
|
625
|
+
*
|
|
626
|
+
* This is the primary method for calculating live open interest:
|
|
627
|
+
* - Aggressor side is determined by comparing trade price to NBBO
|
|
628
|
+
* - Buy aggressor (lifting ask) typically indicates new long positions → OI increases
|
|
629
|
+
* - Sell aggressor (hitting bid) typically indicates closing longs or new shorts → OI decreases
|
|
630
|
+
*/
|
|
631
|
+
updateOptionFromTimesale(occSymbol, event, timestamp) {
|
|
632
|
+
const existing = this.optionCache.get(occSymbol);
|
|
633
|
+
// Parse OCC symbol to extract option details
|
|
634
|
+
let parsed;
|
|
635
|
+
try {
|
|
636
|
+
parsed = (0, occ_1.parseOCCSymbol)(occSymbol);
|
|
637
|
+
}
|
|
638
|
+
catch {
|
|
639
|
+
// Invalid OCC symbol, skip
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
const bid = parseFloat(event.bid);
|
|
643
|
+
const ask = parseFloat(event.ask);
|
|
644
|
+
const last = parseFloat(event.last);
|
|
645
|
+
const size = parseInt(event.size, 10);
|
|
646
|
+
// Determine aggressor side by comparing trade price to NBBO
|
|
647
|
+
const aggressorSide = this.determineAggressorSide(last, bid, ask);
|
|
648
|
+
// Calculate estimated OI change based on aggressor side
|
|
649
|
+
// Buy aggressor (lifting the offer) → typically opening new long positions → +OI
|
|
650
|
+
// Sell aggressor (hitting the bid) → typically closing longs or opening shorts → -OI
|
|
651
|
+
const estimatedOIChange = this.calculateOIChangeFromTrade(aggressorSide, size, parsed.optionType);
|
|
652
|
+
// Update cumulative OI change
|
|
653
|
+
const currentChange = this.cumulativeOIChange.get(occSymbol) ?? 0;
|
|
654
|
+
this.cumulativeOIChange.set(occSymbol, currentChange + estimatedOIChange);
|
|
655
|
+
// Record the trade for analysis
|
|
656
|
+
const trade = {
|
|
657
|
+
occSymbol,
|
|
658
|
+
price: last,
|
|
659
|
+
size,
|
|
660
|
+
bid,
|
|
661
|
+
ask,
|
|
662
|
+
aggressorSide,
|
|
663
|
+
timestamp,
|
|
664
|
+
estimatedOIChange,
|
|
665
|
+
};
|
|
666
|
+
if (!this.intradayTrades.has(occSymbol)) {
|
|
667
|
+
this.intradayTrades.set(occSymbol, []);
|
|
668
|
+
}
|
|
669
|
+
this.intradayTrades.get(occSymbol).push(trade);
|
|
670
|
+
// Emit trade event with aggressor info
|
|
671
|
+
this.emit('optionTrade', trade);
|
|
672
|
+
const option = {
|
|
673
|
+
occSymbol,
|
|
674
|
+
underlying: parsed.symbol,
|
|
675
|
+
strike: parsed.strike,
|
|
676
|
+
expiration: parsed.expiration.toISOString().split('T')[0],
|
|
677
|
+
expirationTimestamp: parsed.expiration.getTime(),
|
|
678
|
+
optionType: parsed.optionType,
|
|
679
|
+
bid,
|
|
680
|
+
bidSize: existing?.bidSize ?? 0, // timesale doesn't include bid/ask size
|
|
681
|
+
ask,
|
|
682
|
+
askSize: existing?.askSize ?? 0,
|
|
683
|
+
mark: (bid + ask) / 2,
|
|
684
|
+
last,
|
|
685
|
+
volume: (existing?.volume ?? 0) + size, // Accumulate volume
|
|
686
|
+
openInterest: existing?.openInterest ?? 0,
|
|
687
|
+
liveOpenInterest: this.calculateLiveOpenInterest(occSymbol),
|
|
688
|
+
impliedVolatility: existing?.impliedVolatility ?? 0,
|
|
689
|
+
timestamp,
|
|
690
|
+
};
|
|
691
|
+
this.optionCache.set(occSymbol, option);
|
|
692
|
+
this.emit('optionUpdate', option);
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Determines the aggressor side of a trade by comparing trade price to NBBO.
|
|
696
|
+
*
|
|
697
|
+
* @param tradePrice - The executed trade price
|
|
698
|
+
* @param bid - The bid price at time of trade
|
|
699
|
+
* @param ask - The ask price at time of trade
|
|
700
|
+
* @returns The aggressor side: 'buy' if lifting offer, 'sell' if hitting bid, 'unknown' if mid
|
|
701
|
+
*
|
|
702
|
+
* @remarks
|
|
703
|
+
* The aggressor is the party that initiated the trade by crossing the spread:
|
|
704
|
+
* - Buy aggressor: Buyer lifts the offer (trades at or above ask) → bullish intent
|
|
705
|
+
* - Sell aggressor: Seller hits the bid (trades at or below bid) → bearish intent
|
|
706
|
+
* - Unknown: Trade occurred mid-market (could be internalized, crossed, or negotiated)
|
|
707
|
+
*/
|
|
708
|
+
determineAggressorSide(tradePrice, bid, ask) {
|
|
709
|
+
// Use a small tolerance for floating point comparison (0.1% of spread)
|
|
710
|
+
const spread = ask - bid;
|
|
711
|
+
const tolerance = spread > 0 ? spread * 0.001 : 0.001;
|
|
712
|
+
if (tradePrice >= ask - tolerance) {
|
|
713
|
+
// Trade at or above ask → buyer lifted the offer
|
|
714
|
+
return 'buy';
|
|
715
|
+
}
|
|
716
|
+
else if (tradePrice <= bid + tolerance) {
|
|
717
|
+
// Trade at or below bid → seller hit the bid
|
|
718
|
+
return 'sell';
|
|
719
|
+
}
|
|
720
|
+
else {
|
|
721
|
+
// Trade mid-market - could be either side or internalized
|
|
722
|
+
return 'unknown';
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Calculates the estimated open interest change from a single trade.
|
|
727
|
+
*
|
|
728
|
+
* @param aggressorSide - The aggressor side of the trade
|
|
729
|
+
* @param size - Number of contracts traded
|
|
730
|
+
* @param optionType - Whether this is a call or put
|
|
731
|
+
* @returns Estimated OI change (positive = OI increase, negative = OI decrease)
|
|
732
|
+
*
|
|
733
|
+
* @remarks
|
|
734
|
+
* This uses a simplified heuristic based on typical market behavior:
|
|
735
|
+
*
|
|
736
|
+
* For CALLS:
|
|
737
|
+
* - Buy aggressor (lifting offer) → typically bullish, opening new longs → +OI
|
|
738
|
+
* - Sell aggressor (hitting bid) → typically closing longs or bearish new shorts → -OI
|
|
739
|
+
*
|
|
740
|
+
* For PUTS:
|
|
741
|
+
* - Buy aggressor (lifting offer) → typically bearish/hedging, opening new longs → +OI
|
|
742
|
+
* - Sell aggressor (hitting bid) → typically closing longs → -OI
|
|
743
|
+
*
|
|
744
|
+
* Note: This is an estimate. Without knowing if trades are opening or closing,
|
|
745
|
+
* we use aggressor side as a proxy. SpotGamma and similar providers use
|
|
746
|
+
* more sophisticated models that may incorporate position sizing, strike
|
|
747
|
+
* selection patterns, and other heuristics.
|
|
748
|
+
*/
|
|
749
|
+
calculateOIChangeFromTrade(aggressorSide, size, optionType) {
|
|
750
|
+
if (aggressorSide === 'unknown') {
|
|
751
|
+
// Mid-market trades are ambiguous - assume neutral impact on OI
|
|
752
|
+
return 0;
|
|
753
|
+
}
|
|
754
|
+
// Simple heuristic: buy aggressor = new positions opening, sell aggressor = positions closing
|
|
755
|
+
// This applies to both calls and puts since we're measuring contract count, not direction
|
|
756
|
+
if (aggressorSide === 'buy') {
|
|
757
|
+
return size; // New positions opening
|
|
758
|
+
}
|
|
759
|
+
else {
|
|
760
|
+
return -size; // Positions closing
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Calculates the live (intraday) open interest estimate for an option.
|
|
765
|
+
*
|
|
766
|
+
* @param occSymbol - OCC option symbol
|
|
767
|
+
* @returns Live OI estimate = base OI + cumulative estimated changes
|
|
768
|
+
*
|
|
769
|
+
* @remarks
|
|
770
|
+
* Live Open Interest = Base OI (from REST at t=0) + Cumulative OI Changes (from trades)
|
|
771
|
+
*
|
|
772
|
+
* This provides a real-time estimate of open interest that updates throughout
|
|
773
|
+
* the trading day as trades occur. The accuracy depends on:
|
|
774
|
+
* 1. The accuracy of aggressor side detection
|
|
775
|
+
* 2. The assumption that aggressors are typically opening new positions
|
|
776
|
+
*
|
|
777
|
+
* The official OI is only updated overnight by the OCC clearing house,
|
|
778
|
+
* so this estimate fills the gap during trading hours.
|
|
779
|
+
*/
|
|
780
|
+
calculateLiveOpenInterest(occSymbol) {
|
|
781
|
+
const baseOI = this.baseOpenInterest.get(occSymbol) ?? 0;
|
|
782
|
+
const cumulativeChange = this.cumulativeOIChange.get(occSymbol) ?? 0;
|
|
783
|
+
// Live OI cannot go negative
|
|
784
|
+
return Math.max(0, baseOI + cumulativeChange);
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Returns the intraday trades for an option with aggressor classification.
|
|
788
|
+
*
|
|
789
|
+
* @param occSymbol - OCC option symbol
|
|
790
|
+
* @returns Array of intraday trades, or empty array if none
|
|
791
|
+
*/
|
|
792
|
+
getIntradayTrades(occSymbol) {
|
|
793
|
+
return this.intradayTrades.get(occSymbol) ?? [];
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* Returns summary statistics for intraday option flow.
|
|
797
|
+
*
|
|
798
|
+
* @param occSymbol - OCC option symbol
|
|
799
|
+
* @returns Object with buy/sell volume, net OI change, and trade count
|
|
800
|
+
*/
|
|
801
|
+
getFlowSummary(occSymbol) {
|
|
802
|
+
const trades = this.intradayTrades.get(occSymbol) ?? [];
|
|
803
|
+
let buyVolume = 0;
|
|
804
|
+
let sellVolume = 0;
|
|
805
|
+
let unknownVolume = 0;
|
|
806
|
+
for (const trade of trades) {
|
|
807
|
+
switch (trade.aggressorSide) {
|
|
808
|
+
case 'buy':
|
|
809
|
+
buyVolume += trade.size;
|
|
810
|
+
break;
|
|
811
|
+
case 'sell':
|
|
812
|
+
sellVolume += trade.size;
|
|
813
|
+
break;
|
|
814
|
+
case 'unknown':
|
|
815
|
+
unknownVolume += trade.size;
|
|
816
|
+
break;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
return {
|
|
820
|
+
buyVolume,
|
|
821
|
+
sellVolume,
|
|
822
|
+
unknownVolume,
|
|
823
|
+
netOIChange: this.cumulativeOIChange.get(occSymbol) ?? 0,
|
|
824
|
+
tradeCount: trades.length,
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Resets intraday tracking data. Call this at market open or when re-fetching base OI.
|
|
829
|
+
*
|
|
830
|
+
* @param occSymbols - Optional specific symbols to reset. If not provided, resets all.
|
|
831
|
+
*/
|
|
832
|
+
resetIntradayData(occSymbols) {
|
|
833
|
+
const symbolsToReset = occSymbols ?? Array.from(this.intradayTrades.keys());
|
|
834
|
+
for (const symbol of symbolsToReset) {
|
|
835
|
+
this.intradayTrades.delete(symbol);
|
|
836
|
+
this.cumulativeOIChange.set(symbol, 0);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
404
839
|
/**
|
|
405
840
|
* Checks if a symbol is an OCC option symbol.
|
|
406
841
|
*/
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { NormalizedOption } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Strike-level probability from the implied PDF
|
|
4
|
+
*/
|
|
5
|
+
export interface StrikeProbability {
|
|
6
|
+
/** Strike price */
|
|
7
|
+
strike: number;
|
|
8
|
+
/** Probability density at this strike (normalized to sum to 1) */
|
|
9
|
+
probability: number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Implied probability distribution derived from option prices
|
|
13
|
+
* using Breeden-Litzenberger style numerical differentiation
|
|
14
|
+
*/
|
|
15
|
+
export interface ImpliedProbabilityDistribution {
|
|
16
|
+
/** Underlying symbol */
|
|
17
|
+
symbol: string;
|
|
18
|
+
/** Expiration timestamp in milliseconds */
|
|
19
|
+
expiryDate: number;
|
|
20
|
+
/** Timestamp when the distribution was calculated (milliseconds) */
|
|
21
|
+
calculationTimestamp: number;
|
|
22
|
+
/** Current underlying price */
|
|
23
|
+
underlyingPrice: number;
|
|
24
|
+
/** Strike probabilities (the PDF) */
|
|
25
|
+
strikeProbabilities: StrikeProbability[];
|
|
26
|
+
/** Most likely price (mode of the distribution) */
|
|
27
|
+
mostLikelyPrice: number;
|
|
28
|
+
/** Median price (50th percentile) */
|
|
29
|
+
medianPrice: number;
|
|
30
|
+
/** Expected value (mean) of the distribution */
|
|
31
|
+
expectedValue: number;
|
|
32
|
+
/** Expected move (standard deviation) */
|
|
33
|
+
expectedMove: number;
|
|
34
|
+
/** Tail skew ratio (right tail / left tail relative to mean) */
|
|
35
|
+
tailSkew: number;
|
|
36
|
+
/** Cumulative probability of finishing above current spot */
|
|
37
|
+
cumulativeProbabilityAboveSpot: number;
|
|
38
|
+
/** Cumulative probability of finishing below current spot */
|
|
39
|
+
cumulativeProbabilityBelowSpot: number;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Result of estimating implied probability distribution
|
|
43
|
+
*/
|
|
44
|
+
export type ImpliedPDFResult = {
|
|
45
|
+
success: true;
|
|
46
|
+
distribution: ImpliedProbabilityDistribution;
|
|
47
|
+
} | {
|
|
48
|
+
success: false;
|
|
49
|
+
error: string;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Estimate an implied probability density function (PDF) for a single expiry
|
|
53
|
+
* using Breeden-Litzenberger style numerical differentiation of call prices.
|
|
54
|
+
*
|
|
55
|
+
* This method computes the second derivative of call option prices with respect
|
|
56
|
+
* to strike price, which under risk-neutral pricing gives the probability density
|
|
57
|
+
* of the underlying ending at each strike.
|
|
58
|
+
*
|
|
59
|
+
* @param symbol - Underlying ticker symbol
|
|
60
|
+
* @param underlyingPrice - Current spot/mark price of the underlying
|
|
61
|
+
* @param callOptions - Array of call options for a single expiry (must have bid > 0 and ask > 0)
|
|
62
|
+
* @returns ImpliedProbabilityDistribution with strike-level probabilities and summary statistics
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```typescript
|
|
66
|
+
* const result = estimateImpliedProbabilityDistribution(
|
|
67
|
+
* 'QQQ',
|
|
68
|
+
* 500.00,
|
|
69
|
+
* callOptionsForExpiry
|
|
70
|
+
* );
|
|
71
|
+
*
|
|
72
|
+
* if (result.success) {
|
|
73
|
+
* console.log('Mode:', result.distribution.mostLikelyPrice);
|
|
74
|
+
* console.log('Expected move:', result.distribution.expectedMove);
|
|
75
|
+
* }
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export declare function estimateImpliedProbabilityDistribution(symbol: string, underlyingPrice: number, callOptions: NormalizedOption[]): ImpliedPDFResult;
|
|
79
|
+
/**
|
|
80
|
+
* Estimate implied probability distributions for all expirations in an option chain
|
|
81
|
+
*
|
|
82
|
+
* @param symbol - Underlying ticker symbol
|
|
83
|
+
* @param underlyingPrice - Current spot/mark price of the underlying
|
|
84
|
+
* @param options - Array of all options (calls and puts, all expirations)
|
|
85
|
+
* @returns Array of ImpliedProbabilityDistribution for each expiration
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```typescript
|
|
89
|
+
* const distributions = estimateImpliedProbabilityDistributions(
|
|
90
|
+
* 'QQQ',
|
|
91
|
+
* 500.00,
|
|
92
|
+
* chain.options
|
|
93
|
+
* );
|
|
94
|
+
*
|
|
95
|
+
* for (const dist of distributions) {
|
|
96
|
+
* console.log(`Expiry: ${new Date(dist.expiryDate).toISOString()}`);
|
|
97
|
+
* console.log(`Mode: ${dist.mostLikelyPrice}`);
|
|
98
|
+
* }
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
export declare function estimateImpliedProbabilityDistributions(symbol: string, underlyingPrice: number, options: NormalizedOption[]): ImpliedProbabilityDistribution[];
|
|
102
|
+
/**
|
|
103
|
+
* Get the probability of the underlying finishing between two price levels
|
|
104
|
+
*
|
|
105
|
+
* @param distribution - Implied probability distribution
|
|
106
|
+
* @param lowerBound - Lower price bound
|
|
107
|
+
* @param upperBound - Upper price bound
|
|
108
|
+
* @returns Probability of finishing between the bounds
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* ```typescript
|
|
112
|
+
* // Probability of QQQ finishing between 490 and 510
|
|
113
|
+
* const prob = getProbabilityInRange(distribution, 490, 510);
|
|
114
|
+
* console.log(`${(prob * 100).toFixed(1)}% chance of finishing in range`);
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
export declare function getProbabilityInRange(distribution: ImpliedProbabilityDistribution, lowerBound: number, upperBound: number): number;
|
|
118
|
+
/**
|
|
119
|
+
* Get the cumulative probability up to a given price level
|
|
120
|
+
*
|
|
121
|
+
* @param distribution - Implied probability distribution
|
|
122
|
+
* @param price - Price level
|
|
123
|
+
* @returns Cumulative probability of finishing at or below the price
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```typescript
|
|
127
|
+
* // Probability of QQQ finishing at or below 495
|
|
128
|
+
* const prob = getCumulativeProbability(distribution, 495);
|
|
129
|
+
* console.log(`${(prob * 100).toFixed(1)}% chance of finishing <= 495`);
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
export declare function getCumulativeProbability(distribution: ImpliedProbabilityDistribution, price: number): number;
|
|
133
|
+
/**
|
|
134
|
+
* Get the quantile (inverse CDF) for a given probability
|
|
135
|
+
*
|
|
136
|
+
* @param distribution - Implied probability distribution
|
|
137
|
+
* @param probability - Probability value between 0 and 1
|
|
138
|
+
* @returns Strike price at the given probability quantile
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```typescript
|
|
142
|
+
* // Find the 5th and 95th percentile strikes
|
|
143
|
+
* const p5 = getQuantile(distribution, 0.05);
|
|
144
|
+
* const p95 = getQuantile(distribution, 0.95);
|
|
145
|
+
* console.log(`90% confidence interval: [${p5}, ${p95}]`);
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
148
|
+
export declare function getQuantile(distribution: ImpliedProbabilityDistribution, probability: number): number;
|