#!/usr/bin/env python3
"""Independent GBP/USD SAR/WR rebuild from original pinned M1 ZIP files.

Only the frozen protocol, manifest and original source archives are inputs.
The implementation uses standard-library arrays, exact Fraction SAR and
integer Williams decisions, and Decimal50 account arithmetic. It imports no
other study module and requires no primary-engine output.
"""
from __future__ import annotations

import argparse
import array
import bisect
import copy
import datetime as dt
import gzip
import hashlib
import json
import re
import zipfile
from decimal import Decimal, getcontext
from fractions import Fraction
from pathlib import Path
from zoneinfo import ZoneInfo

getcontext().prec = 50
D = Decimal
F = Fraction
SCALE = 1000000
STEP = 14400
UTC = dt.timezone.utc
NY = ZoneInfo('America/New_York')
EXPECTED_PROTOCOL_SHA = '5803cd6dcda147d62db9f1ed99703cfb63665f4ea560077565b79b5102fcdff8'
EXPECTED_MANIFEST_SHA = 'b1ab8f1d2bbea5a99b5593d07046e0819ce1d3bc305095a2fa380a6a0ed5b183'
STATE_NAMES = ('incoming_sar', 'direction_before', 'ep_before', 'af_before',
               'sar', 'direction_after', 'ep', 'af', 'reversal', 'ep_updated',
               'raw_next', 'next_sar', 'clamp_applied')
FRACTION_NAMES = ('incoming_sar', 'ep_before', 'af_before', 'sar', 'ep', 'af',
                  'raw_next', 'next_sar')


def epoch(s):
    return int(dt.datetime.fromisoformat(s.replace('Z', '+00:00')).timestamp())


def iso(t):
    return dt.datetime.fromtimestamp(t, UTC).isoformat().replace('+00:00', 'Z')


