Bank Statement Formats Explained: MT940 vs camt.053 vs BAI2 and How to Build Automated Cash Reconciliation (2026)
Most cash reconciliation failures are not matching failures. They are parsing failures that surface three days later as a “missing” receipt, a doubled balance or a reversal nobody noticed. The statement arrived, the matcher ran, and the system was confidently wrong because one adapter dropped a continuation line or read a booking date as a value date. The MT940 vs camt.053 question is therefore not a style preference. It decides how much structure survives the trip from the bank’s core ledger to yours. It matters now because Swift’s interbank statement messages are on a published path from MT to ISO 20022, with camt receipt mandatory from November 2027, while US banks still deliver BAI2 by the million every morning. This guide gives you a field-level map of all three formats, tested Python parsers, a four-pass matching engine, a worked example and the failure modes that break production systems.
What this covers: the Swift migration timeline for statements, MT940/MT942 tag grammar, camt.053 structure from Stmt to TxDtls, BAI2 records and control totals, bank transaction codes, intraday versus end-of-day reporting, a canonical data model, parsers, matching passes, exceptions, failure modes and a format decision table.
Disclaimer: this article describes systems architecture only. It is not financial, accounting, treasury, legal or compliance advice; validate every design decision against your banks’ specifications and your own auditors.
Context and Background
Three statement lineages coexist in corporate treasury today. Swift MT940 (customer statement) and MT942 (interim transaction report) come from the FIN messaging world, where fields are tagged text lines with tight length limits. BAI2 comes from the US Bank Administration Institute’s (BAI) cash management balance reporting specification; its copyright moved to the Accredited Standards Committee X9 in 2008, and X9 later published the revised Balance and Transaction Reporting Standard (BTRS) as ANSI X9.121-2016. ISO 20022 brought XML cash management messages: camt.052 (account report, typically intraday), camt.053 (bank-to-customer statement, typically end-of-day) and camt.054 (debit/credit notification).
The incumbents are entrenched for good reasons. MT940 is supported by practically every ERP and treasury management system, and BAI2 dominates US host-to-host delivery. Both are compact and easy to tail in a terminal. Their weakness is semantic capacity. An MT940 :86: narrative is free text limited to six lines of 65 characters, so remittance data, end-to-end references and counterparty details are often truncated or packed into bank-specific sub-codes. BAI2’s narrative is similarly unstructured, and its transaction type codes were customised so heavily by individual banks that a 2010 AFP survey, cited in a 2012 X9 BTRS orientation webinar, found corporates struggling to import the files consistently.
The regulatory clock is now explicit. Swift’s CBPR+ phase 2 detailed roadmap separates two deadlines that are often blurred. The November 2025 end of coexistence applied to cross-border payment instructions such as MT103 and MT202. Statement and reporting messages (MT900, MT910, MT940, MT942, MT950 and their camt.052/053/054 equivalents) were extended: camt messages become mandatory to receive from November 2027, end of coexistence is planned for Standards Release 2028, and enforcement “will depend on community adoption.” Swift also states it cannot convert MT9xx to camt, so there is no contingency translation for statements. If you need the wider migration picture, our FIX to ISO 20022 migration architecture guide and the ISO 20022 payments migration overview cover the payment-instruction side. This post stays on the statement side, where the data lands in your reconciliation engine.
MT940 vs camt.053 vs BAI2: A Reference Architecture for Automated Cash Reconciliation
MT940 vs camt.053 vs BAI2 is a choice of container, not of process. All three report balances and booked entries per account. camt.053 carries the richest structure: typed balances, ISO bank transaction codes, end-to-end references and structured remittance. A robust system parses every format into one canonical entry model, checks integrity, then matches.

