Model Code Editor Docs

Complete reference for the model code editor.

Every method, data structure, and helper used by the model editor and runtime. Includes signatures, props, return types, and copy-ready examples.

71
Total Entries
71
Visible Entries
Editor highlights

Lifecycle hooks, typed params, series indicators, and backtesting helpers.

initialize, onBar, onTick, onExit
SeriesReader: sma, ema, highest
OrderFactory: buy, sell, exit
runBacktest + ModelRuntime

Search the reference

Search by method name, type, prop, return type, or even code snippets.

71 entries shown
10 sections visible
71 entries total

Quickstart

A complete model file with parameters, state, and lifecycle logic.

examplelib/models/types.ts

Model file structure

Export a ModelDefinition (default export or named export) and use Params helpers.

modellifecycleparams
export const model: ModelDefinition

Properties

idstring

Stable model identifier used by registry and APIs.

timeframeTimeframe

Bar interval for the model run.

parametersParamMap

Runtime parameters built with Params helpers.

onBarModelHandler

Primary bar-by-bar lifecycle handler.

Returns

onBar returns ModelAction | ModelAction[] | void

Implementation Example

import { ModelDefinition, Params, defineParameters } from "@/lib/models";

export const model: ModelDefinition = {
  id: "sma-cross",
  name: "SMA Cross",
  version: "1.0.0",
  timeframe: "1h",
  parameters: defineParameters({
    market: Params.market({
      default: { id: "TOKEN_OR_TICKER", provider: "polymarket" },
      description: "Market to trade",
    }),
    fast: Params.integer({ default: 10, min: 2, max: 100 }),
    slow: Params.integer({ default: 30, min: 5, max: 200 }),
    size: Params.number({ default: 50, min: 1, max: 1000 }),
  }),
  defaultState: { last: "flat" as "flat" | "long" | "short" },
  async onBar(ctx) {
    const { params, orders, state, setState } = ctx;
    const series = ctx.getSeries();
    const fast = series.sma(params.fast);
    const slow = series.sma(params.slow);
    if (!fast || !slow) return;

    if (fast > slow && state.last !== "long") {
      setState({ last: "long" });
      return orders.buy(params.size, { tag: "sma-long" });
    }
    if (fast < slow && state.last !== "short") {
      setState({ last: "short" });
      return orders.sell(params.size, { tag: "sma-short" });
    }
  },
};

export default model;
examplelib/models/types.ts

Polymarket search model

Search Polymarket events, filter by volume, then trade the top event market.

polymarketsearchmodel
export const model: ModelDefinition

Properties

initializeModelHandler

Search once and cache selection in state.

onBarModelHandler

Use the selected market each bar.

Returns

initialize/onBar return ModelAction | ModelAction[] | void

Implementation Example

import { ModelDefinition, Params, defineParameters } from "@/lib/models";

export const model: ModelDefinition = {
  id: "poly-search-demo",
  name: "Polymarket Search Demo",
  version: "1.0.0",
  timeframe: "1h",
  parameters: defineParameters({
    marketSearch: Params.string({
      default: "election",
      description: "Search term used by the backtest to pick an event.",
    }),
    minVolume24h: Params.number({
      default: 1000,
      min: 0,
      description: "Minimum 24h volume filter.",
    }),
    size: Params.number({ default: 50, min: 1, max: 1000 }),
  }),
  defaultState: {
    selectedMarketId: null as string | null,
    selectedEventId: null as string | null,
  },
  async initialize(ctx) {
    const { events } = await ctx.data.searchPolymarket({
      search: ctx.params.marketSearch,
      status: "open",
      sortBy: "volume_24h",
      sortOrder: "desc",
      minVolume24h: ctx.params.minVolume24h,
      limit: 50,
    });

    const top = events[0];
    if (!top) {
      ctx.log("No Polymarket results", {
        query: ctx.params.marketSearch,
        minVolume24h: ctx.params.minVolume24h,
      });
      return;
    }

    // Switch to the top event's leading market
    await ctx.setMarket(top.leading);

    ctx.setState({
      selectedMarketId: top.leading.descriptor.id,
      selectedEventId: top.id,
    });
  },
  async onBar(ctx) {
    const price = ctx.series.close();
    const prev = ctx.series.close(1);
    if (!price || !prev) return;

    if (price > prev) {
      return ctx.orders.buy(ctx.params.size, { tag: "search-buy" });
    }
  },
};

export default model;

Pro Strategy Notes

  • searchPolymarket returns hierarchical events. Each event has a 'leading' market and a 'markets' array.
  • Use await ctx.setMarket(marketOrId) to switch the secondary market being traded. This ensures candles are loaded before onBar.
  • Legacy: when market is omitted from backtest payload, backtests use params.marketSearch to resolve a market before starting.