def digest(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def decimal_fraction(v):
    return D(v.numerator) / D(v.denominator)


def price_int(s):
    if not re.fullmatch(r'[0-9]+(?:\.[0-9]+)?', s):
        raise ValueError('Invalid source price syntax')
    head, _, tail = s.partition('.')
    tail = tail.rstrip('0')
    if len(tail) > 6:
        raise ValueError('Source price finer than one millionth')
    value = int(head) * SCALE + int((tail + '000000')[:6])
    if value <= 0:
        raise ValueError('Source price is not positive')
    return value


def parse_line(line, days):
    fields = line.decode('ascii').rstrip('\r\n').split(';')
    if len(fields) != 6 or not re.fullmatch(r'\d{8} \d{6}', fields[0]):
        raise ValueError('Invalid M1 record')
    date, clock = fields[0].split(' ')
    hour, minute, second = int(clock[:2]), int(clock[2:4]), int(clock[4:])
    if hour > 23 or minute > 59 or second:
        raise ValueError('Source timestamp is not a valid minute anchor')
    if date not in days:
        day = dt.datetime(int(date[:4]), int(date[4:6]), int(date[6:]), tzinfo=UTC)
        days[date] = int(day.timestamp()) + 18000
    t = days[date] + hour * 3600 + minute * 60
    o, h, l, c = map(price_int, fields[1:5])
    if not (l <= o <= h and l <= c <= h):
        raise ValueError('Invalid OHLC bounds')
    return t, o, h, l, c


def original_line(raw, manifest, archive_index, row_number):
    item = manifest['files'][archive_index]
    member = next(m['name'] for m in item['members'] if m['name'].lower().endswith('.csv'))
    with zipfile.ZipFile(raw / item['file']) as archive:
        with archive.open(member) as stream:
            for n, line in enumerate(stream, 1):
                if n == row_number:
                    return line
    raise ValueError('Missing original duplicate record')


def unique_file_indices(columns, lines, name, duplicate_audit):
    n = len(columns['t'])
    ordered = all(columns['t'][i] < columns['t'][i + 1] for i in range(n - 1))
    indices = range(n) if ordered else sorted(range(n), key=columns['t'].__getitem__)
    previous = None
    for i in indices:
        if previous is not None and columns['t'][previous] == columns['t'][i]:
            if lines[previous] != lines[i]:
                raise ValueError('Conflicting duplicate timestamp in ' + name)
            duplicate_audit.append(dict(file=name, first_row=previous + 1,
                                        duplicate_row=i + 1,
                                        ts=int(columns['t'][i]),
                                        line_sha256=hashlib.sha256(lines[i]).hexdigest()))
            continue
        yield i
        previous = i


def load_minutes(raw, manifest, begin, end):
    raw = Path(raw)
    if len(manifest['files']) != 7:
        raise ValueError('Exactly seven pinned annual archives are required')
    all_columns = {k: array.array('q') for k in ('t', 'o', 'h', 'l', 'c')}
    origins = array.array('B')
    origin_rows = array.array('I')
    days, duplicates, backwards, sources = {}, [], [], []
    raw_rows = 0
    for archive_index, item in enumerate(manifest['files']):
        file = raw / item['file']
        if file.stat().st_size != item['bytes'] or digest(file) != item['sha256']:
            raise ValueError('Archive pin mismatch: ' + file.name)
        columns = {k: array.array('q') for k in ('t', 'o', 'h', 'l', 'c')}
        lines = []
        with zipfile.ZipFile(file) as archive:
            actual_members = [dict(name=m.filename, bytes=m.file_size,
                                   crc32=f'{m.CRC:08x}') for m in archive.infolist()]
            if actual_members != item['members']:
                raise ValueError('ZIP member identity mismatch: ' + file.name)
            if archive.testzip() is not None:
                raise ValueError('ZIP CRC failure: ' + file.name)
            csv_members = [m['name'] for m in actual_members if m['name'].lower().endswith('.csv')]
            if len(csv_members) != 1 or 'GBPUSD' not in csv_members[0]:
                raise ValueError('Unexpected source CSV identity')
            previous = None
            with archive.open(csv_members[0]) as stream:
                for row_number, line in enumerate(stream, 1):
                    values = parse_line(line, days)
                    if previous is not None and values[0] < previous:
                        backwards.append(dict(file=file.name, row=row_number,
                                              previous_ts=previous, ts=values[0]))
                    previous = values[0]
                    raw_rows += 1
                    for key, value in zip(columns, values, strict=True):
                        columns[key].append(value)
                    lines.append(line)
            retained = 0
            for i in unique_file_indices(columns, lines, file.name, duplicates):
                for key in all_columns:
                    all_columns[key].append(columns[key][i])
                origins.append(archive_index)
                origin_rows.append(i + 1)
                retained += 1
            sources.append(dict(file=file.name, sha256=item['sha256'],
                                bytes=item['bytes'], csv=csv_members[0],
                                crc_verified=True, raw_rows=len(lines),
                                distinct_rows=retained))
        del columns, lines
    n = len(all_columns['t'])
    ordered = all(all_columns['t'][i] < all_columns['t'][i + 1] for i in range(n - 1))
    order = range(n) if ordered else sorted(range(n), key=all_columns['t'].__getitem__)
    output = {k: array.array('q') for k in all_columns}
    previous = None
    fingerprint = hashlib.sha256()
    for i in order:
        t = int(all_columns['t'][i])
        if previous is not None and t == int(all_columns['t'][previous]):
            a = original_line(raw, manifest, origins[previous], origin_rows[previous])
            b = original_line(raw, manifest, origins[i], origin_rows[i])
            if a != b:
                raise ValueError('Conflicting duplicate across source archives')
            duplicates.append(dict(file=manifest['files'][origins[i]]['file'],
                                   first_file=manifest['files'][origins[previous]]['file'],
                                   first_row=int(origin_rows[previous]),
                                   duplicate_row=int(origin_rows[i]), ts=t,
                                   line_sha256=hashlib.sha256(b).hexdigest()))
            continue
        previous = i
        if not begin <= t < end:
            continue
        values = tuple(int(all_columns[k][i]) for k in output)
        for key, value in zip(output, values, strict=True):
            output[key].append(value)
        fingerprint.update((';'.join(map(str, values)) + '\n').encode('ascii'))
    if not output['t']:
        raise ValueError('No retained source minutes')
    summary = dict(source_files=7, sources=sources, rows=len(output['t']),
                   normalized_m1_rows=len(output['t']),
                   raw_rows_all_archives=raw_rows,
                   exact_duplicate_rows_removed=len(duplicates),
                   duplicate_audit=duplicates, source_backward_jumps=backwards,
                   invalid_count=0, duplicate_count=0,
                   first_ts=int(output['t'][0]), last_ts=int(output['t'][-1]),
                   price_scale=SCALE,
                   normalized_m1_sha256=fingerprint.hexdigest(),
                   quote_basis='observed Bid OHLC; Ask modeled',
                   volume_scope='placeholder discarded, not observed consolidated volume')
    return output, summary


def aggregate(minutes):
    bars, row = [], None
    for i, t in enumerate(minutes['t']):
        anchor = (t // STEP) * STEP
        if row is None or row['ts'] != anchor:
            if row is not None:
                bars.append(row)
            row = dict(ts=int(anchor), source_open_int=int(minutes['o'][i]),
                       source_high_int=int(minutes['h'][i]),
                       source_low_int=int(minutes['l'][i]),
                       source_close_int=int(minutes['c'][i]), n=1,
                       first_ts=int(t), last_ts=int(t))
        else:
            row['n'] += 1
            row['last_ts'] = int(t)
            row['source_high_int'] = max(row['source_high_int'], int(minutes['h'][i]))
            row['source_low_int'] = min(row['source_low_int'], int(minutes['l'][i]))
            row['source_close_int'] = int(minutes['c'][i])
    if row is not None:
        bars.append(row)
    for row in bars:
        for field in ('open', 'high', 'low', 'close'):
            row[field] = D(row['source_' + field + '_int']) / SCALE
        row['canonical'] = (row['n'] == 240 and row['first_ts'] == row['ts']
                            and row['last_ts'] == row['ts'] + STEP - 60)
    return bars


def sar_step(direction, incoming, ep, af, h, l, previous_h, previous_l):
    before, old_ep, old_af = direction, ep, af
    reversal = l <= incoming if direction == 1 else h >= incoming
    extension = False
    if reversal:
        direction = -direction
        dot = max(ep, previous_h, h) if direction == -1 else min(ep, previous_l, l)
        ep = l if direction == -1 else h
        af = F(1, 50)
    else:
        dot = incoming
        if (direction == 1 and h > ep) or (direction == -1 and l < ep):
            ep = h if direction == 1 else l
            af = min(af + F(1, 50), F(1, 5))
            extension = True
    raw = dot + af * (ep - dot)
    next_level = min(raw, previous_l, l) if direction == 1 else max(raw, previous_h, h)
    return dict(incoming_sar=incoming, direction_before=before,
                ep_before=old_ep, af_before=old_af, sar=dot,
                direction_after=direction, ep=ep, af=af, reversal=reversal,
                ep_updated=extension, raw_next=raw, next_sar=next_level,
                clamp_applied=next_level != raw)


def compute_indicators(bars):
    if len(bars) < 2:
        raise ValueError('SAR requires at least two observed H4 buckets')
    h = lambda i: F(bars[i]['source_high_int'], SCALE)
    l = lambda i: F(bars[i]['source_low_int'], SCALE)
    down, up = l(0) - l(1), h(1) - h(0)
    direction = -1 if down > 0 and down > up else 1
    incoming = l(0) if direction == 1 else h(0)
    ep = h(1) if direction == 1 else l(1)
    af = F(1, 50)
    true_ranges, atr = [], None
    for i, row in enumerate(bars):
        hi, lo = row['source_high_int'], row['source_low_int']
        previous_close = bars[i - 1]['source_close_int'] if i else row['source_close_int']
        tr = D(max(hi - lo, abs(hi - previous_close), abs(lo - previous_close))) / SCALE
        true_ranges.append(tr)
        if i == 13:
            atr = sum(true_ranges, D(0)) / 14
        elif i > 13:
            atr = (13 * atr + tr) / 14
        row['atr14'] = atr
        row['wr_num'] = row['wr_den'] = row['wr'] = None
        if i >= 13:
            window = bars[i - 13:i + 1]
            highest = max(r['source_high_int'] for r in window)
            lowest = min(r['source_low_int'] for r in window)
            width = highest - lowest
            row['wr_den'] = width
            if width:
                row['wr_num'] = -100 * (highest - row['source_close_int'])
                row['wr'] = D(row['wr_num']) / width
        if i == 0:
            row.update({name: None for name in STATE_NAMES})
            row['sar_exact'] = None
        else:
            # The second observed bucket uses its own H/L in both clamps.
            prior = i if i == 1 else i - 1
            state = sar_step(direction, incoming, ep, af, h(i), l(i), h(prior), l(prior))
            row['sar_exact'] = {name: [str(state[name].numerator), str(state[name].denominator)]
                                for name in FRACTION_NAMES}
            for name, value in state.items():
                row[name] = decimal_fraction(value) if isinstance(value, F) else value
            direction, incoming, ep, af = (state['direction_after'], state['next_sar'],
                                           state['ep'], state['af'])
        row['observed_index'] = i
        row['warmup_ready'] = i >= 99
        row['eligible'] = bool(i >= 99 and row['canonical'] and bars[i - 1]['canonical']
                               and row['ts'] - bars[i - 1]['ts'] == STEP
                               and row['wr_num'] is not None and atr is not None and atr > 0
                               and row['direction_after'] is not None
                               and bars[i - 1]['direction_after'] is not None)
        row['cross'] = row['direction_after'] if row['eligible'] and row['reversal'] and i > 1 else 0
        row['wr_gate'] = bool(row['cross'] and
                              ((row['wr_num'] > -50 * row['wr_den']) if row['cross'] == 1
                               else (row['wr_num'] < -50 * row['wr_den'])))
    return bars


def calendar(begin, end):
    day = dt.datetime.fromtimestamp(begin, UTC).astimezone(NY).date() - dt.timedelta(days=8)
    last = dt.datetime.fromtimestamp(end, UTC).astimezone(NY).date() + dt.timedelta(days=8)
    rolls, weights, fridays, sessions = [], [], [], []
    while day <= last:
        cutoff = int(dt.datetime.combine(day, dt.time(17), NY).timestamp())
        if day.weekday() < 5:
            rolls.append(cutoff)
            weights.append(3 if day.weekday() == 2 else 1)
        if day.weekday() == 4:
            fridays.append(cutoff)
        if day.weekday() == 6:
            closing = int(dt.datetime.combine(day + dt.timedelta(days=5), dt.time(17), NY).timestamp())
            sessions.append((cutoff, closing))
        day += dt.timedelta(days=1)
    prefix = [0]
    for weight in weights:
        prefix.append(prefix[-1] + weight)
    return dict(rolls=rolls, weights=weights, prefix=prefix, fridays=fridays, sessions=sessions)


def is_session(t, cal):
    return any(a <= t < b for a, b in cal['sessions'])


def rollover_units(cal, entry, event, kind):
    left = bisect.bisect_right(cal['rolls'], entry)
    right = (bisect.bisect_right(cal['rolls'], event) if kind == 'within_1m'
             else bisect.bisect_left(cal['rolls'], event))
    return cal['prefix'][right] - cal['prefix'][left]


def missing_in_sessions(left, right, cal):
    # Missing anchors are in [left,right), both already aligned to minute time.
    total = 0
    for start, stop in cal['sessions']:
        if stop <= left:
            continue
        if start >= right:
            break
        total += max(0, (min(right, stop) - max(left, start)) // 60)
    return total


def gap_summary(minutes, cal):
    gaps, inside, outside = [], 0, 0
    times = minutes['t']
    for i in range(1, len(times)):
        previous, current = int(times[i - 1]), int(times[i])
        if current - previous <= 60:
            continue
        total = (current - previous) // 60 - 1
        n = missing_in_sessions(previous + 60, current, cal)
        inside += n
        outside += total - n
        gaps.append(dict(left=previous, right=current, missing_minutes=total,
                         in_session_unobserved=n, outside_weekly_session=total - n))
    return dict(gaps=gaps, gap_count=len(gaps), missing_minutes=inside + outside,
                in_session_unobserved_minutes=inside,
                outside_weekly_session_minutes=outside)


def trade_missing(gaps, entry, exit_source_ts, cal):
    count = 0
    for gap in gaps:
        if gap['right'] <= entry:
            continue
        if gap['left'] >= exit_source_ts:
            break
        left = max(entry + 60, gap['left'] + 60)
        right = min(exit_source_ts, gap['right'])
        if left < right:
            count += missing_in_sessions(left, right, cal)
    return count


def costs(protocol, key):
    spec = protocol['costs'][key]
    pip = D(str(protocol['pip_size']))
    values = dict(spread=pip * D(str(spec['spread_pips'])),
                  slip=pip * D(str(spec['slippage_pips_per_leg'])),
                  commission=pip * D(str(spec['commission_pips_per_leg'])),
                  carry=pip * D(str(spec['carry_pips_per_rollover_unit'])))
    for name in tuple(values):
        value = values[name] * SCALE
        if value != value.to_integral_value():
            raise ValueError('A cost is not an exact source-price unit')
        values[name + '_int'] = int(value)
    return values


def next_sar_exit(bars, signal_index, direction, end):
    for row in bars[signal_index + 1:]:
        cutoff = row['ts'] + STEP
        if cutoff >= end:
            break
        if row['direction_after'] == -direction:
            return cutoff, not row['canonical']
    return None, False


def liquidation(minutes, entry_index, stop, direction, cost, time_due, week_due, sar_due, end):
    hard_time, hard_rank, hard_reason = min((time_due, 0, 'time'),
                                          (week_due, 1, 'week_close'),
                                          (end, 3, 'period_end'))
    intended = [(time_due, 0, 'time'), (week_due, 1, 'week_close'), (end, 3, 'period_end')]
    if sar_due is not None:
        intended.append((sar_due, 2, 'oscillator'))
    initial_deadline, _, initial_reason = min(intended)
    end_index = bisect.bisect_left(minutes['t'], end)
    last = end_index - 1
    if last < entry_index:
        raise ValueError('No permissible in-period execution minute')
    stop_scaled = stop * SCALE
    spread_scaled = cost['spread_int'] if direction == -1 else 0
    for j in range(entry_index, end_index):
        t = int(minutes['t'][j])
        opening = D(int(minutes['o'][j]) + spread_scaled)
        breached = opening <= stop_scaled if direction == 1 else opening >= stop_scaled
        if breached:
            return dict(index=j, event_ts=t, kind='open', ref=opening / SCALE,
                        reason='stop_gap', terminal_fallback=False,
                        deadline=initial_deadline, deadline_reason=initial_reason)
        due = []
        if time_due <= t:
            due.append((0, time_due, 'time'))
        if week_due <= t:
            due.append((1, week_due, 'week_close'))
        if sar_due is not None and sar_due <= t:
            due.append((2, sar_due, 'oscillator'))
        if due:
            _, deadline, reason = min(due)
            return dict(index=j, event_ts=t, kind='open', ref=opening / SCALE,
                        reason=reason, terminal_fallback=False,
                        deadline=deadline, deadline_reason=reason)
        extreme = D(int(minutes['l' if direction == 1 else 'h'][j]) + spread_scaled)
        touched = extreme <= stop_scaled if direction == 1 else extreme >= stop_scaled
        if touched:
            return dict(index=j, event_ts=t, kind='within_1m', ref=stop,
                        reason='stop', terminal_fallback=False,
                        deadline=initial_deadline, deadline_reason=initial_reason)
        if t + 60 == hard_time:
            reference = D(int(minutes['c'][j]) + spread_scaled) / SCALE
            return dict(index=j, event_ts=t + 60, kind='close', ref=reference,
                        reason=hard_reason, terminal_fallback=False,
                        deadline=hard_time, deadline_reason=hard_reason)
    reference = D(int(minutes['c'][last]) + spread_scaled) / SCALE
    return dict(index=last, event_ts=int(minutes['t'][last]) + 60,
                kind='close', ref=reference, reason='period_end',
                terminal_fallback=True, deadline=initial_deadline,
                deadline_reason=initial_reason)


def make_marks(bars, trades, cost, begin, end, cal, initial):
    marks, closed, occupancy_index = [], 0, 0
    realized = peak = initial
    occupied_count = 0
    for row in bars:
        if not begin <= row['ts'] < end:
            continue
        cutoff = min(end, row['ts'] + STEP)
        while closed < len(trades):
            trade = trades[closed]
            if (trade['exit_event_ts'] < cutoff or
                (trade['exit_event_ts'] == cutoff and trade['exit_event_kind'] == 'close')):
                realized = trade['cash_after']
                closed += 1
            else:
                break
        value = realized
        if closed < len(trades) and trades[closed]['entry_ts'] < cutoff:
            trade = trades[closed]
            kind = trade['exit_event_kind'] if trade['exit_event_ts'] == cutoff else 'within_1m'
            units = rollover_units(cal, trade['entry_ts'], cutoff, kind)
            quote = row['close'] + (cost['spread'] if trade['direction'] == -1 else 0)
            value = (trade['preentry_equity'] - trade['quantity'] * cost['commission']
                     + trade['direction'] * trade['quantity'] * (quote - trade['entry'])
                     - trade['quantity'] * cost['carry'] * units)
        while occupancy_index < len(trades):
            trade = trades[occupancy_index]
            if (trade['exit_event_ts'] < row['ts'] or
                (trade['exit_event_ts'] == row['ts'] and trade['exit_event_kind'] != 'within_1m')):
                occupancy_index += 1
            else:
                break
        occupied = (occupancy_index < len(trades)
                    and trades[occupancy_index]['entry_ts'] < cutoff)
        occupied_count += occupied
        peak = max(peak, value)
        drawdown = 100 * (peak - value) / peak
        marks.append(dict(ts=cutoff, bar_ts=row['ts'], equity=value,
                          cash=realized, drawdown_pct=drawdown, occupied=occupied))
    return marks, occupied_count


def median(values):
    values = sorted(values)
    n = len(values)
    if not n:
        return None
    return values[n // 2] if n % 2 else (values[n // 2 - 1] + values[n // 2]) / 2


def simulate(bars, minutes, protocol, model, cost_key, period, cal, gap_data):
    begin, end = map(epoch, protocol['periods'][period])
    cost = costs(protocol, cost_key)
    initial = D(str(protocol['account']['initial_cash']))
    cash, trades, candidates, previous_trade = initial, [], [], None
    for index, row in enumerate(bars):
        t = row['ts'] + STEP
        direction = row['cross']
        if not begin <= t < end or not direction:
            continue
        entry_index = bisect.bisect_left(minutes['t'], t)
        available = entry_index < len(minutes['t']) and minutes['t'][entry_index] == t
        session = is_session(t, cal)
        partial = sum(not b['canonical'] for b in bars[max(0, index - 25):index + 1])
        candidate = dict(signal_ts=row['ts'], decision_ts=t, direction=direction,
                         side='long' if direction == 1 else 'short',
                         wr=row['wr'], wr_num=row['wr_num'], wr_den=row['wr_den'],
                         wr_gate=row['wr_gate'], sar=row['sar'],
                         incoming_sar=row['incoming_sar'], next_sar=row['next_sar'],
                         ep=row['ep'], af=row['af'],
                         direction_before=row['direction_before'],
                         direction_after=row['direction_after'], reversal=row['reversal'],
                         partial_lookback_buckets=partial,
                         entry_quote_available=bool(available), weekly_session_open=bool(session))
        if model == 'primary' and not row['wr_gate']:
            action = 'wr_rejected'
        elif not session:
            action = 'outside_weekly_session'
        elif cash <= 0:
            action = 'insolvent'
        elif previous_trade and (t < previous_trade['exit_event_ts'] or
                                 (t == previous_trade['exit_event_ts']
                                  and previous_trade['exit_event_kind'] != 'close')):
            action = 'occupied'
        elif not available:
            action = 'missing_entry_open'
        else:
            bid = D(int(minutes['o'][entry_index])) / SCALE
            fill = bid + (cost['spread'] if direction == 1 else 0) + direction * cost['slip']
            distance = 2 * row['atr14']
            stop = fill - direction * distance
            bad = stop <= 0 or (stop >= bid if direction == 1 else stop <= bid + cost['spread'])
            if bad:
                action = 'invalid_stop'
            else:
                unit_loss = distance + cost['slip'] + 2 * cost['commission']
                risk_quantity = D(str(protocol['account']['risk_fraction'])) * cash / unit_loss
                capped_quantity = cash / (fill + cost['commission'])
                quantity = min(risk_quantity, capped_quantity)
                if not quantity.is_finite() or quantity <= 0 or not unit_loss.is_finite():
                    raise ValueError('Invalid quantity or planned loss')
                sar_due, exit_signal_partial = next_sar_exit(bars, index, direction, end)
                time_due = t + protocol['exits']['max_holding_h4_slots'] * STEP
                week_due = cal['fridays'][bisect.bisect_right(cal['fridays'], t)]
                exit_data = liquidation(minutes, entry_index, stop, direction, cost,
                                        time_due, week_due, sar_due, end)
                event, kind, j = exit_data['event_ts'], exit_data['kind'], exit_data['index']
                exit_fill = exit_data['ref'] - direction * cost['slip']
                units = rollover_units(cal, t, event, kind)
                fees = 2 * quantity * cost['commission']
                financing = quantity * cost['carry'] * units
                if kind == 'within_1m':
                    net_source_units = None
                    pnl = -quantity * (unit_loss + cost['carry'] * units)
                    pnl_sign = -1
                else:
                    exit_bid_int = int(minutes['c' if kind == 'close' else 'o'][j])
                    net_source_units = (direction * (exit_bid_int - int(minutes['o'][entry_index]))
                                        - cost['spread_int'] - 2 * cost['slip_int']
                                        - 2 * cost['commission_int'] - cost['carry_int'] * units)
                    pnl = quantity * net_source_units / SCALE
                    pnl_sign = (net_source_units > 0) - (net_source_units < 0)
                source_exit_ts = int(minutes['t'][j])
                exit_bar = (source_exit_ts // STEP) * STEP
                partial_holding = sum(not b['canonical'] for b in bars[index + 1:]
                                      if b['ts'] <= exit_bar and
                                      (b['ts'] < event or (b['ts'] == event and kind == 'within_1m')))
                missing = trade_missing(gap_data['gaps'], t, source_exit_ts, cal)
                total_missing = (source_exit_ts - t) // 60 - (j - entry_index)
                previous_trade = dict(
                    number=len(trades) + 1, model=model, cost=cost_key, period=period,
                    side='long' if direction == 1 else 'short', direction=direction,
                    signal_bar_ts=row['ts'], decision_ts=t, entry_ts=t,
                    exit_event_ts=event, exit_event_kind=kind,
                    source_exit_minute_ts=source_exit_ts, exit_bar_ts=exit_bar,
                    entry=fill, entry_ref=bid,
                    stop_bid_ref=stop - (cost['spread'] if direction == -1 else 0),
                    exit=exit_fill, exit_ref=exit_data['ref'],
                    exit_bid_ref=exit_data['ref'] - (cost['spread'] if direction == -1 else 0),
                    stop=stop, signal_atr=row['atr14'], signal_wr=row['wr'],
                    signal_sar=row['sar'], signal_incoming_sar=row['incoming_sar'],
                    signal_next_sar=row['next_sar'], signal_ep=row['ep'], signal_af=row['af'],
                    signal_direction_before=row['direction_before'],
                    signal_direction_after=row['direction_after'],
                    quantity=quantity, preentry_equity=cash, risk_cash=quantity * unit_loss,
                    lunit=unit_loss, notional=quantity * fill,
                    notional_capped=capped_quantity < risk_quantity,
                    pnl=pnl, pnl_sign=pnl_sign, net_unit_source_int=net_source_units,
                    net_r=pnl / (quantity * unit_loss), fees=fees, financing=financing,
                    rollover_units=units, cash_after=cash + pnl, reason=exit_data['reason'],
                    deadline=exit_data['deadline'], deadline_reason=exit_data['deadline_reason'],
                    oscillator_deadline=sar_due, terminal_fallback=exit_data['terminal_fallback'],
                    crosses_gap=missing > 0, missing_open_minutes_crossed=missing,
                    outside_session_missing_minutes=total_missing - missing,
                    partial_lookback_buckets=partial, partial_holding_buckets=partial_holding,
                    exit_signal_partial=exit_data['reason'] == 'oscillator' and exit_signal_partial,
                    delayed_exit=event > exit_data['deadline'],
                    early_terminal_proxy=exit_data['terminal_fallback'] and event < end,
                    holding_h4_slots_lower=D(event - t) / STEP,
                    holding_h4_slots_upper=D(event - t + (60 if kind == 'within_1m' else 0)) / STEP,
                    quote_side_exit='Bid' if direction == 1 else 'modeled Ask')
                cash += pnl
                trades.append(previous_trade)
                action = 'entry'
        candidates.append(dict(candidate, action=action))
    marks, occupied = make_marks(bars, trades, cost, begin, end, cal, initial)
    if marks and abs(marks[-1]['equity'] - cash) > D('1e-30'):
        raise ValueError('Terminal account mark fails cash reconciliation')
    profits = sum((t['pnl'] for t in trades if t['pnl_sign'] > 0), D(0))
    losses = -sum((t['pnl'] for t in trades if t['pnl_sign'] < 0), D(0))
    rs = [t['net_r'] for t in trades]
    sums = lambda field: sum((t[field] for t in trades), D(0))
    metrics = dict(
        return_pct=100 * (cash / initial - 1), end_cash=cash,
        trades=len(trades), wins=sum(t['pnl_sign'] > 0 for t in trades),
        losses=sum(t['pnl_sign'] < 0 for t in trades),
        breakevens=sum(t['pnl_sign'] == 0 for t in trades),
        profit_factor=profits / losses if losses else None,
        drawdown_pct=max((m['drawdown_pct'] for m in marks), default=D(0)),
        mean_r=sum(rs, D(0)) / len(rs) if rs else None, median_r=median(rs),
        sum_r=sum(rs, D(0)), fees=sums('fees'), financing=sums('financing'),
        rollover_units=sum(t['rollover_units'] for t in trades),
        exposure_pct=D(100 * occupied) / len(marks) if marks else D(0),
        notional_capped=sum(t['notional_capped'] for t in trades),
        canceled_missing_entry=sum(c['action'] == 'missing_entry_open' for c in candidates),
        invalid_stop=sum(c['action'] == 'invalid_stop' for c in candidates),
        gap_trades=sum(t['crosses_gap'] for t in trades),
        partial_trades=sum(t['partial_holding_buckets'] > 0 for t in trades),
        partial_lookback_trades=sum(t['partial_lookback_buckets'] > 0 for t in trades),
        partial_exit_signal_trades=sum(t['exit_signal_partial'] for t in trades),
        delayed_oscillator_exits=sum(t['reason'] == 'oscillator' and t['delayed_exit'] for t in trades),
        delayed_time_week_exits=sum(t['reason'] in ('time', 'week_close') and t['delayed_exit'] for t in trades),
        early_terminal_proxies=sum(t['early_terminal_proxy'] for t in trades),
        spread_cost=sum((t['quantity'] * cost['spread'] for t in trades), D(0)),
        slippage_cost=sum((2 * t['quantity'] * cost['slip'] for t in trades), D(0)),
        turnover=sum((t['quantity'] * (abs(t['entry']) + abs(t['exit'])) for t in trades), D(0)) / initial,
        long_trades=sum(t['direction'] == 1 for t in trades),
        short_trades=sum(t['direction'] == -1 for t in trades), sample_limited=len(trades) < 30)
    annual, opening_value, groups = [], initial, {}
    for mark in marks:
        year = dt.datetime.fromtimestamp(mark['bar_ts'], UTC).year
        groups[year] = mark['equity']
    for year, value in groups.items():
        annual.append(dict(year=year, return_pct=100 * (value / opening_value - 1),
                           start_equity=opening_value, end_equity=value))
        opening_value = value
    return dict(model=model, cost=cost_key, period=period, start_ts=begin, end_ts=end,
                metrics=metrics, trades=trades, equity=marks, annual=annual, candidates=candidates)


def source_observation(minutes, index, role):
    return dict(role=role, ts=int(minutes['t'][index]),
                **{name: D(int(minutes[key][index])) / SCALE
                   for name, key in [('open', 'o'), ('high', 'h'), ('low', 'l'), ('close', 'c')]},
                **{'source_' + name + '_int': int(minutes[key][index])
                   for name, key in [('open', 'o'), ('high', 'h'), ('low', 'l'), ('close', 'c')]})


def choose_gallery(runs, bars, minutes):
    early = runs['primary_base_early']['trades']
    later = runs['primary_base_later']['trades']
    first_later = later[0] if later else None
    opposite = (next((t for t in later[1:] if t['pnl_sign'] * first_later['pnl_sign'] < 0), None)
                if first_later else None)
    choices = [('early', early[0] if early else None, 'first_early'),
               ('later', first_later, 'first_later'),
               ('opposite', opposite or (later[1] if len(later) > 1 else None),
                'opposite_sign' if opposite else 'next_later')]
    result, bar_index = [], {r['ts']: i for i, r in enumerate(bars)}
    for tag, trade, choice in choices:
        item = dict(tag=tag, available=trade is not None,
                    selection_kind=choice if trade else 'unavailable',
                    outcome_conditioned=tag == 'opposite' and opposite is not None)
        if trade is not None:
            a, b = bar_index[trade['signal_bar_ts']], bar_index[trade['exit_bar_ts']]
            entry_i = bisect.bisect_left(minutes['t'], trade['entry_ts'])
            exit_i = bisect.bisect_left(minutes['t'], trade['source_exit_minute_ts'])
            item.update(trade=trade, bars=bars[max(0, a - 20):min(len(bars), b + 4)],
                        source_minutes=[source_observation(minutes, entry_i, 'entry'),
                                        source_observation(minutes, exit_i, 'exit')])
        result.append(item)
    return result


def json_default(value):
    if isinstance(value, D):
        if not value.is_finite():
            raise ValueError('Nonfinite Decimal result')
        return str(value)
    raise TypeError(type(value).__name__)


def write_json(path, data):
    Path(path).write_text(json.dumps(data, ensure_ascii=False, indent=2,
                                     default=json_default, allow_nan=False) + '\n')


def synthetic_tests(protocol):
    assertions, cases = 0, []

    def check(name, condition):
        nonlocal assertions
        assertions += 1
        if not condition:
            raise AssertionError('Synthetic boundary failed: ' + name)
        cases.append(name)

    def throws(name, call):
        try:
            call()
        except (ValueError, OverflowError):
            check(name, True)
        else:
            check(name, False)

    def source_bars(n=100, gap_at=None, partial_at=None, flat=False):
        rows = []
        start = epoch('2019-06-03T00:00:00Z')
        for i in range(n):
            t = start + i * STEP + (STEP if gap_at is not None and i >= gap_at else 0)
            hi, lo = (1300000, 1300000) if flat else (1310000, 1290000)
            rows.append(dict(ts=t, source_open_int=1300000, source_high_int=hi,
                             source_low_int=lo, source_close_int=1300000,
                             open=D('1.3'), high=D(hi) / SCALE, low=D(lo) / SCALE,
                             close=D('1.3'), n=239 if i == partial_at else 240,
                             first_ts=t, last_ts=t + STEP - 60,
                             canonical=i != partial_at))
        return rows

    def minute_array(records):
        result = {k: array.array('q') for k in ('t', 'o', 'h', 'l', 'c')}
        for row in records:
            values = [row[0], *[price_int(str(x)) for x in row[1:]]]
            for key, value in zip(result, values, strict=True):
                result[key].append(value)
        return result

    def record(t, o='1.30000', h=None, l=None, c=None):
        return (t, o, h if h is not None else o,
                l if l is not None else o, c if c is not None else o)

    def fixture(direction=1, begin=None, end=None, records=None, partial_exit=False,
                no_sar=False, reverse_candidate=False, atr='0.001'):
        begin = epoch('2020-01-06T00:00:00Z') if begin is None else begin
        end = begin + 2 * STEP if end is None else end
        p = copy.deepcopy(protocol)
        p['periods'] = {'full': [iso(begin), iso(end)]}
        wr = D(-40 if direction == 1 else -60)

        def bar(t, after, crossing=0, canonical=True):
            b = dict(ts=t, open=D('1.3'), high=D('1.3015'), low=D('1.2995'),
                     close=D('1.3001') if t == begin else D('1.3011'),
                     source_open_int=1300000, source_high_int=1301500,
                     source_low_int=1299500, source_close_int=1300100 if t == begin else 1301100,
                     n=240 if canonical else 239, first_ts=t, last_ts=t + STEP - 60,
                     canonical=canonical, wr=wr, wr_num=int(wr * 10), wr_den=10,
                     atr14=D(atr), incoming_sar=D('1.29'), sar=D('1.29'),
                     next_sar=D('1.291'), ep=D('1.31'), af=D('0.04'),
                     direction_before=-after if crossing else after,
                     direction_after=after, reversal=bool(crossing),
                     ep_updated=False, clamp_applied=False,
                     warmup_ready=True, eligible=bool(crossing), cross=crossing,
                     wr_gate=True, observed_index=100)
            return b

        exit_direction = direction if no_sar else -direction
        bars = [bar(begin - STEP, direction, direction),
                bar(begin, exit_direction, -direction if reverse_candidate else 0,
                    not partial_exit),
                bar(begin + STEP, exit_direction)]
        if reverse_candidate:
            bars[1]['wr'] = D(-60 if direction == 1 else -40)
            bars[1]['wr_num'] = int(bars[1]['wr'] * 10)
        if records is None:
            records = [record(begin, '1.30000', '1.30050', '1.29950', '1.30010'),
                       record(begin + STEP, '1.30100', '1.30150', '1.30050', '1.30100'),
                       record(end - 60, '1.30100', '1.30150', '1.30050', '1.30110')]
        present = {b['ts'] for b in bars}
        for t in sorted({(r[0] // STEP) * STEP for r in records}):
            if t not in present:
                bars.append(bar(t, exit_direction))
                present.add(t)
        bars.sort(key=lambda b: b['ts'])
        minutes = minute_array(records)
        cal = calendar(begin, end)
        gaps = gap_summary(minutes, cal)
        return p, bars, minutes, cal, gaps

    def account(bundle, model='primary', cost='base'):
        p, bars, minutes, cal, gaps = bundle
        return simulate(bars, minutes, p, model, cost, 'full', cal, gaps)

    check('price_exact_millionth', price_int('1.234567000') == 1234567)
    throws('reject_nonrepresentable_price', lambda: price_int('1.0000001'))
    throws('reject_nonpositive_price', lambda: price_int('0.000000'))
    throws('reject_nonfinite_price', lambda: price_int('NaN'))
    fixed = parse_line(b'20200308 020000;1.3;1.4;1.2;1.3;0\n', {})
    check('source_fixed_EST_through_DST', fixed[0] == epoch('2020-03-08T07:00:00Z'))
    throws('reject_nonminute_source_stamp', lambda: parse_line(b'20200308 020001;1.3;1.4;1.2;1.3;0\n', {}))
    throws('reject_invalid_OHLC', lambda: parse_line(b'20200308 020000;1.3;1.2;1.1;1.3;0\n', {}))
    cols = {k: array.array('q', [v, v]) for k, v in zip(('t', 'o', 'h', 'l', 'c'), (60, 10, 11, 9, 10))}
    duplicate_audit = []
    check('collapse_byte_identical_duplicate', list(unique_file_indices(cols, [b'a\n', b'a\n'], 'fixture', duplicate_audit)) == [0] and len(duplicate_audit) == 1)
    throws('reject_conflicting_raw_duplicate', lambda: list(unique_file_indices(cols, [b'a\n', b'b\n'], 'fixture', [])))

    touch = sar_step(1, F(95), F(110), F(3, 25), F(112), F(95), F(109), F(96))
    check('SAR_equal_touch_reverses_first', touch['reversal'] and touch['direction_after'] == -1 and touch['sar'] == 112 and touch['af'] == F(1, 50) and not touch['ep_updated'])
    short_touch = sar_step(-1, F(110), F(95), F(1, 10), F(110), F(94), F(109), F(95))
    check('SAR_short_equal_touch_reverses', short_touch['reversal'] and short_touch['direction_after'] == 1 and short_touch['sar'] == 94)
    equal_ep = sar_step(1, F(90), F(110), F(3, 25), F(110), F(95), F(109), F(96))
    check('SAR_EP_equality_does_not_accelerate', not equal_ep['ep_updated'] and equal_ep['af'] == F(3, 25))
    cap = sar_step(1, F(90), F(110), F(1, 5), F(112), F(95), F(111), F(94))
    check('SAR_strict_extension_at_AF_cap', cap['ep_updated'] and cap['af'] == F(1, 5))
    clamp = sar_step(1, F(90), F(110), F(1, 50), F(112), F(95), F(111), F(451, 5))
    check('SAR_next_projection_clamp', clamp['raw_next'] == F(2272, 25) and clamp['next_sar'] == F(451, 5) and clamp['clamp_applied'])
    small = source_bars(2)
    small[0].update(source_high_int=10000000, source_low_int=9000000)
    small[1].update(source_high_int=11000000, source_low_int=10000000)
    seed = compute_indicators(small)
    check('SAR_first_output_absent', seed[0]['direction_after'] is None and seed[0]['sar'] is None)
    check('SAR_first_clamp_uses_current_HL', seed[1]['next_sar'] == D('9.04') and seed[1]['af'] == D('0.02'))
    tied = compute_indicators(source_bars(2))
    check('SAR_seed_tie_prefers_up_then_can_reverse', tied[1]['direction_before'] == 1 and tied[1]['reversal'] and tied[1]['direction_after'] == -1)
    warm = compute_indicators(source_bars(100, partial_at=50))
    check('warmup_99_not_ready_100_ready', not warm[98]['eligible'] and warm[99]['eligible'])
    check('earlier_partial_does_not_censor_entry', warm[99]['eligible'] and not warm[50]['canonical'])
    check('WR_exact_midpoint_rejects_both_directions', warm[99]['wr'] == -50 and not warm[99]['wr_gate'])
    partial_now = compute_indicators(source_bars(100, partial_at=99))
    check('signal_partial_bucket_blocks_entry', not partial_now[99]['eligible'])
    gap_rows = compute_indicators(source_bars(100, gap_at=30))
    continuous_rows = compute_indicators(source_bars(100))
    check('SAR_state_not_reset_by_calendar_gap', [b['sar_exact'] for b in gap_rows] == [b['sar_exact'] for b in continuous_rows])
    check('WR_flat_window_unavailable', compute_indicators(source_bars(100, flat=True))[-1]['wr_num'] is None)
    check('unrounded_WR_midpoint_positive', -99999999900 > -50 * 2000000000)
    check('unrounded_WR_midpoint_negative', -100000000100 < -50 * 2000000000)

    clock = calendar(epoch('2020-03-01T00:00:00Z'), epoch('2020-03-20T00:00:00Z'))
    check('NY_Friday_before_DST', epoch('2020-03-06T22:00:00Z') in clock['fridays'])
    check('NY_Friday_after_DST', epoch('2020-03-13T21:00:00Z') in clock['fridays'])
    friday = epoch('2020-03-13T21:00:00Z')
    check('Friday17_entry_excluded', not is_session(friday, clock) and is_session(friday - 60, clock))
    wed = epoch('2020-03-11T21:00:00Z')
    check('rollover_open_and_close_at_cutoff_excluded', rollover_units(clock, wed - 60, wed, 'open') == 0 and rollover_units(clock, wed - 60, wed, 'close') == 0)
    check('rollover_intraminute_cutoff_Wednesday_triple', rollover_units(clock, wed - 60, wed, 'within_1m') == 3)
    check('entry_exact_cutoff_excludes_preceding_interval', rollover_units(clock, wed, wed + 60, 'close') == 0)
    base_cost = costs(protocol, 'base')
    check('commission_is_2_50_per_100000_GBP', base_cost['commission'] * 100000 == D('2.5'))
    check('higher_slippage_exact_source_units', costs(protocol, 'higher')['slip_int'] == 30)

    bundle = fixture()
    run = account(bundle)
    trade = run['trades'][0]
    check('full_account_exact_next_open_entry', len(run['trades']) == 1 and trade['entry_ts'] == epoch('2020-01-06T00:00:00Z'))
    check('full_account_completed_SAR_next_open_exit', trade['reason'] == 'oscillator' and trade['exit_event_kind'] == 'open' and trade['exit_event_ts'] == trade['entry_ts'] + STEP)
    check('full_account_long_fill_and_separate_fees', trade['entry'] == D('1.30016') and trade['exit'] == D('1.30099') and trade['fees'] == 2 * trade['quantity'] * D('0.000025'))
    check('full_account_quote_PnL_reconciles_once', abs(trade['pnl'] - (trade['direction'] * trade['quantity'] * (trade['exit'] - trade['entry']) - trade['fees'] - trade['financing'])) < D('1e-40'))
    check('full_account_contract_cash_not_notional_debit', abs(trade['cash_after'] - (D(10000) + trade['pnl'])) < D('1e-40'))
    check('full_account_notional_cap_includes_entry_fee', trade['notional_capped'] and trade['quantity'] * (trade['entry'] + base_cost['commission']) <= D(10000) + D('1e-40'))
    check('full_account_R_denominator_fixed', abs(trade['risk_cash'] - trade['quantity'] * trade['lunit']) < D('1e-40') and abs(trade['net_r'] - trade['pnl'] / trade['risk_cash']) < D('1e-40'))
    check('preopening_mark_excludes_future_exit_costs', abs(run['equity'][0]['equity'] - (D(10000) - trade['quantity'] * base_cost['commission'] + trade['quantity'] * (D('1.3001') - trade['entry']))) < D('1e-40'))
    check('opening_exit_excluded_from_new_bucket_occupancy', run['equity'][0]['occupied'] and not run['equity'][1]['occupied'])

    no_open = fixture(records=[record(epoch('2020-01-06T04:00:00Z'), '1.301'), record(epoch('2020-01-06T07:59:00Z'), '1.301')])
    canceled = account(no_open)
    check('missing_entry_open_canceled_not_deferred', not canceled['trades'] and canceled['candidates'][0]['action'] == 'missing_entry_open')
    check('zero_trade_metrics', canceled['metrics']['return_pct'] == 0 and canceled['metrics']['drawdown_pct'] == 0 and canceled['metrics']['profit_factor'] is None and canceled['metrics']['mean_r'] is None)
    midpoint = fixture()
    midpoint[1][0].update(wr=D(-50), wr_num=-500, wr_den=10, wr_gate=False)
    check('control_removes_only_WR_gate', len(account(midpoint, 'primary')['trades']) == 0 and len(account(midpoint, 'no_wr')['trades']) == 1)
    check('invalid_known_open_stop_rejects_entire_entry', not account(fixture(atr='0.000001'))['trades'] and account(fixture(atr='0.000001'))['metrics']['end_cash'] == 10000)
    partial = account(fixture(partial_exit=True))
    check('future_partial_entry_bucket_does_not_censor', len(partial['trades']) == 1 and partial['trades'][0]['partial_holding_buckets'] > 0)
    check('partial_completed_opposite_SAR_can_exit', partial['trades'][0]['exit_signal_partial'] and partial['trades'][0]['reason'] == 'oscillator')

    start = epoch('2020-01-06T00:00:00Z')
    entry_stop = account(fixture(records=[record(start, '1.30000', '1.30050', '1.29700', '1.30010'), record(start + 2 * STEP - 60, '1.3')]))
    loss = entry_stop['trades'][0]
    check('entry_minute_stop_checked_after_fill', loss['reason'] == 'stop' and loss['exit_event_kind'] == 'within_1m' and loss['exit_event_ts'] == start)
    check('fixed_stop_net_loss_includes_both_fees_and_exit_slip', loss['net_r'] == -1 and loss['pnl'] == -loss['risk_cash'])
    short_gap = account(fixture(direction=-1, records=[record(start, '1.3', '1.3005', '1.2995', '1.3'), record(start + 60, '1.3019'), record(start + 2 * STEP - 60, '1.3')]))
    short = short_gap['trades'][0]
    check('short_opening_stop_uses_modeled_Ask', short['reason'] == 'stop_gap' and short['exit_ref'] == D('1.30205') and short['exit'] == D('1.30206') and short['quote_side_exit'] == 'modeled Ask')
    check('short_stop_plot_level_converted_to_Bid', short['stop_bid_ref'] == short['stop'] - base_cost['spread'])
    same_open = account(fixture(reverse_candidate=True))
    check('no_automatic_reverse_at_SAR_exit_opening', len(same_open['trades']) == 1 and same_open['candidates'][1]['action'] == 'occupied')
    intraminute_open = fixture(no_sar=True, reverse_candidate=True,
                              records=[record(start, '1.3'), record(start + STEP, '1.300', '1.301', '1.297', '1.300'), record(start + 2 * STEP - 60, '1.3')])
    intraminute_open[1][1]['direction_after'] = 1
    intraminute_open[1][1]['direction_before'] = -1
    occupied = account(intraminute_open)
    check('intraminute_exit_does_not_free_same_opening', len(occupied['trades']) == 1 and occupied['candidates'][1]['action'] == 'occupied' and occupied['trades'][0]['exit_event_kind'] == 'within_1m')

    delayed = fixture(records=[record(start, '1.3'), record(start + STEP + 120, '1.301'), record(start + 2 * STEP - 60, '1.301')])
    delayed[1][2]['direction_after'] = 1
    delayed_trade = account(delayed)['trades'][0]
    check('queued_SAR_exit_persists_to_later_actual_open', delayed_trade['reason'] == 'oscillator' and delayed_trade['exit_event_ts'] == start + STEP + 120 and delayed_trade['delayed_exit'])
    check('gap_diagnostic_does_not_remove_entry', delayed_trade['crosses_gap'] and delayed_trade['missing_open_minutes_crossed'] > 0)
    terminal = account(fixture(no_sar=True, records=[record(start, '1.3'), record(start + 60, '1.3001')]))['trades'][0]
    check('no_later_permissible_quote_uses_early_terminal_proxy', terminal['terminal_fallback'] and terminal['early_terminal_proxy'] and terminal['exit_event_ts'] == start + 120)
    break_even = account(fixture(records=[record(start, '1.3'), record(start + STEP, '1.30022'), record(start + 2 * STEP - 60, '1.30022')]))
    check('quoted_net_exact_zero_without_epsilon', break_even['trades'][0]['pnl'] == 0 and break_even['trades'][0]['pnl_sign'] == 0 and break_even['metrics']['breakevens'] == 1)
    zero = account(fixture(records=[record(start, '1.3'), record(start + STEP, '1.3'), record(start + 2 * STEP - 60, '1.3')]), cost='zero')
    check('zero_cost_neutral_trade_stays_zero', zero['trades'][0]['pnl'] == 0 and zero['trades'][0]['fees'] == 0)

    fri_entry = epoch('2020-01-10T20:00:00Z')
    friday_close = fri_entry + 7200
    week_bundle = fixture(begin=fri_entry, no_sar=True,
                          records=[record(fri_entry, '1.3'), record(friday_close - 60, '1.3001'), record(friday_close, '1.3002'), record(fri_entry + 2 * STEP - 60, '1.3003')])
    weekly = account(week_bundle)['trades'][0]
    check('Friday_close_uses_completed_last_minute', weekly['reason'] == 'week_close' and weekly['exit_event_kind'] == 'close' and weekly['exit_event_ts'] == friday_close)
    check('Friday_close_cutoff_carry_not_charged', weekly['rollover_units'] == 0)
    stop_before_close = fixture(begin=fri_entry, no_sar=True,
                               records=[record(fri_entry, '1.3'), record(friday_close - 60, '1.3', '1.301', '1.297', '1.3'), record(friday_close + 60, '1.3')])
    check('stop_range_precedes_same_minute_deadline_close', account(stop_before_close)['trades'][0]['reason'] == 'stop' and account(stop_before_close)['trades'][0]['exit_event_ts'] == friday_close - 60)
    missed_close = fixture(begin=fri_entry, no_sar=True,
                           records=[record(fri_entry, '1.3'), record(friday_close + 120, '1.3002'), record(fri_entry + 2 * STEP - 60, '1.3003')])
    missing_week = account(missed_close)['trades'][0]
    check('missing_hard_close_executes_next_actual_open', missing_week['reason'] == 'week_close' and missing_week['exit_event_kind'] == 'open' and missing_week['exit_event_ts'] == friday_close + 120)
    opening_gap = fixture(begin=fri_entry, no_sar=True,
                          records=[record(fri_entry, '1.3'), record(friday_close + 120, '1.297'), record(fri_entry + 2 * STEP - 60, '1.3')])
    check('stop_gap_beats_delayed_hard_exit', account(opening_gap)['trades'][0]['reason'] == 'stop_gap')
    long_gap_end = start + 9 * 86400
    combined_due = fixture(end=long_gap_end, no_sar=True,
                           records=[record(start, '1.3'), record(start + 7 * 86400, '1.301'), record(long_gap_end - 60, '1.301')])
    multiple = account(combined_due)['trades'][0]
    check('overdue_time_priority_over_week_at_delayed_open', multiple['reason'] == 'time' and multiple['deadline'] == start + 30 * STEP and multiple['delayed_exit'])
    check('missing_path_financing_remains_charged', multiple['financing'] > 0 and multiple['rollover_units'] > 0)

    wed_entry = epoch('2020-01-08T20:00:00Z')
    wed_cutoff = wed_entry + 7200
    within = account(fixture(begin=wed_entry, no_sar=True,
                             records=[record(wed_entry, '1.3'), record(wed_cutoff, '1.3', '1.301', '1.297', '1.3'), record(wed_entry + 2 * STEP - 60, '1.3')]))['trades'][0]
    opening = account(fixture(begin=wed_entry, no_sar=True,
                              records=[record(wed_entry, '1.3'), record(wed_cutoff, '1.297'), record(wed_entry + 2 * STEP - 60, '1.3')]))['trades'][0]
    check('full_account_within_minute_Wednesday_triple', within['rollover_units'] == 3 and within['financing'] == within['quantity'] * base_cost['carry'] * 3)
    check('full_account_opening_at_rollover_excludes_cutoff', opening['rollover_units'] == 0)

    year_bundle = fixture(begin=epoch('2020-12-31T20:00:00Z'))
    year_run = account(year_bundle)
    check('annual_attribution_by_candle_anchor_year', [x['year'] for x in year_run['annual']] == [2020, 2021])
    compounded = D(1)
    for annual in year_run['annual']:
        compounded *= 1 + annual['return_pct'] / 100
    check('annual_compounding_reconciles_account', abs(100 * (compounded - 1) - year_run['metrics']['return_pct']) < D('1e-40'))
    check('every_account_mark_final_balance_reconciles', abs(year_run['equity'][-1]['equity'] - year_run['metrics']['end_cash']) < D('1e-40'))

    # Gallery fixtures isolate its predeclared fallback, not financial execution.
    p, bars, minutes, _, _ = bundle
    one = copy.deepcopy(trade)
    two = copy.deepcopy(trade)
    two['number'] = 2
    two['pnl_sign'] = -one['pnl_sign']
    three = copy.deepcopy(trade)
    three['number'] = 3
    gallery = choose_gallery({'primary_base_early': {'trades': [one]},
                              'primary_base_later': {'trades': [one, two, three]}}, bars, minutes)
    check('gallery_first_later_opposite_sign', gallery[2]['selection_kind'] == 'opposite_sign' and gallery[2]['trade']['number'] == 2)
    check('gallery_two_original_minute_observations', [x['role'] for x in gallery[0]['source_minutes']] == ['entry', 'exit'] and gallery[0]['source_minutes'][0]['source_open_int'] == 1300000)
    one['pnl_sign'] = 0
    one['pnl'] = D(0)
    one['net_r'] = D(0)
    fallback = choose_gallery({'primary_base_early': {'trades': []},
                               'primary_base_later': {'trades': [one, two]}}, bars, minutes)
    check('gallery_zero_first_uses_next_chronological', fallback[2]['selection_kind'] == 'next_later' and not fallback[2]['outcome_conditioned'])
    absent = choose_gallery({'primary_base_early': {'trades': []},
                             'primary_base_later': {'trades': []}}, bars, minutes)
    check('gallery_unavailable_without_candidates', all(not x['available'] for x in absent))
    return dict(status='passed', assertions=assertions, cases=cases,
                scope='Constructed indicator, source-normalization, calendar and complete-account event fixtures; no historical result inputs.')


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--raw', required=True)
    ap.add_argument('--protocol', required=True)
    ap.add_argument('--manifest')
    ap.add_argument('--output', required=True)
    ap.add_argument('--synthetic-only', action='store_true')
    args = ap.parse_args()
    protocol_path = Path(args.protocol)
    manifest_path = Path(args.manifest) if args.manifest else protocol_path.with_name('source-manifest.json')
    if not EXPECTED_PROTOCOL_SHA or not EXPECTED_MANIFEST_SHA:
        raise ValueError('Formal protocol/manifest pins have not been installed')
    if digest(protocol_path) != EXPECTED_PROTOCOL_SHA or digest(manifest_path) != EXPECTED_MANIFEST_SHA:
        raise ValueError('Frozen protocol or source manifest mismatch')
    protocol, manifest = json.loads(protocol_path.read_text()), json.loads(manifest_path.read_text())
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    lock = dict(stage='code_locked_before_first_synthetic_or_raw_calculation',
                at_utc=dt.datetime.now(UTC).isoformat(), code_sha256=digest(__file__),
                protocol_sha256=EXPECTED_PROTOCOL_SHA, manifest_sha256=EXPECTED_MANIFEST_SHA,
                primary_code_or_results_read=False, raw_price_rows_read=False)
    write_json(output.with_name('independent-code-lock.json'), lock)
    tests = synthetic_tests(protocol)
    write_json(output.with_name('synthetic-boundaries.json'), tests)
    print(json.dumps(dict(stage='synthetics', **tests)), flush=True)
    if args.synthetic_only:
        return
    start, end = epoch(protocol['warmup_start_utc']), max(epoch(b[1]) for b in protocol['periods'].values())
    minutes, normalization = load_minutes(args.raw, manifest, start, end)
    print(json.dumps(dict(stage='source_verified', rows=len(minutes['t']),
                          normalized_m1_sha256=normalization['normalized_m1_sha256'])), flush=True)
    bars = compute_indicators(aggregate(minutes))
    cal = calendar(int(minutes['t'][0]), end)
    gaps = gap_summary(minutes, cal)
    runs = {}
    for model in protocol['variants']['models']:
        for cost_key in protocol['variants']['cost_scenarios']:
            for period in protocol['variants']['periods']:
                key = '_'.join((model, cost_key, period))
                runs[key] = simulate(bars, minutes, protocol, model, cost_key, period, cal, gaps)
                print(json.dumps(dict(stage='run', key=key,
                                      **runs[key]['metrics']), default=json_default), flush=True)
    quality = dict(source_files=7, rows=len(bars), source_minute_rows=len(minutes['t']),
                   complete_buckets=sum(r['canonical'] for r in bars),
                   partial_buckets=sum(not r['canonical'] for r in bars),
                   missing_h4_anchors=sum((bars[i]['ts'] - bars[i - 1]['ts']) // STEP - 1
                                          for i in range(1, len(bars))), **gaps)
    diagnostics = {}
    for period, bounds in protocol['periods'].items():
        a, b = map(epoch, bounds)
        rows = [r for r in bars if a <= r['ts'] + STEP < b]
        diagnostics[period] = dict(reversals=sum(bool(r['reversal']) for r in rows),
                                    up_reversals=sum(r['reversal'] and r['direction_after'] == 1 for r in rows),
                                    down_reversals=sum(r['reversal'] and r['direction_after'] == -1 for r in rows),
                                    af_cap_rows=sum(r['af'] == D('0.20') for r in rows),
                                    clamp_rows=sum(bool(r['clamp_applied']) for r in rows))
    payload = dict(protocol=protocol, protocol_sha256=EXPECTED_PROTOCOL_SHA,
                   manifest=manifest, manifest_sha256=EXPECTED_MANIFEST_SHA,
                   normalization=normalization, data_quality=quality, bars=bars, runs=runs,
                   examples=choose_gallery(runs, bars, minutes), sar_diagnostics=diagnostics,
                   cash_reference={k: dict(initial_cash=10000, end_cash=10000,
                                           return_pct=0, drawdown_pct=0)
                                   for k in protocol['periods']}, synthetic_tests=tests)
    packed = json.dumps(payload, ensure_ascii=False, separators=(',', ':'),
                        default=json_default, allow_nan=False).encode('utf-8')
    compressed = gzip.compress(packed, compresslevel=9, mtime=0)
    output.write_bytes(compressed)
    result_lock = dict(status='independently_rebuilt_before_primary_comparison',
                       at_utc=dt.datetime.now(UTC).isoformat(),
                       code_sha256=digest(__file__), protocol_sha256=EXPECTED_PROTOCOL_SHA,
                       manifest_sha256=EXPECTED_MANIFEST_SHA,
                       result_sha256=hashlib.sha256(compressed).hexdigest(),
                       decompressed_result_sha256=hashlib.sha256(packed).hexdigest(),
                       result_hash_scope='gzip archive bytes',
                       source_rows=len(minutes['t']), h4_rows=len(bars), runs=len(runs),
                       trades=sum(len(r['trades']) for r in runs.values()),
                       equity_rows=sum(len(r['equity']) for r in runs.values()),
                       annual_rows=sum(len(r['annual']) for r in runs.values()),
                       candidate_rows=sum(len(r['candidates']) for r in runs.values()),
                       synthetic_assertions=tests['assertions'],
                       primary_code_or_results_read=False, comparison_not_started=True,
                       gzip_bytes=len(compressed), decompressed_bytes=len(packed))
    write_json(output.with_name('independent-result-lock.json'), result_lock)
    print(json.dumps(dict(stage='locked_complete', **result_lock)), flush=True)


if __name__ == '__main__':
    main()
