Overview
A study script reads the events a definition recorded over history and turns them into results you can read: counts, hit rates, forward returns, tables. This section is the code reference for writing one.
A study never marks events itself. It runs over events that already exist, so run the definition over history first. The script has three handlers. scope runs first for each event, in time order, and decides its group from what was known when it fired. onEvent then measures what happened next, and onFinish runs once at the end to aggregate and publish.
Minimal study
meta({ name: "Break count", kind: "study" });
flows.declare({ slug: "or-break", as: "orb", version: 2 });
results.declare({
id: "event_total",
kind: "metric",
title: "Events",
description: "Opening range breaks in the run window.",
});
export function scope(ctx) {
if (ctx.event.flow !== "orb") return null;
return {};
}
export function onEvent(ctx, scope) {
ctx.collect("hits", 1);
}
export function onFinish(ctx) {
ctx.publish("event_total", { value: ctx.collected("hits").length });
}version is the definition version whose events you want. Use its current version, not 1. Declarations explains why.
Pages in this section
Page | Covers |
|---|---|
| |
| |
The three handlers, | |
| |
Payload shape for each result kind, | |
Other events, drawings and indicator values at event time | |
What a study needs before it can go on the chart | |
Attach to chart, step by step | |
Shared with indicators and definitions
Topic | Page |
|---|---|
Declaring indicators and reading their outputs | |
Session helpers | |
Limits and lint | |
Drawing on the chart | Drawing on the chart. The study versions take different arguments, listed in Results and stats. |
What a study cannot use
These throw or fail lint in a study:
ctx.emit,ctx.snapshot,events.declare,outputs.declare,output.*,imports.*. Studies publish results instead.ctx.accum,onBarandtimeframe(...)handles. Studies run per event, not per bar.ctx.volumePriceLevels. Read the levels a definition or indicator already drew instead.await,async function, promises,setTimeout,fetch. A study runs synchronously with no network.Date.now()andnew Date()with no arguments. Usectx.event.time.
Results are cached on the study version, the events and the settings, so a study has to give the same answer every time it runs. Math.random() is seeded for that reason.
