ta-pattern-lib
Version:
Technical Analysis and Backtesting Framework for Node.js
85 lines (84 loc) • 3.11 kB
TypeScript
import { Candle } from "../types/types_ohlc";
/**
* A function that computes a value using candle data and numeric arguments.
*/
type FunctionImplementation = (candles: Candle[], context: Record<string, number>, ...args: number[]) => number;
/**
* Metadata for each function supported in the DSL.
* - `fn`: the implementation
* - `arity`: number of arguments expected (null = variadic)
* - `description`: optional explanation
*/
interface FunctionMeta {
fn: FunctionImplementation;
arity: number | null;
description?: string;
}
/**
* A registry mapping function names to their metadata.
*/
export type FunctionRegistry = Record<string, FunctionMeta>;
/**
* DSLParser evaluates expressions like "ema(9, close(2)) > 100"
* by recursively resolving each indicator or function call.
*/
export declare class DSLParser {
private candles;
private function_registry;
private last_resolved_expression;
/**
* Creates a new DSLParser instance with candle data sliced up to the current evaluation point.
* This avoids any lookahead bias and ensures real-time safe evaluation.
*
* @param sliced_candles - Only the candles up to the current tick (e.g., candles.slice(0, index + 1))
* @param function_registry - Set of known function implementations (ema, close, etc.)
*/
constructor(sliced_candles: Candle[], function_registry: FunctionRegistry);
/**
* Evaluates a DSL expression like "ema(9, 2) > close(0)"
* against the most recent candle in the slice.
*
* Example:
* - ema(9, 2) → compute EMA(9) using candles[0..(len-1-2)]
* - close(0) → get close price of latest candle
*
* @param expression - DSL rule to evaluate
* @param context - External variables (e.g., entry_price, capital)
* @returns boolean or number result
*/
evaluate(expression: string, context?: Record<string, number>): number | boolean;
/**
* Returns the last fully resolved expression after all function calls were evaluated.
* Useful for debugging and understanding how expressions are processed.
*
* @returns The last resolved expression or null if no expression has been evaluated
*/
get_last_resolved_expression(): string | null;
/**
* Parses and resolves all function calls within a DSL expression
* into a final flattened string like "104.2 > 100", ready to be passed to eval().
*
* Supports deeply nested calls like:
* - ema(3, close(0))
* - avg(ema(5, 1), close(0), 10)
*/
private parse_and_evaluate_expression;
/**
* Splits a function argument list string into its individual arguments,
* handling nested function calls and parentheses properly.
*
* Example:
* "ema(3, close(0)), 5, myfunc(1,2)"
* → ["ema(3, close(0))", "5", "myfunc(1,2)"]
*/
private split_arguments;
}
export {};
/**
* Sample Expressions
* ema(2, 3) + ema(7, close(0)) > 100
* ema(2, 3) + ema(7, close(0)) > ema(9, close(0))
* rsi(14, 1) > 50 + current_price()
* my_function(1, 2, 3)
* avg(1, 2, 3)
*/