Core Types

The fundamental data structures shared across the editor and runtime.

typelib/models/types.ts

Timeframe

Union of supported bar intervals.

timeinterval
type Timeframe = '1m' | '5m' | '15m' | '1h' | '4h' | '1d' | '1w'

Implementation Example

const tf: Timeframe = "1h";
interfacelib/models/types.ts

Candle

OHLCV candle data in milliseconds.

marketdata
interface Candle

Properties

timestampnumber

Unix time in milliseconds.

opennumber

Open price.

highnumber

High price.

lownumber

Low price.

closenumber

Close price.

volumenumber | undefined

Optional volume.

Implementation Example

const candle: Candle = {
  timestamp: Date.now(),
  open: 0.55,
  high: 0.6,
  low: 0.52,
  close: 0.58,
  volume: 1200,
};
typelib/models/types.ts

Environment

Execution environment for a model run.

type Environment = 'backtest' | 'paper' | 'live'

Implementation Example

const env: Environment = "backtest";
interfacelib/models/types.ts

MarketDescriptor

Normalized market identity with provider and optional metadata.

interface MarketDescriptor

Properties

idstring

Primary market id (token id or ticker).

provider'polymarket' | 'kalshi' | 'generic'

Market provider.

symbolstring | undefined

Optional symbol alias.

tickerstring | undefined

Optional ticker alias.

metadataRecord<string, unknown> | undefined

Provider-specific metadata.

Implementation Example

const market: MarketDescriptor = {
  id: "123456",
  provider: "polymarket",
  ticker: "ELECTION24",
};
typelib/models/types.ts

MaybePromise

Utility type for sync or async returns.

type MaybePromise<T> = T | Promise<T>

Implementation Example

const value: MaybePromise<number> = Promise.resolve(42);
interfacelib/models/types.ts

ModelSummary

Lightweight model listing returned by registry or APIs.

interface ModelSummary

Properties

idstring

Model identifier.

namestring

Display name.

versionstring

Semantic version string.

timeframeTimeframe

Model timeframe.

descriptionstring | undefined

Short summary.

tagsstring[] | undefined

Categorization labels.

parametersArray<{ key: string; kind: ParamSpec['kind']; default: unknown; description?: string }>

Flattened parameter list.

Implementation Example

const summary: ModelSummary = {
  id: "mean-reversion-v1",
  name: "Mean Reversion",
  version: "1.0.0",
  timeframe: "1h",
  parameters: [{ key: "lookback", kind: "integer", default: 20 }],
};

Parameters API

Parameter specs, helpers, and inference utilities used in the editor.

interfacelib/models/types.ts

BaseParamSpec

Common fields for all parameter specs.

interface BaseParamSpec<TValue>

Properties

kind'number' | 'integer' | 'boolean' | 'string' | 'enum'

Spec kind.

descriptionstring | undefined

Human readable description.

labelstring | undefined

Optional display label.

defaultTValue

Default parameter value.

Implementation Example

const spec: BaseParamSpec<number> = { kind: "number", default: 1, description: "Example" };
interfacelib/models/types.ts

NumberParamSpec

Numeric parameter with optional bounds and units.

interface NumberParamSpec extends BaseParamSpec<number>

Properties

kind'number' | 'integer'

Number or integer spec.

minnumber | undefined

Minimum allowed value.

maxnumber | undefined

Maximum allowed value.

stepnumber | undefined

UI step increment.

unit'pct' | 'usd' | 'bps' | 'contracts' | string | undefined

Display unit.

Implementation Example

const spec: NumberParamSpec = { kind: "number", default: 0.02, min: 0, max: 1, unit: "pct" };
interfacelib/models/types.ts

BooleanParamSpec

Boolean on/off parameter.

interface BooleanParamSpec extends BaseParamSpec<boolean>

Implementation Example

const spec: BooleanParamSpec = { kind: "boolean", default: true, description: "Enable filter" };
interfacelib/models/types.ts

StringParamSpec

String input with optional placeholder.

interface StringParamSpec extends BaseParamSpec<string>

Properties

placeholderstring | undefined

Input hint.

Implementation Example

const spec: StringParamSpec = { kind: "string", default: "BTC", placeholder: "Ticker" };
interfacelib/models/types.ts

EnumParamSpec

Enum parameter with a fixed option set.

interface EnumParamSpec<TOption extends string> extends BaseParamSpec<TOption>

Properties

optionsreadonly TOption[]

Allowed values.

Implementation Example

