Sub topic 8
Computing Exchange Inflows, Outflows, and Netflow
This chapter assumes you can read basic Python (lists, dictionaries, functions) and know what a transaction and an address are. It also assumes you know that Bitcoin uses the UTXO model and Ethereum uses accounts. Earlier chapters covered how addresses are labeled and how exchanges organize wallets. Here you turn labeled transfers into flow numbers and learn where those numbers go wrong.
What the three numbers mean
For one exchange over one time window:
- Inflow is the amount that arrived at addresses the exchange controls, coming from addresses it does not control.
- Outflow is the amount that left addresses the exchange controls, going to addresses it does not control.
- Netflow is inflow minus outflow. A positive value means more coins entered than left. A negative value means more left than entered.
The word "controls" matters. A flow is only a flow when funds cross the boundary of an entity. A transfer between two addresses of the same exchange does not cross it, so it counts as neither inflow nor outflow.
Classifying each transfer
Every transfer has a sender and a receiver. Look up each in your label table and decide which case applies.
A transfer between two different exchanges is both an outflow for the sender's exchange and an inflow for the receiver's exchange. It is counted on both sides, which is correct.
A reference implementation
This function works on account-style transfers, where each record has a day, a sender, a receiver, and an amount.
from collections import defaultdict
def exchange_netflow(transfers, exchange_labels):
"""transfers: dicts with 'day', 'from', 'to', 'amount'.
exchange_labels: maps an address to an exchange name."""
flows = defaultdict(lambda: {"inflow": 0.0, "outflow": 0.0})
for t in transfers:
src = exchange_labels.get(t["from"])
dst = exchange_labels.get(t["to"])
if src == dst:
# Neither side is an exchange, or both belong to the same exchange.
continue
if dst:
flows[(dst, t["day"])]["inflow"] += t["amount"]
if src:
flows[(src, t["day"])]["outflow"] += t["amount"]
return {
key: {**v, "netflow": v["inflow"] - v["outflow"]}
for key, v in flows.items()
}
labels = {"addr_ex1": "ExchangeA", "addr_ex2": "ExchangeA"}
transfers = [
{"day": "2026-11-26", "from": "addr_user", "to": "addr_ex1", "amount": 120.0},
{"day": "2026-11-26", "from": "addr_ex1", "to": "addr_ex2", "amount": 500.0},
{"day": "2026-11-26", "from": "addr_ex2", "to": "addr_other", "amount": 30.0},
]
print(exchange_netflow(transfers, labels))The output is:
{('ExchangeA', '2026-11-26'): {'inflow': 120.0, 'outflow': 30.0, 'netflow': 90.0}}The 500 moved between addr_ex1 and addr_ex2 is skipped because both addresses carry the label ExchangeA. If you removed the src == dst check, the exchange would show 500 of phantom inflow and 500 of phantom outflow. The netflow would still be correct, but the gross numbers would be wrong, and so would any volume-based alert.
Note the condition src == dst also catches the case where both labels are None. That is intentional. Most transfers on a chain involve no labeled exchange at all.
Choosing the window and the unit
The day field is a design decision. Three choices affect your results.
- Time zone. Use UTC and say so. Block timestamps are in UTC. Mixing local days shifts flows between buckets.
- Block time versus wall clock. Block timestamps can be slightly out of order. Bucket by block number if you need exact reproducibility, then map block ranges to days.
- Unit. Report flows in the native asset (BTC, ETH, or a token) first. Converting to a currency at a daily price mixes price movement into a flow metric. If you convert, use the price at the transfer time, not the day's close.
For tokens, remember that raw on-chain amounts are integers scaled by the token's decimals. Divide before summing across tokens, and never add flows of different assets together.
UTXO chains need netting first
On a UTXO chain such as Bitcoin, one transaction has many inputs and many outputs. There is no single sender and receiver, so the transfer-record model above does not apply directly. A typical exchange withdrawal spends one large input, pays the customer, and sends the remainder back to an exchange-owned change address. Naively counting every output paid by an exchange-owned input would call the change an outflow.
The fix is to net each transaction per entity: sum the value of inputs the entity owns, sum the value of outputs it owns, and take the difference.
from collections import defaultdict
def utxo_entity_delta(tx, labels):
"""tx: {'inputs': [(address, sats)], 'outputs': [(address, sats)]}.
Returns net change in sats per labeled entity.
Negative means the entity sent value out; positive means it received."""
delta = defaultdict(int)
for addr, sats in tx["inputs"]:
entity = labels.get(addr)
if entity:
delta[entity] -= sats
for addr, sats in tx["outputs"]:
entity = labels.get(addr)
if entity:
delta[entity] += sats
return dict(delta)
labels = {"ex_hot": "ExchangeA", "ex_change": "ExchangeA"}
tx = {
"inputs": [("ex_hot", 1_000_000_000)],
"outputs": [("customer", 300_000_000), ("ex_change", 699_990_000)],
}
print(utxo_entity_delta(tx, labels))The output is {'ExchangeA': -300010000}. The exchange spent 10 BTC, got 6.9999 BTC back as change, and so lost 3.0001 BTC. The extra 10,000 satoshis are the miner fee, which appears as a small outflow. Many analysts subtract fees or ignore them. Decide once and document it.
Use integers (satoshis) for UTXO amounts. Floating point sums of many small values drift, and a netflow near zero can flip sign from rounding noise.
A tx where the delta is negative counts toward outflow, and a positive delta counts toward inflow. A transaction where an exchange both sends to and receives from other labeled entities may need splitting by counterparty. Netting per entity is the minimum.
Deposit addresses and sweeps
Exchanges give each customer a unique deposit address, then sweep the funds into a hot or warm wallet. Two ways of labeling change what you measure:
| Labeling state | What the customer deposit looks like | What the sweep looks like |
|---|---|---|
| Deposit addresses labeled | Inflow at the moment of deposit | Internal, skipped |
| Deposit addresses unlabeled | Not visible as a flow | Inflow when the sweep reaches a labeled wallet |
Both give the same total over a long window. They differ in timing and in who appears as the sender. In the unlabeled case, the apparent sender is a deposit address that is really the exchange's own, and the data looks like a transfer from an unknown party. A sweep can also be batched, so a day's worth of small deposits shows up as one large inflow. A large single inflow is therefore not evidence of one large depositor.
Fetching the data for tokens
For ERC-20 tokens you rarely read transactions. You read Transfer event logs. This request returns them for a small block range:
{
"jsonrpc": "2.0",
"id": 1,
"method": "eth_getLogs",
"params": [
{
"fromBlock": "0x10d4f00",
"toBlock": "0x10d4f0a",
"address": "<TOKEN_CONTRACT_ADDRESS>",
"topics": [
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
]
}
]
}The first topic is the hash of Transfer(address,address,uint256). The sender and receiver are the next two topics, and the amount is in the data field. Decode them into the from, to, and amount fields used above. Providers limit the block range per call, so query in chunks.
Native ETH moved by ordinary transactions does not emit logs. Transfers made by contract calls appear only in internal-transaction traces. If you track ETH flows from logs alone, you will miss some of them.
Edge cases that corrupt the numbers
- Double counting. One transaction can emit several
Transferlogs. Deduplicate on transaction hash plus log index, not on hash alone. - Reorganizations. Recent blocks can be replaced. Wait for finality, or recompute the last few blocks on each run.
- Stale labels. An address labeled as an exchange wallet last year may have been retired or reused. Store labels with a validity period.
- Contract intermediaries. A deposit routed through a swap router or bridge shows the router as the sender. The true depositor is hidden.
- Wrapped and bridged assets. Wrapped tokens have separate contracts. Decide whether to merge them with the base asset.
- Missing counterparties. Unlabeled exchanges and custodians make a flow look like it came from "the market" when it was exchange-to-exchange.
Reading the result
A positive netflow means coins moved onto exchanges, where they can be sold. A negative one means coins left to places where they are less likely to be sold immediately, such as self-custody. These are tendencies, not facts. Coins sent to an exchange may be used for collateral, market making, or transfers between a firm's own accounts. A later chapter treats interpretation in detail. For now, treat netflow as a measurement with an error bar, and keep the raw inflow and outflow beside it. A netflow of zero can hide large gross movement in both directions.
Exercise
Using the rules in this chapter, compute inflow, outflow, and netflow for ExchangeA and ExchangeB for one day. Labels: a1 and a2 belong to ExchangeA, b1 belongs to ExchangeB. Transfers: (1) user1 sends 100 to a1, (2) a1 sends 60 to a2, (3) a2 sends 40 to b1, (4) b1 sends 10 to user2.
Show answer
Transfer 2 is internal to ExchangeA and is skipped. ExchangeA: inflow 100 (transfer 1), outflow 40 (transfer 3), netflow +60. ExchangeB: inflow 40 (transfer 3), outflow 10 (transfer 4), netflow +30.
Exercise
A UTXO transaction spends 5 BTC from an address labeled ExchangeA. It pays 1 BTC to an unlabeled address and 3.999 BTC to another ExchangeA address. The remaining 0.001 BTC is the fee. What is the entity delta for ExchangeA, and what does it say about outflow?
Show answer
The delta is -5 + 3.999 = -1.001 BTC. The exchange has a net outflow of 1.001 BTC: 1 BTC to the unlabeled address plus 0.001 BTC in fees. The 3.999 BTC is change and is not an outflow.