test / app.py
Alvin3y1's picture
Update app.py
d6d83d7 verified
raw
history blame
35.9 kB
import asyncio
import json
import logging
import time
import bisect
import math
import statistics
import aiohttp
from datetime import datetime
from aiohttp import web
import websockets
SYMBOL_KRAKEN = "BTC/USD"
PORT = 7860
HISTORY_LENGTH = 300
BROADCAST_RATE = 0.1
DECAY_LAMBDA = 50.0
IMPACT_SENSITIVITY = 2.0
WALL_DAMPENING = 0.8
Z_SCORE_THRESHOLD = 3.0
WALL_LOOKBACK = 200
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
market_state = {
"bids": {},
"asks": {},
"history": [],
"pred_history": [],
"trade_vol_history": [],
"ohlc_history": [],
"current_vol_window": {"buy": 0.0, "sell": 0.0, "start": time.time()},
"current_mid": 0.0,
"ready": False
}
connected_clients = set()
def detect_anomalies(orders, scan_depth):
if len(orders) < 10: return []
relevant_orders = orders[:scan_depth]
volumes = [q for p, q in relevant_orders]
if not volumes: return []
try:
avg_vol = statistics.mean(volumes)
stdev_vol = statistics.stdev(volumes)
except statistics.StatisticsError:
return []
if stdev_vol == 0: return []
walls = []
for price, qty in relevant_orders:
z_score = (qty - avg_vol) / stdev_vol
if z_score > Z_SCORE_THRESHOLD:
walls.append({"price": price, "vol": qty, "z_score": z_score})
walls.sort(key=lambda x: x['z_score'], reverse=True)
return walls[:3]
def calculate_micro_price_structure(diff_x, diff_y_net, current_mid, best_bid, best_ask, walls):
if not diff_x or len(diff_x) < 5: return None
weighted_imbalance = 0.0
total_weight = 0.0
for i in range(len(diff_x)):
dist = diff_x[i]
net_vol = diff_y_net[i]
weight = math.exp(-dist / DECAY_LAMBDA)
weighted_imbalance += net_vol * weight
total_weight += weight
rho = weighted_imbalance / total_weight if total_weight > 0 else 0
spread = best_ask - best_bid
theoretical_delta = (spread / 2) * rho * IMPACT_SENSITIVITY
projected_price = current_mid + theoretical_delta
final_delta = theoretical_delta
if final_delta > 0 and walls['asks']:
nearest_wall = walls['asks'][0]
if projected_price >= nearest_wall['price']:
damp_factor = 1.0 / (1.0 + (nearest_wall['z_score'] * 0.2))
final_delta *= damp_factor
elif final_delta < 0 and walls['bids']:
nearest_wall = walls['bids'][0]
if projected_price <= nearest_wall['price']:
damp_factor = 1.0 / (1.0 + (nearest_wall['z_score'] * 0.2))
final_delta *= damp_factor
return {
"projected": current_mid + final_delta,
"rho": rho
}
def calculate_polr(bids, asks, mid):
"""
Path of Least Resistance:
Simulates eating volume on both sides.
Returns the price path where liquidity is thinnest.
"""
if not bids or not asks: return []
sorted_bids = sorted(bids.items(), key=lambda x: -x[0]) # High to Low
sorted_asks = sorted(asks.items(), key=lambda x: x[0]) # Low to High
path_points = []
# We simulate volume stepping from 0.1 BTC up to 20 BTC
# This represents "Time" or "Intensity" on the X-axis of the projection
volume_steps = [i * 0.5 for i in range(1, 41)] # 0.5, 1.0 ... 20.0
current_time = time.time()
for i, target_vol in enumerate(volume_steps):
# 1. Find price cost to eat 'target_vol' UP
ask_cost_dist = 0
cum_vol = 0
target_ask_price = mid
for p, q in sorted_asks:
cum_vol += q
if cum_vol >= target_vol:
target_ask_price = p
break
ask_cost_dist = target_ask_price - mid
# 2. Find price cost to eat 'target_vol' DOWN
bid_cost_dist = 0
cum_vol = 0
target_bid_price = mid
for p, q in sorted_bids:
cum_vol += q
if cum_vol >= target_vol:
target_bid_price = p
break
bid_cost_dist = mid - target_bid_price
# 3. Compare Resistance
# If moving up 10$ costs 5 BTC, but moving down 10$ costs 20 BTC,
# The path of least resistance is UP (it's thinner).
# Here we compare the DISTANCE moved for the SAME volume.
# If for 5 BTC, Price moves UP $10 and DOWN $2.
# The UP side is "thinner" (less resistance to price change), so price "slips" up.
projected_p = mid
# Avoid division by zero or tiny spreads
if bid_cost_dist <= 0: bid_cost_dist = 0.01
if ask_cost_dist <= 0: ask_cost_dist = 0.01
# Logic: Price goes where the book is thinner (Distance is LARGER for same volume)
if ask_cost_dist > bid_cost_dist:
# It takes LESS liquidity to move UP (Price moved further for same vol)
projected_p = target_ask_price
else:
projected_p = target_bid_price
# Add slight smoothing/dampening so it connects to current price
path_points.append({
't': current_time + (i * 2), # Spread points out every 2 seconds into future
'p': projected_p
})
return path_points
def process_market_data():
if not market_state['ready']: return {"error": "Initializing..."}
mid = market_state['current_mid']
now = time.time()
if now - market_state['current_vol_window']['start'] >= 1.0:
market_state['trade_vol_history'].append({
't': now,
'buy': market_state['current_vol_window']['buy'],
'sell': market_state['current_vol_window']['sell']
})
if len(market_state['trade_vol_history']) > 60:
market_state['trade_vol_history'].pop(0)
market_state['current_vol_window'] = {"buy": 0.0, "sell": 0.0, "start": now}
sorted_bids = sorted(market_state['bids'].items(), key=lambda x: -x[0])
sorted_asks = sorted(market_state['asks'].items(), key=lambda x: x[0])
if not sorted_bids or not sorted_asks: return {"error": "Empty Book"}
best_bid = sorted_bids[0][0]
best_ask = sorted_asks[0][0]
bid_walls = detect_anomalies(sorted_bids, WALL_LOOKBACK)
ask_walls = detect_anomalies(sorted_asks, WALL_LOOKBACK)
d_b_x, d_b_y, cum = [], [], 0
for p, q in sorted_bids[:300]:
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 sorted_asks[:300]:
d = p - mid
if d >= 0:
cum += q
d_a_x.append(d); d_a_y.append(cum)
diff_x, diff_y_net = [], []
chart_bids, chart_asks = [], []
if d_b_x and d_a_x:
max_dist = min(d_b_x[-1], d_a_x[-1])
step_size = max_dist / 100
steps = [i * step_size for i in range(1, 101)]
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_x.append(s)
diff_y_net.append(vol_b - vol_a)
chart_bids.append(vol_b)
chart_asks.append(vol_a)
analysis = calculate_micro_price_structure(
diff_x, diff_y_net, mid, best_bid, best_ask,
{"bids": bid_walls, "asks": ask_walls}
)
# Calculate Path of Least Resistance
polr_path = calculate_polr(market_state['bids'], market_state['asks'], mid)
if analysis:
if not market_state['pred_history'] or (now - market_state['pred_history'][-1]['t'] > 0.5):
market_state['pred_history'].append({'t': now, 'p': analysis['projected']})
if len(market_state['pred_history']) > HISTORY_LENGTH:
market_state['pred_history'].pop(0)
return {
"mid": mid,
"history": market_state['history'],
"pred_history": market_state['pred_history'],
"polr": polr_path,
"trade_history": market_state['trade_vol_history'],
"ohlc": market_state['ohlc_history'],
"depth_x": diff_x,
"depth_net": diff_y_net,
"depth_bids": chart_bids,
"depth_asks": chart_asks,
"analysis": analysis,
"walls": {"bids": bid_walls, "asks": ask_walls}
}
HTML_PAGE = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{SYMBOL_KRAKEN}</title>
<script src="https://unpkg.com/lightweight-charts@4.1.1/dist/lightweight-charts.standalone.production.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@500;600&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
<style>
:root {{
--bg-base: #000000;
--bg-panel: #0a0a0a;
--border: #252525;
--text-main: #FFFFFF;
--text-dim: #999999;
--green: #00ff9d;
--red: #ff3b3b;
--blue: #2979ff;
--yellow: #ffeb3b;
--purple: #d500f9;
}}
body {{
margin: 0; padding: 0;
background-color: var(--bg-base);
color: var(--text-main);
font-family: 'Inter', sans-serif;
overflow: hidden;
height: 100vh; width: 100vw;
}}
.layout {{
display: grid;
grid-template-rows: 34px 1fr 1fr;
grid-template-columns: 3fr 1fr;
gap: 1px;
background-color: var(--border);
height: 100vh;
box-sizing: border-box;
}}
.panel {{ background: var(--bg-panel); display: flex; flex-direction: column; overflow: hidden; }}
.status-bar {{
grid-column: 1 / 3;
grid-row: 1 / 2;
background: var(--bg-panel);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 12px;
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
text-transform: uppercase;
border-bottom: 1px solid var(--border);
z-index: 50;
}}
.status-left {{ display: flex; gap: 20px; align-items: center; }}
.live-dot {{ width: 8px; height: 8px; background-color: var(--green); border-radius: 50%; display: inline-block; box-shadow: 0 0 8px var(--green); }}
.ticker-val {{ font-weight: 700; color: #fff; font-size: 13px; }}
#p-chart {{ grid-column: 1 / 2; grid-row: 2 / 3; }}
#p-bottom {{
grid-column: 1 / 2; grid-row: 3 / 4;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1px;
background: var(--border);
}}
.bottom-sub {{ background: var(--bg-panel); display: flex; flex-direction: column; position: relative; }}
#p-sidebar {{
grid-column: 2 / 3;
grid-row: 2 / 4;
padding: 15px;
display: flex;
flex-direction: column;
gap: 15px;
border-left: 1px solid var(--border);
overflow: hidden;
}}
.chart-header {{
height: 24px;
min-height: 24px;
display: flex;
align-items: center;
padding-left: 12px;
font-size: 10px;
font-weight: 700;
color: var(--text-dim);
background: #050505;
border-bottom: 1px solid #151515;
letter-spacing: 0.5px;
}}
.data-group {{ display: flex; flex-direction: column; gap: 4px; }}
.label {{ font-size: 10px; color: var(--text-dim); font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }}
.value {{ font-family: 'JetBrains Mono', monospace; font-size: 20px; font-weight: 700; color: #fff; }}
.value-lg {{ font-size: 26px; }}
.value-sub {{ font-family: 'JetBrains Mono', monospace; font-size: 11px; margin-top: 2px; color: #666; }}
.divider {{ height: 1px; background: var(--border); width: 100%; }}
.c-green {{ color: var(--green); }}
.c-red {{ color: var(--red); }}
.c-dim {{ color: var(--text-dim); }}
.c-purp {{ color: var(--purple); }}
.list-container {{ display: flex; flex-direction: column; gap: 8px; overflow-y: auto; height: 100px; }}
.list-item {{
display: flex; justify-content: space-between;
font-family: 'JetBrains Mono', monospace;
font-size: 11px;
border-bottom: 1px solid #151515;
padding-bottom: 4px;
}}
.list-item span:first-child {{ color: #e0e0e0; }}
.list-item:last-child {{ border: none; }}
.sidebar-chart-box {{
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
}}
.mini-chart {{
flex: 1;
background: rgba(255,255,255,0.02);
border: 1px solid var(--border);
border-radius: 4px;
}}
</style>
</head>
<body>
<div class="layout">
<div class="status-bar">
<div class="status-left">
<span class="live-dot"></span>
<span style="font-weight:700; color:#fff;">{SYMBOL_KRAKEN}</span>
<span id="price-ticker" class="ticker-val">---</span>
</div>
<div class="status-right" id="clock">00:00:00 UTC</div>
</div>
<div id="p-chart" class="panel">
<div class="chart-header">
PRICE (BLUE) // <span class="c-purp">LEAST RESISTANCE (PURPLE)</span> // <span style="color:var(--yellow)">PRED (YELLOW)</span>
</div>
<div id="tv-price" style="flex: 1; width: 100%;"></div>
</div>
<div id="p-bottom">
<div class="bottom-sub">
<div class="chart-header">1M KLINE (KRAKEN OHLC)</div>
<div id="tv-candles" style="flex: 1; width: 100%;"></div>
</div>
<div class="bottom-sub">
<div class="chart-header">ORDER FLOW IMBALANCE</div>
<div id="tv-net" style="flex: 1; width: 100%;"></div>
</div>
</div>
<div id="p-sidebar" class="panel">
<div class="data-group">
<span class="label">Micro-Price Delta</span>
<div style="display:flex; align-items: baseline; gap: 10px;">
<span id="proj-pct" class="value value-lg">--%</span>
<span id="proj-val" class="value-sub">---</span>
</div>
</div>
<div class="divider"></div>
<div class="data-group">
<span class="label">OFI Imbalance Ratio</span>
<span id="score-val" class="value">0.00</span>
</div>
<div class="divider"></div>
<div class="data-group">
<span class="label">Detected Walls (Z > 3.0)</span>
<div id="wall-list" class="list-container">
<span class="c-dim" style="font-size: 11px;">Scanning...</span>
</div>
</div>
<div class="sidebar-chart-box">
<span class="label" style="margin-bottom:4px;">Real-time Volume Ticks</span>
<div id="sidebar-vol" class="mini-chart"></div>
</div>
<div class="sidebar-chart-box">
<span class="label" style="margin-bottom:4px;">Liquidity Density</span>
<div id="sidebar-density" class="mini-chart"></div>
</div>
</div>
</div>
<script>
setInterval(() => {{
const now = new Date();
document.getElementById('clock').innerText = now.toISOString().split('T')[1].split('.')[0] + ' UTC';
}}, 1000);
document.addEventListener('DOMContentLoaded', () => {{
const dom = {{
ticker: document.getElementById('price-ticker'),
score: document.getElementById('score-val'),
projVal: document.getElementById('proj-val'),
projPct: document.getElementById('proj-pct'),
wallList: document.getElementById('wall-list')
}};
const chartOpts = {{
layout: {{ background: {{ type: 'solid', color: '#0a0a0a' }}, textColor: '#888', fontFamily: 'JetBrains Mono' }},
grid: {{ vertLines: {{ color: '#151515' }}, horzLines: {{ color: '#151515' }} }},
rightPriceScale: {{ borderColor: '#222', scaleMargins: {{ top: 0.1, bottom: 0.1 }} }},
timeScale: {{ borderColor: '#222', timeVisible: true, secondsVisible: true }},
crosshair: {{ mode: 1, vertLine: {{ color: '#444', labelBackgroundColor: '#444' }}, horzLine: {{ color: '#444', labelBackgroundColor: '#444' }} }}
}};
const priceChart = LightweightCharts.createChart(document.getElementById('tv-price'), chartOpts);
const priceSeries = priceChart.addLineSeries({{ color: '#2979ff', lineWidth: 2, title: 'Price' }});
// Yellow Line: Mathematical Micro-Price
const predSeries = priceChart.addLineSeries({{ color: '#ffeb3b', lineWidth: 2, lineStyle: 2, title: 'Math Forecast' }});
// Purple Line: Path of Least Resistance (Lowest Volume)
const polrSeries = priceChart.addLineSeries({{ color: '#d500f9', lineWidth: 3, lineStyle: 0, title: 'Least Resistance' }});
const candleChart = LightweightCharts.createChart(document.getElementById('tv-candles'), {{
...chartOpts,
timeScale: {{ timeVisible: true, secondsVisible: false }}
}});
const candleSeries = candleChart.addCandlestickSeries({{
upColor: '#00ff9d', downColor: '#ff3b3b', borderVisible: false, wickUpColor: '#00ff9d', wickDownColor: '#ff3b3b'
}});
const netChart = LightweightCharts.createChart(document.getElementById('tv-net'), {{
...chartOpts, localization: {{ timeFormatter: t => '$' + t.toFixed(2) }}
}});
const netSeries = netChart.addHistogramSeries({{ color: '#2979ff' }});
const volChart = LightweightCharts.createChart(document.getElementById('sidebar-vol'), {{
...chartOpts,
grid: {{ vertLines: {{ visible: false }}, horzLines: {{ visible: false }} }},
rightPriceScale: {{ visible: false }},
timeScale: {{ visible: false }},
handleScroll: false, handleScale: false
}});
const volBuySeries = volChart.addHistogramSeries({{ color: '#00ff9d' }});
const volSellSeries = volChart.addHistogramSeries({{ color: '#ff3b3b' }});
const denChart = LightweightCharts.createChart(document.getElementById('sidebar-density'), {{
...chartOpts,
grid: {{ vertLines: {{ visible: false }}, horzLines: {{ visible: false }} }},
rightPriceScale: {{ visible: false }},
timeScale: {{ visible: false }},
handleScroll: false, handleScale: false
}});
const bidSeries = denChart.addAreaSeries({{ lineColor: '#00ff9d', topColor: 'rgba(0, 255, 157, 0.15)', bottomColor: 'rgba(0,0,0,0)', lineWidth: 1 }});
const askSeries = denChart.addAreaSeries({{ lineColor: '#ff3b3b', topColor: 'rgba(255, 59, 59, 0.15)', bottomColor: 'rgba(0,0,0,0)', lineWidth: 1 }});
let activeLines = [];
let activeCandleLines = [];
new ResizeObserver(entries => {{
for(let entry of entries) {{
const {{width, height}} = entry.contentRect;
if(entry.target.id === 'tv-price') priceChart.applyOptions({{width, height}});
if(entry.target.id === 'tv-candles') candleChart.applyOptions({{width, height}});
if(entry.target.id === 'tv-net') netChart.applyOptions({{width, height}});
if(entry.target.id === 'sidebar-vol') volChart.applyOptions({{width, height}});
if(entry.target.id === 'sidebar-density') denChart.applyOptions({{width, height}});
}}
}}).observe(document.body);
['tv-price', 'tv-candles', 'tv-net', 'sidebar-vol', 'sidebar-density'].forEach(id => {{
new ResizeObserver(e => {{
const t = document.getElementById(id);
if (t.clientWidth && t.clientHeight) {{
if(id === 'tv-price') priceChart.applyOptions({{ width: t.clientWidth, height: t.clientHeight }});
if(id === 'tv-candles') candleChart.applyOptions({{ width: t.clientWidth, height: t.clientHeight }});
if(id === 'tv-net') netChart.applyOptions({{ width: t.clientWidth, height: t.clientHeight }});
if(id === 'sidebar-vol') volChart.applyOptions({{ width: t.clientWidth, height: t.clientHeight }});
if(id === 'sidebar-density') denChart.applyOptions({{ width: t.clientWidth, height: t.clientHeight }});
}}
}}).observe(document.getElementById(id));
}});
function connect() {{
const ws = new WebSocket((location.protocol === 'https:' ? 'wss' : 'ws') + '://' + location.host + '/ws');
ws.onmessage = (e) => {{
const data = JSON.parse(e.data);
if (data.error) return;
if (data.history.length) {{
const hist = data.history.map(d => ({{ time: Math.floor(d.t), value: d.p }}));
const cleanHist = [...new Map(hist.map(i => [i.time, i])).values()];
priceSeries.setData(cleanHist);
const lastP = cleanHist[cleanHist.length-1].value;
const lastTime = cleanHist[cleanHist.length-1].time;
dom.ticker.innerText = lastP.toLocaleString('en-US', {{ minimumFractionDigits: 2 }});
// 1. Yellow Line (Math Forecast)
if (data.analysis) {{
const proj = data.analysis.projected;
const rho = data.analysis.rho;
predSeries.setData([
cleanHist[cleanHist.length-1],
{{ time: lastTime + 60, value: proj }}
]);
// Text updates
const pct = ((proj - lastP) / lastP) * 100;
const sign = pct >= 0 ? "+" : "";
dom.projPct.innerText = `${{sign}}${{pct.toFixed(4)}}%`;
dom.projPct.style.color = pct >= 0 ? "var(--green)" : "var(--red)";
dom.projVal.innerText = proj.toLocaleString('en-US', {{ minimumFractionDigits: 2 }});
dom.score.innerText = rho.toFixed(3);
dom.score.style.color = rho > 0 ? "var(--green)" : (rho < 0 ? "var(--red)" : "var(--text-main)");
}}
// 2. Purple Line (Path of Least Resistance)
if (data.polr && data.polr.length) {{
// Attach start of POLR to current price to make it seamless
const polrData = [
{{ time: lastTime, value: lastP }},
...data.polr.map(d => ({{ time: Math.floor(d.t), value: d.p }}))
];
// Deduplicate times
const uniquePolr = [...new Map(polrData.map(i => [i.time, i])).values()];
polrSeries.setData(uniquePolr);
}}
}}
if (data.ohlc && data.ohlc.length) {{
const candles = data.ohlc.map(c => ({{
time: c.time,
open: c.open,
high: c.high,
low: c.low,
close: c.close
}}));
const uniqueCandles = [...new Map(candles.map(i => [i.time, i])).values()];
candleSeries.setData(uniqueCandles);
}}
if (data.walls) {{
activeLines.forEach(l => priceSeries.removePriceLine(l));
activeLines = [];
activeCandleLines.forEach(l => candleSeries.removePriceLine(l));
activeCandleLines = [];
let html = "";
const addWall = (w, type) => {{
const color = type === 'BID' ? '#00ff9d' : '#ff3b3b';
const lineOpts = {{ price: w.price, color: color, lineWidth: 1, lineStyle: 2, axisLabelVisible: false }};
activeLines.push(priceSeries.createPriceLine(lineOpts));
activeCandleLines.push(candleSeries.createPriceLine(lineOpts));
html += `<div class="list-item"><span style="color:${{color}}">${{type}} ${{w.price}}</span><span class="c-dim">Z:${{w.z_score.toFixed(1)}}</span></div>`;
}};
data.walls.asks.forEach(w => addWall(w, 'ASK'));
data.walls.bids.forEach(w => addWall(w, 'BID'));
dom.wallList.innerHTML = html || '<span class="c-dim" style="font-size:11px">Scanning...</span>';
}}
if (data.trade_history && data.trade_history.length) {{
const buyData = [], sellData = [];
data.trade_history.forEach(t => {{
const time = Math.floor(t.t);
buyData.push({{ time: time, value: t.buy }});
sellData.push({{ time: time, value: t.sell }});
}});
volBuySeries.setData([...new Map(buyData.map(i => [i.time, i])).values()]);
volSellSeries.setData([...new Map(sellData.map(i => [i.time, i])).values()]);
}}
if (data.depth_x.length) {{
const bids = [], asks = [], nets = [];
for(let i=0; i<data.depth_x.length; i++) {{
const t = data.depth_x[i];
bids.push({{ time: t, value: data.depth_bids[i] }});
asks.push({{ time: t, value: data.depth_asks[i] }});
nets.push({{ time: t, value: data.depth_net[i], color: data.depth_net[i] > 0 ? '#00ff9d' : '#ff3b3b' }});
}}
bidSeries.setData(bids);
askSeries.setData(asks);
netSeries.setData(nets);
}}
}};
ws.onclose = () => setTimeout(connect, 2000);
}}
connect();
}});
</script>
</body>
</html>
"""
async def kraken_worker():
global market_state
try:
# Fetch initial history
async with aiohttp.ClientSession() as session:
url = "https://api.kraken.com/0/public/OHLC?pair=XBTUSD&interval=1"
async with session.get(url) as response:
if response.status == 200:
data = await response.json()
if 'result' in data:
for key in data['result']:
if key != 'last':
raw_candles = data['result'][key]
market_state['ohlc_history'] = [
{
'time': int(c[0]),
'open': float(c[1]),
'high': float(c[2]),
'low': float(c[3]),
'close': float(c[4])
}
for c in raw_candles[-120:]
]
break
except Exception as e:
logging.error(f"History fetch failed: {e}")
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}
}))
await ws.send(json.dumps({
"method": "subscribe",
"params": {"channel": "trade", "symbol": [SYMBOL_KRAKEN]}
}))
await ws.send(json.dumps({
"method": "subscribe",
"params": {"channel": "ohlc", "symbol": [SYMBOL_KRAKEN], "interval": 1}
}))
async for message in ws:
payload = json.loads(message)
channel = payload.get("channel")
data = payload.get("data", [])
if channel == "book":
for item in data:
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())
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()
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)
elif channel == "trade":
for trade in data:
try:
qty = float(trade['qty'])
price = float(trade['price'])
side = trade['side']
# Update Vol stats
if side == 'buy': market_state['current_vol_window']['buy'] += qty
else: market_state['current_vol_window']['sell'] += qty
# LIVE CANDLE UPDATE
current_minute_start = int(time.time()) // 60 * 60
if market_state['ohlc_history']:
last_candle = market_state['ohlc_history'][-1]
# If still in the same minute
if last_candle['time'] == current_minute_start:
last_candle['close'] = price
if price > last_candle['high']: last_candle['high'] = price
if price < last_candle['low']: last_candle['low'] = price
# If new minute started
elif current_minute_start > last_candle['time']:
new_candle = {
'time': current_minute_start,
'open': price,
'high': price,
'low': price,
'close': price
}
market_state['ohlc_history'].append(new_candle)
if len(market_state['ohlc_history']) > 200:
market_state['ohlc_history'].pop(0)
except: pass
elif channel == "ohlc":
for candle in data:
try:
# Kraken sends endtime, adjust to starttime
start_time = int(float(candle['endtime'])) - 60
c_data = {
'time': start_time,
'open': float(candle['open']),
'high': float(candle['high']),
'low': float(candle['low']),
'close': float(candle['close'])
}
if market_state['ohlc_history']:
if market_state['ohlc_history'][-1]['time'] == start_time:
market_state['ohlc_history'][-1] = c_data
elif market_state['ohlc_history'][-1]['time'] < start_time:
market_state['ohlc_history'].append(c_data)
if len(market_state['ohlc_history']) > 200:
market_state['ohlc_history'].pop(0)
except Exception as e:
pass
except Exception as e:
logging.warning(f"โš ๏ธ Reconnecting: {e}")
await asyncio.sleep(3)
async def broadcast_worker():
while True:
if connected_clients and market_state['ready']:
payload = process_market_data()
msg = json.dumps(payload)
for ws in list(connected_clients):
try: await ws.send_str(msg)
except: pass
await asyncio.sleep(BROADCAST_RATE)
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
connected_clients.add(ws)
try:
async for msg in ws:
pass
finally:
connected_clients.remove(ws)
return ws
async def handle_index(request):
return web.Response(text=HTML_PAGE, content_type='text/html')
async def start_background(app):
app['kraken_task'] = asyncio.create_task(kraken_worker())
app['broadcast_task'] = asyncio.create_task(broadcast_worker())
async def cleanup_background(app):
app['kraken_task'].cancel()
app['broadcast_task'].cancel()
try: await app['kraken_task']; await app['broadcast_task']
except: pass
async def main():
app = web.Application()
app.router.add_get('/', handle_index)
app.router.add_get('/ws', websocket_handler)
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"๐Ÿš€ Quant Dashboard: http://localhost:{PORT}")
await asyncio.Event().wait()
if __name__ == "__main__":
try: asyncio.run(main())
except KeyboardInterrupt: pass