const spec: EnumParamSpec<"buy" | "sell"> = {
  kind: "enum",
  default: "buy",
  options: ["buy", "sell"] as const,
};
interfacelib/models/types.ts

MarketParamSpec

Market selector parameter.

interface MarketParamSpec extends BaseParamSpec<MarketDescriptor>

Implementation Example

const spec: MarketParamSpec = {
  kind: "market",
  default: { id: "123", provider: "polymarket" },
};
typelib/models/types.ts

ParamSpec

Union of all parameter spec types.

type ParamSpec = NumberParamSpec | BooleanParamSpec | StringParamSpec | EnumParamSpec<string> | MarketParamSpec

Implementation Example

const spec: ParamSpec = { kind: "integer", default: 14, min: 1, max: 100 };
typelib/models/types.ts

ParamMap

Keyed map of parameter specs.

type ParamMap = Record<string, ParamSpec>

Implementation Example

const params: ParamMap = {
  lookback: { kind: "integer", default: 20 },
  enabled: { kind: "boolean", default: true },
};
typelib/models/types.ts

ResolvedParams

Compile-time mapping from ParamMap to value types.

type ResolvedParams<T extends ParamMap | undefined> = ...

Implementation Example

type MyParams = ResolvedParams<{ size: NumberParamSpec; enabled: BooleanParamSpec }>;
typelib/models/types.ts

InferParamType

Resolve a ParamSpec to its value type.

type InferParamType<T extends ParamSpec> = ...

Implementation Example

type SizeValue = InferParamType<NumberParamSpec>; // number
functionlib/models/params.ts

numberParam

Create a NumberParamSpec with kind = 'number'.

numberParam(options: Omit<NumberParamSpec, 'kind'>): NumberParamSpec

Properties

optionsOmit<NumberParamSpec, 'kind'>

Number spec options.

Returns

NumberParamSpec

Implementation Example

const spec = numberParam({ default: 0.5, min: 0, max: 1, unit: "pct" });
functionlib/models/params.ts

integerParam

Create a NumberParamSpec with kind = 'integer'.

integerParam(options: Omit<NumberParamSpec, 'kind'>): NumberParamSpec

Properties

optionsOmit<NumberParamSpec, 'kind'>

Integer spec options.

Returns

NumberParamSpec

Implementation Example

const spec = integerParam({ default: 20, min: 5, max: 200 });
functionlib/models/params.ts

booleanParam

Create a BooleanParamSpec.

booleanParam(options: Omit<BooleanParamSpec, 'kind'>): BooleanParamSpec

Properties

optionsOmit<BooleanParamSpec, 'kind'>

Boolean spec options.

Returns

BooleanParamSpec

Implementation Example

const spec = booleanParam({ default: true, description: "Enable filter" });
functionlib/models/params.ts

stringParam

Create a StringParamSpec.

stringParam(options: Omit<StringParamSpec, 'kind'>): StringParamSpec

Properties

optionsOmit<StringParamSpec, 'kind'>

String spec options.

Returns

StringParamSpec

Implementation Example

const spec = stringParam({ default: "BTC", placeholder: "Ticker" });
functionlib/models/params.ts

enumParam

Create an EnumParamSpec.

enumParam<T extends string>(options: Omit<EnumParamSpec<T>, 'kind'> & { options: readonly T[] }): EnumParamSpec<T>

Properties

optionsOmit<EnumParamSpec<T>, 'kind'> & { options: readonly T[] }

Enum spec options.

Returns

EnumParamSpec<T>

Implementation Example

const spec = enumParam({ default: "buy", options: ["buy", "sell"] as const });
functionlib/models/params.ts

marketParam

Create a MarketParamSpec.

marketParam(options: Omit<MarketParamSpec, 'kind'>): MarketParamSpec

Properties

optionsOmit<MarketParamSpec, 'kind'>

Market spec options.

Returns

MarketParamSpec

Implementation Example

const spec = marketParam({ default: { id: "TOKEN_OR_TICKER", provider: "polymarket" } });
constlib/models/params.ts

Params helpers

Factory helpers for building parameter specs.

paramshelpers
Params.number(options: Omit<NumberParamSpec, 'kind'>): NumberParamSpec
Params.integer(options: Omit<NumberParamSpec, 'kind'>): NumberParamSpec
Params.boolean(options: Omit<BooleanParamSpec, 'kind'>): BooleanParamSpec
Params.string(options: Omit<StringParamSpec, 'kind'>): StringParamSpec
Params.enum<T extends string>(options: Omit<EnumParamSpec<T>, 'kind'> & { options: readonly T[] }): EnumParamSpec<T>
Params.market(options: Omit<MarketParamSpec, 'kind'>): MarketParamSpec