Figure 1: Reference architecture for multi-format automated cash reconciliation. Every channel lands raw, passes through a format adapter into one canonical model, and must clear integrity gates before matching.
Figure 1 reads top to bottom. Four bank channels deliver statements: Swift FIN for MT940 and MT942, Swift MX or a bank portal for camt.053 and camt.052, host-to-host SFTP for BAI2, and increasingly bank APIs returning JSON. Everything first lands in an immutable raw zone with a content hash. Format adapters convert each file into a canonical statement and entry model. Integrity gates check sequence numbers, balance continuity and duplicates. Only then does the matching engine run, sending matched entries to the general ledger and everything else to an exception queue. The canonical model also feeds the treasury cash position directly, because a position needs balances even when matching lags.
Treat every format as an adapter into one canonical entry model
The most expensive mistake in statement processing is letting format-specific structures leak into matching logic. If the matcher knows about :61: subfields or TxDtls nesting, each new bank or format version becomes a matching change, with matching regression risk. Instead, define a canonical entry with a small set of fields: account identifier, currency, signed amount, value date, booking date, bank reference, end-to-end reference, transaction code, remittance text and a reversal flag. Every adapter’s job is to fill that record faithfully and to say explicitly when it cannot.
The canonical model should be closer to camt.053 than to MT940. ISO 20022 already separates booking date from value date, carries the bank’s own reference (AcctSvcrRef), the originator’s end-to-end reference (EndToEndId) and a three-level bank transaction code. When an MT940 adapter cannot fill a field, it leaves it empty and records the gap. That is honest. The opposite approach, flattening camt.053 down to MT940 semantics so that legacy code keeps working, throws away exactly the data that raises match rates. Swift’s own guidance makes the same point indirectly: because there is no MT9xx-to-camt conversion service, counterparties are told to agree formatting and reconciliation requirements before November 2027.
A second rule is to keep amounts signed and in decimal types. MT940 and camt.053 express direction with a separate debit/credit indicator, while BAI2 encodes direction in the type code range and omits the decimal point entirely. Normalising all three to a signed Decimal with the account currency’s minor units removes a whole class of bugs. Floating-point amounts in reconciliation are a defect, not a style choice.
Land raw, hash, and keep the bytes forever
The raw landing zone looks like plumbing, but it is the audit backbone. Store each file or message exactly as received, with its channel metadata, a SHA-256 hash and an arrival timestamp. Parsing then becomes a pure, repeatable function from bytes to canonical entries. When a parser bug is found, you fix it and replay history rather than asking the bank to resend six months of statements.
Hashes also catch the cheapest duplicate: the identical file delivered twice by an SFTP retry. They do not catch a regenerated statement with a new creation timestamp but identical entries, which is why the integrity gates need business-level duplicate keys as well. Treat the raw zone as append-only and the canonical store as derived, rebuildable state. Our post on event sourcing and bitemporal data for financial audit trails describes the same pattern from the ledger side.
Put integrity gates before matching, not after
A matcher that receives a duplicated statement will happily match the second copy of every receipt against nothing and raise hundreds of exceptions, or worse, match them against other open items. A matcher that receives statements with a gap will report a cash position that is silently wrong. Both problems are detectable before matching, cheaply, from fields every format provides.
Three gates do most of the work. A sequence gate checks MT940 :28C: statement numbers or camt.053 ElctrncSeqNb for continuity per account. A balance gate checks that opening balance plus the sum of entries equals closing balance, and that today’s opening equals yesterday’s closing. A duplicate gate rejects a statement whose account, statement identifier and sequence number were already accepted, and flags entries whose business key repeats. A statement that fails any gate is held, not partially processed. Partial processing is how reconciliation systems acquire mysterious orphan entries.
Inside the Formats: Field-Level Anatomy of MT940, camt.053 and BAI2
Before writing parsers, you need a precise map of where each piece of information lives. Figure 2 aligns the three formats around the concepts a reconciliation engine actually consumes: statement identity and sequence, balances, and entries with their narrative.

