"""Consistency check of the StopOutLab results, with the Python 3 standard library only.

Usage:  python stopout_crosscheck.py StopOutLab_<tag>.csv [more files]

This is a second implementation of the article's own rules, not an independent validation.
It reads only the CSV files StopOutLab writes and prints four tables.

1. For every cycle it solves the threshold bid in closed form from the entry line (balance,
   volume, open price, bid, ask, margin after the fill) and compares it with the bid the MQL5
   search printed.
2. For every cycle that ended in a stop-out it takes the last crossing tick before the deal
   (the X line Watch() wrote) and compares two predictions with the bid of that tick: the
   closed form with the swap of the deal added to the balance, and the last snapshot.
3. It splits the last-snapshot difference into two parts. The tick before the crossing tick
   was above the level and the crossing tick at or below it, so the level price lies between
   their bids. A straight line between the two margin levels puts it at one price, the
   "level price". The model part is snapshot minus level price, the tick part is level price
   minus crossing bid.
4. It compares the margin the model computed with the account margin in every snapshot
   taken while only the test symbol was open, and checks whether the account margin moved
   away from its value after the fill while the position was open.

Assumptions:
  - one position is open, and only its own symbol moves
  - the margin stays at its value after the fill when the run used the default basis
    (I line "open"); with InpMarginAtPrice=true (I line "price") the margin of a fixed volume
    is proportional to the price when the profit currency is the account currency (EURUSD,
    XAUUSD on a USD account), and fixed when the base currency is the account currency
    (USDJPY), so margin tiers set on the notional value are outside that formula
  - a buy is valued at the bid and charged margin at the ask, a sell the other way round
  - the spread at entry stays the same
  - the margin level changes along a straight line between two neighboring ticks
"""
import csv, math, sys, statistics


def read(path):
    info, cycles, deals, crosses, checks = None, [], [], [], []
    with open(path, newline="") as f:
        for row in csv.reader(f):
            if not row or row[0] == "kind":
                continue
            if row[0] == "I":
                info = {"symbol": row[2], "contract": float(row[3]), "leverage": float(row[4]),
                        "so": float(row[5]), "base": row[7], "profit": row[8],
                        "basis": row[10] if len(row) > 10 else "price"}
            elif row[0] == "E":
                cycles.append({"time": row[1], "buy": row[2] == "buy", "volume": float(row[3]),
                               "digits": len(row[4].split(".")[1]) if "." in row[4] else 0,
                               "open": float(row[4]), "pred": float(row[5]), "naive": float(row[6]),
                               "balance": float(row[7]), "margin": float(row[8]), "cycle": int(row[9]),
                               "bid": float(row[10]), "ask": float(row[11]), "deals": []})
            elif row[0] == "S":
                if len(row) > 8 and row[8] != "":
                    checks.append(float(row[8]))
                if cycles:
                    cycles[-1].setdefault("margins", []).append(float(row[4]))
            elif row[0] == "X":
                crosses.append({"time": row[1], "bid": float(row[2]), "level": float(row[5]), "pred": float(row[6]),
                                "prev_bid": float(row[7]), "prev_level": float(row[8]), "others": int(row[9])})
            elif row[0] == "D":
                deals.append({"time": row[1], "price": float(row[6]), "buy": row[4] == "buy",
                              "snap_time": row[8], "snap_close": float(row[9]), "swap": float(row[10])})
    for c in cycles:
        c["crosses"] = []
    for d in deals:
        owner = [c for c in cycles if c["time"] <= d["time"]]
        if owner:
            owner[-1]["deals"].append(d)
    for x in crosses:
        owner = [c for c in cycles if c["time"] <= x["time"]]
        if owner:
            owner[-1]["crosses"].append(x)
    return info, cycles, checks


def closed_form(info, c, account="USD"):
    """Threshold bid of one position, or None when there is no formula for the symbol."""
    vc = c["volume"] * info["contract"]
    L = info["so"] / 100.0
    bal, o, b0, s, m0 = c["balance"], c["open"], c["bid"], c["ask"] - c["bid"], c["margin"]
    if info["profit"] == account and info["basis"] == "open":
        # the margin keeps its value from the fill
        if c["buy"]:
            # bal + vc*(b - o) = L*m0
            return o + (L * m0 - bal) / vc
        # bal + vc*(o - b - s) = L*m0
        return o - s - (L * m0 - bal) / vc
    if info["profit"] == account:
        if c["buy"]:
            # bal + vc*(b - o) = L*m0*(b + s)/(b0 + s)
            k = L * m0 / (b0 + s)
            return (k * s - bal + vc * o) / (vc - k)
        # bal + vc*(o - b - s) = L*m0*b/b0
        k = L * m0 / b0
        return (bal + vc * (o - s)) / (vc + k)
    if info["base"] == account:
        if c["buy"]:
            # bal + vc*(b - o)/b = L*m0
            return vc * o / (bal + vc - L * m0)
        # bal + vc*(o - a)/a = L*m0 with a = b + s
        return vc * o / (L * m0 - bal + vc) - s
    return None