Returns

Returns a ParamSpec with the correct kind field set.

Implementation Example

const parameters = {
  lookback: Params.integer({ default: 20, min: 5, max: 200 }),
  size: Params.number({ default: 100, min: 1, max: 10000, unit: "contracts" }),
};
functionlib/models/params.ts

defineParameter

Identity helper for a single parameter spec.

defineParameter<T extends ParamSpec>(spec: T): T

Properties

specT

Parameter spec definition.

Returns

Same spec instance (typed).

Implementation Example

const lookback = defineParameter(Params.integer({ default: 20, min: 5, max: 200 }));
functionlib/models/params.ts

defineParameters

Identity helper for a full parameter map.

defineParameters<T extends ParamMap>(params: T): T

Properties

paramsT

Parameter map.

Returns

Same map instance (typed).

Implementation Example

const params = defineParameters({
  size: Params.number({ default: 100, min: 1, max: 10000 }),
});

Lifecycle and Context

How models run and what the editor gives you at runtime.

interfacelib/models/types.ts

ModelDefinition

Primary model contract consumed by the editor and runtime.

modeldefinition
interface ModelDefinition<P extends ParamMap | undefined, S extends Record<string, unknown>>

Properties

idstring

Unique model id.

namestring

Display name.

versionstring

Model version.

timeframeTimeframe

Primary bar interval.

parametersP | undefined

Parameter map.

defaultStateS | undefined

Initial state object.

marketPartial<MarketDescriptor> | undefined

Default market hints.

requirementsArray<'candles' | 'priceHistory' | 'orderbook' | 'positions'> | undefined

Data requirements hint.

initializeModelHandler | undefined

Runs once at start.

onBarModelHandler | undefined

Runs per bar (primary).

onTickModelHandler | undefined

Optional intra-bar tick handler.

onExitModelHandler | undefined

Runs at end of run.

Implementation Example

const def: ModelDefinition = {
  id: "example",
  name: "Example",
  version: "1.0.0",
  timeframe: "1h",
  onBar: async (ctx) => ctx.log("tick"),
};
typelib/models/types.ts

ModelHandler

Function signature for lifecycle hooks.

type ModelHandler<P, S> = (ctx: ModelContext<P, S>) => MaybePromise<ModelAction<S> | ModelAction<S>[] | void>

Returns

A single action, array of actions, or void.

Implementation Example

const handler: ModelHandler<any, any> = (ctx) => ctx.orders.exit();
interfacelib/models/types.ts

ModelContext

Runtime context injected into lifecycle hooks.

interface ModelContext<P, S>

Properties

nowDate

Timestamp for current bar.

envEnvironment

Execution environment.

indexnumber

Current bar index.

marketMarketDescriptor

Resolved market descriptor.

timeframeTimeframe

Current timeframe.

paramsP

Resolved parameters.

stateS

Mutable model state.

setState(patch: Partial<S> | ((current: S) => S)) => void

Update state.

seriesSeriesReader

Default series reader.

getSeries(key?: string) => SeriesReader

Multi-series accessor.

dataDataContext

Async data access helpers.

portfolioPortfolioState

Current portfolio snapshot.

ordersOrderFactory

Order action builders.

log(message: string, meta?: Record<string, unknown>) => void

Structured logging.

setMarket(marketOrId: MarketDescriptor | string | PolymarketSearchEvent['leading']) => Promise<void>

Dynamically set the primary market and load its candles.

Implementation Example

async function initialize(ctx: ModelContext<any, any>) {
  const { events } = await ctx.data.searchPolymarket({ search: "polymarket" });
  if (events[0]) await ctx.setMarket(events[0].leading);
}
interfacelib/models/types.ts

DataContext

Async data fetchers available inside hooks.

interface DataContext

Properties

candles(opts: { market: MarketDescriptor; timeframe: Timeframe; lookback?: number; start?: number; end?: number; }) => Promise<Candle[]>

Fetch candle history.

priceHistory(opts: { market: MarketDescriptor; interval: '1h' | '6h' | '1d' | '1w' | 'max'; start?: number; end?: number; }) => Promise<Array<{ timestamp: number; price: number }>>

Fetch price history series.

searchPolymarket(opts: PolymarketSearchParams) => Promise<PolymarketSearchResult>

Search Polymarket events and derive top markets from each event (set apiBaseUrl for server runs).

Implementation Example

const history = await ctx.data.priceHistory({
  market: ctx.market,
  interval: "1d",
});

const { markets, events } = await ctx.data.searchPolymarket({
  search: "election",
  limit: 5,
  sortBy: "volume_24h",
});
const topMarket = markets[0]?.market;
const topEvent = events[0];
typelib/models/types.ts

