Examples
Same-order refills, order by order
An iceberg reloads: the visible size at a price is traded away, then reappears. This script follows it event by event with on order, without any ready-made statistic: it records when a price's displayed size reaches zero, and counts a refill when size comes back at that price soon after. The label of the refill that reaches the threshold says whether it came from a known order (an id already seen at that price) or from a new one.
indicator "Refills, raw" { overlay: true }
within = input.duration("Refill within", 2s)
minRefills = input.int("Refills to mark", 3, min: 1)
state emptiedAt = map() // price -> time its displayed size reached 0
state seen = map() // order id -> price where it was seen
state gone = ring(100000) // ids of the last 100,000 orders that left the book
state refills = map() // price -> refills since the session start
on order(o) {
if o.is_add or o.is_modify {
known = seen.get(o.id, na) == o.price
t0 = emptiedAt.get(o.price, na)
grew = o.is_add or o.size > nz(o.previous_size)
if grew and not na(t0) and o.time - t0 <= within {
refills.add(o.price)
emptiedAt.remove(o.price)
if refills[o.price] == minRefills {
label.new(o.time, o.price, str(minRefills) + " refills" + (known ? " (same order)" : " (new order)"), color: o.side == "ask" ? #ef5350 : #26a69a)
}
}
seen[o.id] = o.price
}
if (o.is_fill or o.is_cancel) and mbo.size(o.price) == 0 {
emptiedAt[o.price] = o.time
}
// forget an order 100,000 departures after it left the book (keeps `seen` small on a full day)
if (o.is_fill or o.is_cancel) and na(mbo.order(o.id)) {
if gone.full {
oldest = gone.first()
if na(mbo.order(oldest)) { seen.remove(oldest) }
}
gone.push(o.id)
}
}
if session.is_new {
refills.clear()
seen.clear()
gone.clear()
}What to notice:
- when
on orderruns,mboalready includes the event, sombo.size(o.price) == 0means "this event emptied the price"; o.previous_sizeis the size before a modify;nz()covers adds, where it isna;- maps keyed by price or by order id are ordinary
statevariables, cleared at each session; - a map keyed by order id must also forget orders, or it grows with every order of the day: a list or map holds at most 1,000,000 elements (E941). Here a
ringremembers the last 100,000 orders that left the book; when it is full, the oldest one (gone.first(), read before thepushdrops it) is removed fromseen. A ring'spushandfirst()cost the same whatever its size, unlikeshift()on a list, which costs about1 + n/8operations of the budget; mbo.order(id)isnaonce the order is gone, sona(mbo.order(o.id))after a fill or a cancel means "nothing of this order is left";mbo.level(…).refill_same_idandrefill_new_idgive a ready-made count of the same thing over a window.