Skip to content

@livefolio/sdk

Namespaces

NamespaceDescription
features-
tactical-

Classes

ClassDescription
BacktestExecutorReference 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.
Crypto24x7Calendar24/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.
ExchangeCalendarAbstract 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.
FeatureRuntimeOrchestrates indicator computation for a single backtest run or a live streaming session.
LSEExchangeCalendarLondon 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.
MemoryFeatureCacheIn-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.
NYSEExchangeCalendarNew 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.
RoutingDataFeedA 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.
RoutingDataFeedErrorError thrown by RoutingDataFeed when an asset cannot be routed or when the routed feed does not support the requested optional method.
RoutingStreamingDataFeedA 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.
RoutingStreamingDataFeedErrorError thrown by RoutingStreamingDataFeed when an asset cannot be routed.

Interfaces

InterfaceDescription
CalendarExchange calendar — the single source of truth for trading-day arithmetic.
DataFeedMarket-data source. Provides price bars, fundamentals, and corporate events.
ExecutorOrder-routing layer. Translates a set of Order objects into confirmed Fill records.
FeatureCacheContent-addressed cache for feature computation results.
StrategyThe contract that every allocation strategy must implement.
StreamingDataFeedStreaming 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 AliasDescription
AdhocTimeOverridesMap 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.
AdjustOrderAdjusts 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.
AllocateNodeA 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.
AssetA 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.
AssetIdStable 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.
AssetRefA 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.
BacktestExecutorOptionsConstructor options for BacktestExecutor.
BacktestResultThe return value of runBacktest, containing the full simulation history and the terminal portfolio state.
BacktestSnapshotA point-in-time snapshot of the simulation at the end of a single trading session.
BarA single OHLCV bar for one asset at one point in time.
BarFieldThe 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.
CloseOrderCloses an existing position identified by positionId. If quantity is supplied, only that many shares are closed (partial close); omitting quantity closes the entire position.
ComparisonA 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.
ComparisonOpBinary comparison operator used in a Comparison node.
ComputeFnA 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.
DataEventA single corporate event affecting an asset.
DateRangeHalf-open calendar interval [from, to). Used throughout the SDK wherever a date range is required. from is inclusive; to is exclusive.
EquityAssetAn equity instrument — common stock or ETF.
EventKindCategories of corporate events emitted by DataFeed.events.
ExchangeNameUnion of supported exchange names accepted by getCalendar.
FeatureKeyContent-addressed cache key for a feature computation result.
FeatureKindString literal union of all valid feature kind values derived from FeatureSpec.
FeatureRefA 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.
FeatureRuntimeOptionsConfiguration for a FeatureRuntime instance.
FeaturesConstraint 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.
FeatureScopeIdentifies what an indicator was computed over — either a single asset or a whole universe.
FeatureSpecA discriminated union describing every built-in feature kind and its parameters.
FillExecution confirmation returned by Executor.submit. Each fill corresponds to one order and records the exact price, quantity, and fees that were transacted.
FrequencyBar granularity. Determines the width of each Bar returned by DataFeed.bars.
FromSpecOptionsRuntime dependencies required by fromSpec to hydrate a TacticalSpec into a runnable Strategy.
FundamentalsA 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.
HolidayRuleA 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).
IfNodeA 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.
LiveEventUnified event stream from runLive. Discriminated union of two variants:
MacroAssetA 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.
NextOpenFnCallback that resolves the next-open price for asset as seen from date t. BacktestExecutor calls this once per order to determine the fill price.
OpenOrderOpens a new position in asset. The executor creates a fresh Position entry and debits cash by quantity * fillPrice + fees.
OrderDiscriminated union of all order types. Narrow on order.kind to access kind-specific fields.
PollingSchedule-
PollingStreamOptions-
PortfolioA point-in-time snapshot of the full portfolio state.
PositionA single open position in an asset.
PositionIdStable 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.
PriceMapMaps 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.
RebalanceConfigControls when the strategy is permitted to issue rebalance orders. If omitted from a TacticalSpec, the default is { frequency: 'Daily' }.
RebalanceFrequencyCadence at which the strategy is allowed to rebalance.
RebalanceOrderAdjusts 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.
ReturnModeControls whether returnSeries computes percentage or absolute returns.
RoutingDataFeedRouteFnFunction form of the routing rule. Returns the feed for asset, or undefined when no feed handles it.
RoutingDataFeedRouteMapMap form of the routing rule. Keys are Asset['kind'] discriminants.
RoutingStreamingDataFeedRouteFnFunction form of the routing rule. Returns the feed for asset, or undefined when no feed handles it.
RoutingStreamingDataFeedRouteMapMap form of the routing rule. Keys are Asset['kind'] discriminants.
RuleNodeA node in the tactical rule tree. Either a branching IfNode or a terminal AllocateNode.
RuleTreeStatePersistent 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.
RunBacktestOptionsAll inputs required to run a historical backtest.
RunLiveOptionsRequired inputs to runLive.
SeriesAn ordered time series of scalar values. Used as the output type of feature computations and as the storage unit in FeatureCache.
SessionThe open and close instants for a single trading session.
SpecialCloseA 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.
SpecialOpenA 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.
StreamingBarA 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.
SyntheticAssetA 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.
TacticalFeatureKindUnion of all indicator kind strings that can appear in a TacticalFeatureSpec. Derived automatically from the spec union so it stays in sync.
TacticalFeaturesThe feature bundle computed on each rebalance step and passed to the rule tree. Produced by the features method of the Strategy returned by fromSpec.
TacticalFeatureSpecA 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.
TacticalSpecA fully self-contained declaration of a tactical allocation strategy. Plain data — no methods, no closures. Pass to fromSpec to obtain a runnable Strategy.
TargetWeightsMaps 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.
TimeOfDayWall-clock time of day, expressed in local exchange time.
ToleranceHysteresis 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