PolymarketMarketSortField

Sort keys accepted by Polymarket market search.

type PolymarketMarketSortField = 'volume_24h' | 'open_interest' | 'last_price' | 'close_time' | 'liquidity'

Implementation Example

const field: PolymarketMarketSortField = "volume_24h";
typelib/models/types.ts

PolymarketEventSortField

Sort keys accepted by Polymarket event search.

type PolymarketEventSortField = 'volume_24h' | 'open_interest' | 'volume' | 'close_time' | 'market_count' | 'liquidity' | 'last_price'

Implementation Example

const field: PolymarketEventSortField = "volume_24h";
interfacelib/models/types.ts

PolymarketSearchParams

Search options for ctx.data.searchPolymarket.

interface PolymarketSearchParams

Properties

searchstring | undefined

Search query (title, slug, ticker).

status'open' | 'closed' | undefined

Market/event status filter.

limitnumber | undefined

Event search limit.

sortByPolymarketEventSortField | undefined

Event sort field.

sortOrder'asc' | 'desc' | undefined

Event sort order.

minVolumenumber | undefined

Filter events by total volume.

minVolume24hnumber | undefined

Filter events by 24h volume.

minOpenInterestnumber | undefined

Filter events by open interest.

minLiquiditynumber | undefined

Filter events by liquidity.

minLastPricenumber | undefined

Filter by leading market last price (min).

maxLastPricenumber | undefined

Filter by leading market last price (max).

minCloseDaysnumber | undefined

Minimum days until close.

maxCloseDaysnumber | undefined

Maximum days until close.

categorystring | undefined

Event category filter.

featuredboolean | undefined

Limit to featured events.

cyomboolean | undefined

Limit to create-your-own-market events.

tagIdsstring[] | undefined

Limit to matching tag ids.

Implementation Example

const opts: PolymarketSearchParams = { search: "election", limit: 10 };
interfacelib/models/types.ts

PolymarketSearchEvent

Hierarchical event result with leading market and sub-markets.

interface PolymarketSearchEvent

Properties

idstring

Event identifier.

titlestring

Event title.

leading{ descriptor, title, ticker, lastPrice }

Primary tradeable market.

marketsArray<{ descriptor, title, ticker, ... }>

Constituent markets.

marketCountnumber

Total markets in event.

interfacelib/models/types.ts

PolymarketSearchResult

Hierarchical search results with legacy market list compatibility.

interface PolymarketSearchResult

Properties

eventsPolymarketSearchEvent[]

Polymarket event results.

marketsArray<{ event, market, ... }>

Legacy flat list of top markets.

Implementation Example

const { events } = await ctx.data.searchPolymarket({ search: "election" });
const firstEvent = events[0];
const mainMarket = firstEvent.leading.descriptor;
interfacelib/models/types.ts

OrderFactory

Convenience builders for order actions.

interface OrderFactory

Properties

buy(size: number, options?: Omit<OrderAction, 'type' | 'side' | 'size'>) => OrderAction

Create buy action.

sell(size: number, options?: Omit<OrderAction, 'type' | 'side' | 'size'>) => OrderAction

Create sell action.

exit() => OrderAction

Exit current position.

Implementation Example

const action = ctx.orders.buy(50, { tag: "entry", kind: "market" });
interfacelib/models/types.ts

SeriesProvider

Minimal interface for supplying series readers.

interface SeriesProvider

Properties

getSeries(key?: string) => SeriesReader

Lookup by key.

Implementation Example

const reader = provider.getSeries("alt");

Series API

Read candle values and compute indicators in the editor.

interfacelib/models/types.ts

SeriesReader

Standard indicator access on the current bar.

interface SeriesReader

Properties

lengthnumber

Number of bars available up to current index.

candle(offset?: number) => Candle | undefined

Get candle by offset.

close(offset?: number) => number | undefined

Close price.

open(offset?: number) => number | undefined

Open price.

high(offset?: number) => number | undefined

High price.

low(offset?: number) => number | undefined

Low price.

volume(offset?: number) => number | undefined

Volume.

sma(period: number) => number | undefined

Simple moving average.

ema(period: number) => number | undefined

Exponential moving average.

highest(period: number) => number | undefined

Highest high over period.

lowest(period: number) => number | undefined

Lowest low over period.

Implementation Example

const series = ctx.getSeries();
const price = series.close();
const prev = series.close(1);
const high20 = series.highest(20);
classlib/models/series.ts

Series

Concrete SeriesReader over a candle array and moving cursor.

class Series implements SeriesReader

Properties

constructor(candles: Candle[], cursorRef: () => number)

