Guides
Patterns, clocks and signals
Besides the body that runs once per bar, a script can react to market events, define named patterns that emit signals, and build its own clocks.
Event handlers#
| Handler | Runs for | Details |
|---|---|---|
on trade(t) | every trade | Market data |
on order(o) | every order-by-order add, cancel, modify, fill | Order flow |
on match(m) | every aggressive execution | Order flow |
on book(b) | every book snapshot (250 ms) | Order flow |
on session(s) | each session boundary | Market data |
on signal(s) / on signal(s from "Name") / on signal(s from alias) | each signal of a pattern | below |
on clock name | each tick of a custom clock | below |
on fill(f), on exit(x) | fills and closed trades of a strategy | Strategies |
- Handlers are declared at the top level. The variable name in parentheses is free.
- Any other event name gives E901, with the list of events.
- Each call has its own operation budget.
- Variables created inside a handler are local to that call. Keep anything that must last in a
statevariable.
Patterns#
A pattern is a named condition evaluated on a stream of events. Each time the condition becomes true it emits a signal: a mark on the chart (a diamond, green for "buy", red for "sell", violet without a side) that other code can listen to.
pattern "Name" {
on: trade // the event stream: trade, level, match, order, book or bar
side: "buy" // optional
price: expression // optional
cooldown: 30s // optional
confirm: 2s // optional
show: [value, value] // optional
statements… // computed at each event
when condition // exactly one
}| Setting | Value | Error |
|---|---|---|
on: (required) | trade, level, match, order, book or bar | E934 if missing or unknown |
side: | "buy", "sell" (also "long", "short"), a signed number, or na | E934 |
price: | The signal's price. By default, the event's price (the bar's close for on: bar). | — |
cooldown: | Minimum delay between two signals at the same price and side. A duration; a plain number is read as seconds, na as 0. | E934 otherwise |
confirm: | The condition must stay true for at least this long before the signal is emitted. A duration; a plain number is read as seconds, na as 0. | E934 otherwise |
show: | Values added to the signal's explanation. | — |
- The event variable is named after the unit: inside
on: tradeyou readtrade.price, insideon: orderyou readorder.side, and so on.on: levelis the trade stream, with the variable namedlevel.on: barhas no event variable: readclose,volume… as in the body. - Patterns on events run before the body of their bar.
on: barpatterns run after the body. - The statements before
whenrun at every event. Compute normalizations (norm.*) there, so their population includes every event and not only those where other conditions are true. - A signal is emitted on the rising edge of
when, separately for each price and side (foron: bar, for each side): the condition must become false again before the same price and side can signal again. - Settings may share a line, separated by commas:
on: bar, cooldown: 3m. - Exactly one
whenclause (E108). Two patterns with the same name give E934. Any other setting gives E934 (expire:gives E901).
The explanation. Each signal carries a text that lists each top-level and term of when with its values, then the show: values, for example lv.replenishments = 1 ≥ minRefills = 1.
indicator "Big bars" { overlay: true }
minRank = input.float("Min volume rank", 95)
pattern "Big bar" {
on: bar, cooldown: 3m
side: close > open ? "buy" : "sell"
show: [volume]
rk = stats.rank(volume, 100)
when rk >= minRank
and close != open
}
on signal(s from "Big bar") { label.new(s.time, s.price, s.side) }indicator "Defended ask" { overlay: true, level_history: 2m }
minRefills = input.int("Min refills", 1, min: 1)
pattern "Defended ask" {
on: order
side: "sell"
cooldown: 30s
lv = order.is_add and order.side == "ask" ? mbo.level(order.price, window: 60s) : na
when not na(lv)
and lv.replenishments >= minRefills
}
on signal(s from "Defended ask") { label.new(s.time, s.price, s.explain) }
plot(close, title: "Close")Listening to signals: on signal#
on signal(s) { … } // every pattern of the script
on signal(s from "Name") { … } // one pattern
on signal(s from alias) { … } // every pattern of an imported script| Field | Value |
|---|---|
s.name | Pattern name. |
s.time | Time of the signal. |
s.price | Its price (na if none). |
s.side | "buy", "sell" or na. |
s.start | When the condition became true (before confirm:). |
s.explain | The explanation text. |
from "Name" with no such pattern gives E934, with the list of patterns. In a research script, the signal is what you pass to study(); in a strategy, you can act on it with enter().
signal(...), the function, is something else: it only draws a small mark at the top of the chart, whatever its first argument. It draws at most one mark per call place and per bar (a later call at the same place on the same bar replaces it). Put it inside an if.
Custom clocks#
A clock fires at moments you define, independently of the chart's bars.
clock name = clock.time(1s)
on clock name { … }Clocks are evaluated after each market event (trade, order-by-order event, book snapshot):
| Clock | Fires |
|---|---|
clock.time(d) | On the first event at or after each multiple of the duration d (aligned on the clock: 1m fires at each new minute). |
clock.volume(n) | Each time n contracts have traded since it last fired. |
clock.trades(n) | Each time n trades have occurred since it last fired. |
clock.events(n) | Every n market events of any kind. |
clock.range(d) | Each time the traded high and low since it last fired are d apart (a price distance, e.g. clock.range(4 ticks)). |
when(condition) | Each time the condition becomes true (it must turn false before firing again). |
The thresholds (d, n) are evaluated once, when the script starts; they must be positive (E935 otherwise).
- A clock fires after the handlers and patterns of the event that triggered it.
- Inside
on clock,event.timeis the time of that event andopen,close… describe the chart bar so far. - Two clocks with the same name,
on clock xwithout a clockx, or another form give E935.when(…)outside a clock declaration gives E901.
indicator "Imbalance clock" { overlay: true }
threshold = input.int("Imbalance", 200, min: 1)
state theta = 0
on trade(t) { theta += t.delta }
clock vib = when(abs(theta) >= threshold)
on clock vib {
label.new(event.time, close, str(theta), color: theta > 0 ? #26a69a : #ef5350)
theta = 0
}
plot(close, title: "Close")indicator "One-second sampler" { overlay: false }
clock sec = clock.time(1s)
state spreadSum = 0
state n = 0
on clock sec {
if book.available {
spreadSum += book.spread / instrument.tick
n += 1
}
}
plot(n > 0 ? spreadSum / n : na, #2962ff, title: "Mean spread (ticks)")
spreadSum = 0
n = 0The shipped pattern library#
Strate ships definitions written in StrateScript, imported from strate/patterns/<file>. They are competing definitions: none is a default, and each exposes its thresholds as settings you can change or override in the import line.
| File | Definition |
|---|---|
absorption_held_volume | High aggressor volume at a price that stayed at the best bid or ask for a share of the window, and is still displayed. |
absorption_replenishment | High aggressor volume at a price that was emptied and refilled many times. |
absorption_exhaustion | High aggressor volume at a price while that side's aggressor flow is dying out. |
refill_same_order | A level emptied and refilled many times by an order already seen at that price. |
refill_new_orders | A level emptied and refilled many times by new orders. |
sweep | One aggressive order that traded through several prices, for a large total size; marked once per order. |
stop_run | A trade beyond the recent high or low, inside an unusual burst of same-side trades. |
spoofing_pulled_before_touch | A large order placed away from the best price, resting a while, never filled, canceled in full as price came closer. |
liquidity_pull | Large size canceled at or next to the best price, mostly without being traded against. |
Most of them need order-by-order data. Each file starts with a comment that states its definition precisely.
The script menu of the StrateScript panel lists them as Definition: entries. Choosing one adds its code to the chart as a new script: it is ordinary StrateScript, so you can read it, run it, or copy it as the starting point of your own definition.
indicator "Two absorption definitions" { overlay: true }
import "strate/patterns/absorption_held_volume" as strict { minVol: 99 }
import "strate/patterns/absorption_held_volume" as loose { minVol: 80 }
on signal(s from strict) { label.new(s.time, s.price, "strict") }
on signal(s from loose) { label.new(s.time, s.price, "loose") }The keys you can override are the names of the imported script's top-level declarations. For absorption_held_volume they are window, held, normWindow, volUnit and minVol.