### Install and Update Imports (Bash & JavaScript) Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/PRODUCTION_READY_SUMMARY.md Instructions for installing the 'fast-technical-indicators' package and updating import statements from the original 'technicalindicators' package. This demonstrates the drop-in replacement capability. ```bash npm install fast-technical-indicators npm uninstall technicalindicators ``` ```javascript // Before import { sma, ema, rsi, macd, stochastic, adx, mfi } from 'technicalindicators'; // After - EXACT SAME IMPORTS WORK! import { sma, ema, rsi, macd, stochastic, adx, mfi } from 'fast-technical-indicators'; ``` -------------------------------- ### Install fast-technical-indicators via npm Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md This command installs the 'fast-technical-indicators' package using npm. It's a prerequisite for using the library in your JavaScript or TypeScript project. ```bash npm install fast-technical-indicators ``` -------------------------------- ### TypeScript Example Structure for New Indicators Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/CLAUDE.md This snippet illustrates the expected structure for implementing new technical indicators in TypeScript. It shows both the functional version for batch processing and the class-based version for streaming data, adhering to the dual API pattern. ```typescript // Functional version export function indicatorName(input: InputInterface): OutputType[] // Class version for streaming export class IndicatorName { constructor(input: InputInterface) nextValue(value: InputValue): OutputType | undefined getResult(): OutputType[] } ``` -------------------------------- ### Stochastic Oscillator: Calculate and Analyze with TypeScript Source: https://context7.com/santoshkshirsagar/fast-technical-indicators/llms.txt Demonstrates how to use the Stochastic Oscillator indicator with both functional and streaming APIs in TypeScript. It requires OHLC (Open, High, Low, Close) data as input. The output includes %K and %D values, with examples of identifying overbought/oversold conditions and bullish/bearish crossovers. Dependencies: 'fast-technical-indicators'. ```typescript import { stochastic, Stochastic } from 'fast-technical-indicators'; // Prepare OHLC data const ohlcData = { high: [48.70, 48.72, 48.90, 48.87, 48.82, 49.05, 49.20, 49.35, 49.92, 50.19, 50.12, 49.66, 49.88, 50.19, 50.36, 50.57, 50.65, 50.43, 49.63, 50.33], low: [47.79, 48.14, 48.39, 48.37, 48.24, 48.64, 48.94, 48.86, 49.50, 49.87, 49.20, 48.90, 49.43, 49.73, 49.26, 50.09, 50.30, 49.21, 48.98, 49.61], close: [48.16, 48.61, 48.75, 48.63, 48.74, 49.03, 49.07, 49.32, 49.91, 50.13, 49.53, 49.50, 49.75, 50.03, 50.31, 50.52, 50.41, 49.34, 49.37, 50.23] }; // Functional API - %K period 14, %D period 3 const stochResult = stochastic({ period: 14, signalPeriod: 3, high: ohlcData.high, low: ohlcData.low, close: ohlcData.close }); stochResult.slice(-5).forEach((result, idx) => { console.log(`Period ${idx}:`); console.log(` %K: ${result.k?.toFixed(2)}`); console.log(` %D: ${result.d?.toFixed(2)}`); // Trading signals if (result.k && result.d) { if (result.k > 80 && result.d > 80) { console.log(' → Overbought'); } else if (result.k < 20 && result.d < 20) { console.log(' → Oversold'); } } }); // Streaming API const stochStream = new Stochastic({ period: 14, signalPeriod: 3, high: [], low: [], close: [] }); for (let i = 0; i < ohlcData.close.length; i++) { const result = stochStream.nextValue( ohlcData.high[i], ohlcData.low[i], ohlcData.close[i] ); if (result && result.k && result.d) { console.log(`Bar ${i}: %K=${result.k.toFixed(2)}, %D=${result.d.toFixed(2)}`); // Detect crossovers if (result.k > result.d) { console.log(' → Bullish: %K above %D'); } else { console.log(' → Bearish: %K below %D'); } } } ``` -------------------------------- ### Calculate Bollinger Bands using Functional and Streaming APIs (TypeScript) Source: https://context7.com/santoshkshirsagar/fast-technical-indicators/llms.txt Calculates Bollinger Bands, a volatility indicator, using both functional and streaming APIs. The functional API processes historical price data, while the streaming API updates bands in real-time. It also includes examples of trading signals based on %B and bandwidth. Requires the 'fast-technical-indicators' library. ```typescript import { bollingerbands, BollingerBands } from 'fast-technical-indicators'; // Functional API const prices = [44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.85, 46.08, 45.89, 46.03, 46.83, 47.69, 46.49, 46.26, 47.09, 46.66, 46.80, 46.23, 46.38, 46.33, 46.55, 45.88, 47.82, 47.23]; const bbResult = bollingerbands({ period: 20, values: prices, stdDev: 2 // Number of standard deviations }); bbResult.forEach((band, idx) => { console.log(`Period ${idx}:`); console.log(` Upper Band: ${band.upper?.toFixed(2)}`); console.log(` Middle Band (SMA): ${band.middle?.toFixed(2)}`); console.log(` Lower Band: ${band.lower?.toFixed(2)}`); console.log(` %B: ${band.pb?.toFixed(4)}`); // Position within bands console.log(` Bandwidth: ${band.width?.toFixed(4)}`); }); // Output example: // Upper Band: 48.23 // Middle Band (SMA): 46.15 // Lower Band: 44.07 // %B: 0.7542 // Bandwidth: 0.0901 // Streaming API with trading logic const bbStream = new BollingerBands({ period: 20, values: [], stdDev: 2 }); prices.forEach((price, index) => { const result = bbStream.nextValue(price); if (result) { console.log(`\nBar ${index}: Price = ${price.toFixed(2)}`); console.log(` Bands: [${result.lower?.toFixed(2)}, ${result.middle?.toFixed(2)}, ${result.upper?.toFixed(2)}]`); // Trading signals based on %B if (result.pb && result.pb > 1) { console.log(' → Price above upper band - potential sell signal'); } else if (result.pb && result.pb < 0) { console.log(' → Price below lower band - potential buy signal'); } // Volatility analysis if (result.width && result.width < 0.05) { console.log(' → Low volatility - potential breakout coming'); } else if (result.width && result.width > 0.15) { console.log(' → High volatility - potential reversal coming'); } } }); ``` -------------------------------- ### Average True Range (ATR): Calculate Volatility and Position Size with TypeScript Source: https://context7.com/santoshkshirsagar/fast-technical-indicators/llms.txt Illustrates the use of the Average True Range (ATR) indicator with both functional and streaming APIs in TypeScript. This indicator measures market volatility and requires OHLC data. The examples show how to calculate ATR values for volatility analysis and how to use the streaming API with ATR for position sizing based on risk parameters. Dependencies: 'fast-technical-indicators'. ```typescript import { atr, ATR } from 'fast-technical-indicators'; // OHLC data required for ATR const ohlcData = { high: [48.70, 48.72, 48.90, 48.87, 48.82, 49.05, 49.20, 49.35, 49.92, 50.19, 50.12, 49.66, 49.88, 50.19, 50.36, 50.57, 50.65], low: [47.79, 48.14, 48.39, 48.37, 48.24, 48.64, 48.94, 48.86, 49.50, 49.87, 49.20, 48.90, 49.43, 49.73, 49.26, 50.09, 50.30], close: [48.16, 48.61, 48.75, 48.63, 48.74, 49.03, 49.07, 49.32, 49.91, 50.13, 49.53, 49.50, 49.75, 50.03, 50.31, 50.52, 50.41] }; // Functional API - default period 14 const atrResult = atr({ period: 14, high: ohlcData.high, low: ohlcData.low, close: ohlcData.close }); atrResult.forEach((value, idx) => { console.log(`Period ${idx}: ATR = ${value.toFixed(4)}`); }); // Output: ATR values showing volatility levels // Higher ATR = more volatile market // Lower ATR = less volatile market // Streaming API for position sizing const atrStream = new ATR({ period: 14 }); for (let i = 0; i < ohlcData.close.length; i++) { const result = atrStream.nextValue( ohlcData.high[i], ohlcData.low[i], ohlcData.close[i] ); if (result !== undefined) { console.log(`\nBar ${i}:`); console.log(` ATR: ${result.toFixed(4)}`); console.log(` Price: ${ohlcData.close[i].toFixed(2)}`); // Calculate position size based on ATR const accountSize = 100000; const riskPercent = 0.01; // Risk 1% per trade const riskAmount = accountSize * riskPercent; const stopLoss = 2 * result; // 2x ATR stop loss const positionSize = Math.floor(riskAmount / stopLoss); console.log(` Suggested Stop Loss: ${stopLoss.toFixed(2)}`); console.log(` Position Size: ${positionSize} shares`); } } ``` -------------------------------- ### Run Tests with npm Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md Provides npm commands to execute the comprehensive tests included in the library. These tests compare the results with the original 'technicalindicators' package to ensure accuracy and compatibility. Commands include running tests, watch mode, and generating a coverage report. ```bash npm test # Run tests ``` ```bash npm run test:watch # Watch mode ``` ```bash npm run test:coverage # Coverage report ``` -------------------------------- ### Run Benchmarks with npm Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md Command to execute performance comparisons for the library's indicators. This helps in evaluating the speed improvements over the original 'technicalindicators' package. ```bash npm run benchmark ``` -------------------------------- ### JavaScript: Verify Method Alias Functionality Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/CRITICAL_FIXES_NEEDED.md A verification test script to confirm that the newly added method aliases for 'keltnerchannels', 'ichimokucloud', and 'fibonacciretracement' are correctly registered and callable. ```javascript const myLib = require('./our-library'); console.log(typeof myLib.keltnerchannels); // Should be 'function' console.log(typeof myLib.ichimokucloud); // Should be 'function' console.log(typeof myLib.fibonacciretracement); // Should be 'function' ``` -------------------------------- ### JavaScript: Instantiate Utility Classes Failure Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/CRITICAL_FIXES_NEEDED.md Illustrates the failure that occurs when attempting to instantiate utility classes like 'CandleData' or call utility functions like 'getAvailableIndicators' if they are not properly exported or implemented. ```javascript // These will FAIL const candleData = new ti.CandleData(100, 105, 99, 102); const availableIndicators = ti.getAvailableIndicators(); ``` -------------------------------- ### JavaScript: Success Criteria for Compatibility Fixes Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/CRITICAL_FIXES_NEEDED.md Illustrates the expected successful usage of the 'fast-technical-indicators' library after all critical fixes are implemented. It shows that method aliases, utility classes, and original methods can be used without code changes in existing projects. ```javascript // All these should work without any code changes in existing projects const indicators = require('our-library'); // Method aliases work const kc = indicators.keltnerchannels({...}); const ic = indicators.ichimokucloud({...}); const fib = indicators.fibonacciretracement({...}); // Utility classes work const candle = new indicators.CandleData(100, 105, 99, 102); const available = indicators.getAvailableIndicators(); // Original methods still work const rsi = indicators.rsi({period: 14, values: [...]}); const sma = indicators.sma({period: 20, values: [...]}); ``` -------------------------------- ### Combine Multiple Trading Indicators Strategy in TypeScript Source: https://context7.com/santoshkshirsagar/fast-technical-indicators/llms.txt This TypeScript code demonstrates how to initialize and use multiple technical indicators from the 'fast-technical-indicators' library to form a trading strategy. It processes market data bar by bar, calculates indicator values, and applies trading logic to identify potential buy or sell signals. Dependencies include the 'fast-technical-indicators' package. Inputs are market data objects with timestamp, open, high, low, close, and volume. Outputs include console logs for indicator values and trading signals. ```typescript import { SMA, EMA, RSI, MACD, BollingerBands, ATR, Stochastic } from 'fast-technical-indicators'; // Initialize all indicators const indicators = { sma20: new SMA({ period: 20, values: [] }), sma50: new SMA({ period: 50, values: [] }), ema12: new EMA({ period: 12, values: [] }), rsi: new RSI({ period: 14, values: [] }), macd: new MACD({ values: [], fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 }), bb: new BollingerBands({ period: 20, values: [], stdDev: 2 }), atr: new ATR({ period: 14 }), stoch: new Stochastic({ period: 14, signalPeriod: 3, high: [], low: [], close: [] }) }; // Market data stream const marketData = [ { timestamp: '2024-01-15 09:30', open: 150.25, high: 151.80, low: 150.10, close: 151.45, volume: 125000 }, { timestamp: '2024-01-15 09:35', open: 151.45, high: 152.20, low: 151.30, close: 151.90, volume: 98000 }, { timestamp: '2024-01-15 09:40', open: 151.90, high: 152.10, low: 151.50, close: 151.75, volume: 87000 }, // ... more data ]; // Process each bar function analyzeBar(bar) { // Calculate all indicators const values = { sma20: indicators.sma20.nextValue(bar.close), sma50: indicators.sma50.nextValue(bar.close), ema12: indicators.ema12.nextValue(bar.close), rsi: indicators.rsi.nextValue(bar.close), macd: indicators.macd.nextValue(bar.close), bb: indicators.bb.nextValue(bar.close), atr: indicators.atr.nextValue(bar.high, bar.low, bar.close), stoch: indicators.stoch.nextValue(bar.high, bar.low, bar.close) }; // Trading logic if (values.sma20 && values.sma50 && values.rsi && values.macd && values.bb && values.atr && values.stoch) { console.log(`\n${bar.timestamp} - Price: ${bar.close.toFixed(2)}`); console.log(`SMA20: ${values.sma20.toFixed(2)}, SMA50: ${values.sma50.toFixed(2)}`); console.log(`RSI: ${values.rsi.toFixed(2)}`); console.log(`MACD: ${values.macd.MACD?.toFixed(4)}, Signal: ${values.macd.signal?.toFixed(4)}`); console.log(`BB: [${values.bb.lower?.toFixed(2)}, ${values.bb.middle?.toFixed(2)}, ${values.bb.upper?.toFixed(2)}]`); console.log(`ATR: ${values.atr.toFixed(4)}`); console.log(`Stochastic: K=${values.stoch.k?.toFixed(2)}, D=${values.stoch.d?.toFixed(2)}`); // Buy Signal Logic const bullishCross = values.sma20 > values.sma50; const notOverbought = values.rsi < 70; const macdBullish = values.macd.histogram && values.macd.histogram > 0; const priceAboveBB = values.bb.pb && values.bb.pb > 0.5; const stochNotOverbought = values.stoch.k && values.stoch.k < 80; if (bullishCross && notOverbought && macdBullish && priceAboveBB && stochNotOverbought) { console.log('\n🟢 BUY SIGNAL'); console.log(` Entry: ${bar.close.toFixed(2)}`); console.log(` Stop Loss: ${(bar.close - 2 * values.atr).toFixed(2)}`); console.log(` Take Profit: ${(bar.close + 3 * values.atr).toFixed(2)}`); console.log(` Risk/Reward: 1:1.5`); } // Sell Signal Logic const bearishCross = values.sma20 < values.sma50; const notOversold = values.rsi > 30; const macdBearish = values.macd.histogram && values.macd.histogram < 0; const priceBelowBB = values.bb.pb && values.bb.pb < 0.5; const stochNotOversold = values.stoch.k && values.stoch.k > 20; if (bearishCross && notOversold && macdBearish && priceBelowBB && stochNotOversold) { console.log('\n🔴 SELL SIGNAL'); console.log(` Entry: ${bar.close.toFixed(2)}`); console.log(` Stop Loss: ${(bar.close + 2 * values.atr).toFixed(2)}`); console.log(` Take Profit: ${(bar.close - 3 * values.atr).toFixed(2)}`); console.log(` Risk/Reward: 1:1.5`); } } } // Process market data marketData.forEach(analyzeBar); ``` -------------------------------- ### Import Statement Migration - JavaScript Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/INDICATORS.md This snippet demonstrates how to migrate from the 'technicalindicators' package to the 'fast-technical-indicators' package by changing the import statement. It highlights the backward compatibility, ensuring no other code modifications are required. ```javascript import { sma, ema, rsi, macd, stochastic } from 'technicalindicators'; // After import { sma, ema, rsi, macd, stochastic } from 'fast-technical-indicators'; // Everything else stays exactly the same! ``` -------------------------------- ### JavaScript Method Call Failures in Production Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/CRITICAL_FIXES_NEEDED.md Demonstrates how incorrect method names for certain indicators will result in 'method not found' errors when using the library in production systems. ```javascript const ti = require('our-library'); ti.keltnerchannels(...); // ❌ ERROR: not a function ti.ichimokucloud(...); // ❌ ERROR: not a function ti.fibonacciretracement(...); // ❌ ERROR: not a function ``` -------------------------------- ### Basic Usage of Functional APIs (JavaScript) Source: https://context7.com/santoshkshirsagar/fast-technical-indicators/llms.txt Demonstrates the basic usage of the functional API for calculating common technical indicators like SMA, EMA, and RSI. It takes an array of prices as input and returns an array of indicator values. ```javascript import { sma, ema, rsi, macd, bollingerbands } from 'fast-technical-indicators'; // Sample price data const prices = [44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.85, 46.08, 45.89, 46.03, 46.83, 47.69, 46.49, 46.26, 47.09, 46.66, 46.80, 46.23, 46.38, 46.33, 46.55, 45.88, 47.82, 47.23]; // Simple Moving Average - functional API const smaResult = sma({ period: 10, values: prices }); console.log(smaResult); // Output: [45.157, 45.353, 45.556, 45.739, 45.888, ...] // Exponential Moving Average const emaResult = ema({ period: 10, values: prices }); console.log(emaResult); // Output: [45.234, 45.389, 45.567, 45.723, 45.891, ...] // Relative Strength Index const rsiResult = rsi({ period: 14, values: prices }); console.log(rsiResult); // Output: [52.47, 54.32, 56.18, 58.92, ...] ``` -------------------------------- ### JavaScript: Comprehensive Compatibility Verification Test Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/CRITICAL_FIXES_NEEDED.md A comprehensive test file (`compatibility-verification.js`) that compares the behavior of the 'fast-technical-indicators' library against the 'technicalindicators' npm package. It tests method aliases, class instantiation, and utility function calls. ```javascript // compatibility-verification.js const ti = require('technicalindicators'); const myLib = require('./dist/index.js'); const testData = [44, 44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.85]; // Test method aliases work console.log('Testing method aliases...'); try { const kc1 = ti.keltnerchannels({high: [46,47,48], low: [44,45,46], close: [45,46,47], period: 2}); const kc2 = myLib.keltnerchannels({high: [46,47,48], low: [44,45,46], close: [45,46,47], period: 2}); console.log('✅ keltnerchannels alias works'); } catch(e) { console.log('❌ keltnerchannels alias failed:', e.message); } // Test class instantiation try { const candleData = new myLib.CandleData(100, 105, 99, 102); console.log('✅ CandleData class works'); } catch(e) { console.log('❌ CandleData class failed:', e.message); } // Test utility functions try { const indicators = myLib.getAvailableIndicators(); console.log('✅ getAvailableIndicators works'); } catch(e) { console.log('❌ getAvailableIndicators failed:', e.message); } ``` -------------------------------- ### Simple Moving Average (SMA) - Functional and Streaming APIs (TypeScript) Source: https://context7.com/santoshkshirsagar/fast-technical-indicators/llms.txt Illustrates the implementation of the Simple Moving Average (SMA) indicator using both the functional API for batch processing and the class-based streaming API for real-time data. The functional API takes a period and an array of prices, while the streaming API allows processing prices one by one and retrieving the current result. ```typescript import { sma, SMA } from 'fast-technical-indicators'; // Functional API - batch processing const prices = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; const smaResult = sma({ period: 5, values: prices }); console.log(smaResult); // Output: [12, 13, 14, 15, 16, 17, 18] // Class-based streaming API - real-time processing const smaStream = new SMA({ period: 5, values: [] }); const streamPrices = [45.00, 45.50, 44.80, 46.20, 47.10, 47.50]; streamPrices.forEach(price => { const result = smaStream.nextValue(price); if (result !== undefined) { console.log(`SMA: ${result.toFixed(2)}`); } }); // Output after 5th value: SMA: 45.72 // Output after 6th value: SMA: 46.22 // Get current result const currentSMA = smaStream.getResult(); console.log(currentSMA); // [46.22] ``` -------------------------------- ### Migrate to fast-technical-indicators (TypeScript) Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md Demonstrates how to switch from importing indicators from the 'technicalindicators' package to the 'fast-technical-indicators' package. This change is seamless, requiring only an update to the import statement. ```typescript // Before import { sma, ema, rsi, macd } from 'technicalindicators'; // After import { sma, ema, rsi, macd } from 'fast-technical-indicators'; // Everything else stays the same! ``` -------------------------------- ### Implement CandleData and AvailableIndicators Utility Classes (TypeScript) Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/API_COMPATIBILITY_REPORT.md This snippet defines essential utility classes for handling candle data and managing available technical indicators. The CandleData class models OHLCV data, while AvailableIndicators provides a static method to retrieve a list of all supported indicators. These are crucial for data structure and indicator management within the library. ```typescript export class CandleData { constructor(public open: number, public high: number, public low: number, public close: number, public volume?: number) {} } export class AvailableIndicators { static getAll(): string[] { // Return list of all available indicators } } ``` -------------------------------- ### Basic Usage: Functional API with Technical Indicators in TypeScript Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md Demonstrates how to use the functional API of the 'fast-technical-indicators' library in TypeScript to calculate common technical indicators like SMA, EMA, RSI, MACD, and Bollinger Bands. It takes an array of prices as input and returns the calculated indicator values. ```typescript import { sma, ema, rsi, macd, bollingerbands } from 'fast-technical-indicators'; const prices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Simple Moving Average const smaResult = sma({ period: 4, values: prices }); console.log(smaResult); // [2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5] // Exponential Moving Average const emaResult = ema({ period: 4, values: prices }); // Relative Strength Index const rsiResult = rsi({ period: 14, values: prices }); // MACD const macdResult = macd({ values: prices, fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 }); // Bollinger Bands const bbResult = bollingerbands({ period: 20, values: prices, stdDev: 2 }); ``` -------------------------------- ### Bollinger Bands Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md Calculates Bollinger Bands, including upper band, lower band, middle band, %B, and width. ```APIDOC ## Bollinger Bands ### Description Calculates Bollinger Bands, providing insights into price volatility and potential overbought/oversold conditions. Includes upper band, middle band (SMA), lower band, %B, and width. ### Method - **Functional**: `bollingerbands(input: BollingerBandsInput) => BollingerBandsOutput[]` - **Class-based**: `new BollingerBands(input: BollingerBandsInput)` and `bbInstance.nextValue(price: number) => BollingerBandsOutput | undefined` ### Parameters #### Input Object (`BollingerBandsInput`) - **values** (number[]) - Required - An array of numbers for which to calculate the Bollinger Bands. - **period** (number) - Optional (default: 20) - The period for the moving average and standard deviation calculation. - **stdDev** (number) - Optional (default: 2) - The number of standard deviations to use for the upper and lower bands. #### Class-based `constructor` - **input** (BollingerBandsInput) - Required - Configuration object for Bollinger Bands calculation. #### Class-based `nextValue` - **price** (number) - Required - The next price value to add to the calculation. ### Response Example ```json // Functional [ { "upper": 105.0, "middle": 100.0, "lower": 95.0, "pb": 1.1, "width": 10.0 } ] // Class-based nextValue { "upper": 106.0, "middle": 101.0, "lower": 96.0, "pb": 1.2, "width": 10.0 } ``` ``` -------------------------------- ### Calculate On-Balance Volume (OBV) using fast-technical-indicators Source: https://context7.com/santoshkshirsagar/fast-technical-indicators/llms.txt Calculates On-Balance Volume (OBV) using price and volume data. This indicator accumulates volume on up days and subtracts it on down days. It supports both functional and streaming APIs. Dependencies include the 'fast-technical-indicators' library. ```typescript import { obv, OBV } from 'fast-technical-indicators'; // Price and volume data const priceData = { close: [45.15, 46.26, 46.50, 45.23, 44.89, 46.03, 47.28, 47.45, 47.30, 48.12], volume: [2500, 3200, 2800, 4100, 3900, 3500, 4200, 3100, 2900, 5200] }; // Functional API const obvResult = obv({ close: priceData.close, volume: priceData.volume }); obvResult.forEach((value, idx) => { console.log(`Day ${idx + 1}:`); console.log(` Price: ${priceData.close[idx + 1]?.toFixed(2)}`); console.log(` OBV: ${value.toLocaleString()}`); // Analyze divergence if (idx > 0) { const priceChange = priceData.close[idx + 1] - priceData.close[idx]; const obvChange = value - obvResult[idx - 1]; if (priceChange > 0 && obvChange < 0) { console.log(' → Bearish divergence: price up, volume down'); } else if (priceChange < 0 && obvChange > 0) { console.log(' → Bullish divergence: price down, volume up'); } } }); // Streaming API const obvStream = new OBV(); for (let i = 0; i < priceData.close.length; i++) { const result = obvStream.nextValue(priceData.close[i], priceData.volume[i]); if (result !== undefined) { console.log(`Day ${i}: OBV = ${result.toLocaleString()}`); // Confirm trend with OBV if (result > 0) { console.log(' → Accumulation phase'); } else { console.log(' → Distribution phase'); } } } ``` -------------------------------- ### Calculate Bollinger Bands - TypeScript Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md Computes Bollinger Bands, including upper, middle, and lower bands, along with %B and width. Offers functional and class-based interfaces with customizable periods and standard deviations. The functional approach returns an array of Bollinger Band outputs, and the class-based approach allows incremental calculations using `nextValue`. ```typescript interface BollingerBandsInput { period?: number; // default: 20 values: number[]; stdDev?: number; // default: 2 } interface BollingerBandsOutput { upper?: number; middle?: number; lower?: number; pb?: number; // %B width?: number; // Band width } // Functional bollingerbands(input: BollingerBandsInput) => BollingerBandsOutput[] // Class-based new BollingerBands(input: BollingerBandsInput) bbInstance.nextValue(price: number) => BollingerBandsOutput | undefined ``` -------------------------------- ### TypeScript: Implement CandleData Utility Class Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/CRITICAL_FIXES_NEEDED.md Provides the TypeScript implementation for the 'CandleData' class, including its properties (open, high, low, close, volume) and a constructor to initialize these values. This class is essential for handling candle data structures. ```typescript export class CandleData { public open: number; public high: number; public low: number; public close: number; public volume?: number; constructor(open: number, high: number, low: number, close: number, volume?: number) { this.open = open; this.high = high; this.low = low; this.close = close; this.volume = volume; } } ``` -------------------------------- ### Exponential Moving Average (EMA) - Functional and Streaming APIs (TypeScript) Source: https://context7.com/santoshkshirsagar/fast-technical-indicators/llms.txt Demonstrates the Exponential Moving Average (EMA) indicator, showing both functional API for batch calculations and a class-based streaming API for real-time updates. The functional API processes an array of prices, while the streaming API allows for incremental updates with new price data. ```typescript import { ema, EMA } from 'fast-technical-indicators'; // Functional API const prices = [22.27, 22.19, 22.08, 22.17, 22.18, 22.13, 22.23, 22.43, 22.24, 22.29, 22.15, 22.39, 22.38, 22.61, 23.36, 24.05]; const emaResult = ema({ period: 10, values: prices }); console.log(emaResult.map(v => v.toFixed(2))); // Output: ['22.22', '22.21', '22.24', '22.27', '22.33', '22.52', '22.80', '22.97'] // Streaming API for live data const emaStream = new EMA({ period: 10, values: [] }); // Process initial historical data prices.forEach(price => emaStream.nextValue(price)); // Add new tick const newPrice = 24.15; const currentEMA = emaStream.nextValue(newPrice); console.log(`Current EMA: ${currentEMA?.toFixed(2)}`); // Output: Current EMA: 23.06 ``` -------------------------------- ### Add Aliases for Incompatible Methods and Classes (TypeScript) Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/API_COMPATIBILITY_REPORT.md This TypeScript code snippet demonstrates how to add method and class aliases to achieve drop-in compatibility for incompatible indicators. It addresses specific method name mismatches like 'keltnerchannels' and 'ichimokucloud' by exporting existing functions and classes under their expected names. ```typescript // Add method aliases in index.ts export { keltnerchannel as keltnerchannels } from './volatility/keltner-channels'; export { ichimokukinkouhyou as ichimokucloud } from './trend/ichimoku'; export { fibonacci as fibonacciretracement } from './drawing-tools/fibonacci'; // Add class aliases export { KeltnerChannels as KeltnerChannels } from './volatility/keltner-channels'; export { IchimokuKinkouhyou as IchimokuCloud } from './trend/ichimoku'; ``` -------------------------------- ### Technical Indicator Structure (TypeScript) Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/MISSINGINDICATORS.md Demonstrates the typical structure for technical indicators, including a functional approach and a class-based approach for streaming data. The functional version takes input data and parameters to return output data, while the class version allows for incremental updates. ```typescript // Functional version export function indicatorName(data: InputData, params: Parameters): OutputData // Class version for streaming export class IndicatorName { constructor(params: Parameters) nextValue(value: InputValue): OutputValue | undefined getResult(): OutputData } ``` -------------------------------- ### Simple Moving Average (SMA) Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md Calculates the Simple Moving Average for a given series of values or can be used iteratively. ```APIDOC ## Simple Moving Average (SMA) ### Description Calculates the Simple Moving Average (SMA) for a series of data points. ### Method - **Functional**: `sma({ period: number, values: number[] }) => number[]` - **Class-based**: `new SMA({ period: number, values?: number[] })` and `smaInstance.nextValue(price: number) => number | undefined` ### Parameters #### Functional - **period** (number) - Required - The number of periods to include in the average. - **values** (number[]) - Required - An array of numbers for which to calculate the SMA. #### Class-based `constructor` - **period** (number) - Required - The number of periods to include in the average. - **values** (number[]) - Optional - An initial array of numbers. #### Class-based `nextValue` - **price** (number) - Required - The next price value to add to the calculation. ### Response Example ```json // Functional [ 10.5, 11.2, 12.0 ] // Class-based nextValue 12.5 ``` ``` -------------------------------- ### Calculate MACD using Functional and Streaming APIs (TypeScript) Source: https://context7.com/santoshkshirsagar/fast-technical-indicators/llms.txt Computes the Moving Average Convergence Divergence (MACD) indicator using both functional and streaming APIs. The functional API processes a batch of data, while the streaming API updates the indicator in real-time. Requires the 'fast-technical-indicators' library. ```typescript import { macd, MACD } from 'fast-technical-indicators'; // Functional API with default parameters (12, 26, 9) const prices = [22.27, 22.19, 22.08, 22.17, 22.18, 22.13, 22.23, 22.43, 22.24, 22.29, 22.15, 22.39, 22.38, 22.61, 23.36, 24.05, 23.75, 23.83, 23.95, 23.63, 23.82, 23.87, 23.65, 23.19, 23.10, 23.33, 22.68, 23.10, 22.40, 22.17, 22.17, 22.19, 22.08, 22.17, 22.18]; const macdResult = macd({ values: prices, fastPeriod: 12, slowPeriod: 26, signalPeriod: 9, SimpleMAOscillator: false, // Use EMA (default) SimpleMASignal: false // Use EMA for signal line (default) }); // Display last 3 resultsmacdResult.slice(-3).forEach((result, idx) => { console.log(`Period ${idx}:`); console.log(` MACD: ${result.MACD?.toFixed(4)}`); console.log(` Signal: ${result.signal?.toFixed(4)}`); console.log(` Histogram: ${result.histogram?.toFixed(4)}`); }); // Output example: // Period 0: // MACD: -0.0234 // Signal: -0.0567 // Histogram: 0.0333 // Streaming API for real-time trading const macdStream = new MACD({ values: [], fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 }); prices.forEach((price, index) => { const result = macdStream.nextValue(price); if (result && result.histogram !== undefined) { console.log(`Bar ${index}: Histogram = ${result.histogram.toFixed(4)}`); // Detect crossovers if (result.histogram > 0 && result.MACD && result.signal) { console.log(' → Bullish crossover'); } else if (result.histogram < 0) { console.log(' → Bearish crossover'); } } }); ``` -------------------------------- ### Relative Strength Index (RSI) Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md Calculates the Relative Strength Index (RSI) for a given series of values or can be used iteratively. ```APIDOC ## Relative Strength Index (RSI) ### Description Calculates the Relative Strength Index (RSI), a momentum oscillator measuring the speed and change of price movements. ### Method - **Functional**: `rsi({ period: number, values: number[] }) => number[]` - **Class-based**: `new RSI({ period: number, values?: number[] })` and `rsiInstance.nextValue(price: number) => number | undefined` ### Parameters #### Functional - **period** (number) - Required - The number of periods to calculate the RSI over. - **values** (number[]) - Required - An array of numbers for which to calculate the RSI. #### Class-based `constructor` - **period** (number) - Required - The number of periods to calculate the RSI over. - **values** (number[]) - Optional - An initial array of numbers. #### Class-based `nextValue` - **price** (number) - Required - The next price value to add to the calculation. ### Response Example ```json // Functional [ 65.2, 68.0, 70.5 ] // Class-based nextValue 71.0 ``` ``` -------------------------------- ### Streaming Usage: Class-Based API for Real-time Data in TypeScript Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/README.md Illustrates the class-based API for real-time data processing using 'fast-technical-indicators' in TypeScript. This approach is ideal for applications that receive data points sequentially, allowing for incremental calculation of indicators like SMA and RSI. ```typescript import { SMA, EMA, RSI, MACD } from 'fast-technical-indicators'; // Initialize indicators const smaIndicator = new SMA({ period: 20, values: [] }); const rsiIndicator = new RSI({ period: 14, values: [] }); // Process data point by point const prices = [100, 101, 99, 102, 98, 103]; prices.forEach(price => { const smaValue = smaIndicator.nextValue(price); const rsiValue = rsiIndicator.nextValue(price); if (smaValue !== undefined) { console.log(`SMA: ${smaValue}`); } if (rsiValue !== undefined) { console.log(`RSI: ${rsiValue}`); } }); ``` -------------------------------- ### TypeScript: Implement getAvailableIndicators Utility Function Source: https://github.com/santoshkshirsagar/fast-technical-indicators/blob/main/CRITICAL_FIXES_NEEDED.md Defines the 'getAvailableIndicators' function in TypeScript, which returns an array of strings representing all the technical indicators currently supported by the library. This function is crucial for introspection and dynamic usage. ```typescript export function getAvailableIndicators(): string[] { return [ 'sma', 'ema', 'wma', 'wema', 'macd', 'rsi', 'cci', 'awesomeoscillator', 'roc', 'stochastic', 'williamsr', 'trix', 'stochasticrsi', 'psar', 'kst', 'bollingerbands', 'atr', 'keltnerchannels', 'chandelierexit', 'adx', 'truerange', 'obv', 'adl', 'vwap', 'forceindex', 'mfi', 'volumeprofile', 'ichimokucloud', 'heikinashi', 'renko', 'fibonacciretracement' // Add all available indicators ]; } ```