Pass candles and cursor getter.

lengthnumber

Getter for current length.

candle(offset?: number) => Candle | undefined

Get candle by offset.

close/open/high/low/volume(offset?: number) => number | undefined

Price accessors.

sma/ema/highest/lowest(period: number) => number | undefined

Indicator helpers.

Implementation Example

const series = new Series(candles, () => cursor);
const price = series.close();

Actions and Portfolio

Orders, alerts, state actions, and portfolio tracking structures.

interfacelib/models/types.ts

OrderAction

Order intent produced by a model.

interface OrderAction

Properties

type'order'

Discriminator.

side'buy' | 'sell'

Order side.

sizenumber

Contracts to trade.

pricenumber | undefined

Optional limit price.

kind'market' | 'limit' | undefined

Order kind.

tagstring | undefined

Optional label.

allowPartialboolean | undefined

Partial fill flag.

notestring | undefined

Extra notes.

Implementation Example

const action: OrderAction = {
  type: "order",
  side: "buy",
  size: 100,
  price: 0.58,
  kind: "limit",
  tag: "entry",
};
interfacelib/models/types.ts

AlertAction

Structured alert emitted by a model.

interface AlertAction

Properties

type'alert'

Discriminator.

level'info' | 'warning' | 'error'

Alert level.

messagestring

Alert message.

metaRecord<string, unknown> | undefined

Structured metadata.

Implementation Example

const action: AlertAction = {
  type: "alert",
  level: "warning",
  message: "Low liquidity",
  meta: { spread: 0.12 },
};
interfacelib/models/types.ts

StateAction

State update action (rare, usually handled by setState).

interface StateAction<State>

Properties

type'state'

Discriminator.

patchPartial<State>

State patch.

Implementation Example

const action: StateAction<{ last: string }> = {
  type: "state",
  patch: { last: "long" },
};
typelib/models/types.ts

ModelAction

Union of OrderAction, AlertAction, and StateAction.

type ModelAction<State> = OrderAction | AlertAction | StateAction<State>

Implementation Example

const action: ModelAction = ctx.orders.exit();
interfacelib/models/types.ts

PositionState

Current position snapshot used by portfolio.

interface PositionState

Properties

sizenumber

Positive long, negative short.

avgPricenumber

Average entry price.

lastPricenumber | undefined

Last price seen.

unrealizedPnlnumber

Unrealized profit/loss.

realizedPnlnumber

Realized profit/loss.

Implementation Example

const position: PositionState = {
  size: 100,
  avgPrice: 0.45,
  unrealizedPnl: 12.5,
  realizedPnl: -2.0,
};
interfacelib/models/types.ts

PortfolioState

Portfolio balances and fills tracked during runtime.

interface PortfolioState

Properties

cashnumber

Cash balance.

equitynumber

Cash plus position value.

positionsPositionState

Current position.

feesPaidnumber

Total fees paid.

fillsFill[]

All order fills.

Implementation Example

const portfolio: PortfolioState = {
  cash: 9800,
  equity: 10120,
  positions: { size: 100, avgPrice: 0.5, unrealizedPnl: 20, realizedPnl: 0 },
  feesPaid: 2.1,
  fills: [],
};
interfacelib/models/types.ts

Fill

Single executed trade fill.

interface Fill

Properties

timestampnumber

Execution time (ms).

pricenumber

Execution price.

sizenumber

Signed size (positive buy).

side'buy' | 'sell'

Side.

feenumber | undefined

Fee paid.

tagstring | undefined

Label tag.

Implementation Example

const fill: Fill = {
  timestamp: Date.now(),
  price: 0.62,
  size: 100,
  side: "buy",
  fee: 0.062,
};
interfacelib/models/types.ts

TradeRecord

Fill enriched with pnl and equity for reporting.

interface TradeRecord extends Fill

Properties

pnlnumber | undefined

Profit/loss for the fill.

equitynumber | undefined

Equity after the fill.

Implementation Example

const trade: TradeRecord = {
  timestamp: Date.now(),
  price: 0.62,
  size: 100,
  side: "buy",
  pnl: 5.4,
  equity: 10025,
};

Runtime and Backtesting

Execute models, run backtests, and inspect outputs.

interfacelib/models/runtime.ts

RuntimeOptions

Configuration for ModelRuntime.

interface RuntimeOptions

Properties

envEnvironment | undefined

Execution environment.

initialCashnumber | undefined

Starting cash balance.

logger(msg: string, meta?: Record<string, unknown>) => void

Logger hook.

apiBaseUrlstring | undefined

Base URL for internal API lookups (searchPolymarket).

Implementation Example

