File size: 14,516 Bytes
3469441
 
 
 
c43af34
a5396a6
 
3469441
a5396a6
a6d8311
a5396a6
a6d8311
a5396a6
 
 
 
 
 
 
 
5a89d96
c955262
a5396a6
 
 
a6d8311
a5396a6
3469441
 
 
6c45e3b
3469441
 
c955262
 
c43af34
 
 
6c45e3b
 
c43af34
6c45e3b
 
 
 
 
 
c43af34
 
 
c955262
6c45e3b
 
a5396a6
 
3469441
 
 
a6d8311
 
c43af34
6c45e3b
c43af34
6c45e3b
 
 
 
 
 
c43af34
6c45e3b
 
c43af34
6c45e3b
 
 
 
 
 
c43af34
 
3469441
 
6c45e3b
c955262
6c45e3b
 
 
 
a5396a6
c955262
6c45e3b
a6d8311
6c45e3b
 
 
a6d8311
6c45e3b
a6d8311
 
 
 
 
6c45e3b
c43af34
 
 
a6d8311
3469441
c955262
a5396a6
 
 
3469441
a5396a6
a6d8311
a5396a6
 
3469441
6c45e3b
 
 
 
 
c43af34
6c45e3b
a6d8311
6c45e3b
 
 
 
 
 
 
 
 
 
 
 
c43af34
6c45e3b
 
 
c43af34
a5396a6
6c45e3b
 
 
c43af34
6c45e3b
c43af34
 
5a89d96
a6d8311
c43af34
 
6c45e3b
c43af34
 
 
 
6c45e3b
c43af34
 
5a89d96
6c45e3b
 
 
 
 
 
 
 
 
 
c43af34
6c45e3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c43af34
a5396a6
a6d8311
a5396a6
a6d8311
 
3469441
 
 
 
 
a5396a6
 
3469441
 
a6d8311
 
 
 
 
 
a5396a6
 
a6d8311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c955262
 
 
 
 
 
 
 
a6d8311
c955262
 
 
3469441
 
a6d8311
 
3469441
a5396a6
 
 
 
 
 
 
a6d8311
 
 
c43af34
 
a6d8311
c43af34
a6d8311
a5396a6
a6d8311
a5396a6
a6d8311
 
c43af34
13ec341
a6d8311
a5396a6
a6d8311
a5396a6
a6d8311
 
5a89d96
c43af34
 
a6d8311
 
c43af34
a6d8311
 
 
 
c43af34
a6d8311
 
c43af34
a6d8311
 
 
3469441
c43af34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3469441
a6d8311
 
 
c43af34
 
c955262
3469441
 
75f3b2f
 
 
 
 
c43af34
 
75f3b2f
3469441
 
a5396a6
 
75f3b2f
 
3469441
 
 
a5396a6
3469441
5a89d96
6c45e3b
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
import asyncio
import json
import logging
import time
import bisect
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,
    "ready": False
}

