zt p commited on
Commit
a4999bf
·
1 Parent(s): b530ff1

Add core asset candlestick chart

Browse files
app/core/dashboard.py CHANGED
@@ -208,6 +208,83 @@ def render_dashboard():
208
  font-size: 12px;
209
  overflow-wrap: anywhere;
210
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  .btc-reference {
212
  display: grid;
213
  grid-template-columns: 1fr auto;
@@ -543,6 +620,8 @@ def render_dashboard():
543
  .core-price-panel { border-right: 0; border-bottom: 1px solid rgba(255, 255, 255, .12); }
544
  .market-detail-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
545
  .strategy-grid { grid-template-columns: 1fr; }
 
 
546
  .config-shell { grid-template-columns: 1fr; }
547
  .config-nav { border-right: 0; border-bottom: 1px solid var(--line); display: flex; gap: 8px; overflow-x: auto; }
548
  .config-panel { max-height: 680px; }
@@ -557,6 +636,8 @@ def render_dashboard():
557
  .market-detail-grid { grid-template-columns: 1fr; }
558
  .core-price-panel { padding: 18px; }
559
  .market-tile { min-height: 86px; }
 
 
560
  .btc-reference { grid-template-columns: 1fr; }
561
  .btc-reference strong { white-space: normal; }
562
  .strategy-grid { grid-template-columns: 1fr; }
@@ -662,6 +743,26 @@ def render_dashboard():
662
  </div>
663
  </div>
664
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665
  </section>
666
 
667
  <section>
@@ -1000,6 +1101,11 @@ def render_dashboard():
1000
  let currentConfig = null;
1001
  let currentCoin = null;
1002
  let activePanel = "global";
 
 
 
 
 
1003
  let uiEvents = [];
1004
 
1005
  const globalFields = [
@@ -1113,6 +1219,238 @@ def render_dashboard():
1113
  el.classList.toggle("down", Number.isFinite(n) && n < 0);
1114
  }
1115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1116
  function formatMonitorMeta(monitor) {
1117
  if (!monitor) return "等待监控注册";
1118
  if (isPaused(monitor)) return "已暂停";
@@ -1462,6 +1800,11 @@ def render_dashboard():
1462
  document.getElementById("alertCount").textContent = data.crypto?.stats?.alerts ?? alerts.length;
1463
  document.getElementById("updated").textContent = new Date().toLocaleString();
1464
  renderCoreMarket(data.crypto?.core_market);
 
 
 
 
 
1465
  renderStrategySummary(monitors);
1466
 
1467
  document.getElementById("monitorRows").innerHTML = monitors.map((m) => {
@@ -1922,6 +2265,8 @@ def render_dashboard():
1922
 
1923
  loadStatus();
1924
  loadConfig();
 
 
1925
  setInterval(loadStatus, 15000);
1926
  if ("serviceWorker" in navigator) {
1927
  window.addEventListener("load", () => {
 
208
  font-size: 12px;
209
  overflow-wrap: anywhere;
210
  }
211
+ .core-chart {
212
+ padding: 18px 20px 20px;
213
+ border-top: 1px solid rgba(255, 255, 255, .12);
214
+ }
215
+ .core-chart-head {
216
+ display: flex;
217
+ align-items: center;
218
+ justify-content: space-between;
219
+ gap: 12px;
220
+ flex-wrap: wrap;
221
+ margin-bottom: 14px;
222
+ }
223
+ .core-chart-title h3 {
224
+ margin: 0;
225
+ font-size: 16px;
226
+ font-weight: 750;
227
+ }
228
+ .core-chart-title small {
229
+ display: block;
230
+ margin-top: 4px;
231
+ color: #cbd5e1;
232
+ font-size: 12px;
233
+ }
234
+ .chart-controls {
235
+ display: flex;
236
+ align-items: center;
237
+ gap: 6px;
238
+ flex-wrap: wrap;
239
+ }
240
+ .chart-pill {
241
+ min-height: 30px;
242
+ padding: 5px 10px;
243
+ border: 1px solid rgba(255, 255, 255, .16);
244
+ border-radius: 999px;
245
+ background: rgba(255, 255, 255, .07);
246
+ color: #e5e7eb;
247
+ cursor: pointer;
248
+ box-shadow: none;
249
+ }
250
+ .chart-pill:hover { border-color: rgba(255, 255, 255, .30); background: rgba(255, 255, 255, .11); }
251
+ .chart-pill.active {
252
+ border-color: rgba(45, 212, 191, .55);
253
+ background: rgba(45, 212, 191, .14);
254
+ color: #99f6e4;
255
+ font-weight: 750;
256
+ }
257
+ .chart-shell {
258
+ position: relative;
259
+ height: 330px;
260
+ border: 1px solid rgba(255, 255, 255, .10);
261
+ border-radius: 8px;
262
+ background: linear-gradient(180deg, rgba(255,255,255,.045) 0%, rgba(255,255,255,.015) 100%);
263
+ }
264
+ #coreCandleChart { display: block; width: 100%; height: 100%; cursor: crosshair; }
265
+ .chart-tooltip {
266
+ position: absolute;
267
+ z-index: 3;
268
+ display: none;
269
+ min-width: 168px;
270
+ padding: 9px 10px;
271
+ border: 1px solid rgba(255, 255, 255, .16);
272
+ border-radius: 7px;
273
+ background: rgba(17, 24, 39, .95);
274
+ color: #f9fafb;
275
+ font-size: 12px;
276
+ line-height: 1.45;
277
+ pointer-events: none;
278
+ box-shadow: 0 10px 24px rgba(0, 0, 0, .28);
279
+ }
280
+ .chart-message {
281
+ min-height: 20px;
282
+ margin-top: 9px;
283
+ color: #cbd5e1;
284
+ font-size: 12px;
285
+ }
286
+ .chart-message.error { color: #fda4af; }
287
+ .chart-tooltip { white-space: pre-line; }
288
  .btc-reference {
289
  display: grid;
290
  grid-template-columns: 1fr auto;
 
620
  .core-price-panel { border-right: 0; border-bottom: 1px solid rgba(255, 255, 255, .12); }
621
  .market-detail-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
622
  .strategy-grid { grid-template-columns: 1fr; }
623
+ .core-chart { padding: 16px; }
624
+ .chart-shell { height: 300px; }
625
  .config-shell { grid-template-columns: 1fr; }
626
  .config-nav { border-right: 0; border-bottom: 1px solid var(--line); display: flex; gap: 8px; overflow-x: auto; }
627
  .config-panel { max-height: 680px; }
 
636
  .market-detail-grid { grid-template-columns: 1fr; }
637
  .core-price-panel { padding: 18px; }
638
  .market-tile { min-height: 86px; }
639
+ .core-chart { padding: 14px; }
640
+ .chart-shell { height: 250px; }
641
  .btc-reference { grid-template-columns: 1fr; }
642
  .btc-reference strong { white-space: normal; }
643
  .strategy-grid { grid-template-columns: 1fr; }
 
743
  </div>
744
  </div>
745
  </div>
746
+ <div class="core-chart">
747
+ <div class="core-chart-head">
748
+ <div class="core-chart-title">
749
+ <h3 id="coreChartTitle">核心资产 K线</h3>
750
+ <small id="coreChartMeta">等待行情数据</small>
751
+ </div>
752
+ <div class="chart-controls" id="coreChartControls">
753
+ <button class="chart-pill" data-chart-interval="1m">1m</button>
754
+ <button class="chart-pill" data-chart-interval="15m">15m</button>
755
+ <button class="chart-pill active" data-chart-interval="1h">1h</button>
756
+ <button class="chart-pill" data-chart-interval="4h">4h</button>
757
+ <button class="chart-pill" data-chart-interval="1d">1d</button>
758
+ </div>
759
+ </div>
760
+ <div class="chart-shell">
761
+ <canvas id="coreCandleChart"></canvas>
762
+ <div id="coreChartTooltip" class="chart-tooltip"></div>
763
+ </div>
764
+ <div id="coreChartMessage" class="chart-message">正在加载K线...</div>
765
+ </div>
766
  </section>
767
 
768
  <section>
 
1101
  let currentConfig = null;
1102
  let currentCoin = null;
1103
  let activePanel = "global";
1104
+ let chartInterval = "1h";
1105
+ let chartCoin = null;
1106
+ let chartCandles = [];
1107
+ let chartLayout = null;
1108
+ let chartRequestToken = 0;
1109
  let uiEvents = [];
1110
 
1111
  const globalFields = [
 
1219
  el.classList.toggle("down", Number.isFinite(n) && n < 0);
1220
  }
1221
 
1222
+ function chartIntervalLabel(interval) {
1223
+ return {
1224
+ "1m": "1分钟",
1225
+ "5m": "5分钟",
1226
+ "15m": "15分��",
1227
+ "1h": "1小时",
1228
+ "4h": "4小时",
1229
+ "1d": "日线"
1230
+ }[interval] || interval;
1231
+ }
1232
+
1233
+ function chartTimeLabel(value, short = false) {
1234
+ const date = new Date(Number(value));
1235
+ if (Number.isNaN(date.getTime())) return "--";
1236
+ if (chartInterval === "1d") {
1237
+ return date.toLocaleDateString(undefined, {month: "2-digit", day: "2-digit"});
1238
+ }
1239
+ if (short) {
1240
+ return date.toLocaleString(undefined, {month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hour12: false});
1241
+ }
1242
+ return date.toLocaleString(undefined, {hour12: false});
1243
+ }
1244
+
1245
+ async function loadCoreChart() {
1246
+ const core = currentConfig?.coins ? Object.values(currentConfig.coins).find((coin) => coin.core_display) : null;
1247
+ const coin = core ? Object.keys(currentConfig.coins).find((name) => currentConfig.coins[name].core_display) : "GRAM";
1248
+ if (!coin) return;
1249
+
1250
+ const token = ++chartRequestToken;
1251
+ const message = document.getElementById("coreChartMessage");
1252
+ if (message) {
1253
+ message.textContent = "正在加载K线...";
1254
+ message.className = "chart-message";
1255
+ }
1256
+ try {
1257
+ const res = await fetch(`/api/crypto/${encodeURIComponent(coin)}/klines?interval=${encodeURIComponent(chartInterval)}&limit=160`);
1258
+ if (!res.ok) throw new Error(await res.text());
1259
+ const data = await res.json();
1260
+ if (token !== chartRequestToken) return;
1261
+ chartCoin = coin;
1262
+ chartCandles = (data.candles || []).map((item) => ({
1263
+ time: Number(item.time),
1264
+ open: Number(item.open),
1265
+ high: Number(item.high),
1266
+ low: Number(item.low),
1267
+ close: Number(item.close),
1268
+ volume: Number(item.volume),
1269
+ quoteVolume: Number(item.quote_volume)
1270
+ })).filter((item) => [item.time, item.open, item.high, item.low, item.close].every(Number.isFinite));
1271
+
1272
+ if (!chartCandles.length) throw new Error("K线数据为空");
1273
+ setText("coreChartTitle", `${coin} K线`);
1274
+ setText("coreChartMeta", `${data.symbol || "--"} · ${chartIntervalLabel(chartInterval)} · ${chartCandles.length} 根`);
1275
+ message.textContent = "";
1276
+ drawCoreCandleChart();
1277
+ } catch (err) {
1278
+ if (token === chartRequestToken) {
1279
+ chartCandles = [];
1280
+ drawCoreCandleChart();
1281
+ if (message) {
1282
+ message.textContent = "K线加载失败:" + err.message;
1283
+ message.className = "chart-message error";
1284
+ }
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ function drawCoreCandleChart() {
1290
+ const canvas = document.getElementById("coreCandleChart");
1291
+ if (!canvas) return;
1292
+ const rect = canvas.getBoundingClientRect();
1293
+ const width = Math.max(280, rect.width);
1294
+ const height = Math.max(220, rect.height);
1295
+ const dpr = window.devicePixelRatio || 1;
1296
+ canvas.width = Math.round(width * dpr);
1297
+ canvas.height = Math.round(height * dpr);
1298
+ const ctx = canvas.getContext("2d");
1299
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
1300
+ ctx.clearRect(0, 0, width, height);
1301
+
1302
+ const left = 62;
1303
+ const right = 18;
1304
+ const top = 16;
1305
+ const xAxisHeight = 40;
1306
+ const volumeHeight = Math.max(52, Math.round(height * 0.18));
1307
+ const volumeTop = height - xAxisHeight - volumeHeight;
1308
+ const priceBottom = volumeTop - 12;
1309
+ const plotWidth = Math.max(20, width - left - right);
1310
+ const plotHeight = Math.max(60, priceBottom - top);
1311
+ const count = chartCandles.length;
1312
+ chartLayout = {left, right, top, priceBottom, plotWidth, plotHeight};
1313
+
1314
+ if (!count) {
1315
+ ctx.fillStyle = "#94a3b8";
1316
+ ctx.font = "13px system-ui, -apple-system, BlinkMacSystemFont, sans-serif";
1317
+ ctx.textAlign = "center";
1318
+ ctx.fillText("暂无K线数据", width / 2, height / 2);
1319
+ return;
1320
+ }
1321
+
1322
+ let minPrice = Math.min(...chartCandles.map((item) => item.low));
1323
+ let maxPrice = Math.max(...chartCandles.map((item) => item.high));
1324
+ if (minPrice === maxPrice) { minPrice -= 1; maxPrice += 1; }
1325
+ const pricePadding = (maxPrice - minPrice) * 0.06;
1326
+ minPrice -= pricePadding;
1327
+ maxPrice += pricePadding;
1328
+ const maxVolume = Math.max(...chartCandles.map((item) => item.volume), 0) * 1.05 || 1;
1329
+ const slot = plotWidth / count;
1330
+ const bodyWidth = Math.max(1.5, Math.min(16, slot * 0.66));
1331
+ const priceY = (price) => top + (maxPrice - price) / (maxPrice - minPrice) * plotHeight;
1332
+ const volumeY = (volume) => volumeTop + (1 - volume / maxVolume) * volumeHeight;
1333
+
1334
+ ctx.font = "11px system-ui, -apple-system, BlinkMacSystemFont, sans-serif";
1335
+ ctx.strokeStyle = "rgba(255, 255, 255, .08)";
1336
+ ctx.fillStyle = "#94a3b8";
1337
+ ctx.lineWidth = 1;
1338
+ for (let index = 0; index <= 4; index++) {
1339
+ const price = minPrice + (maxPrice - minPrice) * (index / 4);
1340
+ const y = priceY(price);
1341
+ ctx.beginPath();
1342
+ ctx.moveTo(left, y);
1343
+ ctx.lineTo(width - right, y);
1344
+ ctx.stroke();
1345
+ ctx.textAlign = "right";
1346
+ ctx.fillText(formatPrice(price), left - 8, y + 4);
1347
+ }
1348
+
1349
+ ctx.fillStyle = "rgba(148, 163, 184, .38)";
1350
+ chartCandles.forEach((item, index) => {
1351
+ const x = left + slot * (index + 0.5);
1352
+ const y = volumeY(item.volume);
1353
+ ctx.fillRect(x - bodyWidth / 2, y, bodyWidth, volumeTop - y);
1354
+ });
1355
+
1356
+ chartCandles.forEach((item, index) => {
1357
+ const x = left + slot * (index + 0.5);
1358
+ const up = item.close >= item.open;
1359
+ const color = up ? "#34d399" : "#f87171";
1360
+ ctx.strokeStyle = color;
1361
+ ctx.fillStyle = color;
1362
+ ctx.beginPath();
1363
+ ctx.moveTo(x, priceY(item.high));
1364
+ ctx.lineTo(x, priceY(item.low));
1365
+ ctx.stroke();
1366
+ const openY = priceY(item.open);
1367
+ const closeY = priceY(item.close);
1368
+ const bodyTop = Math.min(openY, closeY);
1369
+ const bodyHeight = Math.max(1, Math.abs(closeY - openY));
1370
+ ctx.fillRect(x - bodyWidth / 2, bodyTop, bodyWidth, bodyHeight);
1371
+ });
1372
+
1373
+ const last = chartCandles[count - 1];
1374
+ const lastY = priceY(last.close);
1375
+ ctx.strokeStyle = "rgba(255, 255, 255, .38)";
1376
+ ctx.setLineDash([4, 4]);
1377
+ ctx.beginPath();
1378
+ ctx.moveTo(left, lastY);
1379
+ ctx.lineTo(width - right, lastY);
1380
+ ctx.stroke();
1381
+ ctx.setLineDash([]);
1382
+
1383
+ ctx.fillStyle = "#94a3b8";
1384
+ ctx.textAlign = "center";
1385
+ const labelCount = Math.min(5, count);
1386
+ for (let index = 0; index < labelCount; index++) {
1387
+ const sourceIndex = Math.round(index * (count - 1) / Math.max(1, labelCount - 1));
1388
+ const x = left + slot * (sourceIndex + 0.5);
1389
+ ctx.fillText(chartTimeLabel(chartCandles[sourceIndex].time, true), x, height - 15);
1390
+ }
1391
+ }
1392
+
1393
+ function showCoreChartTooltip(event) {
1394
+ const tooltip = document.getElementById("coreChartTooltip");
1395
+ const shell = event.currentTarget;
1396
+ if (!tooltip || !chartLayout || !chartCandles.length) return;
1397
+ const rect = shell.getBoundingClientRect();
1398
+ const x = event.clientX - rect.left;
1399
+ if (x < chartLayout.left || x > rect.width - chartLayout.right) {
1400
+ tooltip.style.display = "none";
1401
+ return;
1402
+ }
1403
+ const slot = chartLayout.plotWidth / chartCandles.length;
1404
+ const index = Math.min(chartCandles.length - 1, Math.max(0, Math.floor((x - chartLayout.left) / slot)));
1405
+ const item = chartCandles[index];
1406
+ const previous = chartCandles[index - 1] || item;
1407
+ const change = previous.close ? (item.close / previous.close - 1) * 100 : null;
1408
+ tooltip.innerHTML = [
1409
+ `<strong>${escapeHtml(chartTimeLabel(item.time))}</strong>`,
1410
+ `开 ${escapeHtml(formatPrice(item.open))}`,
1411
+ `高 ${escapeHtml(formatPrice(item.high))}`,
1412
+ `低 ${escapeHtml(formatPrice(item.low))}`,
1413
+ `收 ${escapeHtml(formatPrice(item.close))}`,
1414
+ `涨跌 ${escapeHtml(formatSignedPercent(change, 2))}`,
1415
+ `成交额 ${escapeHtml(formatUsd(item.quoteVolume))}`
1416
+ ].join("<br>");
1417
+ tooltip.style.display = "block";
1418
+ const tooltipWidth = tooltip.offsetWidth;
1419
+ const tooltipHeight = tooltip.offsetHeight;
1420
+ const tooltipLeft = x + tooltipWidth + 24 < rect.width ? x + 14 : x - tooltipWidth - 14;
1421
+ const tooltipTop = Math.max(8, Math.min(event.clientY - rect.top - tooltipHeight / 2, rect.height - tooltipHeight - 8));
1422
+ tooltip.style.left = tooltipLeft + "px";
1423
+ tooltip.style.top = tooltipTop + "px";
1424
+ }
1425
+
1426
+ function hideCoreChartTooltip() {
1427
+ const tooltip = document.getElementById("coreChartTooltip");
1428
+ if (tooltip) tooltip.style.display = "none";
1429
+ }
1430
+
1431
+ function setCoreChartInterval(interval) {
1432
+ if (!["1m", "5m", "15m", "1h", "4h", "1d"].includes(interval)) return;
1433
+ chartInterval = interval;
1434
+ document.querySelectorAll("#coreChartControls .chart-pill").forEach((button) => {
1435
+ button.classList.toggle("active", button.dataset.chartInterval === interval);
1436
+ });
1437
+ loadCoreChart();
1438
+ }
1439
+
1440
+ function bindCoreChart() {
1441
+ document.querySelectorAll("#coreChartControls .chart-pill").forEach((button) => {
1442
+ button.addEventListener("click", () => setCoreChartInterval(button.dataset.chartInterval));
1443
+ });
1444
+ const shell = document.querySelector(".chart-shell");
1445
+ if (shell) {
1446
+ shell.addEventListener("pointermove", showCoreChartTooltip);
1447
+ shell.addEventListener("pointerleave", hideCoreChartTooltip);
1448
+ }
1449
+ window.addEventListener("resize", () => {
1450
+ if (chartCandles.length) drawCoreCandleChart();
1451
+ });
1452
+ }
1453
+
1454
  function formatMonitorMeta(monitor) {
1455
  if (!monitor) return "等待监控注册";
1456
  if (isPaused(monitor)) return "已暂停";
 
1800
  document.getElementById("alertCount").textContent = data.crypto?.stats?.alerts ?? alerts.length;
1801
  document.getElementById("updated").textContent = new Date().toLocaleString();
1802
  renderCoreMarket(data.crypto?.core_market);
1803
+ const core = data.crypto?.core_market?.core || {};
1804
+ if (core.name && core.name !== chartCoin) {
1805
+ chartCoin = core.name;
1806
+ loadCoreChart();
1807
+ }
1808
  renderStrategySummary(monitors);
1809
 
1810
  document.getElementById("monitorRows").innerHTML = monitors.map((m) => {
 
2265
 
2266
  loadStatus();
2267
  loadConfig();
2268
+ bindCoreChart();
2269
+ loadCoreChart();
2270
  setInterval(loadStatus, 15000);
2271
  if ("serviceWorker" in navigator) {
2272
  window.addEventListener("load", () => {
app/core/platform.py CHANGED
@@ -128,6 +128,9 @@ class MonitoringPlatform:
128
  def calibrate_coin(self, name):
129
  return self.crypto.calibrate_coin(name)
130
 
 
 
 
131
  def get_market_move_config(self):
132
  return self.market_move.get_config()
133
 
 
128
  def calibrate_coin(self, name):
129
  return self.crypto.calibrate_coin(name)
130
 
131
+ def get_klines(self, coin_name, interval="1h", limit=120):
132
+ return self.crypto.get_klines(coin_name, interval, limit)
133
+
134
  def get_market_move_config(self):
135
  return self.market_move.get_config()
136
 
app/main.py CHANGED
@@ -191,6 +191,18 @@ def api_calibrate_coin(coin: str):
191
  raise HTTPException(status_code=500, detail=str(exc)) from exc
192
 
193
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  @app.get("/api/market-move/config")
195
  def api_get_market_move_config():
196
  return platform.get_market_move_config()
 
191
  raise HTTPException(status_code=500, detail=str(exc)) from exc
192
 
193
 
194
+ @app.get("/api/crypto/{coin}/klines")
195
+ def api_crypto_klines(coin: str, interval: str = "1h", limit: int = 120):
196
+ try:
197
+ return JSONResponse(platform.get_klines(coin, interval, limit))
198
+ except KeyError as exc:
199
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
200
+ except (TypeError, ValueError) as exc:
201
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
202
+ except Exception as exc:
203
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
204
+
205
+
206
  @app.get("/api/market-move/config")
207
  def api_get_market_move_config():
208
  return platform.get_market_move_config()
app/monitors/crypto_price.py CHANGED
@@ -14,6 +14,7 @@ import coinpush as legacy # noqa: E402
14
 
15
  SERVICE_MONITOR_ID = "crypto:service"
16
  HEALTH_ALERT_COOLDOWN_SEC = 3600
 
17
 
18
 
19
  def utc_after_iso(seconds):
@@ -203,6 +204,50 @@ class CryptoPriceMonitor(BaseMonitor):
203
  with self._lock:
204
  return copy.deepcopy(self.config)
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  def core_market_summary(self):
207
  with self._lock:
208
  cfg = copy.deepcopy(self.config)
 
14
 
15
  SERVICE_MONITOR_ID = "crypto:service"
16
  HEALTH_ALERT_COOLDOWN_SEC = 3600
17
+ KLINE_INTERVALS = {"1m", "5m", "15m", "1h", "4h", "1d"}
18
 
19
 
20
  def utc_after_iso(seconds):
 
204
  with self._lock:
205
  return copy.deepcopy(self.config)
206
 
207
+ def get_klines(self, coin_name, interval="1h", limit=120):
208
+ name = str(coin_name or "").upper()
209
+ interval = str(interval or "1h")
210
+ limit = max(30, min(int(limit), 300))
211
+ if interval not in KLINE_INTERVALS:
212
+ raise ValueError(f"不支持的K线周期: {interval}")
213
+
214
+ with self._lock:
215
+ coin_cfg = copy.deepcopy(self.config.get("coins", {}).get(name, {}))
216
+ if not coin_cfg:
217
+ raise KeyError(f"未知币种: {name}")
218
+
219
+ symbol = coin_cfg.get("symbol")
220
+ if not symbol:
221
+ raise ValueError(f"{name} 未配置交易标的")
222
+
223
+ rows = self._api_for(coin_cfg).klines(symbol, interval, limit)
224
+ if not rows:
225
+ raise RuntimeError(f"{symbol} K线数据不可用")
226
+
227
+ candles = []
228
+ for row in rows:
229
+ try:
230
+ candles.append({
231
+ "time": int(row[0]),
232
+ "open": float(row[1]),
233
+ "high": float(row[2]),
234
+ "low": float(row[3]),
235
+ "close": float(row[4]),
236
+ "volume": float(row[5]),
237
+ "quote_volume": float(row[7]) if len(row) > 7 and row[7] not in (None, "") else 0.0,
238
+ })
239
+ except (TypeError, ValueError, IndexError):
240
+ continue
241
+ if not candles:
242
+ raise RuntimeError(f"{symbol} K线数据格式无效")
243
+
244
+ return {
245
+ "coin": name,
246
+ "symbol": symbol,
247
+ "interval": interval,
248
+ "candles": sorted(candles, key=lambda item: item["time"]),
249
+ }
250
+
251
  def core_market_summary(self):
252
  with self._lock:
253
  cfg = copy.deepcopy(self.config)
coinpush.py CHANGED
@@ -1211,7 +1211,7 @@ class OKXAPI:
1211
  class OKXMarketAdapter:
1212
  """把 OKX v5 行情包装成与 BinanceAPI 兼容的接口,使 CoinEvaluator / calibrate_thresholds
1213
  可无改动地监控手工配置的 OKX 标的。"""
1214
- BAR = {"1m": "1m", "5m": "5m", "15m": "15m", "1h": "1H", "1d": "1D"}
1215
 
1216
  def __init__(self, okx_api, logger):
1217
  self.okx = okx_api
 
1211
  class OKXMarketAdapter:
1212
  """把 OKX v5 行情包装成与 BinanceAPI 兼容的接口,使 CoinEvaluator / calibrate_thresholds
1213
  可无改动地监控手工配置的 OKX 标的。"""
1214
+ BAR = {"1m": "1m", "5m": "5m", "15m": "15m", "1h": "1H", "4h": "4H", "1d": "1D"}
1215
 
1216
  def __init__(self, okx_api, logger):
1217
  self.okx = okx_api