test / app.py
Alvin3y1's picture
Update app.py
deb82b2 verified
raw
history blame
22.8 kB
import asyncio
import json
import logging
import time
import bisect
from aiohttp import web
import websockets
# --- Configuration ---
SYMBOL_KRAKEN = "BTC/USD"
PORT = 7860
HISTORY_LENGTH = 1000 # Increased history for better charts
# --- Logging ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
# --- In-Memory State ---
market_state = {
"bids": {},
"asks": {},
"history": [], # Stores { time: int, value: float }
"current_mid": 0.0,
"prev_mid": 0.0,
"ready": False
}
# --- AI Logic Helper ---
def analyze_structure(diff_x, diff_y, current_mid):
"""
Analyzes the Net Liquidity Curve to find Support, Resistance, and Projected Trend.
"""
if not diff_y or len(diff_y) < 5:
return None
# 1. Momentum Projection
net_total = diff_y[-1]
# Damping factor
momentum_shift = net_total * 0.2
projected_price = current_mid + momentum_shift
# 2. Find Structural Reversals
support_level = None
resistance_level = None
scan_limit = len(diff_y) // 2
for i in range(1, scan_limit):
prev_val = diff_y[i-1]
curr_val = diff_y[i]
dist = diff_x[i]
# Resistance: Buyers (Pos) -> Sellers (Neg)
if prev_val > 0 and curr_val < 0 and resistance_level is None:
resistance_level = current_mid + dist
# Support: Sellers (Neg) -> Buyers (Pos)
if prev_val < 0 and curr_val > 0 and support_level is None:
support_level = current_mid - dist
return {
"projected": projected_price,
"support": support_level,
"resistance": resistance_level,
"net_score": net_total
}
# --- Improved HTML Frontend ---
HTML_PAGE = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AI Liquidity Dashboard | {SYMBOL_KRAKEN}</title>
<!-- TradingView Lightweight Charts -->
<script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script>
<!-- Plotly for Depth Chart -->
<script src="https://cdn.plot.ly/plotly-2.24.1.min.js"></script>
<style>
:root {{
--bg-color: #0b0c10;
--panel-bg: #1f2833;
--text-main: #c5c6c7;
--accent-green: #66fcf1;
--accent-green-dim: #45a29e;
--accent-red: #ff3b3b;
--accent-red-dim: #a82828;
--border: #2d3842;
}}
body {{
margin: 0; padding: 0;
background-color: var(--bg-color);
color: var(--text-main);
font-family: 'JetBrains Mono', 'Courier New', monospace;
overflow: hidden;
height: 100vh;
width: 100vw;
}}
/* --- GRID LAYOUT --- */
.grid-container {{
display: grid;
grid-template-columns: 3fr 1fr; /* Main chart 75%, Side panel 25% */
grid-template-rows: 2fr 1fr; /* Top 66%, Bottom 33% */
gap: 4px;
height: 100vh;
padding: 4px;
box-sizing: border-box;
}}
.panel {{
background: #12141a;
border: 1px solid var(--border);
border-radius: 4px;
position: relative;
display: flex;
flex-direction: column;
overflow: hidden;
}}
/* Grid Areas */
#p-price {{ grid-column: 1 / 2; grid-row: 1 / 2; }}
#p-depth {{ grid-column: 1 / 2; grid-row: 2 / 3; }}
#p-stats {{ grid-column: 2 / 3; grid-row: 1 / 3; border-left: 2px solid var(--accent-green-dim); }}
/* Headers */
.panel-header {{
padding: 8px 12px;
background: #0f1116;
border-bottom: 1px solid var(--border);
font-size: 12px;
text-transform: uppercase;
font-weight: bold;
display: flex;
justify-content: space-between;
align-items: center;
color: var(--accent-green);
}}
/* --- CHART CONTAINERS --- */
#tv-chart {{ flex: 1; width: 100%; }}
#depth-chart {{ flex: 1; width: 100%; }}
/* --- STATS PANEL --- */
.stats-content {{
padding: 15px;
overflow-y: auto;
flex: 1;
}}
.stat-box {{
margin-bottom: 20px;
padding: 10px;
background: rgba(255,255,255,0.02);
border-radius: 4px;
}}
.stat-label {{ font-size: 11px; color: #666; display: block; margin-bottom: 4px; }}
.stat-value {{ font-size: 24px; font-weight: bold; }}
.stat-sub {{ font-size: 12px; margin-left: 5px; }}
.green {{ color: var(--accent-green); }}
.red {{ color: var(--accent-red); }}
/* --- TERMINAL --- */
.terminal-box {{
margin-top: auto;
font-size: 11px;
height: 300px;
overflow-y: hidden;
display: flex;
flex-direction: column;
}}
.term-header {{ border-bottom: 1px dashed #444; margin-bottom: 5px; padding-bottom: 5px; opacity: 0.7; }}
#term-logs {{ flex: 1; overflow-y: hidden; display: flex; flex-direction: column-reverse; }}
.log-line {{ margin-top: 4px; padding-left: 8px; border-left: 2px solid #333; }}
.log-bull {{ border-left-color: var(--accent-green); color: #e0f2f1; }}
.log-bear {{ border-left-color: var(--accent-red); color: #ffebee; }}
/* --- METER --- */
.meter-container {{ width: 100%; height: 6px; background: #333; border-radius: 3px; margin-top: 10px; position: relative; overflow: hidden; }}
.meter-bar {{ height: 100%; width: 50%; background: #555; transition: all 0.5s ease; position: absolute; left: 0; }}
.mid-mark {{ position: absolute; left: 50%; height: 100%; width: 2px; background: #fff; z-index: 10; }}
/* Load Overlay */
#loader {{
position: absolute; top:0; left:0; width:100%; height:100%;
background: rgba(0,0,0,0.9); z-index: 999;
display: flex; justify-content: center; align-items: center;
color: var(--accent-green); font-size: 20px;
}}
</style>
</head>
<body>
<div id="loader">INITIALIZING AI MODELS...</div>
<div class="grid-container">
<!-- PRICE CHART PANEL -->
<div id="p-price" class="panel">
<div class="panel-header">
<span>BTC/USD Price Action</span>
<span id="live-price" style="color:white;">---</span>
</div>
<div id="tv-chart"></div>
</div>
<!-- DEPTH / LIQUIDITY PANEL -->
<div id="p-depth" class="panel">
<div class="panel-header">
<span>Net Liquidity Structure (Bid - Ask)</span>
<span style="font-size:10px; color:#666;">DEPTH 300</span>
</div>
<div id="depth-chart"></div>
</div>
<!-- SIDEBAR / AI STATS -->
<div id="p-stats" class="panel">
<div class="panel-header">AI ANALYTICS ENGINE</div>
<div class="stats-content">
<!-- CURRENT SCORE -->
<div class="stat-box">
<span class="stat-label">NET LIQUIDITY SCORE</span>
<div style="display:flex; align-items:baseline;">
<span id="score-val" class="stat-value">0</span>
</div>
<div class="meter-container">
<div class="mid-mark"></div>
<div id="score-bar" class="meter-bar" style="width: 0%; left: 50%;"></div>
</div>
</div>
<!-- KEY LEVELS -->
<div class="stat-box">
<span class="stat-label">DETECTED STRUCTURE</span>
<div style="margin-top:8px;">
<div style="display:flex; justify-content:space-between;">
<span style="color:#aaa;">RESIST:</span>
<span id="res-val" class="red">---</span>
</div>
<div style="display:flex; justify-content:space-between; margin-top:4px;">
<span style="color:#aaa;">SUPPORT:</span>
<span id="sup-val" class="green">---</span>
</div>
</div>
</div>
<!-- PREDICTED TARGET -->
<div class="stat-box" style="border: 1px solid #444;">
<span class="stat-label" style="color:var(--accent-green);">AI PRICE PROJECTION</span>
<span id="proj-val" class="stat-value" style="font-size:20px;">---</span>
</div>
<!-- TERMINAL -->
<div class="terminal-box">
<div class="term-header">> SYSTEM LOGS</div>
<div id="term-logs"></div>
</div>
</div>
</div>
</div>
<script>
// --- 1. SETUP TRADINGVIEW LIGHTWEIGHT CHART ---
const chartContainer = document.getElementById('tv-chart');
const chart = LightweightCharts.createChart(chartContainer, {{
layout: {{ background: {{ type: 'solid', color: '#12141a' }}, textColor: '#888' }},
grid: {{ vertLines: {{ color: '#1f2833' }}, horzLines: {{ color: '#1f2833' }} }},
crosshair: {{ mode: LightweightCharts.CrosshairMode.Normal }},
rightPriceScale: {{ borderColor: '#2d3842' }},
timeScale: {{ borderColor: '#2d3842', timeVisible: true, secondsVisible: true }},
}});
const lineSeries = chart.addLineSeries({{
color: '#2962FF',
lineWidth: 2,
crosshairMarkerVisible: true,
lastValueVisible: false,
priceLineVisible: false,
}});
// Forecast Line (Dashed)
const predSeries = chart.addLineSeries({{
color: '#ff9800',
lineWidth: 2,
lineStyle: LightweightCharts.LineStyle.Dotted,
title: 'Forecast'
}});
// S/R Lines (Using PriceLines)
let supportLine = null;
let resistanceLine = null;
// Auto Resize
new ResizeObserver(entries => {{
if (entries.length === 0 || entries[0].target !== chartContainer) {{ return; }}
const newRect = entries[0].contentRect;
chart.applyOptions({{ width: newRect.width, height: newRect.height }});
}}).observe(chartContainer);
// --- 2. SETUP PLOTLY (DEPTH) ---
// We use Plotly here because LightweightCharts is bad at non-time-series X/Y plots
const depthDiv = document.getElementById('depth-chart');
const plotlyLayout = {{
paper_bgcolor: '#12141a',
plot_bgcolor: '#12141a',
font: {{ color: '#888', family: 'JetBrains Mono' }},
margin: {{ t: 10, b: 30, l: 40, r: 20 }},
showlegend: false,
xaxis: {{ gridcolor: '#1f2833', title: 'Distance ($)' }},
yaxis: {{ gridcolor: '#1f2833' }}
}};
const plotlyConfig = {{ responsive: true, displayModeBar: false }};
Plotly.newPlot(depthDiv, [], plotlyLayout, plotlyConfig);
// --- 3. LOGIC & UPDATES ---
const dom = {{
price: document.getElementById('live-price'),
loader: document.getElementById('loader'),
scoreVal: document.getElementById('score-val'),
scoreBar: document.getElementById('score-bar'),
resVal: document.getElementById('res-val'),
supVal: document.getElementById('sup-val'),
projVal: document.getElementById('proj-val'),
logs: document.getElementById('term-logs')
}};
let lastTime = 0;
function log(msg, type='neutral') {{
const div = document.createElement('div');
div.className = `log-line ${{type === 'bull' ? 'log-bull' : type === 'bear' ? 'log-bear' : ''}}`;
const timeStr = new Date().toLocaleTimeString('en-US', {{hour12:false}});
div.innerHTML = `<span style="opacity:0.5; font-size:10px;">${{timeStr}}</span> ${{msg}}`;
dom.logs.prepend(div);
if (dom.logs.children.length > 20) dom.logs.removeChild(dom.logs.lastChild);
}}
async function fetchData() {{
try {{
const res = await fetch('/data');
const data = await res.json();
if (data.error) return; // Still initializing
dom.loader.style.display = 'none';
// -- A. UPDATE PRICE CHART --
const history = data.history.map(d => ({{ time: Math.floor(d.t), value: d.p }}));
// De-duplicate times for Lightweight Charts
const uniqueHistory = [];
const seenTimes = new Set();
history.forEach(h => {{
if(!seenTimes.has(h.time)) {{ seenTimes.add(h.time); uniqueHistory.push(h); }}
}});
lineSeries.setData(uniqueHistory);
dom.price.innerHTML = `$${{data.mid.toLocaleString(undefined, {{minimumFractionDigits: 2}})}}`;
// -- B. UPDATE AI ANALYSIS --
if (data.analysis) {{
const {{ projected, support, resistance, net_score }} = data.analysis;
// 1. Prediction Line (Current Time -> Future)
const lastT = uniqueHistory[uniqueHistory.length-1].time;
predSeries.setData([
{{ time: lastT, value: data.mid }},
{{ time: lastT + 60, value: projected }} // 1 min projection
]);
dom.projVal.innerHTML = `$${{projected.toLocaleString(undefined, {{maximumFractionDigits:0}})}}`;
dom.projVal.style.color = projected > data.mid ? '#66fcf1' : '#ff3b3b';
// 2. S/R Lines
if (support) {{
dom.supVal.innerText = `$${{support.toFixed(0)}}`;
if (!supportLine) {{
supportLine = lineSeries.createPriceLine({{
price: support, color: '#00e676', lineWidth: 1, lineStyle: LightweightCharts.LineStyle.Solid, axisLabelVisible: true, title: 'SUP'
}});
}} else supportLine.applyOptions({{ price: support }});
}} else {{
dom.supVal.innerText = '---';
if(supportLine) {{ lineSeries.removePriceLine(supportLine); supportLine=null; }}
}}
if (resistance) {{
dom.resVal.innerText = `$${{resistance.toFixed(0)}}`;
if (!resistanceLine) {{
resistanceLine = lineSeries.createPriceLine({{
price: resistance, color: '#ff1744', lineWidth: 1, lineStyle: LightweightCharts.LineStyle.Solid, axisLabelVisible: true, title: 'RES'
}});
}} else resistanceLine.applyOptions({{ price: resistance }});
}} else {{
dom.resVal.innerText = '---';
if(resistanceLine) {{ lineSeries.removePriceLine(resistanceLine); resistanceLine=null; }}
}}
// 3. Score Meter
dom.scoreVal.innerText = net_score.toFixed(1);
dom.scoreVal.className = net_score > 0 ? "stat-value green" : "stat-value red";
// Meter logic: Range approx -50 to 50
let barWidth = Math.min(Math.abs(net_score)*2, 50);
dom.scoreBar.style.width = `${{barWidth}}%`;
dom.scoreBar.style.left = net_score > 0 ? "50%" : `${{50 - barWidth}}%`;
dom.scoreBar.style.backgroundColor = net_score > 0 ? "var(--accent-green)" : "var(--accent-red)";
// 4. Logs
if (net_score > 25 && Math.random() > 0.9) log(`High Buying Pressure detected`, 'bull');
if (net_score < -25 && Math.random() > 0.9) log(`High Selling Pressure detected`, 'bear');
if (support && Math.random() > 0.95) log(`Price approaching support floor`, 'bull');
}}
// -- C. UPDATE DEPTH CHART --
const traceDiff = {{
x: data.diff.x,
y: data.diff.y,
type: 'scatter',
mode: 'lines',
fill: 'tozeroy',
line: {{color: '#e040fb', width: 2}},
fillcolor: 'rgba(224, 64, 251, 0.1)'
}};
// Add a zero line
const zeroLine = {{ type: 'line', x0: 0, x1: 1, xref: 'paper', y0: 0, y1: 0, line: {{color: '#444', width: 1}} }};
const layoutUpdate = {{ ...plotlyLayout, shapes: [zeroLine] }};
Plotly.react(depthDiv, [traceDiff], layoutUpdate, plotlyConfig);
}} catch (e) {{
console.error(e);
}}
}}
setInterval(fetchData, 1000);
</script>
</body>
</html>
"""
async def kraken_worker():
global market_state
while True:
try:
async with websockets.connect("wss://ws.kraken.com/v2") as ws:
logging.info(f"๐Ÿ”Œ Connected to Kraken ({SYMBOL_KRAKEN})")
await ws.send(json.dumps({
"method": "subscribe",
"params": {"channel": "book", "symbol": [SYMBOL_KRAKEN], "depth": 500}
}))
async for message in ws:
payload = json.loads(message)
channel = payload.get("channel")
data_entries = payload.get("data", [])
if channel == "book":
for item in data_entries:
# Process Bids
for bid in item.get('bids', []):
q, p = float(bid['qty']), float(bid['price'])
if q == 0: market_state['bids'].pop(p, None)
else: market_state['bids'][p] = q
# Process Asks
for ask in item.get('asks', []):
q, p = float(ask['qty']), float(ask['price'])
if q == 0: market_state['asks'].pop(p, None)
else: market_state['asks'][p] = q
if market_state['bids'] and market_state['asks']:
best_bid = max(market_state['bids'].keys())
best_ask = min(market_state['asks'].keys())
mid = (best_bid + best_ask) / 2
market_state['prev_mid'] = market_state['current_mid']
market_state['current_mid'] = mid
market_state['ready'] = True
now = time.time()
# Throttle history updates slightly to prevent spamming duplicates
if not market_state['history'] or (now - market_state['history'][-1]['t'] > 0.5):
market_state['history'].append({'t': now, 'p': mid})
if len(market_state['history']) > HISTORY_LENGTH:
market_state['history'].pop(0)
except Exception as e:
logging.warning(f"โš ๏ธ Reconnecting: {e}")
await asyncio.sleep(3)
async def handle_index(request):
return web.Response(text=HTML_PAGE, content_type='text/html')
async def handle_data(request):
if not market_state['ready']:
return web.json_response({"error": "Initializing..."})
mid = market_state['current_mid']
# Snapshot Bids/Asks
raw_bids = sorted(market_state['bids'].items(), key=lambda x: -x[0])[:300]
raw_asks = sorted(market_state['asks'].items(), key=lambda x: x[0])[:300]
# Calculate Volume at Distance (Cumulative)
d_b_x, d_b_y, cum = [], [], 0
for p, q in raw_bids:
d = mid - p
if d >= 0:
cum += q
d_b_x.append(d); d_b_y.append(cum)
d_a_x, d_a_y, cum = [], [], 0
for p, q in raw_asks:
d = p - mid
if d >= 0:
cum += q
d_a_x.append(d); d_a_y.append(cum)
# Calculate Net Liquidity Curve (The "Diff" Chart)
diff_x, diff_y = [], []
if d_b_x and d_a_x:
max_dist = min(d_b_x[-1], d_a_x[-1])
# Create interpolated steps
step_size = max_dist / 100
steps = [i * step_size for i in range(1, 101)]
for s in steps:
# Find volume at distance 's' for bid and ask
idx_b = bisect.bisect_right(d_b_x, s)
vol_b = d_b_y[idx_b-1] if idx_b > 0 else 0
idx_a = bisect.bisect_right(d_a_x, s)
vol_a = d_a_y[idx_a-1] if idx_a > 0 else 0
diff_x.append(s)
diff_y.append(vol_b - vol_a) # Positive = Bullish Wall, Negative = Bearish Wall
# Run Analysis
analysis = analyze_structure(diff_x, diff_y, mid)
return web.json_response({
"mid": mid,
"history": market_state['history'], # List of {t, p}
"diff": { "x": diff_x, "y": diff_y },
"analysis": analysis
})
async def start_background(app):
app['kraken_task'] = asyncio.create_task(kraken_worker())
async def cleanup_background(app):
app['kraken_task'].cancel()
try: await app['kraken_task']
except asyncio.CancelledError: pass
async def main():
app = web.Application()
app.router.add_get('/', handle_index)
app.router.add_get('/data', handle_data)
app.on_startup.append(start_background)
app.on_cleanup.append(cleanup_background)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, '0.0.0.0', PORT)
await site.start()
print(f"๐Ÿš€ AI Dashboard: http://localhost:{PORT}")
await asyncio.Event().wait()
if __name__ == "__main__":
try: asyncio.run(main())
except KeyboardInterrupt: pass