|
|
import asyncio |
|
|
import json |
|
|
import logging |
|
|
import time |
|
|
import bisect |
|
|
import random |
|
|
from aiohttp import web |
|
|
import websockets |
|
|
|
|
|
|
|
|
SYMBOL_KRAKEN = "BTC/USD" |
|
|
PORT = 7860 |
|
|
HISTORY_LENGTH = 300 |
|
|
|
|
|
|
|
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s') |
|
|
|
|
|
|
|
|
market_state = { |
|
|
"bids": {}, |
|
|
"asks": {}, |
|
|
"history": [], |
|
|
"current_mid": 0.0, |
|
|
"prev_mid": 0.0, |
|
|
"ready": False, |
|
|
"last_comment_time": 0 |
|
|
} |
|
|
|
|
|
|
|
|
def generate_ai_commentary(diff_y, mid, prev_mid): |
|
|
""" |
|
|
Analyzes the Net Liquidity (diff_y) and Price Action to generate commentary. |
|
|
diff_y is a list of (BidVol - AskVol) at increasing distances. |
|
|
""" |
|
|
if not diff_y: |
|
|
return {"text": "Initializing analysis...", "sentiment": "neutral"} |
|
|
|
|
|
|
|
|
net_total = diff_y[-1] |
|
|
avg_liquidity = sum(diff_y) / len(diff_y) |
|
|
|
|
|
|
|
|
price_delta = mid - prev_mid |
|
|
|
|
|
|
|
|
msg = "" |
|
|
sentiment = "neutral" |
|
|
|
|
|
|
|
|
if net_total > 50: |
|
|
sentiment = "bullish" |
|
|
msg = f"π <b>STRONG BUY SUPPORT:</b> Net surplus of {int(net_total)} BTC. Orderbook is heavily tilted towards Bids." |
|
|
elif net_total < -50: |
|
|
sentiment = "bearish" |
|
|
msg = f"π <b>HEAVY SELL PRESSURE:</b> Net deficit of {int(net_total)} BTC. Sellers are dominating the book." |
|
|
|
|
|
|
|
|
|
|
|
elif price_delta < 0 and net_total > 20: |
|
|
sentiment = "warning" |
|
|
msg = f"π‘οΈ <b>ABSORPTION DETECTED:</b> Price is falling, but Bid depth is increasing (+{int(net_total)} BTC). Passive buyers are catching the dump." |
|
|
|
|
|
|
|
|
elif price_delta > 0 and net_total < -20: |
|
|
sentiment = "warning" |
|
|
msg = f"π§± <b>HIDDEN WALL:</b> Price is rising into heavy Sell liquidity ({int(net_total)} BTC diff). Breakout might fail." |
|
|
|
|
|
|
|
|
elif abs(net_total) < 10: |
|
|
sentiment = "neutral" |
|
|
msg = f"βοΈ <b>EQUILIBRIUM:</b> Bids and Asks are perfectly balanced. Expect low volatility or a sudden breakout." |
|
|
|
|
|
|
|
|
else: |
|
|
if net_total > 0: |
|
|
msg = f"π <b>Bullish Bias:</b> Moderate buy support (+{int(net_total)} BTC). Path of least resistance is UP." |
|
|
sentiment = "bullish" |
|
|
else: |
|
|
msg = f"π <b>Bearish Bias:</b> Moderate sell overhang ({int(net_total)} BTC). Path of least resistance is DOWN." |
|
|
|
|
|
return {"text": msg, "sentiment": sentiment, "net": net_total} |
|
|
|
|
|
|
|
|
HTML_PAGE = f""" |
|
|
<!DOCTYPE html> |
|
|
<html> |
|
|
<head> |
|
|
<title>BTC-USD AI Analyst</title> |
|
|
<script src="https://cdn.plot.ly/plotly-2.24.1.min.js"></script> |
|
|
<style> |
|
|
body {{ margin: 0; padding: 0; background-color: #0e0e0e; color: #ccc; font-family: 'Courier New', monospace; overflow: hidden; }} |
|
|
|
|
|
/* Layout Grid */ |
|
|
#container {{ display: flex; flex-direction: column; height: 100vh; width: 100vw; }} |
|
|
|
|
|
/* Row 1: Charts (60% Height) */ |
|
|
#row-charts {{ flex: 6; display: flex; width: 100%; border-bottom: 2px solid #333; }} |
|
|
.col-chart {{ width: 50%; height: 100%; border-right: 1px solid #333; }} |
|
|
|
|
|
/* Row 2: AI Terminal (40% Height) */ |
|
|
#row-terminal {{ flex: 4; display: flex; flex-direction: column; background-color: #050505; padding: 10px; overflow-y: auto; }} |
|
|
|
|
|
/* Terminal Styling */ |
|
|
.terminal-header {{ color: #00bcd4; font-weight: bold; border-bottom: 1px dashed #333; padding-bottom: 5px; margin-bottom: 10px; }} |
|
|
.log-entry {{ margin-bottom: 6px; font-size: 14px; line-height: 1.4; border-left: 3px solid transparent; padding-left: 8px; }} |
|
|
.log-time {{ color: #666; font-size: 12px; margin-right: 10px; }} |
|
|
|
|
|
/* Sentiment Colors */ |
|
|
.bullish {{ border-left-color: #00e676; color: #e8f5e9; }} |
|
|
.bearish {{ border-left-color: #ff1744; color: #ffebee; }} |
|
|
.neutral {{ border-left-color: #999; color: #ccc; }} |
|
|
.warning {{ border-left-color: #ff9800; color: #fff3e0; }} |
|
|
|
|
|
/* Highlight classes for inner HTML */ |
|
|
b {{ font-weight: bold; }} |
|
|
|
|
|
/* Charts fill their containers */ |
|
|
.chart {{ width: 100%; height: 100%; }} |
|
|
|
|
|
#status {{ position: absolute; top: 10px; left: 60px; z-index: 100; font-size: 14px; background: rgba(0,0,0,0.8); padding: 5px 10px; border-radius: 4px; border: 1px solid #333; }} |
|
|
.green {{ color: #00e676; }} |
|
|
.red {{ color: #ff1744; }} |
|
|
</style> |
|
|
</head> |
|
|
<body> |
|
|
<div id="status">Connecting to Neural Net...</div> |
|
|
|
|
|
<div id="container"> |
|
|
<!-- ROW 1: CONTEXT CHARTS --> |
|
|
<div id="row-charts"> |
|
|
<div class="col-chart"> |
|
|
<div id="price-chart" class="chart"></div> |
|
|
</div> |
|
|
<div class="col-chart"> |
|
|
<div id="vol-chart" class="chart"></div> |
|
|
</div> |
|
|
</div> |
|
|
|
|
|
<!-- ROW 2: AI COMMENTATOR --> |
|
|
<div id="row-terminal"> |
|
|
<div class="terminal-header">> AI MARKET ANALYST (Based on Net Liquidity)</div> |
|
|
<div id="terminal-logs"></div> |
|
|
</div> |
|
|
</div> |
|
|
|
|
|
<script> |
|
|
const priceDiv = document.getElementById('price-chart'); |
|
|
const volDiv = document.getElementById('vol-chart'); |
|
|
const termLogs = document.getElementById('terminal-logs'); |
|
|
const statusDiv = document.getElementById('status'); |
|
|
|
|
|
let initPrice = false, initVol = false; |
|
|
let lastLogText = ""; |
|
|
|
|
|
const commonConfig = {{ responsive: true, displayModeBar: false }}; |
|
|
const commonLayout = {{ |
|
|
paper_bgcolor: '#0e0e0e', |
|
|
plot_bgcolor: '#0e0e0e', |
|
|
font: {{ color: '#aaa', family: 'Courier New' }}, |
|
|
margin: {{ t: 30, b: 25, l: 40, r: 20 }}, |
|
|
showlegend: false, |
|
|
xaxis: {{ gridcolor: '#222' }}, |
|
|
yaxis: {{ gridcolor: '#222' }} |
|
|
}}; |
|
|
|
|
|
function addLog(data) {{ |
|
|
// Prevent spamming the exact same message |
|
|
if (data.comment.text === lastLogText) return; |
|
|
lastLogText = data.comment.text; |
|
|
|
|
|
const div = document.createElement('div'); |
|
|
div.className = `log-entry ${{data.comment.sentiment}}`; |
|
|
|
|
|
const timeStr = new Date().toLocaleTimeString(); |
|
|
div.innerHTML = `<span class="log-time">[${{timeStr}}]</span> ${{data.comment.text}}`; |
|
|
|
|
|
// Insert at top |
|
|
termLogs.prepend(div); |
|
|
|
|
|
// Keep max 20 logs |
|
|
if (termLogs.children.length > 20) {{ |
|
|
termLogs.removeChild(termLogs.lastChild); |
|
|
}} |
|
|
}} |
|
|
|
|
|
async function updateCharts() {{ |
|
|
try {{ |
|
|
const res = await fetch('/data'); |
|
|
const data = await res.json(); |
|
|
|
|
|
if (data.error) {{ |
|
|
statusDiv.innerHTML = "Waiting for data..."; |
|
|
return; |
|
|
}} |
|
|
|
|
|
// Update Status |
|
|
statusDiv.innerHTML = `Mid: <span class="${{data.mid >= data.prev_mid ? 'green' : 'red'}}">$${{data.mid.toLocaleString(undefined, {{minimumFractionDigits: 2}})}}</span> | Net Liq: ${{data.comment.net.toFixed(2)}} BTC`; |
|
|
|
|
|
// 1. PRICE CHART |
|
|
const tracePrice = {{ x: data.history.map(d=>new Date(d.t*1000)), y: data.history.map(d=>d.p), type: 'scatter', mode:'lines', line: {{color: '#29b6f6', width: 2}} }}; |
|
|
if (!initPrice) {{ Plotly.newPlot(priceDiv, [tracePrice], {{ ...commonLayout, title: '<b>Midprice</b>', xaxis: {{type:'date', gridcolor:'#222'}} }}, commonConfig); initPrice = true; }} |
|
|
else {{ Plotly.react(priceDiv, [tracePrice], {{ ...commonLayout, title: '<b>Midprice</b>', xaxis: {{type:'date', gridcolor:'#222'}} }}, commonConfig); }} |
|
|
|
|
|
// 2. VOLUME CHART |
|
|
const tracesVol = [ |
|
|
{{ x: data.vol.dist_bids, y: data.vol.vol_bids, type: 'scatter', name: 'Bids', line: {{color: '#00e676'}} }}, |
|
|
{{ x: data.vol.dist_asks, y: data.vol.vol_asks, type: 'scatter', name: 'Asks', line: {{color: '#ff1744'}} }} |
|
|
]; |
|
|
if (!initVol) {{ Plotly.newPlot(volDiv, tracesVol, {{ ...commonLayout, title: '<b>Cumulative Volume by Distance</b>', xaxis: {{title:'Distance ($)'}} }}, commonConfig); initVol = true; }} |
|
|
else {{ Plotly.react(volDiv, tracesVol, {{ ...commonLayout, title: '<b>Cumulative Volume by Distance</b>', xaxis: {{title:'Distance ($)'}} }}, commonConfig); }} |
|
|
|
|
|
// 3. AI COMMENTARY LOG |
|
|
addLog(data); |
|
|
|
|
|
}} catch (e) {{ console.error("Fetch error:", e); }} |
|
|
}} |
|
|
|
|
|
setInterval(updateCharts, 750); // Slower update for readability |
|
|
</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: |
|
|
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 |
|
|
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()) |
|
|
market_state['prev_mid'] = market_state['current_mid'] |
|
|
mid = (best_bid + best_ask) / 2 |
|
|
market_state['current_mid'] = mid |
|
|
market_state['ready'] = True |
|
|
|
|
|
now = time.time() |
|
|
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'] |
|
|
|
|
|
|
|
|
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] |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
diff_values = [] |
|
|
|
|
|
if d_b_x and d_a_x: |
|
|
max_dist = min(d_b_x[-1], d_a_x[-1]) |
|
|
step_size = max_dist / 50 |
|
|
steps = [i * step_size for i in range(1, 51)] |
|
|
|
|
|
for s in steps: |
|
|
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_values.append(vol_b - vol_a) |
|
|
|
|
|
|
|
|
ai_output = generate_ai_commentary(diff_values, mid, market_state['prev_mid']) |
|
|
|
|
|
return web.json_response({ |
|
|
"mid": mid, |
|
|
"prev_mid": market_state['prev_mid'], |
|
|
"vol": { "dist_bids": d_b_x, "vol_bids": d_b_y, "dist_asks": d_a_x, "vol_asks": d_a_y }, |
|
|
"comment": ai_output, |
|
|
"history": market_state['history'] |
|
|
}) |
|
|
|
|
|
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"π BTC-USD AI Dashboard: http://localhost:{PORT}") |
|
|
await asyncio.Event().wait() |
|
|
|
|
|
if __name__ == "__main__": |
|
|
try: asyncio.run(main()) |
|
|
except KeyboardInterrupt: pass |