### Install Indicatorts Package Source: https://github.com/cinar/indicatorts/blob/main/README.md Use npm to install the indicatorts package. This is the first step before importing any indicators. ```bash npm install indicatorts ``` -------------------------------- ### Buy and Hold Strategy Example Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/README.md Implements a basic buy and hold strategy. This strategy generates actions to buy an asset and hold it, serving as a baseline for evaluating other strategies. ```typescript import {buyAndHoldStrategy} from 'indicatorts'; const actions = buyAndHoldStrategy(asset); ``` -------------------------------- ### Create Strategy Instance Source: https://github.com/cinar/indicatorts/blob/main/src/backtest/README.md Example of creating a StrategyInfo object. The strategy function takes an Asset and returns an array of Actions. Ensure the strategy logic is implemented within the function. ```TypeScript import {StrategyInfo} from 'indicatorts'; const strategyInfo: StrategyInfo = { name: 'My Strategy', strategy: (asset: Asset): Action[] => { // Strategy Function } }; ``` -------------------------------- ### Balance of Power Strategy Example Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Employs the Balance of Power (BOP) indicator. Provides a BUY action when BOP is greater than zero, SELL when less than zero, and HOLD otherwise. No configuration is required. ```TypeScript import { bopStrategy } from 'indicatorts'; const actions = bopStrategy(asset); ``` ```TypeScript const actions = balanceOfPowerStrategy(asset); ``` -------------------------------- ### MACD Strategy Example Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Uses MACD indicator values (_macd_, _signal_). Generates a BUY action when _macd_ crosses above _signal_, and a SELL action when _macd_ crosses below _signal_. Default configuration is fast=12, slow=26, signal=9. ```TypeScript import { macdStrategy } from 'indicatorts'; const defaultConfig = { fast: 12, slow: 26, signal: 9 }; const actions = macdStrategy(asset, defaultConfig); ``` ```TypeScript const actions = movingAverageConvergenceDivergenceStrategy(asset, defaultConfig); ``` -------------------------------- ### Chande Forecast Oscillator Strategy Example Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Uses Chande Forecast Oscillator (CFO) values. Generates a BUY action when 'cfo' is below zero and a SELL action when 'cfo' is above zero. No configuration is required. ```TypeScript import { cfoStrategy } from 'indicatorts'; const actions = cfoStrategy(asset); ``` ```TypeScript const actions = chandeForecastOscillatorStrategy(asset); ``` -------------------------------- ### KDJ Strategy Example Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Leverages KDJ indicator values (_k_, _d_, _j_). Provides a BUY action when _k_ crosses above _d_ and _j_ (stronger below 20%), and a SELL action when _k_ crosses below _d_ and _j_ (stronger above 80%). Default configuration is rPeriod=9, kPeriod=3, dPeriod=3. ```TypeScript import { kdjStrategy } from 'indicatorts'; const defaultConfig = { rPeriod: 9, kPeriod: 3, dPeriod: 3 }; const actions = kdjStrategy(asset, defaultConfig); ``` -------------------------------- ### Absolute Price Oscillator Strategy Example Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Uses the Absolute Price Oscillator (APO) indicator values. Provides a BUY action when AO is greater than zero, SELL when less than zero, and HOLD otherwise. Default configuration uses fast=14 and slow=30. ```TypeScript import { apoStrategy } from 'indicatorts'; const defaultConfig = { fast: 14, slow: 30 }; const actions = apoStrategy(asset, defaultConfig); ``` ```TypeScript const actions = absolutePriceOscillatorStrategy(asset, defaultConfig); ``` -------------------------------- ### Aroon Strategy Example Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Utilizes Aroon Indicator values. Generates a BUY action when 'up' is greater than 'down', SELL when 'up' is less than 'down', and HOLD otherwise. The default period is 25. ```TypeScript import { aroonStrategy } from 'indicatorts'; const defaultConfig = { period: 25 }; const actions = aroonStrategy(asset, defaultConfig); ``` -------------------------------- ### Calculate Negative Volume Index (NVI) Indicator Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/volume/README.md The `nvi` function calculates the Negative Volume Index, a cumulative indicator that uses volume changes to gauge smart money activity. Optional configuration includes start value and period. ```TypeScript import { nvi } from 'indicatorts'; const defaultConfig = { start: 1000, period: 255 }; const result = nvi(closings, volumes, defaultConfig); // Alternatively: // const result = negativeVolumeIndex(closings, volumes, defaultConfig); ``` -------------------------------- ### Build Project with npm Source: https://github.com/cinar/indicatorts/blob/main/README.md Use this command to build the project from its source code. ```bash npm run build ``` -------------------------------- ### Reverse Actions Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/README.md Inverts the order of actions in an array. For example, BUY actions become SELL actions and vice versa. ```typescript import {Action, reverseActions} from 'indicatorts'; const actions = [ Action.SELL, Action.HOLD, Action.BUY ]; const result = reverseActions(actions); // [ // Actions.BUY, // Actions.HOLD, // Actions.SELL // ]; ``` -------------------------------- ### Import and Use Awesome Oscillator Source: https://github.com/cinar/indicatorts/blob/main/README.md Import the 'ao' function from 'indicatorts' and use it with arrays of high and low prices. Ensure you have the necessary price data available. ```TypeScript import { ao } from 'indicatorts'; const highs = [10, 20, 30, 40]; const lows = [1, 2, 3, 4]; // Awesome Oscillator! const result = ao(highs, lows); ``` -------------------------------- ### Buy and Hold Strategy in TypeScript Source: https://context7.com/cinar/indicatorts/llms.txt A simple baseline strategy that buys on the first day and holds thereafter. Useful for benchmarking other strategies. ```typescript import { buyAndHoldStrategy } from 'indicatorts'; const actions = buyAndHoldStrategy(asset); // Returns Action.BUY for first element, Action.HOLD for all others // Useful as a benchmark to compare other strategies against ``` -------------------------------- ### Typical Price Strategy Implementation Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Implements a trading strategy based on the Typical Price indicator. Requires the 'indicatorts' library. The strategy generates BUY, SELL, or HOLD actions based on price changes. ```TypeScript import { typpriceStrategy } from 'indicatorts'; const actions = typpriceStrategy(asset); ``` ```TypeScript // Alternatively: // const actions = typicalPriceStrategy(asset); ``` -------------------------------- ### Bollinger Bands Strategy Initialization Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/volatility/README.md Initializes the Bollinger Bands strategy with optional configuration. This strategy provides signals based on the asset's closing price relative to the upper and lower Bollinger Bands. ```TypeScript import { bbStrategy } from 'indicatorts'; const defaultConfig = { period: 20 }; const actions = bbStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = bollingerBandsStrategy(asset, defaultConfig); ``` -------------------------------- ### Acceleration Bands Strategy Initialization Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/volatility/README.md Initializes the Acceleration Bands strategy with optional configuration. Use this to generate trading signals based on upper and lower bands. ```TypeScript import { abStrategy } from 'indicatorts'; const defaultConfig = { period: 20, multiplier: 4 }; const actions = abStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = accelerationBandsStrategy(asset, defaultConfig); ``` -------------------------------- ### Awesome Oscillator Strategy Implementation Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/momentum/README.md Use this strategy to generate BUY/SELL signals based on the Awesome Oscillator's position relative to zero. Configuration options for fast and slow periods are available. ```TypeScript import { aoStrategy } from 'indicatorts'; const defaultConfig = { fast: 5, slow: 34 }; const actions = aoStrategy(asset, defaultConfig); ``` -------------------------------- ### Define and Backtest a Custom Strategy Source: https://context7.com/cinar/indicatorts/llms.txt Create a custom trading strategy by defining its logic and then test its performance using the backtest function. Ensure all necessary imports are included. ```typescript import { StrategyInfo, Asset, Action, backtest, rsi } from 'indicatorts'; // Define a custom strategy const customStrategy: StrategyInfo = { name: 'Custom RSI Strategy', strategy: (asset: Asset): Action[] => { const rsiValues = rsi(asset.closings, { period: 14 }); return rsiValues.map(value => { if (value < 30) return Action.BUY; if (value > 70) return Action.SELL; return Action.HOLD; }); } }; // Test the custom strategy const results = backtest(asset, [customStrategy]); console.log(`Custom Strategy Gain: ${(results[0].gain * 100).toFixed(2)}%`); ``` -------------------------------- ### Create and Draw a Chart Source: https://context7.com/cinar/indicatorts/llms.txt Visualize financial data and indicators using the Chart class. Initialize the chart with a canvas element ID, add datasets, and then draw the chart. Datasets can also be removed. ```typescript import { Chart } from 'indicatorts'; // Initialize chart with canvas element ID const chart = new Chart('chartCanvas'); // Add closing prices chart.add({ legend: 'Closing Prices', values: closings, style: 'blue', width: 2 }); // Add Bollinger Bands import { bb } from 'indicatorts'; const { upper, middle, lower } = bb(closings); chart.add({ legend: 'BB Upper', values: upper, style: 'red', width: 1 }); chart.add({ legend: 'BB Middle', values: middle, style: 'orange', width: 1 }); chart.add({ legend: 'BB Lower', values: lower, style: 'green', width: 1 }); // Draw the chart chart.draw(); // Remove a dataset if needed chart.remove('BB Middle'); chart.draw(); ``` -------------------------------- ### Run Backtest Function Source: https://github.com/cinar/indicatorts/blob/main/src/backtest/README.md Executes the backtest function with a given asset and an array of strategy information. Requires importing the backtest function from 'indicatorts'. ```TypeScript import {bactest} from 'indicatorts'; const results = backtest(asset, STRATEGY_INFOS); ``` -------------------------------- ### Projection Oscillator Strategy Initialization Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/volatility/README.md Initializes the Projection Oscillator strategy with optional configuration. It generates signals by comparing the Projection Oscillator (PO) value against its smoothed value (SPO). ```TypeScript import { poStrategy } from 'indicatorts'; const defaultConfig = { period: 14, smooth: 3 }; const actions = poStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = projectionOscillatorStrategy(asset, defaultConfig); ``` -------------------------------- ### Ichimoku Cloud Strategy Implementation Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/momentum/README.md Implement the Ichimoku Cloud strategy to generate trading signals. BUY signals are generated when leadingSpanA exceeds leadingSpanB, and SELL signals when it's less. Default configuration values can be overridden. ```TypeScript import { ichimokuCloudStrategy } from 'indicatorts'; const defaultConfig = { short: 9, medium: 26, long: 52, close: 26 }; const actions = ichimokuCloudStrategy(asset, defaultConfig); ``` -------------------------------- ### Calculate Balance of Power (BOP) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Use the `bop` function to calculate the Balance of Power, which measures buying and selling pressure. Positive values indicate an upward trend, negative values a downward trend, and zero signifies balance. Requires opening, high, low, and closing prices. ```typescript import { bop } from 'indicatorts'; const result = bop(openings, highs, lows, closings); // Alternatively: // const result = balanceOfPower(openings, highs, lows, closings); ``` -------------------------------- ### Apply Actions to Closings Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/README.md Calculates the gains over time by applying a sequence of actions to a series of closing prices. Requires both closing prices and corresponding actions. ```typescript import {applyActions} from 'indicatorts'; const gains = applyActions(closings, actions); ``` -------------------------------- ### Force Index Strategy Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/volume/README.md Implements the Force Index strategy. Use when FI values are needed to generate buy/sell/hold actions. Requires the 'indicatorts' library. ```TypeScript import { fiStrategy } from 'indicatorts'; const defaultConfig = { period: 13 }; const actions = fiStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = forceIndexStrategy(asset, defaultConfig); ``` -------------------------------- ### Ease of Movement Strategy Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/volume/README.md Implements the Ease of Movement strategy. Use when EMV values are needed for buy/sell/hold signals. Requires the 'indicatorts' library. ```TypeScript import { emvStrategy } from 'indicatorts'; const defaultConfig = { period: 14 }; const actions = emvStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = easeOfMovementStrategy(asset, defaultConfig); ``` -------------------------------- ### Create and Concatenate Assets Source: https://context7.com/cinar/indicatorts/llms.txt Demonstrates creating a new Asset object with specified length and populating its OHLCV data, and concatenating two Asset objects. ```typescript import { Asset, newAssetWithLength, concatAssets } from 'indicatorts'; // Create a new asset with specified length const asset = newAssetWithLength(10); asset.dates = [new Date('2024-01-01'), new Date('2024-01-02'), /* ... */]; asset.openings = [100, 101, 102, 101, 103, 104, 103, 105, 106, 105]; asset.closings = [101, 102, 101, 103, 104, 103, 105, 106, 105, 107]; asset.highs = [102, 103, 103, 104, 105, 105, 106, 107, 107, 108]; asset.lows = [99, 100, 100, 100, 102, 102, 102, 104, 104, 104]; asset.volumes = [1000, 1200, 800, 1500, 2000, 1100, 1800, 2200, 900, 1600]; // Concatenate two assets const combinedAsset = concatAssets(asset1, asset2); ``` -------------------------------- ### Action Enum and Helper Functions in TypeScript Source: https://context7.com/cinar/indicatorts/llms.txt Demonstrates the usage of Action enum and helper functions like reverseActions and applyActions for trading signals and gain calculations. ```typescript import { Action, reverseActions, applyActions } from 'indicatorts'; // Action values const actions = [Action.BUY, Action.HOLD, Action.HOLD, Action.SELL, Action.HOLD]; // Action.BUY = 1, Action.HOLD = 0, Action.SELL = -1 // Reverse actions (useful for short strategies) const reversed = reverseActions(actions); // Returns: [Action.SELL, Action.HOLD, Action.HOLD, Action.BUY, Action.HOLD] // Calculate gains from applying actions to closing prices const closings = [100, 102, 104, 103, 105]; const gains = applyActions(closings, actions); // Returns cumulative gain/loss at each step ``` -------------------------------- ### Calculate Moving Chande Forecast Oscillator (MFCO) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Use the `mfco` function to calculate the moving version of the Chande Forecast Oscillator. This requires a period configuration and closing prices. Default configuration is used if none is provided. ```typescript import { mfco } from 'indicatorts'; const defaultConfig = { period: 4 }; const result = mfco(closings, defaultConfig); // Alternatively: // const result = movingChandeForecastOscillator(closings, defaultConfig); ``` -------------------------------- ### Vortex Strategy Implementation Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Implements a trading strategy using the Vortex Indicator. Requires the 'indicatorts' library. The strategy uses 'plusVi' and 'minusVi' values to determine actions. Configuration includes 'period'. ```TypeScript import { vortexStrategy } from 'indicatorts'; const defaultConfig = { period: 14 }; const actions = vortexStrategy(asset, defaultConfig); ``` -------------------------------- ### Calculate Awesome Oscillator (AO) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/momentum/README.md Calculates the Awesome Oscillator using 5-period and 34-period SMAs of median prices. Requires high and low prices as input. ```TypeScript import { ao } from 'indicatorts'; const defaultConfig = { fast: 5, slow: 34 }; const result = ao(highs, lows, defaultConfig); ``` -------------------------------- ### Volume Weighted Average Price Strategy Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/volume/README.md Implements the Volume Weighted Average Price strategy. Use when closing price is compared against VWAP for buy/sell/hold actions. Requires the 'indicatorts' library. ```TypeScript import { vwapStrategy } from 'indicatorts'; const defaultConfig = { period: 14 }; const actions = vwapStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = volumeWeightedAveragePriceStrategy(asset, defaultConfig); ``` -------------------------------- ### MACD Strategy Implementation in TypeScript Source: https://context7.com/cinar/indicatorts/llms.txt Generates trading signals using the MACD and signal line crossover. Requires asset data and configuration for fast, slow, and signal periods. ```typescript import { macdStrategy } from 'indicatorts'; const asset = { dates: Array(30).fill(0).map((_, i) => new Date(2024, 0, i + 1)), openings: Array(30).fill(0).map((_, i) => 100 + i * 0.5), closings: Array(30).fill(0).map((_, i) => 100 + i * 0.5 + Math.sin(i) * 2), highs: Array(30).fill(0).map((_, i) => 102 + i * 0.5), lows: Array(30).fill(0).map((_, i) => 98 + i * 0.5), volumes: Array(30).fill(10000), }; const config = { fast: 12, slow: 26, signal: 9 }; const actions = macdStrategy(asset, config); // Returns Action.BUY when MACD crosses above signal line // Returns Action.SELL when MACD crosses below signal line ``` -------------------------------- ### Stochastic Oscillator Strategy Implementation Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/momentum/README.md This strategy uses the Stochastic Oscillator (%K and %D lines) to generate trading signals. BUY signals are triggered when both lines are below 20, and SELL signals when both are above 80. Customizable K and D periods are supported. ```TypeScript import { stochStrategy } from 'indicatorts'; const defaultConfig = { kPeriod: 14, dPeriod: 3 }; const actions = stochStrategy(asset, defaultConfig); ``` -------------------------------- ### Negative Volume Index Strategy Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/volume/README.md Implements the Negative Volume Index strategy. Use when NVI is compared against its EMA for buy/sell/hold signals. Requires the 'indicatorts' library. ```TypeScript import { nviStrategy } from 'indicatorts'; const defaultConfig = { start: 1000, period: 255 }; const actions = nviStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = negativeVolumeIndexStrategy(asset, defaultConfig); ``` -------------------------------- ### Calculate On-Balance Volume (OBV) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/volume/README.md Calculates the On-Balance Volume indicator using closing prices and trading volumes. Ensure 'closings' and 'volumes' arrays are provided. ```TypeScript import {obv} from 'indicatorts'; const result = obv(closings, volumes); // Alternatively: // const result = onBalanceVolume(closings, volumes); ``` -------------------------------- ### Williams R Strategy Implementation Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/momentum/README.md Implement the Williams R strategy for trading signals. SELL signals are generated when the Williams %R value is below -20, and BUY signals when it is above -80. The period for the indicator can be configured. ```TypeScript import { willRStrategy } from 'indicatorts'; const defaultConfig = { period: 14 }; const actions = willRStrategy(asset, defaultConfig); ``` -------------------------------- ### Calculate Percentage Price Oscillator (PPO) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/momentum/README.md Calculates the Percentage Price Oscillator, its signal line, and histogram. Uses default EMA periods for fast, slow, and signal lines. ```TypeScript import { ppo } from 'indicatorts'; const defaultConfig = { fast: 12, slow: 26, signal: 9 }; const { ppoResult, signal, histogram } = ppo(prices, defaultConfig); ``` -------------------------------- ### Parabolic SAR Strategy Implementation Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Implements a trading strategy using the Parabolic SAR indicator. Requires the 'indicatorts' library. Configuration options include 'step' and 'max'. ```TypeScript import { psarStrategy } from 'indicatorts'; const defaultConfig = { step: 0.02, max: 0.2 }; const actions = psarStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = parabolicSARStrategy(asset, defaultConfig); ``` -------------------------------- ### Create New Asset with Length Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/README.md Initializes a new asset object with all its time-series fields pre-allocated to the specified length. Use this to prepare an asset structure before populating it with data. ```typescript import {newAssetWithLength} from 'indicatorts'; const asset = newAssetWithLength(2); asset.closings[0] = 10; asset.closings[1] = 20; ``` -------------------------------- ### Initialize Chart Component Source: https://github.com/cinar/indicatorts/blob/main/src/chart/README.md Initializes the Chart component on a given canvas element. Ensure the canvas element exists in your HTML. ```HTML ``` ```TypeScript import {Chart} from 'indicatorts'; const chart = new Chart('canvas'); ``` -------------------------------- ### Volume Weighted Moving Average (VWMA) Strategy Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/trend/README.md Implements a trading strategy using both SMA and VWMA indicators. Requires the 'indicatorts' library. A BUY signal is generated when VWMA is above SMA, and SELL when below. ```TypeScript import { vwmaStrategy } from 'indicatorts'; const defaultConfig = { period: 20 }; const actions = vwmaStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = volumeWeightedMovingAverageStrategy(asset, defaultConfig); ``` -------------------------------- ### Calculate Acceleration Bands (AB) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/volatility/README.md Calculates upper, middle, and lower bands for Acceleration Bands. Uses default configuration if none is provided. ```typescript import { ab } from 'indicatorts'; const defaultConfig = { period: 20, multiplier: 4 }; const { upper, middle, lower } = ab(highs, lows, closings, defaultConfig); ``` -------------------------------- ### Money Flow Index Strategy Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/volume/README.md Implements the Money Flow Index strategy. Use when MFI values are used to determine buy/sell actions based on thresholds. Requires the 'indicatorts' library. ```TypeScript import { mfiStrategy } from 'indicatorts'; const defaultConfig = { period: 14 }; const actions = mfiStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = moneyFlowIndexStrategy(asset, defaultConfig); ``` -------------------------------- ### RSI 2 Strategy Implementation Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/momentum/README.md Utilize the RSI 2 strategy for trading signals. It provides BUY signals when the 2-period RSI drops below 10 and SELL signals when it rises above 90. No configuration is required. ```TypeScript import { rsi2Strategy } from 'indicatorts'; const actions = rsi2Strategy(asset); ``` -------------------------------- ### Calculate Qstick Indicator Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Calculates the Qstick indicator, which measures the ratio of recent up and down bars. Requires opening and closing price data. ```typescript import { qstick } from 'indicatorts'; const defaultConfig = { period: 14 }; const result = qstick(openings, closings, defaultConfig); ``` -------------------------------- ### Bollinger Bands Strategy in TypeScript Source: https://context7.com/cinar/indicatorts/llms.txt Generates signals based on price position relative to Bollinger Bands. Requires asset data and a period configuration. ```typescript import { bbStrategy } from 'indicatorts'; const asset = { dates: Array(25).fill(0).map((_, i) => new Date(2024, 0, i + 1)), openings: Array(25).fill(0).map((_, i) => 100 + Math.sin(i / 3) * 5), closings: Array(25).fill(0).map((_, i) => 100 + Math.sin(i / 3) * 5), highs: Array(25).fill(0).map((_, i) => 102 + Math.sin(i / 3) * 5), lows: Array(25).fill(0).map((_, i) => 98 + Math.sin(i / 3) * 5), volumes: Array(25).fill(10000), }; const config = { period: 20 }; const actions = bbStrategy(asset, config); // Returns Action.BUY when price falls below lower band // Returns Action.SELL when price rises above upper band ``` -------------------------------- ### Strategy Statistics Interface Source: https://github.com/cinar/indicatorts/blob/main/src/backtest/README.md Defines the structure for statistical analysis of a strategy's performance. Includes strategy info, a score based on performance, and min/max/average gain metrics. ```TypeScript interface StrategyStats { strategyInfo: StrategyInfo; score: number; minGain: number; maxGain: number; averageGain: number; } ``` -------------------------------- ### Calculate Volume Weighted Moving Average (VWMA) Source: https://context7.com/cinar/indicatorts/llms.txt Calculates VWMA, which weights price by volume. Requires closing prices, volume data, and a configuration object with the period. ```typescript import { vwma } from 'indicatorts'; const closings = [100, 102, 101, 103, 104, 102, 105, 106, 104, 107]; const volumes = [1000, 1200, 800, 1500, 2000, 1100, 1800, 2200, 900, 1600]; const config = { period: 5 }; const result = vwma(closings, volumes, config); // Returns VWMA: Sum(Price * Volume) / Sum(Volume) for each period ``` -------------------------------- ### Calculate Absolute Price Oscillator (APO) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Use the `apo` function to calculate the Absolute Price Oscillator. It follows trends and indicates bullish or bearish sentiment based on whether it crosses above or below zero. Default configuration is used if none is provided. ```typescript import { apo } from 'indicatorts'; const defaultConfig = { fast: 14, slow: 30 }; const result = apo(values, defaultConfig); // Alternatively: // const result = absolutePriceOscillator(values, defaultConfig); ``` -------------------------------- ### Calculate Mass Index (MI) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Use the mi function to identify trend reversals based on range expansions. It utilizes high-low range and EMAs. Requires high and low prices. ```typescript import { mi } from 'indicatorts'; const defaultConfig = { emaPeriod: 9, miPeriod: 25 }; const result = mi(highs, lows, defaultConfig); ``` -------------------------------- ### Calculate Volume Price Trend (VPT) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/volume/README.md Calculates the Volume Price Trend indicator, correlating volume and price changes. Requires 'closings' and 'volumes' arrays. ```TypeScript import { vpt } from 'indicatorts'; const result = vpt(closings, volumes); // Alternatively: // const result = volumePriceTrend(closings, volumes); ``` -------------------------------- ### Backtesting Function in TypeScript Source: https://context7.com/cinar/indicatorts/llms.txt Evaluates multiple trading strategies against historical asset data. Requires asset data and strategy information. ```typescript import { backtest, StrategyInfo, STRATEGY_INFOS, Action, Asset } from 'indicatorts'; // Define your asset with historical data const asset: Asset = { dates: Array(100).fill(0).map((_, i) => new Date(2024, 0, i + 1)), openings: Array(100).fill(0).map((_, i) => 100 + Math.random() * 10), closings: Array(100).fill(0).map((_, i) => 100 + Math.random() * 10 + i * 0.1), highs: Array(100).fill(0).map((_, i) => 105 + Math.random() * 10 + i * 0.1), lows: Array(100).fill(0).map((_, i) => 95 + Math.random() * 10 + i * 0.1), volumes: Array(100).fill(0).map(() => Math.floor(Math.random() * 10000) + 5000), }; // Run backtest with all available strategies const results = backtest(asset, STRATEGY_INFOS); // Each result contains: results.forEach(result => { console.log(`Strategy: ${result.info.name}`); console.log(`Gain: ${(result.gain * 100).toFixed(2)}%`); console.log(`Last Action: ${result.lastAction === Action.BUY ? 'BUY' : result.lastAction === Action.SELL ? 'SELL' : 'HOLD'}`); }); ``` -------------------------------- ### Compute Strategy Statistics Source: https://github.com/cinar/indicatorts/blob/main/src/backtest/README.md Computes statistical metrics for strategies based on an array of CompanyResult objects. Requires importing the computeStrategyStats function and StrategyStats interface. ```TypeScript import {StrategyStats, computeStrategyStats} from 'indicatorts'; const stats = computeStrategyStats(companyResults); ``` -------------------------------- ### Calculate Moving Average Convergence Divergence (MACD) Source: https://context7.com/cinar/indicatorts/llms.txt Calculates MACD, a trend-following momentum indicator. Requires closing prices and a configuration object with fast, slow, and signal periods. ```typescript import { macd } from 'indicatorts'; const closings = [26.0, 26.5, 27.0, 26.8, 27.2, 27.5, 28.0, 27.8, 28.2, 28.5, 28.3, 28.8, 29.0, 28.7, 29.2, 29.5, 30.0, 29.8, 30.2, 30.5]; const config = { fast: 12, slow: 26, signal: 9 }; const { macdLine, signalLine } = macd(closings, config); // macdLine: MACD = 12-Period EMA - 26-Period EMA // signalLine: 9-Period EMA of MACD ``` -------------------------------- ### Calculate Moving Min (MMIN) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Use the mmin function to find the minimum value within a specified moving period. Useful for tracking moving minimum closing prices. Requires an array of values. ```typescript import { mmin } from 'indicatorts'; const defaultConfig = { period: 4 }; const result = mmin(values, defaultConfig); ``` -------------------------------- ### Calculate Volume Weighted Average Price (VWAP) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/volume/README.md Calculates the Volume Weighted Average Price, representing the average trading price over a period. Requires 'closings' and 'volumes' arrays, and an optional configuration object for the period. ```TypeScript import { vwap } from 'indicatorts'; const defaultConfig = { period: 14 }; const result = vwap(closings, volumes, defaultConfig); // Alternatively: // const result = volumeWeightedAveragePrice(closings, volumes, defaultConfig); ``` -------------------------------- ### Calculate Chande Forecast Oscillator (CFO) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md The `cfo` function calculates the Chande Forecast Oscillator, showing the percentage difference between the closing price and the n-period linear regression forecasted price. It indicates bullishness when above zero and bearishness when below. ```typescript import { cfo } from 'indicatorts'; const result = cfo(closings); // Alternatively: // const result = chandeForecastOscillator(closings); ``` -------------------------------- ### Calculate Awesome Oscillator (AO) Source: https://context7.com/cinar/indicatorts/llms.txt Calculates the Awesome Oscillator by comparing recent price movements to a longer time frame. Positive values indicate bullish momentum, while negative values indicate bearish momentum. ```typescript import { ao } from 'indicatorts'; const highs = [10, 20, 30, 40, 50, 45, 55, 60, 65, 70]; const lows = [5, 15, 25, 35, 45, 40, 50, 55, 60, 65]; const config = { fast: 5, slow: 34 }; const result = ao(highs, lows, config); // Positive values indicate bullish momentum // Negative values indicate bearish momentum ``` -------------------------------- ### Strategy Result Interface Source: https://github.com/cinar/indicatorts/blob/main/src/backtest/README.md Defines the structure for the result of a backtested strategy. Includes the strategy's info, its final gain, and the last action taken. ```TypeScript interface StrategyResult { info: StrategyInfo; gain: number; lastAction: Action; } ``` -------------------------------- ### Calculate Community Channel Index (CCI) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Use the cci function to calculate the momentum-based oscillator. It helps determine overbought or oversold conditions. Requires high, low, and closing prices. ```typescript import { cci } from 'indicatorts'; const defaultConfig = { period: 20 }; const result = cci(highs, lows, closings, defaultConfig); ``` -------------------------------- ### Calculate Simple Moving Average (SMA) Source: https://context7.com/cinar/indicatorts/llms.txt Calculates the arithmetic mean of prices over a specified period. Requires an array of closing prices and a configuration object with the period. ```typescript import { sma } from 'indicatorts'; const closings = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]; const config = { period: 4 }; const result = sma(closings, config); // Returns moving averages: [10, 10.5, 11, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5] ``` -------------------------------- ### Calculate Moving Average Convergence Divergence (MACD) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Use the macd function to calculate the MACD line and signal line, a trend-following momentum indicator. Requires closing prices. ```typescript import { macd } from 'indicatorts'; const defaultConfig = { fast: 12, slow: 26, signal: 9 }; const { macdLine, signalLine } = macd(closings); ``` -------------------------------- ### Calculate Moving Max (MMAX) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Use the mmax function to find the maximum value within a specified moving period. Useful for tracking moving maximum closing prices. Requires an array of values. ```typescript import { mmax } from 'indicatorts'; const defaultConfig = { period: 4 }; const result = mmax(values, defaultConfig); ``` -------------------------------- ### Define Strategy Interface Source: https://github.com/cinar/indicatorts/blob/main/src/backtest/README.md Defines the structure for a strategy, including its name and the strategy function itself. Used to register a new strategy for backtesting. ```TypeScript interface StrategyInfo { name: string; strategy: StrategyFunction; } ``` -------------------------------- ### Define Asset Interface Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/README.md Defines the structure for an asset, containing time-series data like dates, openings, closings, highs, lows, and volumes. ```typescript interface Asset { dates: Date[]; openings: number[]; closings: number[]; highs: number[]; lows: number[]; volumes: number[]; } ``` -------------------------------- ### RSI Strategy Implementation in TypeScript Source: https://context7.com/cinar/indicatorts/llms.txt Identifies overbought and oversold conditions using the 2-period RSI. Returns BUY when RSI < 10 and SELL when RSI > 90. ```typescript import { rsi2Strategy } from 'indicatorts'; const asset = { dates: Array(20).fill(0).map((_, i) => new Date(2024, 0, i + 1)), openings: Array(20).fill(100), closings: [44.34, 44.09, 43.61, 44.33, 44.83, 45.10, 45.42, 45.84, 46.08, 45.89, 46.03, 45.61, 46.28, 46.28, 46.00, 46.03, 46.41, 46.22, 46.25, 45.71], highs: Array(20).fill(47), lows: Array(20).fill(43), volumes: Array(20).fill(10000), }; const actions = rsi2Strategy(asset); // Returns Action.BUY when 2-period RSI < 10 // Returns Action.SELL when 2-period RSI > 90 ``` -------------------------------- ### Chaikin Money Flow Strategy Source: https://github.com/cinar/indicatorts/blob/main/src/strategy/volume/README.md Implements the Chaikin Money Flow strategy. Use when CMF values are needed to determine buy/sell/hold actions. Requires the 'indicatorts' library. ```TypeScript import { cmfStrategy } from 'indicatorts'; const defaultConfig = { period: 20 }; const actions = cmfStrategy(asset, defaultConfig); ``` ```TypeScript // Alternatively: // const actions = chaikinMoneyFlowStrategy(asset, defaultConfig); ``` -------------------------------- ### Define DataSet Interface Source: https://github.com/cinar/indicatorts/blob/main/src/chart/README.md Defines the structure for data sets used in the chart. Includes legend, values, and optional styling and width. ```TypeScript export interface DataSet { legend: string, values: number[], style?: string | string[], width?: number, } ``` -------------------------------- ### Calculate Chaikin Oscillator (CMO) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/momentum/README.md Measures the momentum of the Accumulation/Distribution line using EMAs. Requires high, low, closing prices, and volumes. Default fast and slow periods are 3 and 10. ```TypeScript import { cmo } from 'indicatorts'; const defaultConfig = { fast: 3, slow: 10 }; const { adResult, cmoResult } = cmo(highs, lows, closings, volumes, defaultConfig); ``` -------------------------------- ### Calculate Ichimoku Cloud Source: https://context7.com/cinar/indicatorts/llms.txt Calculates the components of the Ichimoku Cloud indicator, including Tenkan-sen, Kijun-sen, Senkou Span A, Senkou Span B, and the Cloud itself. This indicator provides support/resistance levels, trend direction, and momentum. ```typescript import { ichimokuCloud } from 'indicatorts'; const highs = Array(60).fill(0).map((_, i) => 100 + Math.sin(i / 5) * 10); const lows = Array(60).fill(0).map((_, i) => 90 + Math.sin(i / 5) * 10); const closings = Array(60).fill(0).map((_, i) => 95 + Math.sin(i / 5) * 10); const config = { short: 9, medium: 26, long: 52, close: 26 }; const { tenkan, kijub, ssa, ssb, leadingSpan } = ichimokuCloud(highs, lows, closings, config); // tenkan: Conversion Line (9-period) // kijub: Base Line (26-period) // ssa: Leading Span A (average of Conversion and Base) // ssb: Leading Span B (52-period) // leadingSpan: Cloud boundary ``` -------------------------------- ### Calculate Ease of Movement (EMV) Indicator Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/volume/README.md Use the `emv` function to calculate the Ease of Movement indicator, a volume-based oscillator. You can specify the period using the optional configuration object. ```TypeScript import { emv } from 'indicatorts'; const defaultConfig = { period: 14 }; const result = emv(highs, lows, volumes, defaultConfig); // Alternatively: // const result = easeOfMovement(highs, lows, volumes, defaultConfig); ``` -------------------------------- ### Calculate Exponential Moving Average (EMA) Source: https://context7.com/cinar/indicatorts/llms.txt Calculates EMA, which gives more weight to recent prices. Requires closing prices and a configuration object specifying the period. ```typescript import { ema } from 'indicatorts'; const closings = [22.27, 22.19, 22.08, 22.17, 22.18, 22.13, 22.23, 22.43, 22.24, 22.29]; const config = { period: 10 }; const result = ema(closings, config); // Returns EMA values with exponential weighting ``` -------------------------------- ### Compute Strategy Statistics Source: https://context7.com/cinar/indicatorts/llms.txt Aggregate results from multiple backtests to compute performance statistics for different strategies. This requires CompanyResult and StrategyResult types. ```typescript import { computeStrategyStats, CompanyResult, StrategyResult } from 'indicatorts'; // Assuming you have run backtests on multiple assets const companyResults: CompanyResult[] = [ { companyInfo: { symbol: 'AAPL', name: 'Apple Inc.', sector: 'Technology', subIndustry: 'Hardware' }, strategyResults: results1 }, { companyInfo: { symbol: 'GOOGL', name: 'Alphabet Inc.', sector: 'Technology', subIndustry: 'Internet' }, strategyResults: results2 } ]; const stats = computeStrategyStats(companyResults); stats.forEach(stat => { console.log(`Strategy: ${stat.strategyInfo.name}`); console.log(` Score (wins): ${stat.score}`); console.log(` Min Gain: ${(stat.minGain * 100).toFixed(2)}%`); console.log(` Max Gain: ${(stat.maxGain * 100).toFixed(2)}%`); console.log(` Average Gain: ${(stat.averageGain * 100).toFixed(2)}%`); }); ``` -------------------------------- ### Array Operations: Utility Functions Source: https://context7.com/cinar/indicatorts/llms.txt Utilize utility functions for rounding numbers to a specific number of digits and generating sequences of numbers. Ensure the correct functions are imported. ```typescript import { add, subtract, multiply, divide, addBy, subtractBy, multiplyBy, divideBy, abs, sqrt, pow, max, shiftRightBy, shiftLeftBy, changes, roundDigits, generateNumbers } from 'indicatorts'; const values1 = [10, 20, 30, 40, 50]; const values2 = [2, 4, 6, 8, 10]; // Utility functions const rounded = roundDigits(2, 3.14159); // 3.14 const sequence = generateNumbers(0, 10, 2); // [0, 2, 4, 6, 8] ``` -------------------------------- ### Array Operations: Mathematical and Shifting Source: https://context7.com/cinar/indicatorts/llms.txt Apply mathematical functions like absolute value, square root, power, and max, as well as shifting and change calculation functions to numeric arrays. Imports are crucial. ```typescript import { add, subtract, multiply, divide, addBy, subtractBy, multiplyBy, divideBy, abs, sqrt, pow, max, shiftRightBy, shiftLeftBy, changes, roundDigits, generateNumbers } from 'indicatorts'; const values1 = [10, 20, 30, 40, 50]; const values2 = [2, 4, 6, 8, 10]; // Mathematical functions const absolute = abs([-1, -2, 3, -4]); // [1, 2, 3, 4] const sqrtVals = sqrt([4, 9, 16, 25]); // [2, 3, 4, 5] const powered = pow([2, 3, 4], 2); // [4, 9, 16] const maxVals = max([1, 3, 2], [2, 1, 4]); // [2, 3, 4] // Shifting and changes const rightShifted = shiftRightBy(2, values1); // [0, 0, 10, 20, 30] const priceChanges = changes(1, values1); // [10, 10, 10, 10, 10] ``` -------------------------------- ### Calculate Stochastic Oscillator Source: https://context7.com/cinar/indicatorts/llms.txt Calculates the Stochastic Oscillator (%K and %D lines) by comparing closing prices to the price range over a specified period. Useful for identifying overbought and oversold levels. ```typescript import { stoch } from 'indicatorts'; const highs = [127.01, 127.62, 126.59, 127.35, 128.17, 128.43, 127.37, 126.42, 126.90, 126.85]; const lows = [125.36, 126.16, 124.93, 126.09, 126.82, 126.48, 126.03, 124.83, 126.39, 125.72]; const closings = [125.36, 126.16, 124.93, 127.29, 127.18, 128.01, 127.11, 125.04, 126.60, 125.72]; const config = { kPeriod: 14, dPeriod: 3 }; const { k, d } = stoch(highs, lows, closings, config); // k: %K line (fast stochastic) // d: %D line (3-period SMA of %K) // Values above 80: Overbought; Below 20: Oversold ``` -------------------------------- ### Company Information Interface Source: https://github.com/cinar/indicatorts/blob/main/src/backtest/README.md Defines the structure for company information, including symbol, name, sector, and sub-industry. Used to provide context for company-specific analysis. ```TypeScript interface CompanyInfo { symbol: string; name: string; sector: string; subIndustry: string; } ``` -------------------------------- ### Calculate Bollinger Bands (BB) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/volatility/README.md Calculates Bollinger Bands, including upper, middle, and lower bands, to identify overbought or oversold conditions. The default period is 20. ```typescript import { bb } from 'indicatorts'; const defaultConfig = { period: 20 }; const { upper, middle, lower } = bb(closings, defaultConfig); ``` -------------------------------- ### Calculate Random Index (KDJ) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/trend/README.md Calculates the KDJ indicator (Random Index), useful for analyzing trends and entry points. It includes K, D, and J lines. Requires high, low, and closing price data. ```typescript import { kdj } from 'indicatorts'; const defaultConfig = { rPeriod: 9, kPeriod: 3, dPeriod: 3 }; const { k, d, j } = kdj(highs, lows, closings, defaultConfig); ``` -------------------------------- ### Calculate Chandelier Exit (CE) Source: https://github.com/cinar/indicatorts/blob/main/src/indicator/volatility/README.md Calculates Chandelier Exit levels for trailing stop-losses based on Average True Range (ATR). The default period is 22. ```typescript import { ce } from 'indicatorts'; const defaultConfig = { period: 22 }; const { long, short } = ce(highs, lows, closings, defaultConfig); ```