#!/usr/bin/env python3
"""Export current/live MT5 trading data from binary deal files to HTML"""
import struct
import os
import sys
from datetime import datetime
def parse_deal_file(filepath):
"""Parse MT5 binary deal file and extract trading data"""
if not os.path.exists(filepath):
return None
with open(filepath, 'rb') as f:
data = f.read()
# Look for floating point numbers (profits)
profits = []
for i in range(0, len(data) - 8, 8):
try:
val = struct.unpack('d', data[i:i+8])[0]
# Look for reasonable profit values (-5000 to 15000)
if -5000 < val < 15000 and abs(val) > 10:
# Check if it has decimal precision (not a timestamp)
if abs(val - round(val, 2)) < 0.01:
profits.append(round(val, 2))
except:
pass
# Remove duplicates while preserving order
seen = set()
unique_profits = []
for p in profits:
if p not in seen:
seen.add(p)
unique_profits.append(p)
return unique_profits
def generate_live_report(account_num, profits, output_file):
"""Generate HTML report from live binary data"""
# Calculate statistics
wins = [p for p in profits if p > 0]
losses = [p for p in profits if p < 0]
total_profit = sum(profits)
gross_profit = sum(wins)
gross_loss = sum(losses)
total_trades = len(profits)
win_count = len(wins)
loss_count = len(losses)
win_rate = (win_count / total_trades * 100) if total_trades > 0 else 0
profit_factor = abs(gross_profit / gross_loss) if gross_loss != 0 else 0
largest_win = max(wins) if wins else 0
largest_loss = min(losses) if losses else 0
avg_win = sum(wins) / len(wins) if wins else 0
avg_loss = sum(losses) / len(losses) if losses else 0
starting_balance = 100000.00
current_balance = starting_balance + total_profit
return_pct = (total_profit / starting_balance) * 100
html_content = f'''
MT5 Live Trading Report - Account {account_num}
💰 Performance Summary
{'+' if total_profit > 0 else ''}${total_profit:,.2f}
Total Net Profit
Starting Balance
${starting_balance:,.2f}
Current Balance
${current_balance:,.2f}
Total Return
{return_pct:.2f}%
Profit Factor
{profit_factor:.2f}
Gross Profit
${gross_profit:,.2f}
Gross Loss
${gross_loss:,.2f}
📈 Trade Statistics
{total_trades}
Total Trades
${largest_win:,.2f}
Largest Win
${abs(largest_loss):,.2f}
Largest Loss
${abs(avg_loss):,.2f}
Avg Loss
📝 Recent Trade P&L
'''
# Add trade list (last 20 trades)
for i, profit in enumerate(profits[-20:], 1):
color_class = 'profit' if profit > 0 else 'loss'
sign = '+' if profit > 0 else ''
html_content += f'''
Trade #{i}
{sign}${profit:,.2f}
'''
html_content += f'''
'''
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html_content)
return output_file
def main():
account_num = "104125640"
deal_file = os.path.expanduser(f"~/mt5-docker/config/.wine/drive_c/Program Files/MetaTrader 5/Bases/MetaQuotes-Demo/trades/{account_num}/deals_2026.03.dat")
if not os.path.exists(deal_file):
print(f"❌ Deal file not found: {deal_file}")
sys.exit(1)
print(f"📊 Parsing live data from: {deal_file}")
print(f" File date: {datetime.fromtimestamp(os.path.getmtime(deal_file))}")
print("")
profits = parse_deal_file(deal_file)
if not profits:
print("❌ No profit data found")
sys.exit(1)
print(f"✅ Found {len(profits)} trades")
# Generate output
timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
output_file = os.path.expanduser(f"~/mt5-live-report-{account_num}-{timestamp}.html")
generate_live_report(account_num, profits, output_file)
# Calculate summary
total = sum(profits)
wins = len([p for p in profits if p > 0])
print(f"")
print(f"✅ Live report exported to: {output_file}")
print(f"")
print(f"📊 SUMMARY:")
print(f" Account: {account_num}")
print(f" Total Trades: {len(profits)}")
print(f" Winning Trades: {wins}")
print(f" Total P&L: ${total:,.2f}")
print(f" Balance: ${100000 + total:,.2f}")
print(f" Return: {(total/100000)*100:.2f}%")
print(f"")
print(f"🌐 Open in browser:")
print(f" file://{output_file}")
if __name__ == "__main__":
main()