Examples
Volume imbalance bars
A custom clock that closes a "bar" each time the signed aggressor volume since the last one exceeds a threshold that adapts: the threshold follows an exponential average of the previous bars' imbalance.
indicator "Imbalance bars" { overlay: true }
initial = input.float("Initial threshold", 200, min: 1)
alphaW = input.float("Adaptation weight", 0.1, min: 0.01, max: 1, step: 0.01)
state theta = 0
state expected = na
state started = na
on trade(t) {
if na(started) { started = t.time }
theta += t.delta
}
clock vib = when(abs(theta) >= nz(expected, initial))
on clock vib {
label.new(event.time, close, str(theta, "+0") + " in " + str((event.time - started) / 1s, "0.0") + "s", color: theta > 0 ? #26a69a : #ef5350)
expected = na(expected) ? abs(theta) : alphaW * abs(theta) + (1 - alphaW) * expected
theta = 0
started = na
}What to notice:
when(condition)fires on the rising edge of the condition, evaluated after every event;theta,expectedandstartedarestatevariables shared by the trade handler and the clock;event.timeinside the clock handler is the time of the trade that closed the bar.