const options: RuntimeOptions = { env: "backtest", initialCash: 5000 };
classlib/models/runtime.ts

ModelRuntime

Core runtime that executes a ModelDefinition over candles.

class ModelRuntime<P, S>

Properties

constructor(definition: ModelDefinition, candles: Candle[], params: P, options?: RuntimeOptions)

Create runtime.

run() => Promise<BacktestResult>

Execute the model run.

Returns

run returns BacktestResult

Implementation Example

const runtime = new ModelRuntime(model, candles, params, { initialCash: 10000 });
const result = await runtime.run();
interfacelib/models/backtester.ts

BacktestOptions

Options for runBacktest and backtestFromPayload.

interface BacktestOptions

Properties

initialCashnumber | undefined

Starting cash.

logger(msg: string, meta?: Record<string, unknown>) => void

Logger hook.

apiBaseUrlstring | undefined

Base URL for internal API lookups (searchPolymarket).

Implementation Example

const options: BacktestOptions = { initialCash: 25000 };
functionlib/models/backtester.ts

runBacktest

Run a backtest for a model and candle series.

runBacktest(model: ModelDefinition, candles: Candle[], params?: Record<string, unknown>, options?: BacktestOptions): Promise<BacktestResult>

Properties

modelModelDefinition

Model to execute.

candlesCandle[]

Input candles.

paramsRecord<string, unknown> | undefined

Parameter values (include market if needed).

optionsBacktestOptions | undefined

Runtime options.

Returns

Promise<BacktestResult>

Implementation Example

const result = await runBacktest(model, candles, { market: { id: "123", provider: "polymarket" } });
functionlib/models/backtester.ts

backtestFromPayload

Backtest convenience when you already have a payload object.

backtestFromPayload(payload: BacktestRequestPayload, model: ModelDefinition, candles: Candle[], options?: BacktestOptions): Promise<BacktestResult>

Properties

payloadBacktestRequestPayload

Request payload.

modelModelDefinition

Resolved model definition.

candlesCandle[]

Input candles.

optionsBacktestOptions | undefined

Runtime options.

Returns

Promise<BacktestResult>

Implementation Example

const result = await backtestFromPayload({ modelId: "x", params: { size: 100 } }, model, candles);
interfacelib/models/types.ts

BacktestRequestPayload

Payload used by API and backtest helpers.

interface BacktestRequestPayload

Properties

modelIdstring

Model id to run.

paramsRecord<string, unknown> | undefined

Parameter values.

marketMarketDescriptor | undefined

Override market.

timeframeTimeframe | undefined

Override timeframe.

startnumber | undefined

Start timestamp (Unix ms).

endnumber | undefined

End timestamp (Unix ms).

candlesCandle[] | undefined

Optional candle override.

Implementation Example

const payload: BacktestRequestPayload = {
  modelId: "mean-reversion-v1",
  params: { lookback: 30 },
  timeframe: "1h",
  start: Date.parse("2024-01-01T00:00:00Z"),
  end: Date.parse("2024-02-01T00:00:00Z"),
};
interfacelib/models/types.ts

BacktestResult

Backtest output summary and trade list.

interface BacktestResult

Properties

modelIdstring

Model id.

timeframeTimeframe

Run timeframe.

stats{ netProfit: number; returnPct: number; maxDrawdown: number; winRate: number; trades: number }

Summary stats.

equityCurveArray<{ t: number; equity: number }>

Equity over time.

tradesTradeRecord[]

Trade history.

paramsRecord<string, unknown>

Params used in run.

Implementation Example

const result: BacktestResult = {
  modelId: "x",
  timeframe: "1h",
  stats: { netProfit: 120, returnPct: 0.012, maxDrawdown: 0.04, winRate: 0.5, trades: 10 },
  equityCurve: [],
  trades: [],
  params: {},
};

Registry and Loading

Register models and parse code for editor insights.

functionlib/models/registry.ts

registerModel

Register a model definition in the runtime registry.

registerModel(def: ModelDefinition): void

Properties

defModelDefinition

Model definition to register.

Returns

void (throws if id already exists)

Implementation Example

registerModel(model);
functionlib/models/registry.ts

listModels

List all registered models as summaries.

listModels(): ModelSummary[]

Returns

ModelSummary[]

Implementation Example

const models = listModels();
functionlib/models/registry.ts

getModel

Fetch a model by id from the registry.

getModel(id: string): ModelDefinition | undefined

Properties

idstring

Model identifier.

Returns

ModelDefinition | undefined

Implementation Example

const model = getModel("mean-reversion-v1");
functionlib/models/loader.ts

loadModelFromCode

Transpile and evaluate TypeScript model code.

