Sub topic 11
Building threshold-based whale alerts
A whale alert is a message sent when on-chain activity crosses a line you defined in advance. The line might be a single transfer above a size, a large net movement into an exchange within an hour, or a large holder changing its balance. This chapter shows how to turn the labeled transfers from earlier chapters into alerts that people will read and trust.
This chapter assumes you can already:
- Produce labeled transfers with
from,to,amount, and a timestamp. - Compute exchange inflow, outflow, and netflow.
- Read Python with dictionaries, classes, and
collections.
What an alert system has to do
A threshold alert is simple in principle: compare a number to a limit and notify. Most of the work lies in the surrounding decisions:
- Which events count? Raw transfers, per-exchange netflow, or balance changes of known holders.
- How big is big? A fixed amount, or an amount relative to recent activity.
- When is the event final? A block that is later reorganized should not trigger a permanent alert.
- How often may it fire? Without limits, one busy hour produces hundreds of near-identical messages.
- What does the message say? An alert needs enough context for the reader to judge it in a few seconds.
The pipeline below follows this order.
Three kinds of alerts
Single-transfer alerts
These fire when one transfer meets a minimum amount. They are easy to explain and easy to test. They are also easy to evade: a holder who splits 10,000 coins into twenty transfers of 500 never trips a 1,000-coin rule.
Windowed netflow alerts
These sum signed flows per exchange over a rolling window, for example the last hour. Inflows count as positive and outflows as negative. The rule fires when the absolute net amount crosses a threshold. This catches split transfers, and it ignores two transfers that cancel each other out.
Holder-activity alerts
These watch a list of known large holders and fire when one of them moves funds, especially to an exchange address. They depend on your holder list and labels, so they inherit any labeling errors.
Choosing thresholds
A fixed number such as "10,000 ETH" is predictable, but it ages. As prices and volumes change, the same number becomes too noisy or too quiet. There are three common approaches:
| Approach | Example rule | Strength | Weakness |
|---|---|---|---|
| Fixed amount | amount ≥ 1,000 | Simple, explainable | Drifts as price and activity change |
| Fixed value in fiat | amount × price ≥ 5 million USD | Stable in value terms | Needs a trustworthy price feed |
| Percentile of history | amount ≥ 99.9th percentile of last 30 days | Adapts to activity | Harder to explain, slow to adapt to sudden regime shifts |
A practical start is a fixed amount chosen by looking at a few weeks of history. Count how many alerts per day it would have produced. If the number is more than a reader can look at, raise the threshold. Review it on a schedule, because a rule that nobody revisits turns into noise.
Implementation
The first function handles single-transfer alerts. It deduplicates on (tx_hash, log_index), not on tx_hash alone, because one transaction can emit many Transfer logs. It also skips transfers inside one entity, which matches the netflow logic from the previous chapter.
def transfer_alerts(transfers, labels, min_amount, seen):
"""Return alert dicts for large transfers not seen before.
transfers: dicts with 'tx_hash', 'log_index', 'from', 'to', 'amount'.
labels: maps an address to an entity name.
seen: a set that persists between calls.
"""
alerts = []
for t in transfers:
if t["amount"] < min_amount:
continue
transfer_id = (t["tx_hash"], t["log_index"])
if transfer_id in seen:
continue
seen.add(transfer_id)
src = labels.get(t["from"])
dst = labels.get(t["to"])
if src is not None and src == dst:
continue # internal move inside one entity
alerts.append({
"kind": "large_transfer",
"amount": t["amount"],
"from": src or t["from"],
"to": dst or t["to"],
"tx_hash": t["tx_hash"],
})
return alerts
labels = {"addr_ex1": "ExchangeA", "addr_ex2": "ExchangeA"}
seen = set()
batch = [
{"tx_hash": "0x01", "log_index": 0, "from": "addr_user", "to": "addr_ex1", "amount": 1500.0},
{"tx_hash": "0x01", "log_index": 0, "from": "addr_user", "to": "addr_ex1", "amount": 1500.0},
{"tx_hash": "0x02", "log_index": 3, "from": "addr_ex1", "to": "addr_ex2", "amount": 9000.0},
{"tx_hash": "0x03", "log_index": 1, "from": "addr_ex2", "to": "addr_other", "amount": 200.0},
]
print(transfer_alerts(batch, labels, 1000.0, seen))This prints one alert. The repeated first transfer is dropped as a duplicate, the 9,000 internal move is skipped, and the 200 transfer is below the threshold.
The second piece is the rolling netflow monitor. It keeps a queue of recent signed amounts per exchange and a running total. When a new event arrives, it adds the event and removes events that fell out of the window. A cooldown prevents repeated alerts while the total stays above the threshold.
from collections import defaultdict, deque
class NetflowMonitor:
"""Rolling netflow alerts. Events must arrive in timestamp order."""
def __init__(self, window_s, threshold, cooldown_s):
self.window_s = window_s
self.threshold = threshold
self.cooldown_s = cooldown_s
self.events = defaultdict(deque)
self.net = defaultdict(float)
self.last_alert = {}
def add(self, exchange, ts, signed_amount):
"""signed_amount: positive for inflow, negative for outflow."""
queue = self.events[exchange]
queue.append((ts, signed_amount))
self.net[exchange] += signed_amount
while queue and queue[0][0] <= ts - self.window_s:
_, old = queue.popleft()
self.net[exchange] -= old
if abs(self.net[exchange]) < self.threshold:
return None
last = self.last_alert.get(exchange)
if last is not None and ts - last < self.cooldown_s:
return None
self.last_alert[exchange] = ts
return (exchange, self.net[exchange])
monitor = NetflowMonitor(window_s=3600, threshold=1000.0, cooldown_s=1800)
events = [
("ExchangeA", 0, 600.0),
("ExchangeA", 1200, 500.0),
("ExchangeA", 1500, 400.0),
("ExchangeA", 4000, -50.0),
]
for exchange, ts, amount in events:
result = monitor.add(exchange, ts, amount)
if result:
print(ts, result)The only line printed is 1200 ('ExchangeA', 1100.0). At 1500 the net is 1,500, but the cooldown suppresses the alert. At 4000 the first event has left the window, so the net falls to 850.
Handling confirmations and reorganizations
A chain can replace its most recent blocks with a different set of blocks. This is a reorganization. If an alert fires on a block that is later replaced, you have announced a transfer that never happened on the final chain.
Two common defenses:
- Confirmation depth. Process a block only after N newer blocks exist on top of it. A larger N is safer and slower. Choose N from the chain's finality behavior and from how time-sensitive your alert is.
- Revision handling. Alert early, but store the block hash with each alert. If the block hash at that height later changes, send a correction.
Either way, keep the deduplication key stable. When a transaction reappears in a different block after a reorganization, its (tx_hash, log_index) is the same, so it will not alert twice. Decide whether that is what you want. If you store the block hash, you can tell the two cases apart.
Delivery: polling or subscription
Your data source determines how events arrive.
- Polling queries a node or API for new blocks or logs on an interval. It is simple, resumable (store the last processed block number), and tolerates restarts. This is the right default.
- Subscriptions push new events to you, usually over a websocket. They have lower latency, but connections drop silently. You still need to backfill missed blocks after a reconnect, so a subscription system ends up containing a polling loop.
In both cases, save your position (last processed block and the seen set or its equivalent) to durable storage. Otherwise a restart either replays old transfers as new alerts or skips events that occurred while the process was down.
Writing the message
An alert should answer questions the reader would otherwise have to research. Include:
- Amount, asset, and approximate value, with the price source and time.
- Sender and receiver, as entity names where known and shortened addresses where not.
- Label confidence, so that "ExchangeA (high)" is distinguishable from "ExchangeA (inferred by clustering)".
- A link to the transaction.
- The rule that fired, such as "net inflow over 1 hour ≥ 1,000".
Avoid wording that asserts intent, like "whale dumping". The alert can state that a transfer to an exchange address occurred. It cannot state why.
Common errors
- Alerting on unlabeled addresses as if they were exchanges. Keep "unknown" separate from labeled entities.
- Counting internal moves. A transfer between two wallets of the same exchange is not a flow. The check in
transfer_alertsexists for this reason. - No cooldown. One large position unwinding in many steps floods the channel.
- Threshold never reviewed. Alert volume drifts, people mute the channel, and then real events are missed.
- Missing contract and custodian addresses. A large transfer to a smart contract or custodian is not necessarily a holder moving to an exchange.
- Treating the alert as a signal. The alert reports an observation. Interpretation comes in the next chapters.
Exercise
The single-transfer function deduplicates on (txhash, logindex) instead of txhash alone. Give a case where using txhash alone would cause a missed alert, and say what you would change in NetflowMonitor if events could arrive out of timestamp order.
Show answer
One transaction can emit several Transfer logs, for example a swap or a batch payout that sends tokens to several recipients. If the first log was below the threshold or was already recorded under that txhash, a later large log in the same transaction would be treated as a duplicate and silently dropped. Keying on (txhash, log_index) identifies each log separately. For out-of-order events, the deque-based window breaks, because it assumes the oldest event is at the front. You would either buffer and sort events by block timestamp before calling add, or keep events in a structure ordered by timestamp (for example a heap) and recompute the window total when late events arrive.