@livefolio/sdk
Namespaces
| Namespace | Description |
|---|---|
| features | - |
| tactical | - |
Classes
| Class | Description |
|---|---|
| BacktestExecutor | Reference Executor implementation for backtesting. Fills each order at the next-open price returned by the NextOpenFn callback, with optional slippage and per-share commissions applied. |
| Crypto24x7Calendar | 24/7 calendar where every day is a single session running midnight UTC to the next midnight UTC. Suitable for crypto strategies (BTC, ETH) and any always-on market. |
| ExchangeCalendar | Abstract base class for exchange trading calendars. Implements the full Calendar interface by composing up to nine overridable hooks that subclasses provide. Concrete implementations ship for NYSEExchangeCalendar and LSEExchangeCalendar; additional exchanges can be added by extending this class. |
| FeatureRuntime | Orchestrates indicator computation for a single backtest run or a live streaming session. |
| LSEExchangeCalendar | London Stock Exchange (LSE) trading-day calendar. Faithful port of pandas_market_calendars' lse.py and holidays/uk.py. Historical coverage begins 1801-01-01, aligned with the start of the modern exchange after the Banking and Financial Dealings Act 1971 codified the current bank-holiday framework. |
| MemoryFeatureCache | In-process, Map-backed implementation of FeatureCache. Caches computed indicator series in memory for the lifetime of the instance. There is no eviction policy — the cache grows until the instance is garbage-collected. |
| NYSEExchangeCalendar | New York Stock Exchange (NYSE) trading-day calendar covering 1885-01-01 to the present. Also applicable to NYSE-equivalent venues (NASDAQ, BATS, DJIA, DOW). Faithful port of pandas_market_calendars' nyse.py. |
| RoutingDataFeed | A DataFeed that delegates each call to one of several underlying feeds based on the asset. Use this to compose vendors — e.g. Yahoo for equities and FRED for macro series — behind a single DataFeed instance accepted by runBacktest, FeatureRuntime, and BacktestExecutor. |
| RoutingDataFeedError | Error thrown by RoutingDataFeed when an asset cannot be routed or when the routed feed does not support the requested optional method. |
| RoutingStreamingDataFeed | A StreamingDataFeed that delegates subscribe() to one of several underlying feeds based on the asset. Use this to compose vendors — e.g. Polygon for equities and a polling adapter for macro series — behind a single StreamingDataFeed instance accepted by runLive. |
| RoutingStreamingDataFeedError | Error thrown by RoutingStreamingDataFeed when an asset cannot be routed. |
Interfaces
| Interface | Description |
|---|---|
| Calendar | Exchange calendar — the single source of truth for trading-day arithmetic. |
| DataFeed | Market-data source. Provides price bars, fundamentals, and corporate events. |
| Executor | Order-routing layer. Translates a set of Order objects into confirmed Fill records. |
| FeatureCache | Content-addressed cache for feature computation results. |
| Strategy | The contract that every allocation strategy must implement. |
| StreamingDataFeed | Streaming market-data source. Sibling interface to DataFeed — they are NOT a union. Historical adapters implement DataFeed.bars(); streaming adapters implement StreamingDataFeed.subscribe(). A single vendor that offers both (e.g. Polygon, Alpaca) implements both interfaces on one class. |
Type Aliases
| Type Alias | Description |
|---|---|
| AdhocTimeOverrides | Map of YYYY-MM-DD date strings to override times. Used for one-off historical specials (e.g. a single early close due to a snowstorm) that do not fit a repeating year-derived rule. Keys must be in YYYY-MM-DD format in UTC. |
| AdjustOrder | Adjusts fields of an existing position without fully closing it. Currently supports changing quantity (e.g. after a corporate action). Cash is not affected other than deducting fees. |
| AllocateNode | A leaf node in a RuleNode tree that terminates evaluation and returns a target weight allocation. weights is a map from asset IDs to fractional weights; weights should sum to 1 for a fully-invested portfolio, but the runtime does not enforce this constraint. |
| Asset | A tradeable or queryable instrument. Discriminated by kind. Add a new variant to this union when introducing a new asset class (futures, option, crypto, etc.); each variant is the natural narrowing point for vendor- specific fields. |
| AssetId | Stable string identifier for an asset. Matches the id field of Asset. Use this type when you only need to key or compare assets without carrying the full Asset object. |
| AssetRef | A reference to an asset within a TacticalSpec. Unlike the runtime Asset type, AssetRef is the spec-form representation: it lives inside serialized JSON specs and carries only the fields a spec author needs to declare. |
| BacktestExecutorOptions | Constructor options for BacktestExecutor. |
| BacktestResult | The return value of runBacktest, containing the full simulation history and the terminal portfolio state. |
| BacktestSnapshot | A point-in-time snapshot of the simulation at the end of a single trading session. |
| Bar | A single OHLCV bar for one asset at one point in time. |
| BarField | The OHLCV field of a Bar that should be used when converting a bar array into a scalar time series. Defaults to 'close' throughout the feature pipeline unless overridden via FeatureRuntimeOptions.field. |
| CloseOrder | Closes an existing position identified by positionId. If quantity is supplied, only that many shares are closed (partial close); omitting quantity closes the entire position. |
| Comparison | A binary comparison between two operands. Each operand is either a literal number or a FeatureRef resolved at evaluation time. The result is true when left op right holds. |
| ComparisonOp | Binary comparison operator used in a Comparison node. |
| ComputeFn | A pure function that computes a feature Series from an input price Series and the typed FeatureSpec describing the indicator's parameters. Implementations must be deterministic and side-effect free — the SDK uses the function as a content-addressed dispatch token via getFeatureCompute and as the registration target for defineFeature. |
| DataEvent | A single corporate event affecting an asset. |
| DateRange | Half-open calendar interval [from, to). Used throughout the SDK wherever a date range is required. from is inclusive; to is exclusive. |
| EquityAsset | An equity instrument — common stock or ETF. |
| EventKind | Categories of corporate events emitted by DataFeed.events. |
| ExchangeName | Union of supported exchange names accepted by getCalendar. |
| FeatureKey | Content-addressed cache key for a feature computation result. |
| FeatureKind | String literal union of all valid feature kind values derived from FeatureSpec. |
| FeatureRef | A reference to a computed feature value within a rule node. The ref string must match an id declared in the features array of the enclosing TacticalSpec. At evaluation time the runtime replaces the ref with the resolved numeric value. |
| FeatureRuntimeOptions | Configuration for a FeatureRuntime instance. |
| Features | Constraint on the feature map type parameter used throughout the strategy API. A Features object is a plain, readonly record that maps string keys to arbitrary computed values. Keeping it generic (rather than forcing Record<string, number>) lets callers attach structured objects, series snapshots, or price maps alongside numeric scalars. |
| FeatureScope | Identifies what an indicator was computed over — either a single asset or a whole universe. |
| FeatureSpec | A discriminated union describing every built-in feature kind and its parameters. |
| Fill | Execution confirmation returned by Executor.submit. Each fill corresponds to one order and records the exact price, quantity, and fees that were transacted. |
| Frequency | Bar granularity. Determines the width of each Bar returned by DataFeed.bars. |
| FromSpecOptions | Runtime dependencies required by fromSpec to hydrate a TacticalSpec into a runnable Strategy. |
| Fundamentals | A flat record of fundamental data points for an asset at a point in time. Values may be numeric (e.g. P/E ratio), string (e.g. sector name), or null when a data provider does not carry that field. |
| HolidayRule | A year-derived holiday rule consumed by ExchangeCalendar. The rule is active only for years in the range [validFrom, validUntil] (both inclusive; omit either bound to leave it open). |
| IfNode | A branching node in a RuleNode tree. Evaluates cond and recurses into then when the condition is true, or into else otherwise. Nesting IfNode trees builds arbitrary decision logic over computed features. |
| LiveEvent | Unified event stream from runLive. Discriminated union of two variants: |
| MacroAsset | A macroeconomic time series — e.g. a FRED series like DGS10 (10-year Treasury yield) or CPIAUCSL (CPI, all items). Models single-value series as bars whose OHLC are equal to the published value. |
| NextOpenFn | Callback that resolves the next-open price for asset as seen from date t. BacktestExecutor calls this once per order to determine the fill price. |
| OpenOrder | Opens a new position in asset. The executor creates a fresh Position entry and debits cash by quantity * fillPrice + fees. |
| Order | Discriminated union of all order types. Narrow on order.kind to access kind-specific fields. |
| PollingSchedule | - |
| PollingStreamOptions | - |
| Portfolio | A point-in-time snapshot of the full portfolio state. |
| Position | A single open position in an asset. |
| PositionId | Stable opaque string identifier for a Position. Generated by the SDK when a position is opened; callers should treat this as an opaque key and not parse its contents. |
| PriceMap | Maps each asset ID to its current market price. Required for every asset that appears in TargetWeights and for every asset currently held in the portfolio. reconcile throws if a target asset has no corresponding price entry. |
| RebalanceConfig | Controls when the strategy is permitted to issue rebalance orders. If omitted from a TacticalSpec, the default is { frequency: 'Daily' }. |
| RebalanceFrequency | Cadence at which the strategy is allowed to rebalance. |
| RebalanceOrder | Adjusts a long position in asset by delta shares. Positive delta increases the position (buy); negative delta decreases it (sell). If no position exists and delta > 0, a new position is opened. |
| ReturnMode | Controls whether returnSeries computes percentage or absolute returns. |
| RoutingDataFeedRouteFn | Function form of the routing rule. Returns the feed for asset, or undefined when no feed handles it. |
| RoutingDataFeedRouteMap | Map form of the routing rule. Keys are Asset['kind'] discriminants. |
| RoutingStreamingDataFeedRouteFn | Function form of the routing rule. Returns the feed for asset, or undefined when no feed handles it. |
| RoutingStreamingDataFeedRouteMap | Map form of the routing rule. Keys are Asset['kind'] discriminants. |
| RuleNode | A node in the tactical rule tree. Either a branching IfNode or a terminal AllocateNode. |
| RuleTreeState | Persistent state carried across rebalance steps for all named Comparison nodes that use hysteresis (tolerance set). Maps comparison.id to the last evaluated outcome: 1 = condition was true, 0 = condition was false. |
| RunBacktestOptions | All inputs required to run a historical backtest. |
| RunLiveOptions | Required inputs to runLive. |
| Series | An ordered time series of scalar values. Used as the output type of feature computations and as the storage unit in FeatureCache. |
| Session | The open and close instants for a single trading session. |
| SpecialClose | A year-derived early-close rule consumed by ExchangeCalendar. Follows the same validity bounds and resolve contract as HolidayRule, but instead of marking a day closed entirely it overrides the session close time to closeAt for the matched date. |
| SpecialOpen | A year-derived late-open rule consumed by ExchangeCalendar. Follows the same validity bounds and resolve contract as HolidayRule, but overrides the session open time to openAt for the matched date. |
| StreamingBar | A single tick or bar update from a streaming market-data source. The bar's t is the arrival timestamp of this tick — for a 24/7 source like Yahoo WS, ticks arrive continuously and the runtime is responsible for deciding which session/bar the tick belongs to via the Calendar. |
| SyntheticAsset | A simulated leveraged or expense-adjusted asset that the runtime synthesizes on-the-fly from its underlying data feed. The bar stream is computed by withSynthetics, which wraps a real DataFeed and intercepts requests for the synthetic's id. |
| TacticalFeatureKind | Union of all indicator kind strings that can appear in a TacticalFeatureSpec. Derived automatically from the spec union so it stays in sync. |
| TacticalFeatures | The feature bundle computed on each rebalance step and passed to the rule tree. Produced by the features method of the Strategy returned by fromSpec. |
| TacticalFeatureSpec | A single feature entry in a TacticalSpec. Each variant declares the indicator kind, the asset to compute it on, and the time-series lookup parameters. The id is the name used to reference the computed value in FeatureRef inside the rule tree. |
| TacticalSpec | A fully self-contained declaration of a tactical allocation strategy. Plain data — no methods, no closures. Pass to fromSpec to obtain a runnable Strategy. |
| TargetWeights | Maps each asset ID to its desired portfolio weight as a fraction of total portfolio value (e.g. 0.6 means 60 %). Weights need not sum to 1; any residual becomes cash. Passing a weight of 0 or omitting an asset entirely will generate a full exit order for any existing long position in that asset. |
| TimeOfDay | Wall-clock time of day, expressed in local exchange time. |
| Tolerance | Hysteresis band applied to a Comparison with op: 'gt' or op: 'lt'. Once the comparison has flipped, it will not flip back until the left operand exits the tolerance band around the right operand. |
Functions
| Function | Description |
|---|---|
| applyFills | Applies a batch of confirmed fills to a portfolio, returning a new Portfolio snapshot. This is the single function that advances portfolio state after order execution. |
| applyOrders | Projects a portfolio forward through a set of pending (unfilled) orders, returning a structurally updated snapshot. Used by strategy build helpers to read the expected post-step state before fills arrive. |
| barsToSeries | Converts an array of OHLCV bars into a Series by extracting a single numeric field from each bar. |
| collectBars | Drains an AsyncIterable<Bar> into a plain Bar[] array. |
| defineFeature | Registers a compute function for a new or existing feature kind. |
| drawdown | Computes the rolling drawdown relative to the period high for each bar. |
| ema | Computes an Exponential Moving Average (EMA) over a price series. |
| evaluateFeatureSpecs | Resolves each TacticalFeatureSpec in specs to a scalar value as of date t by calling into runtime and reading the series at the appropriate bar index. All specs are computed in parallel via Promise.all. |
| evaluateRuleTree | Evaluates a RuleNode tree against a resolved set of feature values and returns the target allocation weights together with the updated hysteresis state. |
| fromSpec | Hydrates a plain TacticalSpec data object into a runnable Strategy that runBacktest can drive step-by-step. |
| getCalendar | Returns a new instance of the ExchangeCalendar registered under name. Acts as a simple factory / registry for the two built-in calendar implementations. |
| getFeatureCompute | Retrieves the registered compute function for a given feature kind. |
| isRebalanceDay | Returns true when t is the last trading day of its rebalance period according to freq and calendar. The check is: periodKey(t) !== periodKey(next(t)). For 'Daily' cadence this always returns true. |
| paramsHash | Returns a deterministic string that depends only on the spec's logical content — key order and undefined optional fields are normalized away. |
| periodKey | Returns a stable string key that identifies the rebalance period containing date t for the given freq. Two dates that map to the same key belong to the same period and therefore produce the same rebalance decision. Used internally by isRebalanceDay to detect period boundaries. |
| pollingStreamFromHistorical | - |
| reconcile | Converts target portfolio weights into a minimal set of RebalanceOrder instructions that move the current portfolio toward the desired allocation. |
| returnSeries | Computes a rolling period return over a price series. |
| rsi | Computes the Relative Strength Index (RSI) using Wilder's smoothing method. |
| runBacktest | Drives a Strategy over a historical date range and returns a full audit trail of orders, fills, and portfolio states. |
| runLive | Drives a Strategy against a streaming market-data source and yields a unified event stream that consumer charts can append to historical snapshots without code branching. |
| seriesAt | Looks up the value at or immediately before timestamp t in a sorted Series. |
| sma | Computes a Simple Moving Average (SMA) over a price series. |
| volatility | Computes a rolling historical volatility as the population standard deviation of daily log-like returns over a sliding window. |
| withSynthetics | Wraps a DataFeed so that requests for any asset whose id appears in synthetics are intercepted and their bar stream is derived on-the-fly from the corresponding underlying asset. |