Figure 2: Concept-level mapping between MT940 tags, camt.053 elements and BAI2 records. The mapping is approximate; each format carries details the others cannot express.
The figure shows three rows. Identity and sequence map from MT940 :20:, :25: and :28C: to camt.053 Stmt/Id, Acct and ElctrncSeqNb, and to BAI2’s 01, 02 and 03 header records. Balances map from :60F: and :62F: to Bal elements typed OPBD and CLBD, and to BAI2 status type codes 010 and 015 on the 03 record. Entries map from :61: plus :86: to Ntry with its NtryDtls/TxDtls, and to BAI2 16 records plus 88 continuations.
MT940 and MT942: tagged lines with a dense statement-line grammar
An MT940 message body is a sequence of tagged fields. :20: is the transaction reference number (16x), :21: an optional related reference, :25: the account identification (35x), and :28C: the statement number and optional sequence number (5n[/5n]). Long statements are split across several messages; the first part of statement 111 is 111/1, the second 111/2. The opening balance is :60F: on the first message and :60M: (intermediate) on continuation messages, with matching :62M: and final :62F: closing balances. Each balance has the layout 1!a6!n3!a15d: a D or C mark, a YYMMDD date, an ISO currency code and an amount using a comma as the decimal separator. Optional :64: gives the closing available balance and :65: forward available balances.
The heart of the format is the :61: statement line, defined as 6!n[4!n]2a[1!a]15d1!a3!c16x[//16x][34x]. In order, that is a six-digit value date, an optional four-digit entry (booking) date, a debit/credit mark, an optional funds code, an amount of up to 15 characters, a transaction type identification code of one letter plus three characters (for example NTRF), a 16-character reference for the account owner, an optional bank reference after //, and optional supplementary details on a new line. The debit/credit mark can be C, D, RC (reversal of credit) or RD (reversal of debit). Each :61: may be followed by an :86: “information to account owner” field of up to six lines of 65 characters.
Three details trip up parsers. The entry date has no year, so it must be inferred from the value date, and that inference breaks across New Year. The amount field has no fixed width, so the regex must find where the amount ends and the type code begins. And :86: has no universal structure; German banks commonly use ?20-style sub-fields, Dutch and Polish banks use /TAG/value/ sub-fields, and others use plain prose. You need a per-bank narrative profile.
MT942 reuses the :61: and :86: grammar for intraday reporting. It adds :34F: (a floor limit indicator with currency and optional D/C mark), :13D: (creation date, time and UTC offset) and :90D:/:90C: (number and sum of debit and credit entries). It does not carry a booked closing balance, which is why intraday data must stay provisional.
camt.053 bank statement: typed XML from Stmt down to TxDtls
A camt.053 bank statement document has a BkToCstmrStmt root with one group header (GrpHdr: MsgId, CreDtTm, optional pagination) and one or more Stmt elements, typically one per account. Each Stmt carries an Id, optional ElctrncSeqNb and LglSeqNb (both decimals of up to 18 digits in version .001.08), optional StmtPgntn with PgNb and LastPgInd, the account (Acct/Id/IBAN or Acct/Id/Othr/Id), one or more Bal elements and zero or more Ntry elements.
Balances are typed by code under Bal/Tp/CdOrPrtry/Cd. The common ones are OPBD (opening booked), CLBD (closing booked), CLAV (closing available), ITBD (interim booked), OPAV (opening available) and PRCD (previously closed booked). Each balance has an Amt with a Ccy attribute, a CdtDbtInd of CRDT or DBIT, and a date. Amounts are positive; the indicator carries the sign. This is cleaner than MT940 but has the same trap: forget the indicator and every overdraft becomes a credit balance.
Each Ntry holds the booked entry: Amt, CdtDbtInd, optional RvslInd, Sts, BookgDt, ValDt, AcctSvcrRef, BkTxCd and NtryDtls. The status representation changed between versions. In camt.053.001.02, Sts is a bare EntryStatus2Code such as BOOK; in .001.08 it is a choice between Cd and Prtry, so the XML reads <Sts><Cd>BOOK</Cd></Sts>. For a statement the status is expected to be BOOK, while camt.052 may carry pending (PDNG) entries. A parser that hard-codes one shape breaks the day a bank upgrades.
The bank transaction code under BkTxCd/Domn has three levels: a domain code (PMNT for payments, ACMT for account management), a family (RCDT received credit transfers, ICDT issued credit transfers, RDDT received direct debits, CCRD customer card transactions, MDOP miscellaneous debit operations) and a sub-family (ESCT SEPA credit transfer, ESDD SEPA core direct debit, POSD point-of-sale debit card, CHRG charges). The ISO 20022 Registration Authority publishes these as an external code set with combination and description files, on a quarterly update cycle. Banks may also supply a proprietary code under BkTxCd/Prtry alongside or instead.
NtryDtls is where camt.053 earns its keep. It may contain a Btch element (number of transactions and total amount) and one or more TxDtls. Each TxDtls can carry Refs (MsgId, PmtInfId, InstrId, EndToEndId, TxId, MndtId, and in newer versions UETR), AmtDtls with instructed and transaction amounts, related parties and agents, purpose, and RmtInf with either unstructured Ustrd lines or structured Strd remittance such as creditor references. When a bank batch-books 200 outgoing supplier payments as one debit, TxDtls is the only place the 200 individual amounts and references survive.
BAI2 format: comma-delimited records with control totals
The BAI2 format is a hierarchy of comma-delimited records. A file starts with an 01 file header (sender, receiver, creation date and time, file ID, optional record length and block size, version 2) and ends with a 99 file trailer. Inside are groups, each opened by an 02 group header (ultimate receiver, originator, group status, as-of date, optional currency and as-of-date modifier) and closed by a 98 group trailer. Inside each group are accounts, opened by an 03 account identifier and closed by a 49 account trailer. Transaction detail lives in 16 records, and an 88 continuation record extends the preceding 03, 16 or 88 record. Non-text records end with a slash; text fields run to the end of the record.
Amounts carry no decimal point, with implied decimals set by the currency, so 125000 in a USD account is 1,250.00. Status and summary amounts appear on the 03 record as repeating groups of type code, amount, item count and funds type. Type code ranges carry direction: 001–099 for account status, 100 and 101–399 for credits, 400 and 401–699 for debits, 700–899 unused by BAI, and 900–999 reserved for bank-customised codes. Common status codes include 010 opening ledger, 015 closing ledger, 040 opening available and 045 closing available. Transaction detail amounts on 16 records are unsigned; direction comes from the type code range.
Funds type describes availability: 0 (immediate), 1 (one day), 2 (two or more days), S (distributed, followed by immediate, one-day and two-plus-day amounts), V (value dated, followed by a date and optional time), D (distributed with an explicit count of day/amount pairs) and Z (unknown). These optional trailing fields mean a 16 record has a variable number of fields before the text. Parsers that count commas without honouring the funds type misalign the bank reference, customer reference and text.
The redeeming feature of BAI2 is its control totals. The 49 record holds the algebraic sum of all amounts in the account plus a record count including the 03, 16, 88 and 49 records. The 98 and 99 records hold group and file totals and counts. Validating these before parsing anything else catches truncated transfers and mangled continuation lines. Implementations differ in edge cases; for example, one large vendor’s validator excludes type code 890 from the account control total, so test against each bank’s sample files.
Bank transaction codes: three vocabularies, one mapping table
Every format codes the transaction type, and none of them agree. MT940 uses a one-letter prefix and three characters, where N codes such as NTRF (transfer), NCHG (charges) or NDDT (direct debit) are common. BAI2 uses three-digit numeric type codes, heavily customised by banks in the 900s. camt.053 uses the ISO Domain/Family/SubFamily tree plus optional proprietary codes. Banks map their internal codes to each vocabulary differently; ING, for example, provides its transaction code mappings to SWIFT and ISO codes on request at implementation time rather than as a published universal table.
Treat bank transaction codes as routing hints, not truth. Map each bank’s codes into a small internal taxonomy (customer receipt, supplier payment, card settlement, direct debit, fee, interest, FX, internal transfer, return) through a versioned table per bank and format. That taxonomy drives which matching rules apply. When a code is unmapped, route the entry to an exception with reason “unknown transaction code” instead of guessing.
Intraday versus end-of-day: provisional data has to stay provisional
camt.052 and MT942 report intraday activity; camt.053 and MT940 report the booked end-of-day statement; camt.054 notifies individual debits or credits. Intraday reports may include entries that later change status, get reversed or are booked with a different value date. The end-of-day statement is the record of truth for the general ledger.
The architectural consequence is two-phase matching. Intraday entries feed the treasury position and can produce provisional matches, but those matches must be confirmed or unwound when the end-of-day statement arrives. Our guide to real-time treasury and intraday liquidity architecture covers the position-keeping side. Here, the rule is simple: never post to the general ledger from an intraday report alone.
Walk-through: Bank Statement Parsing in Python
The following code is a compact, tested reference implementation of bank statement parsing for all three formats. It uses only the standard library plus lxml, and it targets the canonical model described above. It is deliberately strict: any line it cannot parse raises an error instead of being skipped.
The canonical entry and the MT940 parser
The MT940 parser has two layers. split_tags splits a message body into (tag, value) pairs while preserving continuation lines inside each value. parse_61 applies a regular expression that mirrors the :61: format definition and converts the result into a canonical entry.
import re
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from typing import Optional
@dataclass
class StatementLine:
account: str
currency: str
amount: Decimal # signed: + credit, - debit
value_date: date
booking_date: Optional[date]
bank_ref: str = ""
end_to_end: str = ""
tx_code: str = "" # SWIFT 4-char or ISO Domn/Fmly/SubFmly
text: str = ""
reversal: bool = False
TAG = re.compile(r"^:(\d{2}[A-Z]?):", re.M)
def split_tags(block4: str):
"""Return [(tag, value)] with continuation lines kept inside the value."""
body = block4.strip().removeprefix("{4:").removesuffix("-}").strip()
parts = TAG.split(body)
return [(parts[i], parts[i + 1].strip("\r\n")) for i in range(1, len(parts), 2)]
LINE_61 = re.compile(r"""
(?P<vdate>\d{6})
(?P<edate>\d{4})?
(?P<mark>RC|RD|C|D)
(?P<funds>[A-Z])?
(?P<amount>\d[\d,]{0,14})
(?P<ttype>[SNF][A-Z0-9]{3})
(?P<custref>(?:(?!//)[^\n]){1,16})
(?://(?P<bankref>[^\n]{1,16}))?
(?:\n(?P<supp>[^\n]{1,34}))?
$""", re.X)
def _yymmdd(s: str) -> date:
return date(2000 + int(s[:2]), int(s[2:4]), int(s[4:6]))
def _entry_date(vdate: date, mmdd: str) -> date:
m, d = int(mmdd[:2]), int(mmdd[2:])
year = vdate.year
if vdate.month == 12 and m == 1:
year += 1 # booked in January for a December value date
elif vdate.month == 1 and m == 12:
year -= 1 # booked in December, value-dated into January
return date(year, m, d)
def parse_61(value: str, account: str, currency: str) -> StatementLine:
m = LINE_61.match(value)
if not m:
raise ValueError(f"bad :61: {value!r}")
vdate = _yymmdd(m["vdate"])
amt = Decimal(m["amount"].replace(",", "."))
mark = m["mark"]
sign = 1 if mark in ("C", "RD") else -1 # RD reverses a debit, so it adds
return StatementLine(
account=account, currency=currency, amount=sign * amt,
value_date=vdate,
booking_date=_entry_date(vdate, m["edate"]) if m["edate"] else None,
bank_ref=(m["bankref"] or "").strip(),
end_to_end=m["custref"].strip(),
tx_code=m["ttype"], text=(m["supp"] or "").strip(),
reversal=mark.startswith("R"))
def parse_mt940(block4: str):
tags = split_tags(block4)
account = next(v for t, v in tags if t == "25")
opening = next(v for t, v in tags if t in ("60F", "60M"))
currency = opening[7:10]
lines, last = [], None
for t, v in tags:
if t == "61":
last = parse_61(v, account, currency)
lines.append(last)
elif t == "86" and last is not None:
last.text = (last.text + " " + v.replace("\n", "")).strip()
last = None # a trailing :86: after :62F: describes the statement
return lines, tags
A few design choices deserve explanation. The year prefix 2000 + is a simplification that holds for current data; a production parser should apply a pivot year. The sign logic treats RD as a credit-side movement because it reverses an earlier debit, and RC as a debit-side movement because it reverses an earlier credit. The :86: handler attaches narrative only to the immediately preceding :61:; a second :86: after the closing balance describes the statement as a whole and must not be glued onto the last transaction. Finally, the parser keeps the raw tag list so the integrity gate can read :28C:, :60F: and :62F: without re-parsing.
Run against a sample statement whose :61: line is 2611161116C1250,00NTRFINV-2026-0042//BK7781234, the parser yields a credit of 1,250.00 EUR with value and booking date 16 November 2026, type NTRF, customer reference INV-2026-0042 and bank reference BK7781234. A line 2611171116RC300,00NTRFNONREF//BK7781299 yields −300.00 with the reversal flag set, value date 17 November and booking date 16 November. That one line is a reminder that booking and value dates diverge in ordinary data.
The camt.053 parser with lxml
The camt.053 parser walks Stmt, then Ntry, then TxDtls. It uses lxml’s {*} namespace wildcard so the same code reads .001.02 and .001.08 documents, and it disables entity resolution and network access to avoid XML external entity (XXE) attacks on files received from outside.
from lxml import etree
SAFE = etree.XMLParser(resolve_entities=False, no_network=True, huge_tree=False)
def _t(el, path):
r = el.find(path)
return r.text.strip() if r is not None and r.text else ""
def parse_camt053(xml_bytes: bytes):
root = etree.fromstring(xml_bytes, SAFE)
out = []
for stmt in root.iterfind(".//{*}Stmt"):
acct = _t(stmt, "{*}Acct/{*}Id/{*}IBAN") or _t(stmt, "{*}Acct/{*}Id/{*}Othr/{*}Id")
for ntry in stmt.iterfind("{*}Ntry"):
# .001.02: <Sts>BOOK</Sts> .001.08: <Sts><Cd>BOOK</Cd></Sts>
sts = _t(ntry, "{*}Sts/{*}Cd") or _t(ntry, "{*}Sts")
if sts != "BOOK":
continue
amt_el = ntry.find("{*}Amt")
sign = 1 if _t(ntry, "{*}CdtDbtInd") == "CRDT" else -1
vd = _t(ntry, "{*}ValDt/{*}Dt") or _t(ntry, "{*}ValDt/{*}DtTm")[:10]
bd = _t(ntry, "{*}BookgDt/{*}Dt") or _t(ntry, "{*}BookgDt/{*}DtTm")[:10]
dom = ntry.find("{*}BkTxCd/{*}Domn")
code = "" if dom is None else "/".join([
_t(dom, "{*}Cd"), _t(dom, "{*}Fmly/{*}Cd"), _t(dom, "{*}Fmly/{*}SubFmlyCd")])
txs = ntry.findall("{*}NtryDtls/{*}TxDtls")
if len(txs) <= 1:
tx = txs[0] if txs else None
out.append(StatementLine(
account=acct, currency=amt_el.get("Ccy"),
amount=sign * Decimal(amt_el.text),
value_date=date.fromisoformat(vd),
booking_date=date.fromisoformat(bd) if bd else None,
bank_ref=_t(ntry, "{*}AcctSvcrRef"),
end_to_end=_t(tx, "{*}Refs/{*}EndToEndId") if tx is not None else "",
tx_code=code,
text=" ".join(x.text for x in ntry.iterfind(".//{*}RmtInf/{*}Ustrd")),
reversal=_t(ntry, "{*}RvslInd") == "true"))
else:
# batch booking: one Ntry, many TxDtls -> explode to transaction level
for tx in txs:
tamt = tx.find("{*}Amt")
out.append(StatementLine(
account=acct, currency=tamt.get("Ccy"),
amount=sign * Decimal(tamt.text),
value_date=date.fromisoformat(vd),
booking_date=date.fromisoformat(bd) if bd else None,
bank_ref=_t(ntry, "{*}AcctSvcrRef"),
end_to_end=_t(tx, "{*}Refs/{*}EndToEndId"),
tx_code=code,
text=" ".join(x.text for x in tx.iterfind("{*}RmtInf/{*}Ustrd"))))
return out
The batch branch is the important one. When a bank books a 700.00 EUR debit made of two supplier payments of 400.00 and 300.00, the parser emits two canonical lines carrying end-to-end references PAY-1 and PAY-2. Each can then match its own payable exactly. An MT940 for the same booking would usually show one 700.00 line, and the reconciliation engine would need a many-to-one rule to recover what camt.053 states explicitly.
The parser skips non-BOOK entries, which is correct for statements and deliberate for intraday camt.052, where pending entries belong in a provisional store rather than in the matcher. It also falls back from Dt to DtTm, because both choices are legal for booking and value dates. In production you would also capture Bal elements for the balance gate, StmtPgntn for multi-page statements, and structured remittance from RmtInf/Strd.
BAI2 control-total validation
For BAI2, validate control totals before trusting any detail. The function below joins 88 continuation records onto their predecessor and recomputes each account’s control total from 03 and 16 amounts.
def check_bai2(text: str):
recs = []
for raw in text.strip().splitlines():
raw = raw.rstrip()
if raw.startswith("88,"):
recs[-1] += "," + raw[3:] # continuation joins the previous record
else:
recs.append(raw)
acct_sum, errors = 0, []
for r in recs:
f = r.rstrip("/").split(",")
if f[0] == "03":
acct_sum, vals = 0, f[3:]
for i in range(0, len(vals) - 1, 4): # type, amount, count, funds
if vals[i + 1].lstrip("+-").isdigit():
acct_sum += int(vals[i + 1])
elif f[0] == "16" and f[2].lstrip("+-").isdigit():
acct_sum += int(f[2])
elif f[0] == "49" and int(f[1]) != acct_sum:
errors.append(f"account total {f[1]} != computed {acct_sum}")
return errors
On a sample with an 03 record carrying opening ledger 5000000 and closing ledger 5725000, a 16 credit of 125000 continued by an 88 record, and a 16 debit of 30000, the computed total is 10880000. A 49 record stating 10880000 passes; one stating 10880001 is reported. This simplified checker assumes funds types without trailing fields on the 03 record. A full parser must read the funds type and consume the extra S, V or D fields before moving to the next type code, and it must verify record counts as well as amounts.
Balance continuity: the cheapest gate that catches the most
The balance gate needs no format knowledge once data is canonical. Opening balance plus the sum of signed entries must equal the closing booked balance. In the sample MT940, the opening is 50,000.00 EUR and the entries are +1,250.00, +4,100.00, +2,975.00 and −300.00, so the closing :62F: must be 58,025.00.
def check_continuity(opening: Decimal, lines, closing: Decimal) -> Optional[Decimal]:
diff = opening + sum(l.amount for l in lines) - closing
return None if diff == 0 else diff
If the check fails, the difference is diagnostic. A difference equal to one entry suggests a dropped or duplicated line. A difference equal to a batch total suggests the parser exploded a batch and also kept the batch line. A difference that is a multiple of 10 or 100 of an entry often means the decimal handling failed.
Building the Matching Engine for Automated Cash Reconciliation
Clean canonical entries make matching tractable. Automated cash reconciliation then becomes a cascade of passes ordered from most certain to least certain, where each pass only sees what the previous passes left. Figure 3 shows the cascade.

Figure 3: The four-pass matching cascade. Only the first three passes auto-match; fuzzy results are proposals that a human confirms, and every exception can produce a new rule.
The figure starts with a booked canonical entry. Pass 1 tries an exact reference and amount match. Pass 2 applies rules that extract references, such as invoice numbers, from remittance text. Pass 3 searches for many-to-one combinations, where one bank entry settles several open items. Pass 4 produces fuzzy proposals using amount tolerance, date windows and name similarity. Hits in passes 1 to 3 post automatically. Fuzzy hits go to a human. Misses become reason-coded exceptions, and resolved exceptions can create new rules or aliases that feed back into pass 2.
Why the order of passes matters
Each pass trades precision for recall. An exact match on EndToEndId plus amount is close to certain, because the payer generated the reference and the bank carried it end to end. A rule-based match on an invoice number extracted from free text is very likely right but can be fooled by a customer quoting the wrong invoice. A many-to-one match proves only that some subset of open items sums to the bank amount; with many small invoices, several subsets can sum to the same total. A fuzzy match is a hypothesis.
Running passes in this order means each entry is claimed by the most certain evidence available. It also means open items consumed by high-confidence passes are no longer candidates for low-confidence ones, which shrinks the search space and the false-positive rate. The reconciliation engine architecture post on this site covers the engine’s storage and scaling model; here the focus is how statement formats feed it.
A compact matching engine
from difflib import SequenceMatcher
from itertools import combinations
@dataclass
class OpenItem:
id: str
amount: Decimal # signed, same convention as StatementLine
currency: str
due: date
reference: str
counterparty: str
matched: bool = False
INV = re.compile(r"\bINV[-/ ]?\d{4}[-/ ]?\d{3,6}\b", re.I)
def _norm(s):
return re.sub(r"[^A-Z0-9]", "", s.upper())
def match(lines, items, fee_tolerance=Decimal("25.00"), window=3, max_k=4):
results = []
for ln in lines:
open_ = [i for i in items if not i.matched and i.currency == ln.currency]
hit = None
# pass 1: exact reference + exact amount
for it in open_:
if ln.end_to_end and _norm(ln.end_to_end) == _norm(it.reference) \
and it.amount == ln.amount:
hit = ("exact", [it], Decimal(0)); break
# pass 2: rule-based reference extracted from remittance text
if not hit:
refs = {_norm(r) for r in INV.findall(ln.text + " " + ln.end_to_end)}
for it in open_:
if _norm(it.reference) in refs and it.amount == ln.amount:
hit = ("rule", [it], Decimal(0)); break
# pass 3: many-to-one, one bank line settles several items
if not hit:
cands = [i for i in open_ if (i.amount > 0) == (ln.amount > 0)
and _norm(i.counterparty)[:6] in _norm(ln.text)][:20]
for k in range(2, max_k + 1):
combo = next((c for c in combinations(cands, k)
if sum(x.amount for x in c) == ln.amount), None)
if combo:
hit = ("many-to-one", list(combo), Decimal(0)); break
# pass 4: fuzzy proposal, never auto-posted
if not hit:
best, best_s = None, 0.0
for it in open_:
diff = abs(abs(it.amount) - abs(ln.amount))
if diff > fee_tolerance or abs((ln.value_date - it.due).days) > window:
continue
cp = _norm(it.counterparty)
s = SequenceMatcher(None, cp, _norm(ln.text)).find_longest_match().size / max(1, len(cp))
s -= float(diff / fee_tolerance) * 0.2
if s > best_s:
best, best_s = it, s
if best and best_s >= 0.6:
hit = ("fuzzy-proposal", [best], abs(abs(best.amount) - abs(ln.amount)))
if hit and hit[0] != "fuzzy-proposal":
for it in hit[1]:
it.matched = True
results.append((ln, hit))
return results
The many-to-one pass bounds its search on purpose. Subset sum is NP-complete in general, and the number of combinations of 20 candidates taken up to 4 at a time is 6,175, which is cheap. Taken up to 10 at a time it exceeds 600,000 per entry, and with hundreds of unmatched entries the batch window disappears. The candidate filter, here a crude counterparty-prefix check, is what keeps the search small. In production you would key candidates on a resolved customer ID from a payer-alias table rather than on text.
The fuzzy pass scores counterparty-name overlap and penalises amount differences, within a date window. The 0.6 threshold and the 25.00 tolerance are illustrative, not recommendations. Tune them on labelled historical data per bank and per entry type, and measure precision of proposals, not just recall.
Worked example: one statement, four outcomes
Consider the sample MT940 used above, reconciled against four open receivables. The numbers are illustrative. Open items are AR1 (Acme GmbH, INV-2026-0042, 1,250.00 EUR), AR2 (Beta Logistics SARL, INV-2026-0050, 1,800.00), AR3 (Beta Logistics SARL, INV-2026-0051, 2,300.00) and AR4 (Gamma Retail BV, INV-2026-0060, 3,000.00).
| Statement entry | Evidence available | Pass that fires | Outcome |
|---|---|---|---|
| +1,250.00, ref INV-2026-0042 | Exact reference and amount | Pass 1 exact | AR1 cleared automatically |
| +4,100.00, ref NONREF, narrative “BETA LOGISTICS SARL PAYMENT INV-2026-0050 INV-2026-0051” | No single item equals 4,100.00 | Pass 3 many-to-one | AR2 + AR3 cleared automatically |
| +2,975.00, narrative “GAMMA RETAIL BV INVOICE 0060” | Name match, amount short by 25.00, date within window | Pass 4 fuzzy | Proposal to AR4 with 25.00 difference |
| −300.00, mark RC | Reversal of an earlier credit, no open item | None | Exception: “credit reversed” |
The run, using the code above, reproduces this table exactly. Two outcomes deserve comment. The 4,100.00 receipt quoted both invoice numbers, so a smarter pass 2 could have matched it as a rule-based multi-invoice payment, which is more certain than a subset-sum search. That is a typical rule learned from exceptions. The 2,975.00 receipt is short by 25.00, which may be an intermediary bank fee deducted in transit or a customer short-payment. The engine cannot know which, so it proposes and asks. The analyst’s decision becomes training data: if the same payer is short by a similar fee every month, a rule can post the difference to a bank-charges account automatically, subject to your accounting policy.
The reversal shows why the reversal flag belongs in the canonical model. An RC line is not a new outgoing payment. It undoes a prior credit, so the correct action is to find the original matched credit and reopen the item it cleared. Without the flag, the engine would hunt for a 300.00 payable and fail.
The exception workflow and the intraday-to-end-of-day handover
Exceptions are not leftovers; they are the product’s user interface. Each exception needs a reason code (no candidate, amount mismatch, ambiguous many-to-one, unknown transaction code, reversal, duplicate suspected, integrity hold), an owner, an age and an audit trail of the decision. Ageing buckets drive operational priorities, and reason-code counts drive engineering priorities: if “unknown transaction code” dominates, fix the mapping table rather than hiring more analysts.

Figure 4: Intraday reports create provisional matches; the end-of-day statement either confirms them or, if the sequence check fails, holds the statement for an analyst.
Figure 4 follows a business day. The bank sends intraday camt.052 or MT942 reports; ingestion flags those entries as provisional, and reconciliation updates the intraday treasury position. At end of day the bank sends camt.053 or MT940. Ingestion checks the statement sequence number and file hash. If a duplicate or a gap appears, the statement is held and an integrity exception goes to a cash operations analyst. Otherwise booked entries replace provisional ones, intraday matches are confirmed or unwound, the final position and closing balance go to treasury, and unmatched items reach analysts with reason codes. Analyst resolutions flow back as write-offs, manual matches or new rules.
The replacement step needs a join key between intraday and end-of-day entries. With camt, AcctSvcrRef or NtryRef usually survives from camt.052 to camt.053, but confirm this with each bank. With MT942 and MT940, the bank reference after // often works but is not guaranteed unique. A fallback composite key of account, amount, value date and normalised reference handles most cases, with a manual queue for the rest.
Decision table: which format to ask your bank for
The right format depends on region, bank capability and how much structure your matcher can use. The table below summarises the trade-offs.
| Situation | Preferred format | Why | Watch out for |
|---|---|---|---|
| New multi-bank integration, EU or global | camt.053 (plus camt.052 intraday) | Typed balances, ISO bank transaction codes, end-to-end references, batch detail | Bank-specific usage of optional elements; version differences such as Sts |
| Interbank or correspondent reporting over Swift | camt.053 by November 2027 | Swift roadmap makes camt receipt mandatory from November 2027 | No Swift conversion from MT9xx; agree formats bilaterally |
| US domestic banks via host-to-host | BAI2 or BTRS now, camt.053 where offered | Universal support, control totals | Custom 900-range type codes, funds-type field variability |
| Legacy ERP that only imports MT940 | MT940 short term, with a camt adapter plan | Avoids ERP change today | :86: truncation, lost batch detail, year inference |
| High-volume SEPA collections or payouts | camt.053 with TxDtls or camt.054 |
Per-transaction references inside batch bookings | Large files; stream-parse instead of loading the full tree |
| Intraday liquidity monitoring | camt.052 or MT942 | Timely, includes pending items | Provisional data; never post to ledger from it |
The pattern is consistent. Ask for camt.053 wherever the bank can supply it with populated TxDtls, keep MT940 and BAI2 adapters for banks that cannot, and make the canonical model rich enough that the richer format pays off immediately.
Trade-offs, Gotchas, and What Goes Wrong
Duplicate statements. Banks resend statements after outages, SFTP clients retry, and Swift users sometimes request a re-send with MT920. A content hash catches byte-identical copies only. Add a business key of account, statement identifier and sequence number, and an entry-level key. Without it, the second copy creates duplicate unmatched credits that analysts may “match” to the wrong items.
Missing sequence numbers. A gap in :28C: or ElctrncSeqNb means a statement never arrived. Note that ElctrncSeqNb is optional in the base camt.053 schema, although some market practice guides make it mandatory, so confirm each bank populates it. If not, fall back to balance continuity across days, which also detects gaps.
Value date versus booking date. Booking date is when the bank posted the entry; value date is when funds start or stop earning interest. They diverge for back-valued corrections, weekend processing and cross-border flows. Use booking date for statement continuity and ledger posting periods, and value date for interest, liquidity and matching windows. Mixing them creates false breaks around month-end.
FX and multi-currency accounts. A receivable invoiced in USD may arrive in a EUR account after conversion. camt.053 can carry instructed amount and exchange information in AmtDtls; MT940 rarely can. Match on the original currency when it is present, otherwise apply rate tolerances explicitly. Rounding to minor units must follow each currency’s exponent, not two decimals everywhere, as our multi-currency ledger architecture post explains.
Batch bookings. One debit for 500 payments cannot be matched to 500 payables without detail. Insist on TxDtls, or use camt.054 notifications, or reconcile against your own payment-file batch IDs. Never keep both the batch line and its exploded lines in the matcher.
Narrative truncation and character sets. MT :86: is capped at six lines of 65 characters and uses a restricted character set, so names lose accents and remittance gets cut. Fuzzy name matching must tolerate that. BAI2 text has its own bank-specific limits.
Reversals and returns. RC/RD marks, RvslInd, and return transaction codes all mean “undo.” Model them as links to the original entry, not as fresh transactions.
Year and timezone inference. MT940 entry dates lack a year, and DtTm values can carry offsets. Normalise to the account’s booking calendar.
Practical Recommendations
Start from the data model, not the parser. Write down the canonical entry and statement records, including fields your current banks do not send yet. Then build adapters that fill them, and make every adapter fail loudly on anything it does not understand. A rejected statement on Tuesday morning is a ticket; a silently mis-parsed one is a quarter-end restatement.
Engage banks early on the 2027 milestone. Swift’s roadmap tells counterparties to agree formatting and reconciliation requirements before camt receipt becomes mandatory, and corporate channels will follow the same direction. Request sample camt.053 files with real batch bookings, returns and fees, and test against them before go-live. Ask explicitly whether TxDtls, EndToEndId, ElctrncSeqNb and structured remittance will be populated.
Measure the system as a pipeline. Track parse rejects per bank, integrity holds, auto-match rate per pass, fuzzy proposal acceptance rate, exception ageing and the share of exceptions by reason code. These numbers tell you whether the next improvement is a parser fix, a bank conversation, a new rule or a data-model change.
- Land raw files immutably with a hash; make parsing replayable.
- Normalise amounts to signed decimals in currency minor units.
- Gate on sequence, balance continuity and duplicates before matching.
- Keep booking date and value date as separate fields everywhere.
- Explode batch bookings once, and drop the batch line from matching.
- Order matching passes from exact to fuzzy; never auto-post fuzzy results.
- Version per-bank transaction-code maps and narrative profiles.
- Treat intraday matches as provisional until the end-of-day statement confirms them.
- Track auto-match rate and exception reasons per bank and per pass.
Frequently Asked Questions
What is the main difference between MT940 and camt.053?
MT940 is a Swift FIN text message with tagged fields, where each transaction is a compact :61: line plus an optional free-text :86: narrative of up to six 65-character lines. camt.053 is an ISO 20022 XML statement with typed balances, separate booking and value dates, a three-level bank transaction code, end-to-end references and structured remittance. Both report the same booked activity, but camt.053 preserves far more of the data a reconciliation engine needs, especially for batch bookings and cross-border payments.
Is MT940 being discontinued?
For interbank traffic over Swift, the CBPR+ roadmap makes camt.052, camt.053 and camt.054 mandatory to receive from November 2027 and plans the end of MT/MX coexistence for statements in Standards Release 2028, with enforcement depending on community adoption. Swift states it will not convert MT9xx messages to camt. Corporate-to-bank channels are not bound by the same dates, and many banks will continue to offer MT940 to corporates for some time. Check each bank’s published roadmap for your channel.
What is the BAI2 format used for?
BAI2 is a comma-delimited cash management balance reporting format widely used by US banks to deliver prior-day and current-day balances and transaction detail. Files are organised as file, group and account levels with header and trailer records (01/99, 02/98, 03/49), 16 transaction detail records and 88 continuations. Its control totals make integrity checks straightforward. The X9 standards body, which holds the BAI2 copyright since 2008, published the revised BTRS standard as ANSI X9.121-2016.
What is the difference between camt.052, camt.053 and camt.054?
camt.052 is the bank-to-customer account report, typically used for intraday balances and entries, including pending ones. camt.053 is the bank-to-customer statement, the booked end-of-day record used for accounting and reconciliation. camt.054 is the debit/credit notification, which reports individual movements as they occur, and is often used to deliver per-transaction detail behind batch bookings. A typical architecture uses camt.052 for liquidity, camt.053 for ledger posting and camt.054 to enrich batches.
How do I reconcile a batch booking that appears as one line in MT940?
If the bank cannot send camt.053 TxDtls or camt.054 notifications, reconcile against your own payment instruction file. The batch total, value date and a batch or payment-information reference usually let you match the single debit to the batch you sent, then clear the individual payables from the batch record. A subset-sum many-to-one search is a fallback, not a strategy. The durable fix is to request transaction-level detail from the bank.
What auto-match rate should automated cash reconciliation achieve?
There is no universal benchmark, because the rate depends on the share of payments carrying usable references, the format, customer behaviour and how exceptions are counted. Rather than chasing an external number, measure the rate per bank, per transaction type and per matching pass, and investigate the reason codes behind exceptions. Moving a bank from MT940 to camt.053 with populated end-to-end references, and adding rules learned from resolved exceptions, are typically the two biggest levers.
Further Reading
- Reconciliation engine architecture for payments and fintech — storage, scaling and state model for the matcher this post feeds.
- FIX to ISO 20022 migration architecture — how message-format migrations are staged without breaking downstream systems.
- Real-time treasury and intraday liquidity architecture — using camt.052 and MT942 data for intraday positions.
- Double-entry ledger database architecture — where matched entries are finally posted.
- ACH and NACHA payment rails architecture — the US file-based rail behind many BAI2 entries and returns.
References
- Swift, CBPR+ phase 2 detailed roadmap, v4.2 — statement and reporting message migration dates.
- ISO 20022 Registration Authority, External code sets, including Bank Transaction Code combinations.
- Payments Canada, Bank to customer statement V08 (camt.053.001.08) message definition.
- Nordea, Message implementation guide, camt.053.001.02.
- ANSI/ASC X9, X9.121-2016 Balance and Transaction Reporting Standard (BTRS).
- Federal Reserve Bank of Minneapolis Remittance Coalition, BTRS implementation orientation webinar (2012).
- Oracle NetSuite, BAI2 parser validations and Oracle JD Edwards, BAI2 transaction types.
- python-mt940 tag reference — an open-source
:61:grammar implementation.
By Riju — about
