|
|
import asyncio |
|
|
import json |
|
|
import logging |
|
|
import time |
|
|
import bisect |
|
|
import math |
|
|
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, |
|
|
"ready": False |
|
|
} |
|
|
|
|
|
|
|
|
HTML_PAGE = f""" |
|
|
<!DOCTYPE html> |
|
|
<html> |
|
|
<head> |
|
|
<title>BTC-USD Mean Pressure</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: sans-serif; overflow: hidden; }} |
|
|
|
|
|
/* Layout Grid - 2 Rows x 2 Columns */ |
|
|
#container {{ display: flex; flex-direction: column; height: 100vh; width: 100vw; }} |
|
|
|
|
|
/* Rows */ |
|
|
.row {{ flex: 1; display: flex; width: 100%; border-bottom: 1px solid #333; }} |
|
|
|
|
|
/* Columns */ |
|
|
.col {{ width: 50%; height: 100%; border-right: 1px solid #333; position: relative; }} |
|
|
.col:last-child {{ border-right: none; }} |
|
|
|
|
|
/* Charts fill their containers */ |
|
|
.chart {{ width: 100%; height: 100%; }} |
|
|
|
|
|
/* Status Badge */ |
|
|
#status {{ position: absolute; top: 10px; left: 60px; z-index: 100; font-size: 14px; background: rgba(0,0,0,0.7); padding: 5px 10px; border-radius: 4px; pointer-events: none; border: 1px solid #333; }} |
|
|
.green {{ color: #00e676; }} |
|
|
.red {{ color: #ff1744; }} |
|
|
</style> |
|
|
</head> |
|
|
<body> |
|
|
<div id="status">Connecting...</div> |
|
|
|
|
|
<div id="container"> |
|
|
<!-- ROW 1 --> |
|
|
<div class="row"> |
|
|
<div class="col"> |
|
|
<!-- Top Left: Price --> |
|
|
<div id="price-chart" class="chart"></div> |
|
|
</div> |
|
|
<div class="col"> |
|
|
<!-- Top Right: Pressure % --> |
|
|
<div id="imb-percent-chart" class="chart"></div> |
|
|
</div> |
|
|
</div> |
|
|
|
|
|
<!-- ROW 2 --> |
|
|
<div class="row"> |
|
|
<div class="col"> |
|
|
<!-- Bottom Left: Volume --> |
|
|
<div id="vol-chart" class="chart"></div> |
|
|
</div> |
|
|
<div class="col"> |
|
|
<!-- Bottom Right: Average Pressure (Mean Integral) --> |
|
|
<div id="mean-chart" class="chart"></div> |
|
|
</div> |
|
|
</div> |
|
|
</div> |
|
|
|
|
|
<script> |
|
|
const priceDiv = document.getElementById('price-chart'); |
|
|
const imbPercentDiv = document.getElementById('imb-percent-chart'); |
|
|
const volDiv = document.getElementById('vol-chart'); |
|
|
const meanDiv = document.getElementById('mean-chart'); |
|
|
|
|
|
const statusDiv = document.getElementById('status'); |
|
|
|
|
|
let initPrice = false, initImbP = false, initVol = false, initMean = false; |
|
|
|
|
|
const commonConfig = {{ responsive: true, displayModeBar: false }}; |
|
|
const commonLayout = {{ |
|
|
paper_bgcolor: '#0e0e0e', |
|
|
plot_bgcolor: '#0e0e0e', |
|
|
font: {{ color: '#aaa' }}, |
|
|
margin: {{ t: 30, b: 25, l: 40, r: 20 }}, |
|
|
showlegend: false, |
|
|
xaxis: {{ gridcolor: '#222' }}, |
|
|
yaxis: {{ gridcolor: '#222' }} |
|
|
}}; |
|
|
|
|
|
async function updateCharts() {{ |
|
|
try {{ |
|
|
const res = await fetch('/data'); |
|
|
const data = await res.json(); |
|
|
|
|
|
if (data.error) {{ |
|
|
statusDiv.innerHTML = "Waiting for data..."; |
|
|
return; |
|
|
}} |
|
|
|
|
|
statusDiv.innerHTML = `Mid: <span class="${{data.mid >= data.prev_mid ? 'green' : 'red'}}">$${{data.mid.toLocaleString(undefined, {{minimumFractionDigits: 2}})}}</span> | Avg Bias: ${{data.mean.last_val ? data.mean.last_val.toFixed(3) : 0}}`; |
|
|
|
|
|
// 1. PRICE HISTORY |
|
|
if (!initPrice) {{ |
|
|
Plotly.newPlot(priceDiv, [{{ 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}} }}], |
|
|
{{ ...commonLayout, title: '<b>Midprice</b>', xaxis: {{type:'date', gridcolor:'#222'}} }}, commonConfig); |
|
|
initPrice = true; |
|
|
}} else {{ |
|
|
Plotly.react(priceDiv, [{{ 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}} }}], |
|
|
{{ ...commonLayout, title: '<b>Midprice</b>', xaxis: {{type:'date', gridcolor:'#222'}} }}, commonConfig); |
|
|
}} |
|
|
|
|
|
// 2. IMBALANCE % |
|
|
const layoutImbP = {{ ...commonLayout, title: '<b>Pressure % (-100 to 100)</b>', yaxis: {{range: [-105, 105], gridcolor:'#222'}} }}; |
|
|
if (!initImbP) {{ Plotly.newPlot(imbPercentDiv, [{{ x: data.imbalance_pct.x, y: data.imbalance_pct.y, type: 'scatter', mode: 'lines', fill: 'tozeroy', line: {{color: '#ffeb3b'}} }}], layoutImbP, commonConfig); initImbP = true; }} |
|
|
else {{ Plotly.react(imbPercentDiv, [{{ x: data.imbalance_pct.x, y: data.imbalance_pct.y, type: 'scatter', mode: 'lines', fill: 'tozeroy', line: {{color: '#ffeb3b'}} }}], layoutImbP, commonConfig); }} |
|
|
|
|
|
// 3. VOLUME BY DISTANCE |
|
|
const layoutVol = {{ ...commonLayout, title: '<b>Volume by Distance</b>' }}; |
|
|
const tracesVol = [ |
|
|
{{ x: data.imbalance_vol.dist_bids, y: data.imbalance_vol.vol_bids, type: 'scatter', name: 'Bid', line: {{color: '#00e676'}} }}, |
|
|
{{ x: data.imbalance_vol.dist_asks, y: data.imbalance_vol.vol_asks, type: 'scatter', name: 'Ask', line: {{color: '#ff1744'}} }} |
|
|
]; |
|
|
if (!initVol) {{ Plotly.newPlot(volDiv, tracesVol, layoutVol, commonConfig); initVol = true; }} |
|
|
else {{ Plotly.react(volDiv, tracesVol, layoutVol, commonConfig); }} |
|
|
|
|
|
// 4. MEAN PRESSURE (-1 to +1) |
|
|
const layoutMean = {{ ...commonLayout, |
|
|
title: '<b>Average Pressure (Integral / Steps)</b>', |
|
|
xaxis: {{title: 'Distance ($)', gridcolor:'#222'}}, |
|
|
yaxis: {{title: 'Bias', range: [-1.1, 1.1], gridcolor:'#222', zeroline: true, zerolinecolor: '#fff'}} |
|
|
}}; |
|
|
|
|
|
const traceMean = {{ |
|
|
x: data.mean.x, |
|
|
y: data.mean.y, |
|
|
type: 'scatter', |
|
|
mode: 'lines', |
|
|
fill: 'tozeroy', |
|
|
line: {{color: '#00bcd4', width: 2}} // Cyan |
|
|
}}; |
|
|
|
|
|
if (!initMean) {{ Plotly.newPlot(meanDiv, [traceMean], layoutMean, commonConfig); initMean = true; }} |
|
|
else {{ Plotly.react(meanDiv, [traceMean], layoutMean, commonConfig); }} |
|
|
|
|
|
}} catch (e) {{ console.error("Fetch error:", e); }} |
|
|
}} |
|
|
|
|
|
setInterval(updateCharts, 500); |
|
|
</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()) |
|
|
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] |
|
|
|
|
|
|
|
|
dist_bids = [(mid - p, q) for p, q in raw_bids if mid - p >= 0] |
|
|
d_b_x, d_b_y = [], [] |
|
|
cum_d = 0 |
|
|
for d, q in dist_bids: |
|
|
cum_d += q |
|
|
d_b_x.append(d); d_b_y.append(cum_d) |
|
|
|
|
|
dist_asks = [(p - mid, q) for p, q in raw_asks if p - mid >= 0] |
|
|
d_a_x, d_a_y = [], [] |
|
|
cum_d = 0 |
|
|
for d, q in dist_asks: |
|
|
cum_d += q |
|
|
d_a_x.append(d); d_a_y.append(cum_d) |
|
|
|
|
|
|
|
|
imb_x, imb_y = [], [] |
|
|
mean_x, mean_y = [], [] |
|
|
running_integral = 0 |
|
|
|
|
|
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 i, s in enumerate(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 |
|
|
|
|
|
|
|
|
total_vol = vol_b + vol_a |
|
|
pct = ((vol_b - vol_a) / total_vol) * 100 if total_vol > 0 else 0 |
|
|
|
|
|
imb_x.append(s) |
|
|
imb_y.append(pct) |
|
|
|
|
|
|
|
|
|
|
|
running_integral += pct |
|
|
step_count = i + 1 |
|
|
mean_pressure = running_integral / step_count |
|
|
|
|
|
|
|
|
norm_mean = mean_pressure / 100.0 |
|
|
|
|
|
mean_x.append(s) |
|
|
mean_y.append(norm_mean) |
|
|
|
|
|
return web.json_response({ |
|
|
"mid": mid, |
|
|
"prev_mid": market_state['history'][-2]['p'] if len(market_state['history']) > 1 else mid, |
|
|
"imbalance_vol": { "dist_bids": d_b_x, "vol_bids": d_b_y, "dist_asks": d_a_x, "vol_asks": d_a_y }, |
|
|
"imbalance_pct": { "x": imb_x, "y": imb_y }, |
|
|
"mean": { "x": mean_x, "y": mean_y, "last_val": mean_y[-1] if mean_y else 0 }, |
|
|
"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 Mean Pressure Dashboard: http://localhost:{PORT}") |
|
|
await asyncio.Event().wait() |
|
|
|
|
|
if __name__ == "__main__": |
|
|
try: asyncio.run(main()) |
|
|
except KeyboardInterrupt: pass |