# --- HTML Frontend (Plotly.js) ---
HTML_PAGE = f"""
<!DOCTYPE html>
<html>
<head>
    <title>BTC-USD Premium Dashboard</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 */
        #container {{ display: flex; flex-direction: column; height: 100vh; width: 100vw; }}
        
        /* Row 1: High Priority (Price & Ratio) */
        #row-top {{ flex: 1; display: flex; width: 100%; border-bottom: 1px solid #333; }}
        
        /* Row 2: Secondary Data (Depth & Imbalance) */
        #row-bot {{ flex: 1; display: flex; width: 100%; }}

        /* Columns */
        .col-left {{ width: 50%; border-right: 1px solid #333; position: relative; }}
        .col-right {{ width: 50%; position: relative; }}

        /* 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">
        <!-- TOP ROW: PRICE & RATIO -->
        <div id="row-top">
            <div class="col-left">
                <div id="price-chart" class="chart"></div>
            </div>
            <div class="col-right">
                <div id="ratio-chart" class="chart"></div>
            </div>
        </div>

        <!-- BOTTOM ROW: DEPTH & IMBALANCE -->
        <div id="row-bot">
            <div class="col-left">
                <div id="depth-chart" class="chart"></div>
            </div>
            <div class="col-right">
                <div id="imbalance-chart" class="chart"></div>
            </div>
        </div>
    </div>

    <script>
        // Chart Targets
        const priceDiv = document.getElementById('price-chart');
        const ratioDiv = document.getElementById('ratio-chart');
        const depthDiv = document.getElementById('depth-chart');
        const imbDiv = document.getElementById('imbalance-chart');
        
        const statusDiv = document.getElementById('status');
        
        // Init Flags
        let initPrice = false;
        let initRatio = false;
        let initDepth = false;
        let initImb = false;

        // Shared Config
        const commonConfig = {{ responsive: true, displayModeBar: false }};
        const commonLayout = {{
            paper_bgcolor: '#0e0e0e',
            plot_bgcolor: '#0e0e0e',
            font: {{ color: '#aaa' }},
            margin: {{ t: 40, b: 30, l: 50, 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;
                }}

                // Status Header
                const lastRatio = data.ratio.last_val;
                let ratioColor = '#aaa';
                if(lastRatio > 1.2) ratioColor = '#00e676'; // Bullish
                if(lastRatio < 0.8) ratioColor = '#ff1744'; // Bearish

                statusDiv.innerHTML = `Mid: <span class="${{data.mid >= data.prev_mid ? 'green' : 'red'}}">$${{data.mid.toLocaleString(undefined, {{minimumFractionDigits: 2}})}}</span> | Ratio: <span style="color:${{ratioColor}}">${{lastRatio ? lastRatio.toFixed(2) : '-'}}</span>`;

                // ----------------------------------------------------
                // 1. PRICE HISTORY (Top Left)
                // ----------------------------------------------------
                const timeData = data.history.map(d => new Date(d.t * 1000));
                const priceData = data.history.map(d => d.p);
                const layoutPrice = {{ ...commonLayout, title: '<b>Midprice History</b>', xaxis: {{type:'date', gridcolor:'#222'}} }};
                
                if (!initPrice) {{
                    Plotly.newPlot(priceDiv, [
                        {{ x: timeData, y: priceData, type: 'scatter', mode:'lines', name: 'Mid', line: {{color: '#29b6f6', width: 2}} }}
                    ], layoutPrice, commonConfig);
                    initPrice = true;
                }} else {{
                    Plotly.react(priceDiv, [
                        {{ x: timeData, y: priceData, type: 'scatter', mode:'lines', name: 'Mid', line: {{color: '#29b6f6', width: 2}} }}
                    ], layoutPrice, commonConfig);
                }}

                // ----------------------------------------------------
                // 2. RATIO (Top Right)
                // ----------------------------------------------------
                const layoutRatio = {{ ...commonLayout, 
                    title: '<b>Buy/Sell Liquidity Ratio</b>', 
                    xaxis: {{title: 'Distance ($)', gridcolor:'#222'}},
                    shapes: [{{ type: 'line', x0: 0, x1: 1, xref: 'paper', y0: 1, y1: 1, line: {{color: '#666', width: 1, dash:'dot'}} }}] 
                }};
                
                if (!initRatio) {{
                    Plotly.newPlot(ratioDiv, [
                        {{ x: data.ratio.x, y: data.ratio.y, type: 'scatter', mode:'lines', name: 'Ratio', line: {{color: '#00bcd4', width:2}} }}
                    ], layoutRatio, commonConfig);
                    initRatio = true;
                }} else {{
                    Plotly.react(ratioDiv, [
                        {{ x: data.ratio.x, y: data.ratio.y, type: 'scatter', mode:'lines', name: 'Ratio', line: {{color: '#00bcd4', width:2}} }}
                    ], layoutRatio, commonConfig);
                }}

                // ----------------------------------------------------
                // 3. DEPTH CHART (Bottom Left)
                // ----------------------------------------------------
                const layoutDepth = {{ ...commonLayout, title: 'Orderbook Depth', xaxis: {{title: 'Price', gridcolor:'#222'}} }};
                if (!initDepth) {{
                    Plotly.newPlot(depthDiv, [
                        {{ x: data.depth.bids_x, y: data.depth.bids_y, fill: 'tozeroy', type: 'scatter', name: 'Bids', line: {{color: '#00e676'}} }},
                        {{ x: data.depth.asks_x, y: data.depth.asks_y, fill: 'tozeroy', type: 'scatter', name: 'Asks', line: {{color: '#ff1744'}} }}
                    ], layoutDepth, commonConfig);
                    initDepth = true;
                }} else {{
                    Plotly.react(depthDiv, [
                        {{ x: data.depth.bids_x, y: data.depth.bids_y, fill: 'tozeroy', type: 'scatter', name: 'Bids', line: {{color: '#00e676'}} }},
                        {{ x: data.depth.asks_x, y: data.depth.asks_y, fill: 'tozeroy', type: 'scatter', name: 'Asks', line: {{color: '#ff1744'}} }}
                    ], layoutDepth, commonConfig);
                }}

                // ----------------------------------------------------
                // 4. IMBALANCE VOL (Bottom Right)
                // ----------------------------------------------------
                const layoutImb = {{ ...commonLayout, title: 'Volume by Distance', xaxis: {{title: 'Distance ($)', gridcolor:'#222'}} }};
                if (!initImb) {{
                    Plotly.newPlot(imbDiv, [
                        {{ x: data.imbalance.dist_bids, y: data.imbalance.vol_bids, type: 'scatter', name: 'Bid Vol', line: {{color: '#00e676'}} }},
                        {{ x: data.imbalance.dist_asks, y: data.imbalance.vol_asks, type: 'scatter', name: 'Ask Vol', line: {{color: '#ff1744'}} }}
                    ], layoutImb, commonConfig);
                    initImb = true;
                }} else {{
                    Plotly.react(imbDiv, [
                        {{ x: data.imbalance.dist_bids, y: data.imbalance.vol_bids, type: 'scatter', name: 'Bid Vol', line: {{color: '#00e676'}} }},
                        {{ x: data.imbalance.dist_asks, y: data.imbalance.vol_asks, type: 'scatter', name: 'Ask Vol', line: {{color: '#ff1744'}} }}
                    ], layoutImb, 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']
    
    # --- Prepare Raw Data ---
    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]

    # --- 1. Depth (Price) ---
    b_x, b_y = [], []
    cum = 0
    for p, q in raw_bids:
        cum += q
        b_x.append(p)
        b_y.append(cum)
    b_x.reverse(); b_y.reverse()

    a_x, a_y = [], []
    cum = 0
    for p, q in raw_asks:
        cum += q
        a_x.append(p)
        a_y.append(cum)

    # --- 2. Distance Arrays ---
    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)

    # --- 3. Ratio Calculation (Interp) ---
    r_x, r_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
            
            if vol_a > 0:
                ratio = vol_b / vol_a
                if ratio > 5: ratio = 5
                r_x.append(s)
                r_y.append(ratio)

    return web.json_response({
        "mid": mid,
        "prev_mid": market_state['history'][-2]['p'] if len(market_state['history']) > 1 else mid,
        "depth": { "bids_x": b_x, "bids_y": b_y, "asks_x": a_x, "asks_y": a_y },
        "imbalance": { "dist_bids": d_b_x, "vol_bids": d_b_y, "dist_asks": d_a_x, "vol_asks": d_a_y },
        "ratio": { "x": r_x, "y": r_y, "last_val": r_y[-1] if r_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 Premium Dashboard: http://localhost:{PORT}")
    await asyncio.Event().wait()

if __name__ == "__main__":
    try: asyncio.run(main())
    except KeyboardInterrupt: pass