File size: 19,211 Bytes
3469441
 
 
 
c43af34
b788fc7
a5396a6
 
3469441
a5396a6
a6d8311
a5396a6
b788fc7
a5396a6
 
 
 
 
 
 
 
b788fc7
c955262
74c1714
2324f1b
a5396a6
 
deb82b2
e5d67bc
 
 
 
deb82b2
 
 
e5d67bc
 
deb82b2
e5d67bc
 
74c1714
e5d67bc
74c1714
e5d67bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74c1714
deb82b2
a5396a6
3469441
deb82b2
3469441
deb82b2
 
 
3469441
 
deb82b2
 
 
 
 
 
 
 
b788fc7
 
 
 
 
deb82b2
 
b788fc7
deb82b2
b788fc7
 
 
 
 
deb82b2
 
 
b788fc7
 
 
 
deb82b2
 
b788fc7
 
 
deb82b2
 
b788fc7
 
3469441
 
 
deb82b2
b788fc7
 
 
 
 
deb82b2
 
 
b788fc7
deb82b2
69a5bc2
deb82b2
b788fc7
deb82b2
 
 
b788fc7
deb82b2
 
 
b788fc7
 
deb82b2
 
b788fc7
 
 
deb82b2
 
b788fc7
 
deb82b2
 
 
 
 
66a96ba
d702b3f
c43af34
3469441
 
b788fc7
 
 
 
 
 
 
deb82b2
 
 
 
b788fc7
 
deb82b2
 
 
 
 
 
a6d8311
3469441
b788fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74c1714
deb82b2
74c1714
b788fc7
 
 
deb82b2
 
74c1714
 
deb82b2
a5396a6
b788fc7
 
a5396a6
b788fc7
 
 
 
 
 
 
deb82b2
 
b788fc7
deb82b2
b788fc7
 
 
 
deb82b2
 
b788fc7
 
 
deb82b2
b788fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deb82b2
e5d67bc
b788fc7
 
 
 
 
 
 
 
d702b3f
deb82b2
 
b788fc7
 
deb82b2
a5396a6
a6d8311
deb82b2
3469441
 
 
 
 
a5396a6
 
3469441
 
a6d8311
 
 
 
 
 
a5396a6
 
a6d8311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c955262
 
 
 
deb82b2
c955262
 
b788fc7
c955262
b788fc7
 
c955262
 
 
3469441
 
a6d8311
 
3469441
a5396a6
 
 
 
b788fc7
a5396a6
 
 
a6d8311
 
b788fc7
c43af34
 
a6d8311
74c1714
 
 
 
 
 
 
 
 
 
 
 
 
 
b788fc7
66a96ba
c43af34
 
66a96ba
 
c43af34
74c1714
c43af34
 
 
 
 
66a96ba
b788fc7
69a5bc2
e5d67bc
c43af34
3469441
a6d8311
b788fc7
66a96ba
deb82b2
3469441
 
75f3b2f
 
 
 
 
c43af34
 
75f3b2f
3469441
 
a5396a6
 
75f3b2f
 
3469441
 
 
a5396a6
3469441
5a89d96
deb82b2
3469441
 
a5396a6
5a89d96
 
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
import asyncio
import json
import logging
import time
import bisect
import random
from aiohttp import web
import websockets

# --- Configuration ---
SYMBOL_KRAKEN = "BTC/USD"
PORT = 7860
HISTORY_LENGTH = 300 

# --- Logging ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')

# --- In-Memory State ---
market_state = {
    "bids": {},
    "asks": {},
    "history": [],
    "current_mid": 0.0,
    "prev_mid": 0.0,
    "ready": False
}