loadModelFromCode(code: string): { model: ModelDefinition } | { error: string }

Properties

codestring

TypeScript code for a model file.

Returns

Union with model or error string

Implementation Example

const result = loadModelFromCode(code);
if ("error" in result) {
  console.error(result.error);
} else {
  registerModel(result.model);
}
functionlib/models/parse.ts

parseModelParameters

Extract parameter metadata from a model code string.

parseModelParameters(code: string): ParsedParam[]

Properties

codestring

Model source code.

Returns

ParsedParam[]

Implementation Example

const params = parseModelParameters(code);
// => [{ key: "lookback", kind: "integer", default: 20 }]
interfacelib/models/parse.ts

ParsedParam

Parameter metadata extracted by parseModelParameters.

interface ParsedParam

Properties

keystring

Parameter name.

kindParamSpec['kind']

Param kind.

defaultunknown

Default value.

descriptionstring | undefined

Param description.

Implementation Example

const parsed: ParsedParam = { key: "size", kind: "number", default: 100, description: "Contracts" };

Candle Sources and Utilities

Market data fetchers and timeframe utilities.

interfacelib/models/sources.ts

CandleSource

Standard candle fetcher interface.

interface CandleSource

Properties

fetchCandles(opts: { market: MarketDescriptor; timeframe: Timeframe; start?: number; end?: number; limit?: number }) => Promise<Candle[]>

Fetch candles for a market and timeframe.

Implementation Example

const candles = await source.fetchCandles({
  market: { id: "123", provider: "polymarket" },
  timeframe: "1h",
});
classlib/models/sources.ts

KalshiCandleSource

Candle source backed by Kalshi API.

class KalshiCandleSource implements CandleSource

Properties

constructor(client: KalshiClient)

Initialize with Kalshi client.

fetchCandles(opts) => Promise<Candle[]>

Fetch candlesticks.

Implementation Example

const source = new KalshiCandleSource(kalshiClient);
const candles = await source.fetchCandles({ market, timeframe: "1h" });
classlib/models/sources.ts

PolymarketCandleSource

Candle source backed by Polymarket prices history.

class PolymarketCandleSource implements CandleSource

Properties

constructor(client: PolymarketPublicClient)

Initialize with Polymarket client.

fetchCandles(opts) => Promise<Candle[]>

Fetch price history.

Implementation Example

const source = new PolymarketCandleSource(polyClient);
const candles = await source.fetchCandles({ market, timeframe: "1h" });
classlib/models/sources.ts

MemoryCandleSource

In-memory candle source for tests or demos.

class MemoryCandleSource implements CandleSource

Properties

constructor(data: Record<string, Candle[]>)

Pass a map of market id to candles.

fetchCandles(opts) => Promise<Candle[]>

Return stored candles.

Implementation Example

const source = new MemoryCandleSource({
  BTC: candles,
});
const out = await source.fetchCandles({ market: { id: "BTC", provider: "generic" }, timeframe: "1h" });
functionlib/models/sources.ts

timeframeToMs

Convert a Timeframe to milliseconds.

timeframeToMs(tf: Timeframe): number

Properties

tfTimeframe

Timeframe value.

Returns

number

Implementation Example

const ms = timeframeToMs("1h");

Templates and Built-ins

Editor defaults and built-in sample strategies.

constlib/models/templates.ts

BASE_METHODS

Quick insert snippets used by the editor UI.

const BASE_METHODS: Array<{ name: string; description: string }>

Implementation Example

const [first] = BASE_METHODS;
// => { name: "getSeries()", description: "Get the default series reader..." }

Pro Strategy Notes

  • Includes getSeries, series.close, series.sma, series.ema, series.highest, series.lowest, orders.buy, orders.sell, orders.exit, setState, log, data.searchPolymarket.
functionlib/models/templates.ts

defaultTemplate

Generate a starter model file string.

defaultTemplate(name: string, timeframe?: Timeframe): string

Properties

namestring

Model name used in template.

timeframeTimeframe | undefined

Defaults to '1h'.

Returns

string (TypeScript model file)

Implementation Example

const code = defaultTemplate("My Model", "4h");
constlib/models/builtins.ts

meanReversionModel

Built-in mean reversion example strategy.

const meanReversionModel: ModelDefinition

Implementation Example

registerModel(meanReversionModel);
constlib/models/builtins.ts

breakoutModel

Built-in breakout example strategy.

const breakoutModel: ModelDefinition

Implementation Example

registerModel(breakoutModel);
functionlib/models/builtins.ts

registerBuiltinModels

Registers built-in models into the registry.

registerBuiltinModels(): void

Returns

void

Implementation Example

registerBuiltinModels();