BrainDock/src/web_dashboard_v0.3_backup.py

671 lines
17 KiB
Python

#!/usr/bin/env python3
from fastapi import FastAPI, Response
from binance.client import Client
import json, os, time
from datetime import datetime
app = FastAPI()
env = {}
with open('/home/marc/bot-deploy/.env') as f:
for line in f:
k,_,v = line.partition('=')
env[k.strip()] = v.strip()
binance = Client(env.get('BINANCE_API_KEY_LIVE'), env.get('BINANCE_API_SECRET_LIVE'))
price_cache = {'prices': {}, 'timestamp': 0}
def get_live_prices():
global price_cache
if time.time() - price_cache['timestamp'] < 5:
return price_cache['prices']
prices = {'USDT': 1.0}
pairs = ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT', 'XRPUSDT']
for pair in pairs:
try:
ticker = binance.get_ticker(symbol=pair)
asset = pair.replace('USDT', '')
prices[asset] = float(ticker['lastPrice'])
except:
pass
price_cache['prices'] = prices
price_cache['timestamp'] = time.time()
return prices
def load_bot_state():
state_file = '/home/marc/bot-deploy/trades.json'
if os.path.exists(state_file):
try:
with open(state_file) as f:
return json.load(f)
except:
pass
return {'current': {}, 'completed': [], 'balance': {}}
@app.get('/api/state')
async def get_state():
try:
account = binance.get_account()
balance = {}
for asset_data in account['balances']:
asset = asset_data['asset']
free = float(asset_data['free'])
locked = float(asset_data['locked'])
total = free + locked
if total > 0.00001:
balance[asset] = {
'free': free,
'locked': locked,
'total': total
}
prices = get_live_prices()
portfolio_value = 0
tracked_assets = ['BTC', 'ETH', 'SOL', 'BNB', 'XRP', 'USDT', 'USDC']
for asset in tracked_assets:
if asset in balance:
data = balance[asset]
price = prices.get(asset, 0)
portfolio_value += data['total'] * price
usdt_free = balance.get('USDT', {}).get('free', 0)
# P&L CALCULATION
initial_capital = 137.79
pnl_usdt = portfolio_value - initial_capital
pnl_pct = (pnl_usdt / initial_capital * 100) if initial_capital > 0 else 0
pnl_status = "🟢 PROFIT" if pnl_usdt > 0.01 else ("🔴 LOSS" if pnl_usdt < -0.01 else "⚪ BREAK")
pnl_color = "accent" if pnl_usdt > 0.01 else ("negative" if pnl_usdt < -0.01 else "neutral")
# Count active positions from bot's active_trades.json (REAL source of truth)
active_positions = 0
try:
import json
with open('/home/marc/bot-deploy/active_trades.json', 'r') as f:
bot_state = json.load(f)
active_positions = bot_state.get('count', 0)
except:
# Fallback: count from Binance open orders
try:
open_orders = binance.get_open_orders()
active_positions = len(open_orders)
except:
# Last resort: count locked coins
active_positions = 0
for asset in ['BTC', 'ETH', 'SOL', 'BNB', 'XRP']:
if asset in balance and balance[asset]['locked'] > 0.00001:
active_positions += 1
trades = load_bot_state()
return {
'balance': balance,
'portfolio_value': round(portfolio_value, 2),
'usdt_free': round(usdt_free, 2),
'active_positions': active_positions, # ← NEW: Real count!
'current_trades': trades.get('current', {}),
'pnl_usdt': round(pnl_usdt, 2),
'pnl_pct': round(pnl_pct, 2),
'pnl_status': pnl_status,
'pnl_color': pnl_color,
'completed_trades': trades.get('completed', []),
'prices': prices,
'timestamp': datetime.now().isoformat()
}
except Exception as e:
return {'error': str(e), 'portfolio_value': 0, 'usdt_free': 0, 'active_positions': 0}
@app.get('/')
async def root():
state = await get_state()
portfolio_val = state.get('portfolio_value', 0)
usdt_free = state.get('usdt_free', 0)
trades_count = state.get('active_positions', 0) # ← FIXED: Use real count!
prices = state.get('prices', {})
# P&L from state
pnl_usdt = state.get("pnl_usdt", 0)
pnl_pct = state.get("pnl_pct", 0)
pnl_status = state.get("pnl_status", "⚪ BREAK")
pnl_color = state.get("pnl_color", "neutral")
html = f'''<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>Trading Bot V0.3</title>
<style>
:root {{
--bg-primary: #1a1a1a;
--bg-secondary: #252525;
--bg-tertiary: #2a2a2a;
--bg-hover: #303030;
--border: #404040;
--text-primary: #e0e0e0;
--text-secondary: #a0a0a0;
--accent: #00ff88;
--spacing: 1rem;
}}
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
html, body {{
width: 100%;
height: 100%;
}}
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Monaco', 'Menlo', monospace;
background: var(--bg-primary);
color: var(--text-primary);
line-height: 1.6;
font-size: clamp(14px, 2vw, 16px);
overflow-x: hidden;
}}
.app-container {{
width: 100%;
min-height: 100vh;
padding: calc(var(--spacing) * 1.5);
}}
.header {{
margin-bottom: calc(var(--spacing) * 2.5);
}}
.logo {{
font-size: clamp(24px, 6vw, 32px);
font-weight: bold;
color: var(--accent);
margin-bottom: 0.5rem;
}}
.version {{
font-size: clamp(11px, 2vw, 13px);
color: var(--text-secondary);
}}
/* ===== METRICS GRID ===== */
.metrics-grid {{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: calc(var(--spacing) * 1.5);
margin-bottom: calc(var(--spacing) * 3);
}}
.metric-card {{
background: var(--bg-tertiary);
border: 1px solid var(--border);
padding: calc(var(--spacing) * 1.5);
border-radius: 8px;
transition: all 0.3s ease;
cursor: pointer;
min-height: 140px;
display: flex;
flex-direction: column;
justify-content: space-between;
}}
.metric-card:active {{
transform: scale(0.98);
}}
.metric-card:hover {{
background: var(--bg-hover);
border-color: var(--accent);
box-shadow: 0 0 20px rgba(0, 255, 136, 0.1);
}}
.metric-label {{
font-size: clamp(11px, 1.5vw, 12px);
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.8px;
margin-bottom: 1rem;
}}
.metric-value {{
font-size: clamp(20px, 5vw, 32px);
font-weight: bold;
color: var(--text-primary);
word-break: break-word;
}}
.metric-value.accent {{
color: var(--accent);
}}
/* ===== SECTIONS ===== */
.section {{
margin-bottom: calc(var(--spacing) * 3);
}}
.section-header {{
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
padding: calc(var(--spacing) * 0.75) 0;
border-bottom: 1px solid var(--border);
margin-bottom: calc(var(--spacing) * 1.25);
user-select: none;
transition: all 0.2s ease;
}}
.section-header:hover {{
color: var(--accent);
}}
.section-title {{
font-size: clamp(13px, 2.5vw, 15px);
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 1.2px;
transition: color 0.2s ease;
}}
.section-toggle {{
font-size: clamp(14px, 2vw, 16px);
color: var(--text-secondary);
transition: transform 0.3s ease;
margin-left: 0.5rem;
}}
.section-toggle.expanded {{
transform: rotate(180deg);
}}
.section-content {{
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
}}
.section-content.expanded {{
max-height: 2000px;
}}
/* ===== TABLES ===== */
.table-wrapper {{
overflow-x: auto;
-webkit-overflow-scrolling: touch;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--bg-tertiary);
}}
table {{
width: 100%;
border-collapse: collapse;
font-size: clamp(12px, 2vw, 14px);
}}
th {{
background: var(--bg-tertiary);
color: var(--text-secondary);
padding: calc(var(--spacing) * 1);
text-align: left;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.6px;
border-bottom: 1px solid var(--border);
white-space: nowrap;
font-size: clamp(10px, 1.5vw, 12px);
}}
td {{
padding: calc(var(--spacing) * 0.875);
border-bottom: 1px solid var(--border);
}}
tr:last-child td {{
border-bottom: none;
}}
tbody tr {{
transition: background 0.2s ease;
}}
tbody tr:hover {{
background: var(--bg-hover);
}}
tbody tr:active {{
background: var(--bg-secondary);
}}
.price-positive {{
color: var(--accent);
font-weight: 600;
}}
/* ===== RESPONSIVE ===== */
@media (max-width: 1200px) {{
.metrics-grid {{
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}}
}}
@media (max-width: 768px) {{
:root {{
--spacing: 0.875rem;
}}
.app-container {{
padding: calc(var(--spacing) * 1.25);
}}
.metrics-grid {{
grid-template-columns: repeat(2, 1fr);
gap: var(--spacing);
}}
.metric-card {{
padding: var(--spacing);
min-height: 120px;
}}
.metric-label {{
margin-bottom: 0.75rem;
font-size: 10px;
}}
.metric-value {{
font-size: clamp(18px, 4vw, 26px);
}}
.section {{
margin-bottom: calc(var(--spacing) * 1.75);
}}
th, td {{
padding: calc(var(--spacing) * 0.75);
font-size: 11px;
}}
th {{
font-size: 10px;
}}
}}
@media (max-width: 480px) {{
:root {{
--spacing: 0.75rem;
}}
.app-container {{
padding: var(--spacing);
}}
.metrics-grid {{
grid-template-columns: repeat(2, 1fr);
gap: calc(var(--spacing) * 0.75);
}}
.metric-card {{
padding: calc(var(--spacing) * 0.875);
min-height: 110px;
}}
.metric-label {{
font-size: 9px;
margin-bottom: 0.5rem;
letter-spacing: 0.5px;
}}
.metric-value {{
font-size: clamp(16px, 3.5vw, 22px);
}}
.logo {{
font-size: clamp(20px, 5vw, 26px);
}}
.version {{
font-size: 10px;
}}
.section-title {{
font-size: 11px;
}}
th, td {{
padding: calc(var(--spacing) * 0.6);
font-size: 9px;
}}
th {{
font-size: 8px;
}}
.table-wrapper {{
border-radius: 6px;
}}
}}
/* ===== SCROLLBAR ===== */
::-webkit-scrollbar {{
width: 6px;
height: 6px;
}}
::-webkit-scrollbar-track {{
background: var(--bg-secondary);
}}
::-webkit-scrollbar-thumb {{
background: var(--border);
border-radius: 3px;
}}
::-webkit-scrollbar-thumb:hover {{
background: var(--text-secondary);
}}
/* ===== ANIMATIONS ===== */
@keyframes fadeIn {{
from {{
opacity: 0;
transform: translateY(10px);
}}
to {{
opacity: 1;
transform: translateY(0);
}}
}}
.metric-card {{
animation: fadeIn 0.5s ease forwards;
}}
.metric-card:nth-child(2) {{
animation-delay: 0.1s;
}}
.metric-card:nth-child(3) {{
animation-delay: 0.2s;
}}
</style>
</head>
<body>
<div class="app-container">
<div class="header">
<div class="logo">💰 Trading Bot</div>
<div class="version">V0.3</div>
</div>
<div class="metrics-grid">
<div class="metric-card">
<div class="metric-label">Portfolio Value</div>
<div class="metric-value">${portfolio_val:.2f}</div>
</div>
<div class="metric-card">
<div class="metric-label">USDT Available</div>
<div class="metric-value accent">${usdt_free:.2f}</div>
</div>
<div class="metric-card">
<div class="metric-label">Open Positions</div>
<div class="metric-value">{trades_count}</div>
</div>
<div class="metric-card">
<div class="metric-label">Total P&L</div>
<div class="metric-value {pnl_color}">${pnl_usdt:+.2f} ({pnl_pct:+.1f}%)</div>
</div>
<div class="metric-card">
<div class="metric-label">P&L Status</div>
<div class="metric-value {pnl_color}">{pnl_status}</div>
</div>
</div>
<div class="section">
<div class="section-header" onclick="toggleSection(this)">
<div class="section-title">Live Prices</div>
<div class="section-toggle">▼</div>
</div>
<div class="section-content">
<div class="table-wrapper">
<table>
<thead>
<tr>
<th>Asset</th>
<th>Price</th>
</tr>
</thead>
<tbody>'''
for asset, price in prices.items():
html += f'''<tr>
<td>{asset}</td>
<td class="price-positive">${price:.2f}</td>
</tr>'''
html += '''</tbody>
</table>
</div>
</div>
</div>
<div class="section">
<div class="section-header" onclick="toggleSection(this)">
<div class="section-title">Holdings</div>
<div class="section-toggle">▼</div>
</div>
<div class="section-content">
<div class="table-wrapper">
<table>
<thead>
<tr>
<th>Asset</th>
<th>Free</th>
<th>Total</th>
<th>Value</th>
</tr>
</thead>
<tbody>'''
tracked = ['BTC', 'ETH', 'SOL', 'BNB', 'XRP', 'USDT', 'USDC']
balance = state.get('balance', {})
for asset in tracked:
if asset in balance:
data = balance[asset]
price = prices.get(asset, 0)
value = data['total'] * price
html += f'''<tr>
<td>{asset}</td>
<td>{data['free']:.4f}</td>
<td>{data['total']:.4f}</td>
<td class="price-positive">${value:.2f}</td>
</tr>'''
html += '''</tbody>
</table>
</div>
</div>
</div>
</div>
<script>
function toggleSection(header) {
const content = header.nextElementSibling;
const toggle = header.querySelector('.section-toggle');
content.classList.toggle('expanded');
toggle.classList.toggle('expanded');
}
// Refresh prices every 5 seconds
setInterval(function() {{
location.reload();
}}, 10000);
</script>
</body>
</html>'''
return Response(content=html, media_type='text/html')
@app.get('/api/pnl')
async def get_pnl():
"""Get live Profit & Loss (P&L) calculation"""
try:
account = binance.get_account()
# Get current account value
prices = get_live_prices()
current_value = 0
for asset_data in account['balances']:
asset = asset_data['asset']
total = float(asset_data['free']) + float(asset_data['locked'])
if total > 0.00001 and asset != 'LDDOGE' and asset != 'LDBTTC':
price = prices.get(asset, 1.0)
current_value += total * price
# Benchmark: Initial capital was $137.79 (before trading)
# This should be stored, but for now use a reference
initial_capital = 137.79
pnl_usdt = current_value - initial_capital
pnl_pct = (pnl_usdt / initial_capital * 100) if initial_capital > 0 else 0
# Get open trades for unrealized portion
state_file = '/home/marc/bot-deploy/trades.json'
open_trades = {}
if os.path.exists(state_file):
try:
data = json.load(state_file)
open_trades = data.get('current', {})
except:
pass
return {
'current_value': round(current_value, 2),
'initial_capital': initial_capital,
'total_pnl_usdt': round(pnl_usdt, 2),
'total_pnl_percent': round(pnl_pct, 2),
'status': '🟢 PROFIT' if pnl_usdt > 0 else ('🔴 LOSS' if pnl_usdt < 0 else '⚪ BREAK'),
'open_positions': len(open_trades),
'timestamp': datetime.now().isoformat()
}
except Exception as e:
return {'error': str(e)}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='0.0.0.0', port=7000)