File size: 35,897 Bytes
3469441 25c08cc a0c3495 25c08cc c044198 25c08cc 30fe49c a5396a6 3469441 6349f64 a5396a6 7c6576b 58b7790 3a80860 7c6576b a5396a6 25c08cc 6d1f4cf a5396a6 7c6576b 6349f64 c955262 25c08cc a5396a6 669adc5 25c08cc 7740db1 25c08cc 7740db1 25c08cc 3a80860 25c08cc 3a80860 25c08cc 3a80860 25c08cc 7c6576b 25c08cc 6d1f4cf 25c08cc 74c1714 d6d83d7 669adc5 6349f64 669adc5 6349f64 25c08cc 7c6576b 25c08cc 7c6576b 25c08cc 6349f64 25c08cc d6d83d7 7c6576b 25c08cc 6349f64 669adc5 1530d0a 25c08cc d6d83d7 25c08cc a574eba 25c08cc 3a80860 7740db1 669adc5 df9cdf6 3469441 deb82b2 3469441 deb82b2 25c08cc 7252530 6eaed7c 3469441 25c08cc d6d83d7 25c08cc 6eaed7c 25c08cc df9cdf6 25c08cc 8b9c571 25c08cc 6eaed7c 25c08cc 8b9c571 25c08cc d6d83d7 25c08cc 3469441 7c6576b df9cdf6 7c6576b 25c08cc 7c6576b d6d83d7 7c6576b 25c08cc 7c6576b df9cdf6 7c6576b 25c08cc 7c6576b df9cdf6 7c6576b 25c08cc 7c6576b 25c08cc 7c6576b 25c08cc 7c6576b 25c08cc 7c6576b 25c08cc 7c6576b 25c08cc 7c6576b 25c08cc 7c6576b d702b3f c43af34 7c6576b d6d83d7 7c6576b 25c08cc 7c6576b 78b3589 7c6576b 6349f64 7c6576b d6d83d7 7c6576b d6d83d7 7c6576b d6d83d7 7c6576b d6d83d7 7c6576b 25c08cc d6d83d7 7c6576b 7740db1 7c6576b 25c08cc 7c6576b 78b3589 7c6576b 78b3589 7c6576b 25c08cc 7c6576b 25c08cc 7c6576b 25c08cc 7c6576b 3469441 a5396a6 c044198 d6d83d7 c044198 6349f64 c044198 25c08cc c044198 25c08cc c044198 3469441 a6d8311 25c08cc f95b3cf 25c08cc a5396a6 a6d8311 30fe49c a6d8311 30fe49c a6d8311 25c08cc a6d8311 25c08cc df9cdf6 c955262 25c08cc c955262 25c08cc f95b3cf 25c08cc 78b3589 25c08cc 78b3589 25c08cc 78b3589 d6d83d7 78b3589 d6d83d7 78b3589 d6d83d7 78b3589 a574eba 25c08cc d6d83d7 78b3589 25c08cc 78b3589 25c08cc 78b3589 25c08cc 3469441 25c08cc 3469441 669adc5 25c08cc 669adc5 175cf4a 669adc5 c43af34 669adc5 3469441 75f3b2f 669adc5 75f3b2f 669adc5 25c08cc 75f3b2f 3469441 a5396a6 30fe49c 75f3b2f 3469441 a5396a6 3469441 25c08cc 3469441 a5396a6 df9cdf6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
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 |