import MetaTrader5 as mt5
from datetime import datetime, timedelta

mt5.initialize()

ticket = 1675593149

print("METHOD 1: history_deals_get with position= parameter")
print("=" * 70)
deals = mt5.history_deals_get(position=ticket)
if deals:
    for d in deals:
        entry_label = {0: "IN", 1: "OUT", 2: "INOUT", 3: "OUT_BY"}.get(d.entry, str(d.entry))
        print(f"  deal={d.ticket} pos={d.position_id} type={'BUY' if d.type==0 else 'SELL'} "
              f"entry={entry_label} vol={d.volume} price={d.price} "
              f"profit={d.profit} swap={d.swap} comm={d.commission} "
              f"time={datetime.fromtimestamp(d.time)}")
    total = sum(d.profit + d.swap + d.commission for d in deals)
    print(f"\n  TOTAL P&L from position query: {total:.2f}")
else:
    print(f"  No deals found via position= query (returned: {deals})")

print()
print("METHOD 2: wide date range (7 days), filter by position_id")
print("=" * 70)
deals2 = mt5.history_deals_get(datetime.now() - timedelta(days=7), datetime.now())
matching = [d for d in (deals2 or []) if d.position_id == ticket]
print(f"  Deals matching pos_id {ticket}: {len(matching)}")
for d in matching:
    entry_label = {0: "IN", 1: "OUT", 2: "INOUT", 3: "OUT_BY"}.get(d.entry, str(d.entry))
    print(f"  deal={d.ticket} entry={entry_label} profit={d.profit} "
          f"time={datetime.fromtimestamp(d.time)}")

print()
print("METHOD 3: account balance check")
print("=" * 70)
acct = mt5.account_info()
print(f"  Current balance: {acct.balance}")
print(f"  (Was 95291.10 before this trade — delta tells us realized P&L)")

mt5.shutdown()