def level_price(x, so):
    """Bid between the tick before the crossing and the crossing tick where the level is so."""
    if x["prev_bid"] <= 0.0 or x["prev_level"] <= x["level"]:
        return None
    w = (x["prev_level"] - so) / (x["prev_level"] - x["level"])
    return x["prev_bid"] + w * (x["bid"] - x["prev_bid"])


def point_of(cycles):
    # the CSV prints prices with the symbol's digits, so the text gives the point size
    return 10.0 ** -max(c["digits"] for c in cycles)


def main(paths):
    rows = {}
    for path in paths:
        info, cycles, checks = read(path)
        if info is None or not cycles:
            continue
        r = rows.setdefault(info["symbol"], {"runs": 0, "x": 0, "diff": [], "swap": [], "snap": [], "model": [],
                                             "jump": [], "inside": 0, "others": 0, "checks": [], "moved": 0,
                                             "mbuy": [], "msell": []})
        r["runs"] += 1
        r["checks"] += checks
        point = point_of(cycles)
        snap = lambda v, buy: (math.floor if buy else math.ceil)(v / point + (1e-7 if buy else -1e-7)) * point
        for c in cycles:
            if any(abs(m - c["margin"]) > 0.005 for m in c.get("margins", [])):
                r["moved"] += 1
            cf = closed_form(info, c)
            if cf is None:
                continue
            r["diff"].append((c["pred"] - snap(cf, c["buy"])) / point)
            if not c["crosses"] or not c["deals"]:
                continue
            x = c["crosses"][-1]                  # the crossing the stop-out followed
            r["x"] += 1
            r["others"] += x["others"] > 0
            sign = 1.0 if c["buy"] else -1.0     # positive: crossed further away than predicted
            with_swap = dict(c, balance=c["balance"] + c["deals"][0]["swap"])
            r["swap"].append(sign * (snap(closed_form(info, with_swap), c["buy"]) - x["bid"]) / point)
            r["snap"].append(sign * (x["pred"] - x["bid"]) / point)
            lp = level_price(x, info["so"])
            if lp is not None:
                r["model"].append(sign * (x["pred"] - lp) / point)
                r["mbuy" if c["buy"] else "msell"].append(abs(x["pred"] - lp) / point)
                r["jump"].append(sign * (lp - x["bid"]) / point)
                lo, hi = sorted((x["bid"], x["prev_bid"]))
                r["inside"] += lo - 1e-9 <= x["pred"] <= hi + 1e-9
    num = lambda v: round(v) + 0                 # whole points, and no "-0"
    rows = dict(sorted(rows.items(), key=lambda kv: ["USDJPY", "XAUUSD", "EURUSD"].index(kv[0])
                       if kv[0] in ("USDJPY", "XAUUSD", "EURUSD") else 9))
    med = lambda xs: f"{round(statistics.median(xs), 1) + 0.0:.1f}"
    fmt = lambda xs: f"{med(xs):>7} ({num(min(xs)):5d},{num(max(xs)):5d})" if xs else " " * 21
    print("1, 2. Crossed past the prediction, points: median (min, max)")
    print("symbol  runs  crossings  bisection minus   |  formula with the swap        last snapshot")
    print("                         formula (min, max) |")
    for sym, r in rows.items():
        rng = f"({num(min(r['diff'])):3d},{num(max(r['diff'])):3d})" if r["diff"] else ""
        print(f"{sym:<7} {r['runs']:>4} {r['x']:>10} {rng:>17}  |  {fmt(r['swap'])}      {fmt(r['snap'])}")
    print()
    print("3. Last snapshot split at the level price between the two ticks, points: median (min, max)")
    print("symbol  crossings  model part             tick part              snapshot between    other symbols")
    print("                   (snapshot - level)     (level - crossing)     the two ticks       open")
    for sym, r in rows.items():
        print(f"{sym:<7} {len(r['model']):>9}  {fmt(r['model'])}  {fmt(r['jump'])}  {r['inside']:>9} of {len(r['model']):<3}"
              f"     {r['others']:>5}")
    print()
    print("   largest model part without its sign, points: buys / sells")
    for sym, r in rows.items():
        big = lambda xs: f"{max(xs):.2f} ({len(xs)})" if xs else "none"
        print(f"   {sym:<7} {big(r['mbuy'])} / {big(r['msell'])}")
    print()
    print("4. Account margin minus model margin, percent of the account margin")
    print("symbol  snapshots  largest difference   runs where the account margin moved after the fill")
    for sym, r in rows.items():
        big = max(abs(v) for v in r["checks"]) if r["checks"] else float("nan")
        print(f"{sym:<7} {len(r['checks']):>9}  {big:18.4f}   {r['moved']} of {r['runs']}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit(__doc__)
    main(sys.argv[1:])