FunctionDescription
applyFillsApplies 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.
applyOrdersProjects 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.
barsToSeriesConverts an array of OHLCV bars into a Series by extracting a single numeric field from each bar.
collectBarsDrains an AsyncIterable<Bar> into a plain Bar[] array.
defineFeatureRegisters a compute function for a new or existing feature kind.
drawdownComputes the rolling drawdown relative to the period high for each bar.
emaComputes an Exponential Moving Average (EMA) over a price series.
evaluateFeatureSpecsResolves 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.
evaluateRuleTreeEvaluates a RuleNode tree against a resolved set of feature values and returns the target allocation weights together with the updated hysteresis state.
fromSpecHydrates a plain TacticalSpec data object into a runnable Strategy that runBacktest can drive step-by-step.
getCalendarReturns a new instance of the ExchangeCalendar registered under name. Acts as a simple factory / registry for the two built-in calendar implementations.
getFeatureComputeRetrieves the registered compute function for a given feature kind.
isRebalanceDayReturns 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.
paramsHashReturns a deterministic string that depends only on the spec's logical content — key order and undefined optional fields are normalized away.
periodKeyReturns 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-
reconcileConverts target portfolio weights into a minimal set of RebalanceOrder instructions that move the current portfolio toward the desired allocation.
returnSeriesComputes a rolling period return over a price series.
rsiComputes the Relative Strength Index (RSI) using Wilder's smoothing method.
runBacktestDrives a Strategy over a historical date range and returns a full audit trail of orders, fills, and portfolio states.
runLiveDrives 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.
seriesAtLooks up the value at or immediately before timestamp t in a sorted Series.
smaComputes a Simple Moving Average (SMA) over a price series.
volatilityComputes a rolling historical volatility as the population standard deviation of daily log-like returns over a sliding window.
withSyntheticsWraps 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.

Released under the MIT License.