# --- AI Logic Helper ---
def analyze_structure(diff_x, diff_y, current_mid):
    if not diff_y or len(diff_y) < 5:
        return None

    # 1. Momentum Projection
    net_total = diff_y[-1] 
    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]

        if prev_val > 0 and curr_val < 0 and resistance_level is None:
            resistance_level = current_mid + dist

        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>
    <script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script>
    <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-red: #ff3b3b;
            --border: #2d3842;
        }}
        body {{ margin: 0; padding: 0; background-color: var(--bg-color); color: var(--text-main); font-family: monospace; overflow: hidden; height: 100vh; width: 100vw; }}
        
        .grid-container {{ display: grid; grid-template-columns: 3fr 1fr; grid-template-rows: 2fr 1fr; 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; }}
        
        #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 #45a29e; }}

        .panel-header {{ padding: 8px 12px; background: #0f1116; border-bottom: 1px solid var(--border); font-size: 12px; font-weight: bold; display: flex; justify-content: space-between; color: var(--accent-green); }}
        
        #tv-chart, #depth-chart {{ flex: 1; width: 100%; }}
        .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; }}
        .green {{ color: var(--accent-green); }}
        .red {{ color: var(--accent-red); }}
        
        .terminal-box {{ margin-top: auto; font-size: 11px; height: 300px; display: flex; flex-direction: column; }}
        .term-header {{ border-bottom: 1px dashed #444; margin-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; }}
        
        .meter-container {{ width: 100%; height: 6px; background: #333; margin-top: 10px; position: relative; overflow: hidden; }}
        .meter-bar {{ height: 100%; width: 50%; background: #555; position: absolute; left: 0; transition: all 0.5s; }}
        .mid-mark {{ position: absolute; left: 50%; height: 100%; width: 2px; background: #fff; z-index: 10; }}

        #loader {{ position: absolute; top:0; left:0; width:100%; height:100%; background: rgba(0,0,0,0.95); z-index: 999; display: flex; flex-direction: column; justify-content: center; align-items: center; color: var(--accent-green); }}
        #error-log {{ color: var(--accent-red); font-size: 12px; margin-top: 20px; max-width: 80%; text-align: center; }}
    </style>
</head>
<body>

    <div id="loader">
        <div style="font-size: 24px; margin-bottom: 10px;">INITIALIZING AI MODELS...</div>
        <div id="loading-status" style="font-size: 14px; color: #888;">Connecting to WebSocket...</div>
        <div id="error-log"></div>
    </div>

    <div class="grid-container">
        <div id="p-price" class="panel">
            <div class="panel-header"><span>BTC/USD Price Action</span><span id="live-price">---</span></div>
            <div id="tv-chart"></div>
        </div>
        <div id="p-depth" class="panel">
            <div class="panel-header"><span>Liquidity Structure</span><span>DEPTH 300</span></div>
            <div id="depth-chart"></div>
        </div>
        <div id="p-stats" class="panel">
            <div class="panel-header">ANALYTICS ENGINE</div>
            <div class="stats-content">
                <div class="stat-box">
                    <span class="stat-label">NET LIQUIDITY SCORE</span>
                    <span id="score-val" class="stat-value">0</span>
                    <div class="meter-container"><div class="mid-mark"></div><div id="score-bar" class="meter-bar" style="left: 50%; width: 0%;"></div></div>
                </div>
                <div class="stat-box">
                    <span class="stat-label">STRUCTURE</span>
                    <div style="display:flex; justify-content:space-between;"><span>RES:</span><span id="res-val" class="red">---</span></div>
                    <div style="display:flex; justify-content:space-between;"><span>SUP:</span><span id="sup-val" class="green">---</span></div>
                </div>
                <div class="stat-box" style="border: 1px solid #444;">
                    <span class="stat-label" style="color:var(--accent-green);">AI PROJECTION</span>
                    <span id="proj-val" class="stat-value">---</span>
                </div>
                <div class="terminal-box">
                    <div class="term-header">> SYSTEM LOGS</div>
                    <div id="term-logs"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Global Error Handler
        window.onerror = function(msg, url, lineNo, columnNo, error) {{
            const errDiv = document.getElementById('error-log');
            errDiv.innerHTML += `ERROR: ${{msg}} (Line: ${{lineNo}})<br>`;
            document.getElementById('loading-status').style.color = 'red';
            document.getElementById('loading-status').innerText = "SYSTEM FAILURE - CHECK CONSOLE";
            return false;
        }};

        const dom = {{
            loader: document.getElementById('loader'),
            status: document.getElementById('loading-status'),
            price: document.getElementById('live-price'),
            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')
        }};

        // Verify Libraries
        if (typeof LightweightCharts === 'undefined') throw new Error("LightweightCharts CDN failed to load.");
        if (typeof Plotly === 'undefined') throw new Error("Plotly CDN failed to load.");

        // --- CHART SETUP ---
        const chart = LightweightCharts.createChart(document.getElementById('tv-chart'), {{
            layout: {{ background: {{ type: 'solid', color: '#12141a' }}, textColor: '#888' }},
            grid: {{ vertLines: {{ color: '#1f2833' }}, horzLines: {{ color: '#1f2833' }} }},
            timeScale: {{ timeVisible: true, secondsVisible: true }},
        }});
        const lineSeries = chart.addLineSeries({{ color: '#2962FF', lineWidth: 2 }});
        const predSeries = chart.addLineSeries({{ color: '#ff9800', lineWidth: 2, lineStyle: 2 }}); // Dotted
        
        let supportLine = null, resistanceLine = null;

        // Auto Resize
        new ResizeObserver(entries => {{
            if (entries[0].target) {{
                const r = entries[0].contentRect;
                chart.applyOptions({{ width: r.width, height: r.height }});
            }}
        }}).observe(document.getElementById('tv-chart'));

        // Plotly Setup
        Plotly.newPlot('depth-chart', [], {{
            paper_bgcolor: '#12141a', plot_bgcolor: '#12141a',
            font: {{ color: '#888', family: 'monospace' }},
            margin: {{ t: 10, b: 30, l: 40, r: 20 }},
            xaxis: {{ gridcolor: '#1f2833' }}, yaxis: {{ gridcolor: '#1f2833' }},
            showlegend: false
        }}, {{ responsive: true, displayModeBar: false }});

        function log(msg, type='neutral') {{
            const div = document.createElement('div');
            div.className = 'log-line';
            div.style.borderLeftColor = type === 'bull' ? '#66fcf1' : type === 'bear' ? '#ff3b3b' : '#333';
            div.innerHTML = `<span style="opacity:0.5">${{new Date().toLocaleTimeString()}}</span> ${{msg}}`;
            dom.logs.prepend(div);
            if (dom.logs.children.length > 20) dom.logs.removeChild(dom.logs.lastChild);
        }}

        async function fetchData() {{
            try {{
                // Cache busting with timestamp to prevent stuck "Initializing" state
                const res = await fetch('/data?t=' + Date.now());
                const data = await res.json();

                if (data.error) {{
                    dom.status.innerText = "Waiting for market data...";
                    return;
                }}

                // Data received - Hide Loader
                dom.loader.style.display = 'none';

                // 1. Update Price Chart
                const uniqueHistory = [];
                const seen = new Set();
                data.history.forEach(d => {{
                    const t = Math.floor(d.t); 
                    if (!seen.has(t)) {{ seen.add(t); uniqueHistory.push({{ time: t, value: d.p }}); }}
                }});
                
                if (uniqueHistory.length > 0) {{
                    lineSeries.setData(uniqueHistory);
                    const last = uniqueHistory[uniqueHistory.length - 1];
                    
                    if (data.analysis) {{
                        const {{ projected, support, resistance, net_score }} = data.analysis;
                        
                        // Prediction
                        predSeries.setData([last, {{ time: last.time + 60, value: projected }}]);
                        dom.projVal.innerText = projected.toFixed(2);
                        dom.price.innerText = data.mid.toFixed(2);

                        // S/R Lines
                        if (support) {{
                            dom.supVal.innerText = support.toFixed(0);
                            if (!supportLine) supportLine = lineSeries.createPriceLine({{ price: support, color: '#00e676', 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', title: 'RES' }});
                            else resistanceLine.applyOptions({{ price: resistance }});
                        }} else {{
                            dom.resVal.innerText = '---';
                            if (resistanceLine) {{ lineSeries.removePriceLine(resistanceLine); resistanceLine = null; }}
                        }}

                        // Score Meter
                        dom.scoreVal.innerText = net_score.toFixed(1);
                        dom.scoreVal.className = net_score > 0 ? "stat-value green" : "stat-value red";
                        let barW = Math.min(Math.abs(net_score)*2, 50);
                        dom.scoreBar.style.width = barW + '%';
                        dom.scoreBar.style.left = net_score > 0 ? '50%' : (50 - barW) + '%';
                        dom.scoreBar.style.background = net_score > 0 ? '#66fcf1' : '#ff3b3b';

                        // Random Logs
                        if (Math.random() > 0.95) {{
                            if (net_score > 30) log("Significant Bullish flow", 'bull');
                            if (net_score < -30) log("Significant Bearish flow", 'bear');
                        }}
                    }}
                }}

                // 2. Update Depth Chart
                const trace = {{ x: data.diff.x, y: data.diff.y, type: 'scatter', fill: 'tozeroy', line: {{color: '#e040fb'}} }};
                Plotly.react('depth-chart', [trace], {{
                    paper_bgcolor: '#12141a', plot_bgcolor: '#12141a',
                    font: {{ color: '#888' }}, margin: {{ t: 10, b: 20, l: 30, r: 10 }},
                    xaxis: {{ showgrid: false }}, yaxis: {{ showgrid: true, gridcolor: '#333' }},
                    shapes: [{{ type: 'line', x0: 0, x1: 1, xref: 'paper', y0: 0, y1: 0, line: {{color: '#555'}} }}]
                }}, {{ displayModeBar: false }});

            }} catch (e) {{
                console.error(e);
                // Do not show error on UI for transient fetch errors, just log to console
                // unless it persists
            }}
        }}

        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:
                            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()
                            # Throttle history recording (200ms)
                            if not market_state['history'] or (now - market_state['history'][-1]['t'] > 0.2):
                                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):
    # Returns JSON. If not ready, returns error field.
    if not market_state['ready']:
        return web.json_response({"error": "Initializing..."})

    mid = market_state['current_mid']
    
    # Snapshot & process
    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)

    # Net Liquidity Curve
    diff_x, diff_y = [], []
    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.append(vol_b - vol_a)

    analysis = analyze_structure(diff_x, diff_y, mid)

    return web.json_response({
        "mid": mid,
        "history": market_state['history'],
        "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