Compare commits
17 Commits
snapshot/2
...
feat/candl
| Author | SHA1 | Date | |
|---|---|---|---|
| 5a9d61d674 | |||
| f76045a9a5 | |||
| fa79340cf5 | |||
| a9ccc0b00e | |||
| 9420c89f52 | |||
| 545e1abfaa | |||
| 759173b5be | |||
| 194d596284 | |||
| 444f427420 | |||
| af267ad6c9 | |||
| f3c4a999c3 | |||
| 1c8a6900e8 | |||
| abaee44835 | |||
| f57366fad2 | |||
| b0c7806cb6 | |||
| a12c86f1f8 | |||
| 6107c4e0ef |
22
.gitignore
vendored
22
.gitignore
vendored
@@ -1,7 +1,23 @@
|
||||
# Secrets (never commit)
|
||||
tokens/*
|
||||
!tokens/*.example.json
|
||||
!tokens/*.example.yml
|
||||
!tokens/*.example.yaml
|
||||
|
||||
# Local secrets (never commit)
|
||||
pass/
|
||||
argo/pass
|
||||
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
*.log
|
||||
tokens/*.json
|
||||
tokens/*.yml
|
||||
tokens/*.yaml
|
||||
|
||||
# Baremetal IaC local overlays (do not commit)
|
||||
infra/baremetal-solana-rpc/ansible/inventory/hosts.ini
|
||||
infra/baremetal-solana-rpc/ansible/group_vars/solana_rpc.yml
|
||||
infra/baremetal-solana-rpc/ansible/group_vars/vault.yml
|
||||
|
||||
# Local scratch / build output
|
||||
_tmp/
|
||||
apps/visualizer/dist/
|
||||
|
||||
15
README.md
15
README.md
@@ -12,6 +12,21 @@ npm ci
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Dev z backendem na VPS (staging)
|
||||
|
||||
Najprościej: trzymaj `VITE_API_URL=/api` i podepnij Vite proxy do VPS (żeby nie bawić się w CORS i nie wkładać tokena do przeglądarki):
|
||||
|
||||
```bash
|
||||
cd apps/visualizer
|
||||
API_PROXY_TARGET=https://trade.mpabi.pl \
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Vite proxy’uje wtedy: `/api/*`, `/whoami`, `/auth/*`, `/logout` do VPS. Dodatkowo w dev usuwa `Secure` z `Set-Cookie`, żeby sesja działała na `http://localhost:5173`.
|
||||
|
||||
Jeśli staging jest dodatkowo chroniony basic auth (np. Traefik `basicAuth`), ustaw:
|
||||
`API_PROXY_BASIC_AUTH='USER:PASS'` albo `API_PROXY_BASIC_AUTH_FILE=tokens/frontend.json` (pola `username`/`password`).
|
||||
|
||||
## Docker
|
||||
|
||||
```bash
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
SSH_TUNNEL_TARGET="${SSH_TUNNEL_TARGET:-mevnode_bot}"
|
||||
K8S_NAMESPACE="${K8S_NAMESPACE:-trade-staging}"
|
||||
|
||||
SSH_FRONTEND_LOCAL_PORT="${SSH_FRONTEND_LOCAL_PORT:-13081}"
|
||||
SSH_HASURA_LOCAL_PORT="${SSH_HASURA_LOCAL_PORT:-18080}"
|
||||
|
||||
SSH_FRONTEND_REMOTE_HOST="${SSH_FRONTEND_REMOTE_HOST:-127.0.0.1}"
|
||||
SSH_FRONTEND_REMOTE_PORT="${SSH_FRONTEND_REMOTE_PORT:-30081}"
|
||||
SSH_HASURA_REMOTE_PORT="${SSH_HASURA_REMOTE_PORT:-8080}"
|
||||
|
||||
VITE_DEV_PORT="${VITE_DEV_PORT:-5174}"
|
||||
|
||||
SSH_PID=""
|
||||
|
||||
require_cmd() {
|
||||
if ! command -v "$1" >/dev/null 2>&1; then
|
||||
echo "Missing required command: $1" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
wait_for_listen() {
|
||||
local port="$1"
|
||||
local label="$2"
|
||||
local tries="${3:-80}"
|
||||
local delay="${4:-0.25}"
|
||||
local i
|
||||
|
||||
for ((i = 0; i < tries; i += 1)); do
|
||||
if ss -ltnH | awk '{print $4}' | grep -Eq "(^|[:])${port}$"; then
|
||||
return 0
|
||||
fi
|
||||
sleep "${delay}"
|
||||
done
|
||||
|
||||
echo "Timed out waiting for ${label} on port ${port}" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
get_cluster_ip() {
|
||||
local service="$1"
|
||||
ssh \
|
||||
-o BatchMode=yes \
|
||||
-o StrictHostKeyChecking=accept-new \
|
||||
-T "${SSH_TUNNEL_TARGET}" \
|
||||
"kubectl -n ${K8S_NAMESPACE} get svc ${service} -o jsonpath='{.spec.clusterIP}'"
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
local code=$?
|
||||
trap - EXIT INT TERM
|
||||
|
||||
if [[ -n "${SSH_PID}" ]] && kill -0 "${SSH_PID}" 2>/dev/null; then
|
||||
kill "${SSH_PID}" 2>/dev/null || true
|
||||
wait "${SSH_PID}" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
exit "${code}"
|
||||
}
|
||||
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
require_cmd ssh
|
||||
require_cmd npm
|
||||
require_cmd ss
|
||||
|
||||
HASURA_CLUSTER_IP="${HASURA_CLUSTER_IP:-$(get_cluster_ip hasura)}"
|
||||
|
||||
if [[ -z "${HASURA_CLUSTER_IP}" ]]; then
|
||||
echo "Could not resolve ClusterIP for hasura in namespace ${K8S_NAMESPACE}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "SSH target: ${SSH_TUNNEL_TARGET}"
|
||||
echo "Namespace: ${K8S_NAMESPACE}"
|
||||
echo "hasura ClusterIP: ${HASURA_CLUSTER_IP}"
|
||||
|
||||
echo "Starting SSH tunnel..."
|
||||
ssh \
|
||||
-o StrictHostKeyChecking=accept-new \
|
||||
-o ExitOnForwardFailure=yes \
|
||||
-o ServerAliveInterval=30 \
|
||||
-o ServerAliveCountMax=3 \
|
||||
-N \
|
||||
-L "${SSH_FRONTEND_LOCAL_PORT}:${SSH_FRONTEND_REMOTE_HOST}:${SSH_FRONTEND_REMOTE_PORT}" \
|
||||
-L "${SSH_HASURA_LOCAL_PORT}:${HASURA_CLUSTER_IP}:${SSH_HASURA_REMOTE_PORT}" \
|
||||
"${SSH_TUNNEL_TARGET}" &
|
||||
SSH_PID=$!
|
||||
|
||||
wait_for_listen "${SSH_FRONTEND_LOCAL_PORT}" "frontend SSH tunnel"
|
||||
wait_for_listen "${SSH_HASURA_LOCAL_PORT}" "Hasura SSH tunnel"
|
||||
|
||||
echo "Starting Vite on :${VITE_DEV_PORT}..."
|
||||
cd "${SCRIPT_DIR}"
|
||||
|
||||
export VITE_DEV_PORT
|
||||
export VITE_HASURA_URL="${VITE_HASURA_URL:-/graphql}"
|
||||
export VITE_HASURA_WS_URL="${VITE_HASURA_WS_URL:-ws://127.0.0.1:${SSH_HASURA_LOCAL_PORT}/v1/graphql}"
|
||||
export FRONTEND_PROXY_TARGET="${FRONTEND_PROXY_TARGET:-http://127.0.0.1:${SSH_FRONTEND_LOCAL_PORT}}"
|
||||
export GRAPHQL_PROXY_TARGET="${GRAPHQL_PROXY_TARGET:-http://127.0.0.1:${SSH_HASURA_LOCAL_PORT}}"
|
||||
export GRAPHQL_PROXY_PATH="${GRAPHQL_PROXY_PATH:-/v1/graphql}"
|
||||
|
||||
echo "Frontend auth proxy: ${FRONTEND_PROXY_TARGET}"
|
||||
echo "GraphQL proxy: ${GRAPHQL_PROXY_TARGET}${GRAPHQL_PROXY_PATH}"
|
||||
echo "Open: http://localhost:${VITE_DEV_PORT}/"
|
||||
|
||||
exec npm run dev
|
||||
@@ -6,14 +6,9 @@ ROOT_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
|
||||
|
||||
cd "${SCRIPT_DIR}"
|
||||
|
||||
if [[ -n "${SSH_TUNNEL_PORT:-}" ]]; then
|
||||
export FRONTEND_PROXY_TARGET="${FRONTEND_PROXY_TARGET:-http://127.0.0.1:${SSH_TUNNEL_PORT}}"
|
||||
export GRAPHQL_PROXY_TARGET="${GRAPHQL_PROXY_TARGET:-http://127.0.0.1:${SSH_TUNNEL_PORT}}"
|
||||
else
|
||||
export FRONTEND_PROXY_TARGET="${FRONTEND_PROXY_TARGET:-https://trade.mpabi.pl}"
|
||||
export GRAPHQL_PROXY_TARGET="${GRAPHQL_PROXY_TARGET:-https://trade.mpabi.pl}"
|
||||
fi
|
||||
|
||||
export API_PROXY_TARGET="${API_PROXY_TARGET:-https://trade.mpabi.pl}"
|
||||
export GRAPHQL_PROXY_TARGET="${GRAPHQL_PROXY_TARGET:-https://trade.mpabi.pl}"
|
||||
export VITE_API_URL="${VITE_API_URL:-/api}"
|
||||
export VITE_HASURA_URL="${VITE_HASURA_URL:-/graphql}"
|
||||
export VITE_HASURA_WS_URL="${VITE_HASURA_WS_URL:-/graphql-ws}"
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="pl">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Trade system diagram</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/diagram-main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
216
apps/visualizer/package-lock.json
generated
216
apps/visualizer/package-lock.json
generated
@@ -6,7 +6,6 @@
|
||||
"": {
|
||||
"name": "trade-visualizer",
|
||||
"dependencies": {
|
||||
"@xyflow/react": "^12.8.5",
|
||||
"chart.js": "^4.4.1",
|
||||
"chartjs-adapter-luxon": "^1.3.1",
|
||||
"lightweight-charts": "^5.0.8",
|
||||
@@ -1111,49 +1110,6 @@
|
||||
"@babel/types": "^7.28.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-color": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
|
||||
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="
|
||||
},
|
||||
"node_modules/@types/d3-drag": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
|
||||
"integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
|
||||
"dependencies": {
|
||||
"@types/d3-selection": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-interpolate": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
|
||||
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
|
||||
"dependencies": {
|
||||
"@types/d3-color": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-selection": {
|
||||
"version": "3.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",
|
||||
"integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w=="
|
||||
},
|
||||
"node_modules/@types/d3-transition": {
|
||||
"version": "3.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
|
||||
"integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
|
||||
"dependencies": {
|
||||
"@types/d3-selection": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-zoom": {
|
||||
"version": "3.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",
|
||||
"integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",
|
||||
"dependencies": {
|
||||
"@types/d3-interpolate": "*",
|
||||
"@types/d3-selection": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/estree": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
|
||||
@@ -1165,14 +1121,14 @@
|
||||
"version": "15.7.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
|
||||
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "18.3.27",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz",
|
||||
"integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
@@ -1210,36 +1166,6 @@
|
||||
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@xyflow/react": {
|
||||
"version": "12.10.1",
|
||||
"resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.10.1.tgz",
|
||||
"integrity": "sha512-5eSWtIK/+rkldOuFbOOz44CRgQRjtS9v5nufk77DV+XBnfCGL9HAQ8PG00o2ZYKqkEU/Ak6wrKC95Tu+2zuK3Q==",
|
||||
"dependencies": {
|
||||
"@xyflow/system": "0.0.75",
|
||||
"classcat": "^5.0.3",
|
||||
"zustand": "^4.4.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=17",
|
||||
"react-dom": ">=17"
|
||||
}
|
||||
},
|
||||
"node_modules/@xyflow/system": {
|
||||
"version": "0.0.75",
|
||||
"resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.75.tgz",
|
||||
"integrity": "sha512-iXs+AGFLi8w/VlAoc/iSxk+CxfT6o64Uw/k0CKASOPqjqz6E0rb5jFZgJtXGZCpfQI6OQpu5EnumP5fGxQheaQ==",
|
||||
"dependencies": {
|
||||
"@types/d3-drag": "^3.0.7",
|
||||
"@types/d3-interpolate": "^3.0.4",
|
||||
"@types/d3-selection": "^3.0.10",
|
||||
"@types/d3-transition": "^3.0.8",
|
||||
"@types/d3-zoom": "^3.0.8",
|
||||
"d3-drag": "^3.0.0",
|
||||
"d3-interpolate": "^3.0.1",
|
||||
"d3-selection": "^3.0.0",
|
||||
"d3-zoom": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.9.11",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz",
|
||||
@@ -1327,11 +1253,6 @@
|
||||
"luxon": ">=1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/classcat": {
|
||||
"version": "5.0.5",
|
||||
"resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",
|
||||
"integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w=="
|
||||
},
|
||||
"node_modules/convert-source-map": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
||||
@@ -1343,105 +1264,9 @@
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/d3-color": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
|
||||
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-dispatch": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
|
||||
"integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-drag": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
|
||||
"integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
|
||||
"dependencies": {
|
||||
"d3-dispatch": "1 - 3",
|
||||
"d3-selection": "3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-ease": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
|
||||
"integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-interpolate": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
|
||||
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
|
||||
"dependencies": {
|
||||
"d3-color": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-selection": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
|
||||
"integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-timer": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
|
||||
"integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-transition": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
|
||||
"integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
|
||||
"dependencies": {
|
||||
"d3-color": "1 - 3",
|
||||
"d3-dispatch": "1 - 3",
|
||||
"d3-ease": "1 - 3",
|
||||
"d3-interpolate": "1 - 3",
|
||||
"d3-timer": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"d3-selection": "2 - 3"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-zoom": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
|
||||
"integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
|
||||
"dependencies": {
|
||||
"d3-dispatch": "1 - 3",
|
||||
"d3-drag": "2 - 3",
|
||||
"d3-interpolate": "1 - 3",
|
||||
"d3-selection": "2 - 3",
|
||||
"d3-transition": "2 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
@@ -1839,14 +1664,6 @@
|
||||
"browserslist": ">= 4.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/use-sync-external-store": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
|
||||
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "5.4.21",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
|
||||
@@ -1913,33 +1730,6 @@
|
||||
"integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/zustand": {
|
||||
"version": "4.5.7",
|
||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
|
||||
"integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
|
||||
"dependencies": {
|
||||
"use-sync-external-store": "^1.2.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.7.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=16.8",
|
||||
"immer": ">=9.0.6",
|
||||
"react": ">=16.8"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"immer": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xyflow/react": "^12.8.5",
|
||||
"chart.js": "^4.4.1",
|
||||
"chartjs-adapter-luxon": "^1.3.1",
|
||||
"lightweight-charts": "^5.0.8",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { CSSProperties } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useLocalStorageState } from './app/hooks/useLocalStorageState';
|
||||
import AppShell from './layout/AppShell';
|
||||
import ChartPanel from './features/chart/ChartPanel';
|
||||
@@ -17,9 +17,6 @@ import { useDlobL2 } from './features/market/useDlobL2';
|
||||
import { useDlobSlippage } from './features/market/useDlobSlippage';
|
||||
import { useDlobDepthBands } from './features/market/useDlobDepthBands';
|
||||
import DlobDashboard from './features/market/DlobDashboard';
|
||||
import BotObserverPanel from './features/bot/BotObserverPanel';
|
||||
import BotObserverSummaryCard from './features/bot/BotObserverSummaryCard';
|
||||
import { useBotObserver } from './features/bot/useBotObserver';
|
||||
|
||||
function envNumber(name: string, fallback: number): number {
|
||||
const v = (import.meta as any).env?.[name];
|
||||
@@ -55,95 +52,22 @@ function formatCompact(v: number | null | undefined): string {
|
||||
return v.toPrecision(4);
|
||||
}
|
||||
|
||||
function formatOrderbookUsd(v: number | null | undefined): string {
|
||||
if (v == null || !Number.isFinite(v)) return '—';
|
||||
const abs = Math.abs(v);
|
||||
if (abs >= 1_000_000) return `${(v / 1_000_000).toFixed(2)}M`;
|
||||
if (abs >= 100_000) return `${(v / 1000).toFixed(1)}K`;
|
||||
if (abs >= 10_000) return `${(v / 1000).toFixed(2)}K`;
|
||||
if (abs >= 1000) return `${(v / 1000).toFixed(2)}K`;
|
||||
if (abs >= 100) return v.toFixed(0);
|
||||
if (abs >= 1) return v.toFixed(2);
|
||||
return v.toPrecision(4);
|
||||
}
|
||||
|
||||
function formatClockTime(iso: string | null | undefined): string {
|
||||
if (!iso) return '—';
|
||||
const ts = Date.parse(iso);
|
||||
if (!Number.isFinite(ts)) return '—';
|
||||
return new Date(ts).toLocaleTimeString(undefined, {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
function resolveOrderbookGroupingLabel(symbol: string, mode: string, referencePrice: number | null): string {
|
||||
const normalizedMode = String(mode || 'drift').trim().toLowerCase();
|
||||
if (normalizedMode === 'raw') return 'Raw';
|
||||
if (normalizedMode !== 'drift') return normalizedMode;
|
||||
const px = referencePrice == null || !Number.isFinite(referencePrice) ? 0 : Math.abs(referencePrice);
|
||||
let step = 0.000001;
|
||||
if (px >= 1000) step = 0.1;
|
||||
else if (px >= 100) step = 0.01;
|
||||
else if (px >= 10) step = 0.001;
|
||||
else if (px >= 1) step = 0.0001;
|
||||
else if (px >= 0.1) step = 0.00001;
|
||||
return `Drift (${step.toFixed(step >= 0.1 ? 1 : step >= 0.01 ? 2 : step >= 0.001 ? 3 : step >= 0.0001 ? 4 : 6).replace(/0+$/, '').replace(/\.$/, '')})`;
|
||||
}
|
||||
|
||||
function clamp01(scale: number): number {
|
||||
return Number.isFinite(scale) && scale > 0 ? Math.min(1, scale) : 0;
|
||||
}
|
||||
|
||||
function orderbookRowBarStyle(totalScale: number): CSSProperties {
|
||||
function barCurve(scale01: number): number {
|
||||
// Makes small rows visible without letting a single wall dominate.
|
||||
return Math.sqrt(clamp01(scale01));
|
||||
}
|
||||
|
||||
function orderbookRowBarStyle(totalScale: number, levelScale: number): CSSProperties {
|
||||
return {
|
||||
['--ob-bar-scale' as any]: clamp01(totalScale),
|
||||
['--ob-total-scale' as any]: barCurve(totalScale),
|
||||
['--ob-level-scale' as any]: barCurve(levelScale),
|
||||
} as CSSProperties;
|
||||
}
|
||||
|
||||
const ORDERBOOK_LEVELS_STACKED = 12;
|
||||
const ORDERBOOK_LEVELS_LADDER = 20;
|
||||
type OrderbookLayoutMode = 'stacked' | 'ladder';
|
||||
type OrderbookBarScaleMode = 'per-side' | 'shared-log';
|
||||
type VisualTheme = 'day' | 'night';
|
||||
|
||||
function normalizeVisualTheme(value: unknown): VisualTheme {
|
||||
return value === 'day' ? 'day' : 'night';
|
||||
}
|
||||
|
||||
function OrderbookLayoutIcon({ mode }: { mode: OrderbookLayoutMode }) {
|
||||
if (mode === 'ladder') {
|
||||
return (
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true">
|
||||
<path d="M1.5 4.5h4v2h-4zm9 0h4v2h-4zM1.5 7.5h4v2h-4zm9 0h4v2h-4zM1.5 10.5h4v2h-4zm9 0h4v2h-4zM6.75 3.5h2.5v9h-2.5z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true">
|
||||
<path d="M2 3.5h12v2H2zm0 3.5h12v2H2zm0 3.5h12v2H2z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function OrderbookScaleIcon({ mode }: { mode: OrderbookBarScaleMode }) {
|
||||
if (mode === 'shared-log') {
|
||||
return (
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true">
|
||||
<path d="M2 12.5h2v-2h2v-2h2v-2h2v-2h2v8H2z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true">
|
||||
<path d="M2 11.5h3v-6H2zm4.5 2h3v-10h-3zm4.5-4h3v-2h-3z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function liquidityStyle(bid: number, ask: number): CSSProperties {
|
||||
const max = Math.max(1e-9, bid, ask);
|
||||
const b = Number.isFinite(bid) && bid > 0 ? Math.min(1, bid / max) : 0;
|
||||
@@ -160,24 +84,8 @@ type WhoamiResponse = {
|
||||
export default function App() {
|
||||
const [user, setUser] = useState<string | null>(null);
|
||||
const [authLoading, setAuthLoading] = useState(true);
|
||||
const [storedTheme, setStoredTheme] = useLocalStorageState<VisualTheme>('trade.theme.v1', 'night');
|
||||
const devAuthUser = useMemo(() => envString('VITE_DEV_AUTH_USER', '').trim(), []);
|
||||
const theme = normalizeVisualTheme(storedTheme);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme;
|
||||
return () => {
|
||||
delete document.documentElement.dataset.theme;
|
||||
};
|
||||
}, [theme]);
|
||||
|
||||
useEffect(() => {
|
||||
if (devAuthUser) {
|
||||
setUser(devAuthUser);
|
||||
setAuthLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setAuthLoading(true);
|
||||
fetch('/whoami', { cache: 'no-store' })
|
||||
@@ -202,7 +110,7 @@ export default function App() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [devAuthUser]);
|
||||
}, []);
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
@@ -226,39 +134,22 @@ export default function App() {
|
||||
return <LoginScreen onLoggedIn={setUser} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<TradeApp
|
||||
user={user}
|
||||
theme={theme}
|
||||
onToggleTheme={() => setStoredTheme(theme === 'day' ? 'night' : 'day')}
|
||||
onLogout={() => void logout()}
|
||||
/>
|
||||
);
|
||||
return <TradeApp user={user} onLogout={() => void logout()} />;
|
||||
}
|
||||
|
||||
function TradeApp({
|
||||
user,
|
||||
theme,
|
||||
onToggleTheme,
|
||||
onLogout,
|
||||
}: {
|
||||
user: string;
|
||||
theme: VisualTheme;
|
||||
onToggleTheme: () => void;
|
||||
onLogout: () => void;
|
||||
}) {
|
||||
function TradeApp({ user, onLogout }: { user: string; onLogout: () => void }) {
|
||||
const markets = useMemo(() => ['PUMP-PERP', 'SOL-PERP', '1MBONK-PERP', 'BTC-PERP', 'ETH-PERP'], []);
|
||||
|
||||
const [symbol, setSymbol] = useLocalStorageState('trade.symbol', envString('VITE_SYMBOL', 'SOL-PERP'));
|
||||
const [source, setSource] = useLocalStorageState('trade.source', envString('VITE_SOURCE', ''));
|
||||
const [tf, setTf] = useLocalStorageState('trade.tf.v2', envString('VITE_TF', '1s'));
|
||||
const [tf, setTf] = useLocalStorageState('trade.tf', envString('VITE_TF', '1m'));
|
||||
const [pollMs, setPollMs] = useLocalStorageState('trade.pollMs', envNumber('VITE_POLL_MS', 1000));
|
||||
const [limit, setLimit] = useLocalStorageState('trade.limit', envNumber('VITE_LIMIT', 300));
|
||||
const [showIndicators, setShowIndicators] = useLocalStorageState('trade.showIndicators', true);
|
||||
const [showBuild, setShowBuild] = useLocalStorageState('trade.showBuild', true);
|
||||
const [tab, setTab] = useLocalStorageState<'orderbook' | 'trades'>('trade.sidebarTab', 'orderbook');
|
||||
const [bottomTab, setBottomTab] = useLocalStorageState<
|
||||
'dlob' | 'bot' | 'positions' | 'orders' | 'balances' | 'orderHistory' | 'positionHistory'
|
||||
'dlob' | 'positions' | 'orders' | 'balances' | 'orderHistory' | 'positionHistory'
|
||||
>('trade.bottomTab', 'positions');
|
||||
const [tradeSide, setTradeSide] = useLocalStorageState<'long' | 'short'>('trade.form.side', 'long');
|
||||
const [tradeOrderType, setTradeOrderType] = useLocalStorageState<'market' | 'limit' | 'other'>(
|
||||
@@ -267,17 +158,6 @@ function TradeApp({
|
||||
);
|
||||
const [tradePrice, setTradePrice] = useLocalStorageState<number>('trade.form.price', 0);
|
||||
const [tradeSize, setTradeSize] = useLocalStorageState<number>('trade.form.size', 0.1);
|
||||
const [orderbookGrouping, setOrderbookGrouping] = useLocalStorageState('trade.orderbookGrouping.v1', 'drift');
|
||||
const [orderbookLayout, setOrderbookLayout] = useLocalStorageState<OrderbookLayoutMode>(
|
||||
'trade.orderbookLayout.v1',
|
||||
'ladder'
|
||||
);
|
||||
const [orderbookBarScaleMode, setOrderbookBarScaleMode] = useLocalStorageState<OrderbookBarScaleMode>(
|
||||
'trade.orderbookBarScale.v1',
|
||||
'per-side'
|
||||
);
|
||||
const [chartResetView, setChartResetView] = useState<(() => void) | null>(null);
|
||||
const orderbookLevels = orderbookLayout === 'ladder' ? ORDERBOOK_LEVELS_LADDER : ORDERBOOK_LEVELS_STACKED;
|
||||
|
||||
useEffect(() => {
|
||||
if (symbol === 'BONK-PERP') {
|
||||
@@ -289,7 +169,7 @@ function TradeApp({
|
||||
}
|
||||
}, [markets, setSymbol, symbol]);
|
||||
|
||||
const { candles, indicators, meta, loading, error, refresh, hasMoreHistory, requestHistoryBefore } = useChartData({
|
||||
const { candles, indicators, meta, loading, error, refresh } = useChartData({
|
||||
symbol,
|
||||
source: source.trim() ? source : undefined,
|
||||
tf,
|
||||
@@ -298,20 +178,14 @@ function TradeApp({
|
||||
});
|
||||
|
||||
const { stats: dlob, connected: dlobConnected, error: dlobError } = useDlobStats(symbol);
|
||||
const { l2: dlobL2, connected: dlobL2Connected, error: dlobL2Error } = useDlobL2(symbol, {
|
||||
levels: orderbookLevels,
|
||||
grouping: orderbookGrouping,
|
||||
});
|
||||
const { l2: dlobL2, connected: dlobL2Connected, error: dlobL2Error } = useDlobL2(symbol, { levels: 10 });
|
||||
const { rows: slippageRows, connected: slippageConnected, error: slippageError } = useDlobSlippage(symbol);
|
||||
const { rows: depthBands, connected: depthBandsConnected, error: depthBandsError } = useDlobDepthBands(symbol);
|
||||
const botObserver = useBotObserver(symbol);
|
||||
|
||||
const latest = candles.length ? candles[candles.length - 1] : null;
|
||||
const first = candles.length ? candles[0] : null;
|
||||
const changePct =
|
||||
first && latest && first.close > 0 ? ((latest.close - first.close) / first.close) * 100 : null;
|
||||
const liveLastPrice = latest?.close ?? dlob?.markPrice ?? dlob?.mid ?? null;
|
||||
const liveOraclePrice = latest?.oracle ?? dlob?.oraclePrice ?? null;
|
||||
|
||||
const orderbook = useMemo(() => {
|
||||
if (dlobL2) {
|
||||
@@ -321,22 +195,12 @@ function TradeApp({
|
||||
mid: dlobL2.mid as number | null,
|
||||
bestBid: dlobL2.bestBid,
|
||||
bestAsk: dlobL2.bestAsk,
|
||||
updatedAt: dlobL2.updatedAt,
|
||||
};
|
||||
}
|
||||
if (!latest) {
|
||||
return {
|
||||
asks: [],
|
||||
bids: [],
|
||||
mid: null as number | null,
|
||||
bestBid: null as number | null,
|
||||
bestAsk: null as number | null,
|
||||
updatedAt: null as string | null,
|
||||
};
|
||||
}
|
||||
if (!latest) return { asks: [], bids: [], mid: null as number | null, bestBid: null as number | null, bestAsk: null as number | null };
|
||||
const mid = latest.close;
|
||||
const step = Math.max(mid * 0.00018, 0.0001);
|
||||
const levels = orderbookLevels;
|
||||
const levels = 10;
|
||||
|
||||
const asksRaw = Array.from({ length: levels }, (_, i) => ({
|
||||
price: mid + (i + 1) * step,
|
||||
@@ -368,8 +232,20 @@ function TradeApp({
|
||||
return { ...r, sizeUsd, totalBase: bidTotalBase, totalUsd: bidTotalUsd };
|
||||
});
|
||||
|
||||
return { asks, bids, mid, bestBid: bidsRaw[0]?.price ?? null, bestAsk: asksRaw[0]?.price ?? null, updatedAt: null };
|
||||
}, [dlobL2, latest, orderbookLevels]);
|
||||
return { asks, bids, mid, bestBid: bidsRaw[0]?.price ?? null, bestAsk: asksRaw[0]?.price ?? null };
|
||||
}, [dlobL2, latest]);
|
||||
|
||||
const maxAskTotal = useMemo(() => {
|
||||
let max = 0;
|
||||
for (const r of orderbook.asks) max = Math.max(max, (r as any).totalUsd || 0);
|
||||
return max;
|
||||
}, [orderbook.asks]);
|
||||
|
||||
const maxBidTotal = useMemo(() => {
|
||||
let max = 0;
|
||||
for (const r of orderbook.bids) max = Math.max(max, (r as any).totalUsd || 0);
|
||||
return max;
|
||||
}, [orderbook.bids]);
|
||||
|
||||
const maxAskSize = useMemo(() => {
|
||||
let max = 0;
|
||||
@@ -394,69 +270,6 @@ function TradeApp({
|
||||
return { bidUsd: bid, askUsd: ask, spreadAbs, spreadPct };
|
||||
}, [orderbook.asks, orderbook.bids, orderbook.bestAsk, orderbook.bestBid, orderbook.mid]);
|
||||
|
||||
const orderbookVersion = orderbook.updatedAt ?? String(latest?.time ?? '');
|
||||
const orderbookGroupingLabel = useMemo(
|
||||
() => resolveOrderbookGroupingLabel(symbol, orderbookGrouping, orderbook.mid),
|
||||
[orderbook.mid, orderbookGrouping, symbol]
|
||||
);
|
||||
const previousOrderbookMid = useRef<number | null>(null);
|
||||
const [orderbookMidTone, setOrderbookMidTone] = useState<'flat' | 'up' | 'down'>('flat');
|
||||
|
||||
useEffect(() => {
|
||||
const nextMid = orderbook.mid;
|
||||
const prevMid = previousOrderbookMid.current;
|
||||
|
||||
if (nextMid == null || !Number.isFinite(nextMid)) {
|
||||
previousOrderbookMid.current = null;
|
||||
setOrderbookMidTone('flat');
|
||||
return;
|
||||
}
|
||||
|
||||
if (prevMid != null && Number.isFinite(prevMid) && nextMid !== prevMid) {
|
||||
setOrderbookMidTone(nextMid > prevMid ? 'up' : 'down');
|
||||
}
|
||||
|
||||
previousOrderbookMid.current = nextMid;
|
||||
}, [orderbook.mid]);
|
||||
|
||||
const orderbookLadderRows = useMemo(() => {
|
||||
const asksNearMid = orderbook.asks.slice().reverse();
|
||||
const bidsNearMid = orderbook.bids;
|
||||
const rowCount = Math.max(asksNearMid.length, bidsNearMid.length);
|
||||
return Array.from({ length: rowCount }, (_, index) => ({
|
||||
ask: asksNearMid[index] ?? null,
|
||||
bid: bidsNearMid[index] ?? null,
|
||||
}));
|
||||
}, [orderbook.asks, orderbook.bids]);
|
||||
|
||||
const orderbookLadderViewRows = useMemo(() => {
|
||||
let maxAsk = 0;
|
||||
let maxBid = 0;
|
||||
|
||||
for (const row of orderbookLadderRows) {
|
||||
maxAsk = Math.max(maxAsk, (row.ask as any)?.sizeUsd || 0);
|
||||
maxBid = Math.max(maxBid, (row.bid as any)?.sizeUsd || 0);
|
||||
}
|
||||
|
||||
const maxShared = Math.max(maxAsk, maxBid);
|
||||
const logDen = Math.log1p(maxShared);
|
||||
|
||||
const scaleValue = (value: number, side: 'bid' | 'ask'): number => {
|
||||
if (!Number.isFinite(value) || value <= 0) return 0;
|
||||
if (orderbookBarScaleMode === 'shared-log') {
|
||||
return logDen > 0 ? Math.log1p(value) / logDen : 0;
|
||||
}
|
||||
const denom = side === 'bid' ? maxBid : maxAsk;
|
||||
return denom > 0 ? value / denom : 0;
|
||||
};
|
||||
|
||||
return orderbookLadderRows.map((row) => ({
|
||||
...row,
|
||||
bidScale: scaleValue((row.bid as any)?.sizeUsd || 0, 'bid'),
|
||||
askScale: scaleValue((row.ask as any)?.sizeUsd || 0, 'ask'),
|
||||
}));
|
||||
}, [orderbookBarScaleMode, orderbookLadderRows]);
|
||||
|
||||
const trades = useMemo(() => {
|
||||
const slice = candles.slice(-24).reverse();
|
||||
return slice.map((c) => {
|
||||
@@ -472,8 +285,8 @@ function TradeApp({
|
||||
|
||||
const effectiveTradePrice = useMemo(() => {
|
||||
if (tradeOrderType === 'limit') return tradePrice;
|
||||
return liveLastPrice ?? tradePrice;
|
||||
}, [liveLastPrice, tradeOrderType, tradePrice]);
|
||||
return latest?.close ?? tradePrice;
|
||||
}, [latest?.close, tradeOrderType, tradePrice]);
|
||||
|
||||
const orderValueUsd = useMemo(() => {
|
||||
if (!Number.isFinite(tradeSize) || tradeSize <= 0) return null;
|
||||
@@ -496,7 +309,7 @@ function TradeApp({
|
||||
const topItems = useMemo(
|
||||
() => [
|
||||
{ key: 'BTC', label: 'BTC', changePct: 1.28, active: false },
|
||||
{ key: 'SOL', label: 'SOL', changePct: 1.89, active: true },
|
||||
{ key: 'SOL', label: 'SOL', changePct: 1.89, active: false },
|
||||
],
|
||||
[]
|
||||
);
|
||||
@@ -506,7 +319,7 @@ function TradeApp({
|
||||
{
|
||||
key: 'last',
|
||||
label: 'Last',
|
||||
value: formatUsd(liveLastPrice),
|
||||
value: formatUsd(latest?.close),
|
||||
sub:
|
||||
changePct == null ? (
|
||||
'—'
|
||||
@@ -517,7 +330,7 @@ function TradeApp({
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ key: 'oracle', label: 'Oracle', value: formatUsd(liveOraclePrice) },
|
||||
{ key: 'oracle', label: 'Oracle', value: formatUsd(latest?.oracle ?? null) },
|
||||
{ key: 'bid', label: 'Bid', value: formatUsd(dlob?.bestBid ?? null) },
|
||||
{ key: 'ask', label: 'Ask', value: formatUsd(dlob?.bestAsk ?? null) },
|
||||
{
|
||||
@@ -539,7 +352,7 @@ function TradeApp({
|
||||
sub: dlobL2Error ? <span className="neg">{dlobL2Error}</span> : dlobL2?.updatedAt || '—',
|
||||
},
|
||||
];
|
||||
}, [changePct, dlob, dlobConnected, dlobError, dlobL2, dlobL2Connected, dlobL2Error, liveLastPrice, liveOraclePrice]);
|
||||
}, [latest?.close, latest?.oracle, changePct, dlob, dlobConnected, dlobError, dlobL2, dlobL2Connected, dlobL2Error]);
|
||||
|
||||
const seriesLabel = useMemo(() => `Candles: Mark (oracle overlay)`, []);
|
||||
const seriesKey = useMemo(() => `${symbol}|${source}|${tf}`, [symbol, source, tf]);
|
||||
@@ -547,20 +360,8 @@ function TradeApp({
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
header={
|
||||
<TopNav
|
||||
active="trade"
|
||||
rightSlot={
|
||||
<AuthStatus
|
||||
user={user}
|
||||
theme={theme}
|
||||
onResetView={chartResetView}
|
||||
onToggleTheme={onToggleTheme}
|
||||
onLogout={onLogout}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
}
|
||||
header={<TopNav active="trade" rightEndSlot={<AuthStatus user={user} onLogout={onLogout} />} />}
|
||||
top={<TickerBar items={topItems} />}
|
||||
main={
|
||||
<div className="tradeMain">
|
||||
<Card
|
||||
@@ -620,8 +421,6 @@ function TradeApp({
|
||||
<ChartPanel
|
||||
candles={candles}
|
||||
indicators={indicators}
|
||||
theme={theme}
|
||||
tickerItems={topItems}
|
||||
timeframe={tf}
|
||||
bucketSeconds={bucketSeconds}
|
||||
seriesKey={seriesKey}
|
||||
@@ -630,10 +429,7 @@ function TradeApp({
|
||||
onToggleIndicators={() => setShowIndicators((v) => !v)}
|
||||
showBuild={showBuild}
|
||||
onToggleBuild={() => setShowBuild((v) => !v)}
|
||||
onResetViewReady={(handler) => setChartResetView(() => handler)}
|
||||
seriesLabel={seriesLabel}
|
||||
hasMoreHistory={hasMoreHistory}
|
||||
onRequestHistoryBefore={requestHistoryBefore}
|
||||
dlobQuotes={{ bid: dlob?.bestBid ?? null, ask: dlob?.bestAsk ?? null, mid: dlob?.mid ?? null }}
|
||||
/>
|
||||
|
||||
@@ -658,11 +454,6 @@ function TradeApp({
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'bot',
|
||||
label: 'Bot',
|
||||
content: <BotObserverPanel marketName={symbol} observer={botObserver} />,
|
||||
},
|
||||
{ id: 'positions', label: 'Positions', content: <div className="placeholder">Positions (next)</div> },
|
||||
{ id: 'orders', label: 'Orders', content: <div className="placeholder">Orders (next)</div> },
|
||||
{ id: 'balances', label: 'Balances', content: <div className="placeholder">Balances (next)</div> },
|
||||
@@ -684,173 +475,83 @@ function TradeApp({
|
||||
</div>
|
||||
}
|
||||
sidebar={
|
||||
<Card className="orderbookCard">
|
||||
<Card
|
||||
className="orderbookCard"
|
||||
title={
|
||||
<div className="sideHead">
|
||||
<div className="sideHead__title">Orderbook</div>
|
||||
<div className="sideHead__subtitle">{loading ? 'loading…' : orderbook.mid != null ? formatUsd(orderbook.mid) : latest ? formatUsd(latest.close) : '—'}</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tabs
|
||||
items={[
|
||||
{
|
||||
id: 'orderbook',
|
||||
label: 'Orderbook',
|
||||
content: (
|
||||
<div className="orderbook">
|
||||
<div className="orderbook__toolbar">
|
||||
<label className="marketSelect orderbook__grouping">
|
||||
<span className="marketSelect__label">Grouping</span>
|
||||
<select
|
||||
className="marketSelect__input orderbook__groupingInput"
|
||||
value={orderbookGrouping}
|
||||
onChange={(e) => setOrderbookGrouping(e.target.value)}
|
||||
>
|
||||
<option value="drift">{orderbookGroupingLabel}</option>
|
||||
<option value="raw">Raw</option>
|
||||
<option value="0.001">0.001</option>
|
||||
<option value="0.005">0.005</option>
|
||||
<option value="0.01">0.01</option>
|
||||
<option value="0.05">0.05</option>
|
||||
<option value="0.1">0.1</option>
|
||||
</select>
|
||||
</label>
|
||||
{orderbookLayout === 'ladder' ? (
|
||||
<div className="orderbookToolbarSwitch" role="group" aria-label="Orderbook bar scale">
|
||||
<button
|
||||
type="button"
|
||||
className={`orderbookToolbarSwitch__btn${orderbookBarScaleMode === 'per-side' ? ' is-active' : ''}`}
|
||||
onClick={() => setOrderbookBarScaleMode('per-side')}
|
||||
title="Per-side scale"
|
||||
aria-pressed={orderbookBarScaleMode === 'per-side'}
|
||||
>
|
||||
<OrderbookScaleIcon mode="per-side" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`orderbookToolbarSwitch__btn${orderbookBarScaleMode === 'shared-log' ? ' is-active' : ''}`}
|
||||
onClick={() => setOrderbookBarScaleMode('shared-log')}
|
||||
title="Shared log scale"
|
||||
aria-pressed={orderbookBarScaleMode === 'shared-log'}
|
||||
>
|
||||
<OrderbookScaleIcon mode="shared-log" />
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{orderbookLayout === 'ladder' ? (
|
||||
<>
|
||||
<div className={`orderbookMid orderbookMid--${orderbookMidTone} orderbookMid--ladder`}>
|
||||
<span className="orderbookMid__label">mid</span>
|
||||
<span className="orderbookMid__price">{formatQty(orderbook.mid, 3)}</span>
|
||||
</div>
|
||||
<div className="orderbook__header orderbook__header--ladder">
|
||||
<span className="orderbookLadderHead__side">Size (USD)</span>
|
||||
<span className="orderbookLadderHead__price">Price</span>
|
||||
<span className="orderbookLadderHead__side orderbookLadderHead__side--right">Size (USD)</span>
|
||||
</div>
|
||||
<div className="orderbook__rows orderbook__rows--ladder">
|
||||
{orderbookLadderViewRows.map((row, index) => (
|
||||
<div key={`pair-${index}-${orderbookVersion}`} className="orderbookPair">
|
||||
<span
|
||||
className="orderbookPair__num orderbookPair__num--bid"
|
||||
style={orderbookRowBarStyle(row.bidScale)}
|
||||
>
|
||||
{row.bid ? formatOrderbookUsd((row.bid as any).sizeUsd) : '—'}
|
||||
</span>
|
||||
<span className="orderbookPair__price orderbookPair__price--bid">
|
||||
{row.bid ? formatQty(row.bid.price, 3) : '—'}
|
||||
</span>
|
||||
<span className="orderbookPair__price orderbookPair__price--ask">
|
||||
{row.ask ? formatQty(row.ask.price, 3) : '—'}
|
||||
</span>
|
||||
<span
|
||||
className="orderbookPair__num orderbookPair__num--ask"
|
||||
style={orderbookRowBarStyle(row.askScale)}
|
||||
>
|
||||
{row.ask ? formatOrderbookUsd((row.ask as any).sizeUsd) : '—'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="orderbook__header">
|
||||
<span>Price</span>
|
||||
<span className="orderbook__num">Size (USD)</span>
|
||||
<span className="orderbook__num">Cum. (USD)</span>
|
||||
</div>
|
||||
<div className="orderbook__rows">
|
||||
<div className={`orderbookMid orderbookMid--${orderbookMidTone}`}>
|
||||
<span className="orderbookMid__price">{formatQty(orderbook.mid, 3)}</span>
|
||||
<span className="orderbookMid__label">mid</span>
|
||||
</div>
|
||||
{orderbook.asks.map((r, index) => (
|
||||
<div
|
||||
key={`a-${index}-${r.price}-${orderbookVersion}`}
|
||||
className="orderbookRow orderbookRow--ask"
|
||||
style={orderbookRowBarStyle(maxAskSize > 0 ? (r as any).sizeUsd / maxAskSize : 0)}
|
||||
>
|
||||
<span className="orderbookRow__price">{formatQty(r.price, 3)}</span>
|
||||
<span className="orderbookRow__num">{formatOrderbookUsd((r as any).sizeUsd)}</span>
|
||||
<span className="orderbookRow__num">{formatOrderbookUsd((r as any).totalUsd)}</span>
|
||||
</div>
|
||||
))}
|
||||
{orderbook.bids.map((r, index) => (
|
||||
<div
|
||||
key={`b-${index}-${r.price}-${orderbookVersion}`}
|
||||
className="orderbookRow orderbookRow--bid"
|
||||
style={orderbookRowBarStyle(maxBidSize > 0 ? (r as any).sizeUsd / maxBidSize : 0)}
|
||||
>
|
||||
<span className="orderbookRow__price">{formatQty(r.price, 3)}</span>
|
||||
<span className="orderbookRow__num">{formatOrderbookUsd((r as any).sizeUsd)}</span>
|
||||
<span className="orderbookRow__num">{formatOrderbookUsd((r as any).totalUsd)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className="orderbookMeta">
|
||||
<div className="orderbookMeta__row">
|
||||
<span className="muted">Updated</span>
|
||||
<span className="orderbookMeta__val">{formatClockTime(orderbook.updatedAt)}</span>
|
||||
</div>
|
||||
<div className="orderbookMeta__row">
|
||||
<span className="muted">Spread</span>
|
||||
<span className="orderbookMeta__val">
|
||||
<div className="orderbook">
|
||||
<div className="orderbook__header">
|
||||
<span>Price</span>
|
||||
<span className="orderbook__num">Size (USD)</span>
|
||||
<span className="orderbook__num">Total (USD)</span>
|
||||
</div>
|
||||
<div className="orderbook__rows">
|
||||
{orderbook.asks.map((r) => (
|
||||
<div
|
||||
key={`a-${r.price}`}
|
||||
className="orderbookRow orderbookRow--ask"
|
||||
style={orderbookRowBarStyle(
|
||||
maxAskTotal > 0 ? (r as any).totalUsd / maxAskTotal : 0,
|
||||
maxAskSize > 0 ? (r as any).sizeUsd / maxAskSize : 0
|
||||
)}
|
||||
>
|
||||
<span className="orderbookRow__price">{formatQty(r.price, 3)}</span>
|
||||
<span className="orderbookRow__num">{formatCompact((r as any).sizeUsd)}</span>
|
||||
<span className="orderbookRow__num">{formatCompact((r as any).totalUsd)}</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="orderbookMid">
|
||||
<span className="orderbookMid__price">{formatQty(orderbook.mid, 3)}</span>
|
||||
<span className="orderbookMid__label">mid</span>
|
||||
</div>
|
||||
{orderbook.bids.map((r) => (
|
||||
<div
|
||||
key={`b-${r.price}`}
|
||||
className="orderbookRow orderbookRow--bid"
|
||||
style={orderbookRowBarStyle(
|
||||
maxBidTotal > 0 ? (r as any).totalUsd / maxBidTotal : 0,
|
||||
maxBidSize > 0 ? (r as any).sizeUsd / maxBidSize : 0
|
||||
)}
|
||||
>
|
||||
<span className="orderbookRow__price">{formatQty(r.price, 3)}</span>
|
||||
<span className="orderbookRow__num">{formatCompact((r as any).sizeUsd)}</span>
|
||||
<span className="orderbookRow__num">{formatCompact((r as any).totalUsd)}</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="orderbookMeta">
|
||||
<div className="orderbookMeta__row">
|
||||
<span className="muted">Spread</span>
|
||||
<span className="orderbookMeta__val">
|
||||
{liquidity.spreadAbs == null || liquidity.spreadPct == null
|
||||
? '—'
|
||||
: `${formatUsd(liquidity.spreadAbs)} (${liquidity.spreadPct.toFixed(3)}%)`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="orderbookMeta__row">
|
||||
<span className="muted">{`Liquidity (L1–L${orderbookLevels})`}</span>
|
||||
<span className="muted">Liquidity (L1–L10)</span>
|
||||
<span className="orderbookMeta__val">
|
||||
<span className="pos">{formatUsd(liquidity.bidUsd)}</span> <span className="muted">/</span>{' '}
|
||||
<span className="neg">{formatUsd(liquidity.askUsd)}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="liquidityBar" style={liquidityStyle(liquidity.bidUsd, liquidity.askUsd)}>
|
||||
<div className="liquidityBar__bid" />
|
||||
<div className="liquidityBar__ask" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="orderbookLayoutSwitch" role="group" aria-label="Orderbook layout">
|
||||
<button
|
||||
type="button"
|
||||
className={`orderbookLayoutSwitch__btn${orderbookLayout === 'stacked' ? ' is-active' : ''}`}
|
||||
onClick={() => setOrderbookLayout('stacked')}
|
||||
title="Stacked book"
|
||||
aria-pressed={orderbookLayout === 'stacked'}
|
||||
>
|
||||
<OrderbookLayoutIcon mode="stacked" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`orderbookLayoutSwitch__btn${orderbookLayout === 'ladder' ? ' is-active' : ''}`}
|
||||
onClick={() => setOrderbookLayout('ladder')}
|
||||
title="Ladder book"
|
||||
aria-pressed={orderbookLayout === 'ladder'}
|
||||
>
|
||||
<OrderbookLayoutIcon mode="ladder" />
|
||||
</button>
|
||||
<div className="liquidityBar" style={liquidityStyle(liquidity.bidUsd, liquidity.askUsd)}>
|
||||
<div className="liquidityBar__bid" />
|
||||
<div className="liquidityBar__ask" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -950,7 +651,7 @@ function TradeApp({
|
||||
<input
|
||||
className="formField__input"
|
||||
value={tradeOrderType === 'market' ? '' : String(tradePrice)}
|
||||
placeholder={tradeOrderType === 'market' ? formatQty(liveLastPrice ?? null, 3) : '0'}
|
||||
placeholder={tradeOrderType === 'market' ? formatQty(latest?.close ?? null, 3) : '0'}
|
||||
disabled={tradeOrderType !== 'limit'}
|
||||
onChange={(e) => setTradePrice(Number(e.target.value))}
|
||||
inputMode="decimal"
|
||||
@@ -1009,10 +710,6 @@ function TradeApp({
|
||||
<span className="tradeMeta__value">—</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="tradeBotSummary">
|
||||
<BotObserverSummaryCard marketName={symbol} observer={botObserver} />
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import '@xyflow/react/dist/style.css';
|
||||
import './diagram.css';
|
||||
import { TradeSystemFlowPage } from './diagram/TradeSystemFlowPage';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<TradeSystemFlowPage />
|
||||
</React.StrictMode>
|
||||
);
|
||||
@@ -1,943 +0,0 @@
|
||||
:root {
|
||||
--rf-bg: #efe7db;
|
||||
--rf-panel: rgba(255, 252, 246, 0.94);
|
||||
--rf-card: #fffdf9;
|
||||
--rf-ink: #1b1714;
|
||||
--rf-muted: #625b52;
|
||||
--rf-line: rgba(99, 91, 82, 0.18);
|
||||
--rf-shadow: 0 24px 54px rgba(27, 23, 20, 0.12);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'IBM Plex Sans', 'Segoe UI', sans-serif;
|
||||
color: var(--rf-ink);
|
||||
background:
|
||||
radial-gradient(circle at top left, rgba(31, 111, 139, 0.14), transparent 26%),
|
||||
radial-gradient(circle at top right, rgba(176, 79, 53, 0.14), transparent 24%),
|
||||
linear-gradient(180deg, #f8f3eb 0%, var(--rf-bg) 100%);
|
||||
}
|
||||
|
||||
.rfPage {
|
||||
min-height: 100%;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.rfToolbar,
|
||||
.rfCanvas,
|
||||
.rfInspector {
|
||||
background: var(--rf-panel);
|
||||
border: 1px solid rgba(217, 204, 187, 0.92);
|
||||
border-radius: 24px;
|
||||
box-shadow: var(--rf-shadow);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.rfToolbar {
|
||||
min-height: 76px;
|
||||
padding: 14px 18px;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(260px, 340px) minmax(220px, auto) minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.rfToolbar__eyebrow,
|
||||
.rfInspector__eyebrow,
|
||||
.rfCard__subtitle {
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfToolbar__brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.rfToolbar__mark {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 5px;
|
||||
background:
|
||||
linear-gradient(135deg, #1f6f8b 0%, #1f6f8b 46%, #b04f35 46%, #b04f35 100%);
|
||||
box-shadow: 0 0 0 4px rgba(31, 111, 139, 0.1);
|
||||
}
|
||||
|
||||
.rfToolbar__copy {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.rfToolbar__title {
|
||||
margin-top: 2px;
|
||||
font-size: clamp(1.1rem, 1.3vw, 1.45rem);
|
||||
font-weight: 800;
|
||||
line-height: 1.05;
|
||||
font-family: 'IBM Plex Serif', Georgia, serif;
|
||||
}
|
||||
|
||||
.rfToolbar__summary,
|
||||
.rfInspector p,
|
||||
.rfCard__host,
|
||||
.rfCard__bullets,
|
||||
.rfSection li {
|
||||
color: var(--rf-muted);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.rfInspector__metricGrid {
|
||||
margin: 10px 0 4px;
|
||||
}
|
||||
|
||||
.rfToolbar__summary {
|
||||
margin-top: 3px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.rfFilters {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.rfHistoryWrap {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.rfFilter {
|
||||
border: 1px solid rgba(99, 91, 82, 0.15);
|
||||
border-radius: 999px;
|
||||
background: #fffaf2;
|
||||
color: var(--rf-ink);
|
||||
font: inherit;
|
||||
font-weight: 800;
|
||||
padding: 9px 13px;
|
||||
cursor: pointer;
|
||||
transition: 140ms ease;
|
||||
}
|
||||
|
||||
.rfFilter:hover,
|
||||
.rfFilter.isActive {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 12px 24px rgba(27, 23, 20, 0.08);
|
||||
}
|
||||
|
||||
.rfFilter.isMeta {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.rfFilter:disabled {
|
||||
opacity: 0.44;
|
||||
cursor: default;
|
||||
transform: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.rfHistoryPanel {
|
||||
position: absolute;
|
||||
top: calc(100% + 10px);
|
||||
right: 0;
|
||||
z-index: 24;
|
||||
width: 340px;
|
||||
max-height: 420px;
|
||||
overflow: auto;
|
||||
padding: 14px;
|
||||
border: 1px solid rgba(99, 91, 82, 0.16);
|
||||
border-radius: 18px;
|
||||
background: rgba(255, 252, 246, 0.98);
|
||||
box-shadow: 0 24px 48px rgba(27, 23, 20, 0.18);
|
||||
}
|
||||
|
||||
.rfHistoryPanel__head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rfHistoryPanel__eyebrow {
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfHistoryPanel__title {
|
||||
margin-top: 3px;
|
||||
font-size: 1rem;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.rfHistoryPanel__close,
|
||||
.rfHistoryItem__restore {
|
||||
border: 1px solid rgba(99, 91, 82, 0.14);
|
||||
border-radius: 999px;
|
||||
background: #fffaf2;
|
||||
color: var(--rf-ink);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
padding: 8px 11px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.rfHistoryPanel__close:hover,
|
||||
.rfHistoryItem__restore:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 10px 22px rgba(27, 23, 20, 0.08);
|
||||
}
|
||||
|
||||
.rfHistoryItem__restore:disabled {
|
||||
opacity: 0.46;
|
||||
cursor: default;
|
||||
transform: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.rfHistoryPanel__note {
|
||||
margin-top: 12px;
|
||||
font-size: 13px;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfHistoryPanel__note.isError {
|
||||
color: #8b3d24;
|
||||
}
|
||||
|
||||
.rfHistoryPanel__list {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.rfHistoryItem {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 8px 12px;
|
||||
align-items: center;
|
||||
padding: 12px;
|
||||
border: 1px solid rgba(99, 91, 82, 0.12);
|
||||
border-radius: 14px;
|
||||
background: rgba(255, 255, 255, 0.74);
|
||||
}
|
||||
|
||||
.rfHistoryItem.isCurrent {
|
||||
border-color: rgba(31, 111, 139, 0.25);
|
||||
box-shadow: inset 0 0 0 1px rgba(31, 111, 139, 0.12);
|
||||
}
|
||||
|
||||
.rfHistoryItem__meta {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.rfHistoryItem__action {
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.rfHistoryItem__time,
|
||||
.rfHistoryItem__sub {
|
||||
font-size: 12px;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfStatusRail {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.rfStatusRail__summary {
|
||||
margin-bottom: 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfStatusRail__list {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.rfStatusPill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 36px;
|
||||
padding: 0 11px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(99, 91, 82, 0.12);
|
||||
background: rgba(255, 250, 242, 0.92);
|
||||
color: var(--rf-ink);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
transition: 140ms ease;
|
||||
}
|
||||
|
||||
.rfStatusPill:hover,
|
||||
.rfStatusPill.isSelected {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 12px 24px rgba(27, 23, 20, 0.08);
|
||||
}
|
||||
|
||||
.rfStatusPill__name {
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.rfStatusPill__state {
|
||||
font-size: 10px;
|
||||
font-weight: 900;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.rfStatusPill.is-ok .rfStatusPill__state {
|
||||
color: #185f39;
|
||||
}
|
||||
|
||||
.rfStatusPill.is-warn .rfStatusPill__state {
|
||||
color: #8b3d24;
|
||||
}
|
||||
|
||||
.rfStatusPill.is-info .rfStatusPill__state {
|
||||
color: #425466;
|
||||
}
|
||||
|
||||
.rfLayout {
|
||||
margin-top: 12px;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.2fr) 410px;
|
||||
gap: 18px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.rfCanvas {
|
||||
height: calc(100vh - 126px);
|
||||
min-height: 760px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rfInspector {
|
||||
padding: 22px;
|
||||
max-height: calc(100vh - 126px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.rfInspector h2 {
|
||||
margin: 10px 0 8px;
|
||||
font-size: 1.8rem;
|
||||
line-height: 1.05;
|
||||
font-family: 'IBM Plex Serif', Georgia, serif;
|
||||
}
|
||||
|
||||
.rfInspector__host {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.rfSection {
|
||||
margin-top: 18px;
|
||||
padding-top: 18px;
|
||||
border-top: 1px solid rgba(99, 91, 82, 0.12);
|
||||
}
|
||||
|
||||
.rfSection h3 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 0.98rem;
|
||||
}
|
||||
|
||||
.rfSection ul {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
}
|
||||
|
||||
.rfSection li {
|
||||
margin: 6px 0;
|
||||
}
|
||||
|
||||
.rfRouteList {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.rfRouteItem {
|
||||
padding: 10px 12px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(99, 91, 82, 0.12);
|
||||
background: rgba(255, 252, 246, 0.84);
|
||||
}
|
||||
|
||||
.rfRouteItem.isEmpty {
|
||||
color: var(--rf-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.rfRouteItem__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.rfRouteItem__meta {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--rf-ink);
|
||||
}
|
||||
|
||||
.rfRouteItem__desc {
|
||||
margin-top: 4px;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfRouteBadge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 20px;
|
||||
padding: 0 7px;
|
||||
border-radius: 999px;
|
||||
font-size: 10px;
|
||||
font-weight: 900;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.rfRouteBadge.is-in {
|
||||
background: rgba(75, 85, 99, 0.12);
|
||||
color: #3f4854;
|
||||
}
|
||||
|
||||
.rfRouteBadge.is-out {
|
||||
background: rgba(20, 114, 109, 0.14);
|
||||
color: #126863;
|
||||
}
|
||||
|
||||
.rfRouteBadge.is-path-read {
|
||||
background: rgba(31, 111, 139, 0.12);
|
||||
color: #1f6f8b;
|
||||
}
|
||||
|
||||
.rfRouteBadge.is-path-live {
|
||||
background: rgba(176, 79, 53, 0.12);
|
||||
color: #a04a33;
|
||||
}
|
||||
|
||||
.rfRouteBadge.is-path-write {
|
||||
background: rgba(122, 98, 19, 0.14);
|
||||
color: #7a6213;
|
||||
}
|
||||
|
||||
.rfRouteBadge.is-path-control {
|
||||
background: rgba(75, 85, 99, 0.12);
|
||||
color: #4b5563;
|
||||
}
|
||||
|
||||
.rfLegend {
|
||||
background: rgba(255, 252, 246, 0.9);
|
||||
border: 1px solid rgba(99, 91, 82, 0.12);
|
||||
border-radius: 16px;
|
||||
padding: 12px 14px;
|
||||
box-shadow: 0 12px 28px rgba(27, 23, 20, 0.08);
|
||||
}
|
||||
|
||||
.rfLegend__title {
|
||||
margin-bottom: 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfLegend__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--rf-ink);
|
||||
}
|
||||
|
||||
.rfLegend__row span {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 999px;
|
||||
flex: 0 0 12px;
|
||||
}
|
||||
|
||||
.rfCard {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 1px solid rgba(99, 91, 82, 0.14);
|
||||
border-left: 6px solid var(--lane-color);
|
||||
border-radius: 18px;
|
||||
background: var(--rf-card);
|
||||
box-shadow: 0 16px 32px rgba(27, 23, 20, 0.08);
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
user-select: none;
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.rfCard.isWorkflow {
|
||||
border-color: rgba(50, 130, 80, 0.72);
|
||||
box-shadow:
|
||||
inset 0 0 0 2px rgba(88, 175, 112, 0.22),
|
||||
0 18px 34px rgba(32, 92, 52, 0.12);
|
||||
}
|
||||
|
||||
.rfCard.isWorkflow .rfCard__subtitle {
|
||||
color: #2d6b3f;
|
||||
}
|
||||
|
||||
.rfCard.isSelected {
|
||||
box-shadow: 0 18px 38px rgba(27, 23, 20, 0.16);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.rfCard.isDragging {
|
||||
border-color: rgba(176, 48, 35, 0.78);
|
||||
box-shadow:
|
||||
0 0 0 3px rgba(176, 48, 35, 0.3),
|
||||
0 20px 42px rgba(176, 48, 35, 0.16);
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.rfCard__head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.rfDragHandle {
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.rfCard__title {
|
||||
margin-top: 4px;
|
||||
font-size: 0.94rem;
|
||||
font-weight: 800;
|
||||
color: var(--rf-ink);
|
||||
}
|
||||
|
||||
.rfCard__host {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.rfCard__runtime {
|
||||
margin-top: 10px;
|
||||
padding: 9px 10px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(99, 91, 82, 0.12);
|
||||
background: linear-gradient(180deg, rgba(251, 247, 239, 0.96), rgba(246, 239, 227, 0.82));
|
||||
}
|
||||
|
||||
.rfCard__runtimeLabel {
|
||||
margin-bottom: 8px;
|
||||
font-size: 10px;
|
||||
font-weight: 900;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfCard__metricGrid,
|
||||
.rfInspector__metricGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.rfCard__metricGrid {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.rfMetricChip {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
padding: 8px 9px;
|
||||
border-radius: 12px;
|
||||
background: rgba(255, 253, 249, 0.92);
|
||||
border: 1px solid rgba(99, 91, 82, 0.1);
|
||||
}
|
||||
|
||||
.rfMetricChip span {
|
||||
font-size: 10px;
|
||||
font-weight: 900;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfMetricChip strong {
|
||||
font-size: 12px;
|
||||
line-height: 1.3;
|
||||
color: var(--rf-ink);
|
||||
}
|
||||
|
||||
.rfFactGrid,
|
||||
.rfPanelGrid {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.rfFactGrid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.rfFact {
|
||||
padding: 11px 12px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(99, 91, 82, 0.12);
|
||||
background: rgba(255, 252, 246, 0.84);
|
||||
}
|
||||
|
||||
.rfFact span {
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
font-size: 10px;
|
||||
font-weight: 900;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfFact strong {
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
color: var(--rf-ink);
|
||||
}
|
||||
|
||||
.rfPanelCard {
|
||||
padding: 12px 13px;
|
||||
border-radius: 16px;
|
||||
border: 1px solid rgba(99, 91, 82, 0.12);
|
||||
background: rgba(255, 252, 246, 0.84);
|
||||
}
|
||||
|
||||
.rfPanelCard__title {
|
||||
margin-bottom: 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 900;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--rf-muted);
|
||||
}
|
||||
|
||||
.rfPanelCard p,
|
||||
.rfPanelCard li {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.rfPanelCard ul {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
}
|
||||
|
||||
.rfPanelCard li + li {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.rfCard__bullets {
|
||||
margin: 10px 0 0;
|
||||
padding-left: 18px;
|
||||
font-size: 12px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rfCard__bullets li {
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.rfStatus {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
border-radius: 999px;
|
||||
padding: 5px 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.rfStatus.isOk {
|
||||
background: rgba(30, 107, 67, 0.11);
|
||||
color: #185f39;
|
||||
}
|
||||
|
||||
.rfStatus.isWarn {
|
||||
background: rgba(176, 79, 53, 0.11);
|
||||
color: #8b3d24;
|
||||
}
|
||||
|
||||
.rfHandle {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
background: var(--lane-color);
|
||||
border: 2px solid #fff;
|
||||
}
|
||||
|
||||
.rfHandle.isRouteHandle {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 2px solid rgba(255, 253, 249, 0.98);
|
||||
box-shadow: 0 0 0 2px rgba(27, 23, 20, 0.08);
|
||||
}
|
||||
|
||||
.rfZone {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 26px;
|
||||
border: 1px solid rgba(110, 101, 91, 0.14);
|
||||
padding: 12px 14px;
|
||||
user-select: none;
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.rfZone__head {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
min-height: 64px;
|
||||
width: min(100%, 320px);
|
||||
padding: 2px 2px 10px;
|
||||
}
|
||||
|
||||
.rfZone__title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 28px;
|
||||
padding: 0 10px;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 251, 244, 0.96);
|
||||
box-shadow: 0 6px 16px rgba(27, 23, 20, 0.06);
|
||||
font-size: 0.96rem;
|
||||
font-weight: 900;
|
||||
color: var(--rf-ink);
|
||||
font-family: 'IBM Plex Serif', Georgia, serif;
|
||||
}
|
||||
|
||||
.rfZone__subtitle {
|
||||
margin-top: 6px;
|
||||
max-width: 250px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--rf-muted);
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.rfZone.is-host {
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255, 253, 249, 0.92), rgba(244, 236, 225, 0.66));
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
||||
.rfZone.is-namespace {
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255, 251, 246, 0.78), rgba(236, 228, 214, 0.52));
|
||||
border-style: dashed;
|
||||
border-color: rgba(98, 91, 82, 0.22);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
|
||||
.rfZone.is-subzone {
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255, 254, 250, 0.72), rgba(248, 242, 233, 0.46));
|
||||
border-color: rgba(98, 91, 82, 0.12);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.16);
|
||||
}
|
||||
|
||||
.rfZone.isDragging {
|
||||
border-color: rgba(176, 48, 35, 0.72);
|
||||
box-shadow:
|
||||
inset 0 0 0 2px rgba(176, 48, 35, 0.22),
|
||||
0 0 0 3px rgba(176, 48, 35, 0.14);
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.rfZone.isDragging .rfZone__title {
|
||||
box-shadow:
|
||||
0 0 0 2px rgba(176, 48, 35, 0.18),
|
||||
0 8px 18px rgba(176, 48, 35, 0.16);
|
||||
}
|
||||
|
||||
.react-flow__renderer {
|
||||
background:
|
||||
linear-gradient(rgba(225, 214, 198, 0.22) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(225, 214, 198, 0.22) 1px, transparent 1px),
|
||||
linear-gradient(180deg, #fffdf8 0%, #faf4ea 100%);
|
||||
background-size: 20px 20px, 20px 20px, 100% 100%;
|
||||
}
|
||||
|
||||
.react-flow__nodes {
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.react-flow__edges,
|
||||
.react-flow__edgelabel-renderer {
|
||||
z-index: 30 !important;
|
||||
}
|
||||
|
||||
.react-flow__attribution {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.react-flow__controls,
|
||||
.react-flow__minimap {
|
||||
border: 1px solid rgba(99, 91, 82, 0.14);
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 12px 24px rgba(27, 23, 20, 0.08);
|
||||
}
|
||||
|
||||
.react-flow__controls button {
|
||||
background: rgba(255, 252, 246, 0.92);
|
||||
color: var(--rf-ink);
|
||||
border-bottom-color: rgba(99, 91, 82, 0.12);
|
||||
}
|
||||
|
||||
.react-flow__edge-text {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.rfResizeHandle {
|
||||
width: 12px !important;
|
||||
height: 12px !important;
|
||||
border-radius: 999px !important;
|
||||
border: 2px solid rgba(255, 253, 249, 0.96) !important;
|
||||
background: rgba(31, 111, 139, 0.72) !important;
|
||||
box-shadow: 0 0 0 2px rgba(27, 23, 20, 0.08);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 120ms ease, transform 120ms ease, background 120ms ease;
|
||||
}
|
||||
|
||||
.rfResizeLine {
|
||||
border-color: rgba(31, 111, 139, 0.28) !important;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 120ms ease, border-color 120ms ease;
|
||||
}
|
||||
|
||||
.rfCard:hover .rfResizeHandle,
|
||||
.rfCard:hover .rfResizeLine,
|
||||
.rfCard.isSelected .rfResizeHandle,
|
||||
.rfCard.isSelected .rfResizeLine,
|
||||
.rfCard.isDragging .rfResizeHandle,
|
||||
.rfCard.isDragging .rfResizeLine,
|
||||
.rfZone:hover .rfResizeHandle,
|
||||
.rfZone:hover .rfResizeLine,
|
||||
.rfZone.isSelected .rfResizeHandle,
|
||||
.rfZone.isSelected .rfResizeLine,
|
||||
.rfZone.isDragging .rfResizeHandle,
|
||||
.rfZone.isDragging .rfResizeLine {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.rfCard:hover .rfResizeHandle,
|
||||
.rfCard.isSelected .rfResizeHandle,
|
||||
.rfCard.isDragging .rfResizeHandle,
|
||||
.rfZone:hover .rfResizeHandle,
|
||||
.rfZone.isSelected .rfResizeHandle,
|
||||
.rfZone.isDragging .rfResizeHandle {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.rfCard:hover .rfResizeLine,
|
||||
.rfCard.isSelected .rfResizeLine,
|
||||
.rfCard.isDragging .rfResizeLine {
|
||||
border-color: rgba(31, 111, 139, 0.42) !important;
|
||||
}
|
||||
|
||||
.rfZone:hover .rfResizeLine,
|
||||
.rfZone.isSelected .rfResizeLine,
|
||||
.rfZone.isDragging .rfResizeLine {
|
||||
border-color: rgba(176, 48, 35, 0.26) !important;
|
||||
}
|
||||
|
||||
.rfZone .rfResizeHandle {
|
||||
background: rgba(176, 48, 35, 0.72) !important;
|
||||
}
|
||||
|
||||
.rfPage.isUltraWide .rfLayout {
|
||||
grid-template-columns: minmax(0, 1.45fr) 430px;
|
||||
}
|
||||
|
||||
.rfPage.isUltraWide .rfCanvas {
|
||||
height: calc(100vh - 118px);
|
||||
min-height: 820px;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: 'IBM Plex Mono', monospace;
|
||||
background: rgba(27, 23, 20, 0.05);
|
||||
padding: 2px 6px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.rfPage {
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.rfToolbar {
|
||||
grid-template-columns: 1fr;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.rfStatusRail__list {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.rfLayout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.rfCanvas {
|
||||
height: 72vh;
|
||||
min-height: 620px;
|
||||
}
|
||||
|
||||
.rfCard__metricGrid,
|
||||
.rfInspector__metricGrid,
|
||||
.rfFactGrid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,282 +0,0 @@
|
||||
import type { BotEventRow, BotObserverData, BotObserverRuntimeState } from './useBotObserver';
|
||||
|
||||
function formatUsd(v: number | null | undefined): string {
|
||||
if (v == null || !Number.isFinite(v)) return '—';
|
||||
if (Math.abs(v) >= 1_000_000) return `$${(v / 1_000_000).toFixed(2)}M`;
|
||||
if (Math.abs(v) >= 1000) return `$${(v / 1000).toFixed(1)}K`;
|
||||
return `$${v.toFixed(2)}`;
|
||||
}
|
||||
|
||||
function formatBps(v: number | null | undefined): string {
|
||||
if (v == null || !Number.isFinite(v)) return '—';
|
||||
return `${v.toFixed(2)} bps`;
|
||||
}
|
||||
|
||||
function formatPct(v: number | null | undefined): string {
|
||||
if (v == null || !Number.isFinite(v)) return '—';
|
||||
return `${(v * 100).toFixed(0)}%`;
|
||||
}
|
||||
|
||||
function formatAge(iso: string | null | undefined): string {
|
||||
if (!iso) return '—';
|
||||
const ts = Date.parse(iso);
|
||||
if (!Number.isFinite(ts)) return '—';
|
||||
const seconds = Math.max(0, Math.floor((Date.now() - ts) / 1000));
|
||||
if (seconds < 60) return `${seconds}s ago`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return `${minutes}m ago`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `${hours}h ago`;
|
||||
}
|
||||
|
||||
function formatClock(iso: string | null | undefined): string {
|
||||
if (!iso) return '—';
|
||||
const ts = Date.parse(iso);
|
||||
if (!Number.isFinite(ts)) return '—';
|
||||
return new Date(ts).toLocaleTimeString(undefined, {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
function numericClass(v: number | null | undefined): string {
|
||||
if (v == null || !Number.isFinite(v) || v === 0) return '';
|
||||
return v > 0 ? 'pos' : 'neg';
|
||||
}
|
||||
|
||||
function gateTone(value: boolean | null | undefined): 'ok' | 'bad' | 'muted' {
|
||||
if (value === true) return 'ok';
|
||||
if (value === false) return 'bad';
|
||||
return 'muted';
|
||||
}
|
||||
|
||||
function eventSummary(event: BotEventRow): string {
|
||||
const payload = event.payload || {};
|
||||
if (event.type === 'decision' || event.type === 'skip') {
|
||||
const decision = (payload as any).decision || {};
|
||||
const side = typeof decision.side === 'string' ? decision.side.toUpperCase() : '—';
|
||||
const confidence = typeof decision.confidence === 'number' ? `${Math.round(decision.confidence * 100)}%` : '—';
|
||||
const target = typeof decision.target_notional_usd === 'number' ? formatUsd(decision.target_notional_usd) : '—';
|
||||
const skipReason = typeof decision.skip_reason === 'string' && decision.skip_reason ? ` • ${decision.skip_reason}` : '';
|
||||
return `${side} • ${confidence} • ${target}${skipReason}`;
|
||||
}
|
||||
if (event.type === 'status') {
|
||||
const status = (payload as any).status || {};
|
||||
const bot = (payload as any).bot || {};
|
||||
const mode = typeof bot.mode === 'string' ? bot.mode : '—';
|
||||
const active = status.active === true ? 'active' : 'inactive';
|
||||
const note = typeof status.note === 'string' && status.note ? ` • ${status.note}` : '';
|
||||
return `${mode} • ${active}${note}`;
|
||||
}
|
||||
if (event.type === 'error') {
|
||||
return typeof (payload as any).error === 'string' ? (payload as any).error : 'error';
|
||||
}
|
||||
return JSON.stringify(payload);
|
||||
}
|
||||
|
||||
function kpiValueClass(side: string | null | undefined): string {
|
||||
if (side === 'long') return 'pos';
|
||||
if (side === 'short') return 'neg';
|
||||
return '';
|
||||
}
|
||||
|
||||
function renderFeatureRow(label: string, value: string, valueClass = '') {
|
||||
return (
|
||||
<div className="botFeatureRow" key={label}>
|
||||
<span className="botFeatureRow__label">{label}</span>
|
||||
<span className={['botFeatureRow__value', valueClass].filter(Boolean).join(' ')}>{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function BotObserverPanel({
|
||||
marketName,
|
||||
observer,
|
||||
}: {
|
||||
marketName: string;
|
||||
observer: BotObserverData;
|
||||
}) {
|
||||
const { bot, resolvedBy, state, events, loading, error, warning, lastUpdatedAt } = observer;
|
||||
const runtimeState: BotObserverRuntimeState | null = state?.state || null;
|
||||
const lastDecision = runtimeState?.last_decision || null;
|
||||
const lastFeatures = runtimeState?.last_features || null;
|
||||
const lastGates = runtimeState?.last_gates || null;
|
||||
const lastSnapshot = runtimeState?.last_snapshot || null;
|
||||
const counters = runtimeState?.counters || null;
|
||||
|
||||
if (loading && !bot) {
|
||||
return <div className="placeholder">Loading bot observer…</div>;
|
||||
}
|
||||
|
||||
if (error && !bot) {
|
||||
return <div className="uiError">{error}</div>;
|
||||
}
|
||||
|
||||
if (!bot) {
|
||||
if (warning === 'bot_control_plane_schema_missing') {
|
||||
return (
|
||||
<div className="botDash botDash--empty">
|
||||
<div className="botDash__emptyTitle">Bot control plane is not deployed here.</div>
|
||||
<div className="muted">This Hasura environment does not expose `bot_config`, `bot_state`, or `bot_events` yet.</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="botDash botDash--empty">
|
||||
<div className="botDash__emptyTitle">No bot configured for this market.</div>
|
||||
<div className="muted">Set `VITE_BOT_ID` / `VITE_BOT_NAME` or create a bot for {marketName}.</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="botDash dlobDash">
|
||||
<div className="dlobDash__head">
|
||||
<div className="dlobDash__title">Bot Observer</div>
|
||||
<div className="dlobDash__meta">
|
||||
<span className="dlobDash__market">{bot.name}</span>
|
||||
<span className="muted">{bot.market_name}</span>
|
||||
<span className="muted">{resolvedBy ? `resolved ${resolvedBy}` : 'manual'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error ? <div className="uiError">{error}</div> : null}
|
||||
|
||||
{bot.market_name !== marketName ? (
|
||||
<div className="botDash__note muted">Current chart market is {marketName}, panel shows bot for {bot.market_name}.</div>
|
||||
) : null}
|
||||
|
||||
<div className="dlobDash__statuses">
|
||||
<div className="dlobStatus">
|
||||
<span className="dlobStatus__label">mode</span>
|
||||
<span className="dlobStatus__value">{bot.mode}</span>
|
||||
</div>
|
||||
<div className="dlobStatus">
|
||||
<span className="dlobStatus__label">status</span>
|
||||
<span className="dlobStatus__value">{runtimeState?.status || '—'}</span>
|
||||
</div>
|
||||
<div className="dlobStatus">
|
||||
<span className="dlobStatus__label">heartbeat</span>
|
||||
<span className="dlobStatus__value">{formatAge(state?.last_heartbeat_at)}</span>
|
||||
</div>
|
||||
<div className="dlobStatus">
|
||||
<span className="dlobStatus__label">updated</span>
|
||||
<span className="dlobStatus__value">{lastUpdatedAt ? formatClock(lastUpdatedAt) : '—'}</span>
|
||||
</div>
|
||||
<div className="dlobStatus">
|
||||
<span className="dlobStatus__label">kill switch</span>
|
||||
<span className={['dlobStatus__value', bot.kill_switch ? 'neg' : 'pos'].join(' ')}>
|
||||
{bot.kill_switch ? 'enabled' : 'off'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="dlobDash__grid">
|
||||
<div className="dlobKpi">
|
||||
<div className="dlobKpi__label">Decision</div>
|
||||
<div className={['dlobKpi__value', kpiValueClass(lastDecision?.side || null)].join(' ')}>
|
||||
{lastDecision?.side || '—'}
|
||||
</div>
|
||||
<div className="dlobKpi__sub muted">{lastDecision?.skip_reason || 'current signal'}</div>
|
||||
</div>
|
||||
<div className="dlobKpi">
|
||||
<div className="dlobKpi__label">Confidence</div>
|
||||
<div className="dlobKpi__value">{formatPct(lastDecision?.confidence ?? null)}</div>
|
||||
</div>
|
||||
<div className="dlobKpi">
|
||||
<div className="dlobKpi__label">Target</div>
|
||||
<div className="dlobKpi__value">{formatUsd(lastDecision?.target_notional_usd ?? null)}</div>
|
||||
<div className="dlobKpi__sub muted">{lastDecision?.horizon_s != null ? `${lastDecision.horizon_s}s horizon` : '—'}</div>
|
||||
</div>
|
||||
<div className="dlobKpi">
|
||||
<div className="dlobKpi__label">Long Score</div>
|
||||
<div className={['dlobKpi__value', numericClass(lastDecision?.long_score ?? null)].join(' ')}>
|
||||
{lastDecision?.long_score == null ? '—' : lastDecision.long_score.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="dlobKpi">
|
||||
<div className="dlobKpi__label">Short Score</div>
|
||||
<div className={['dlobKpi__value', numericClass(lastDecision?.short_score ?? null)].join(' ')}>
|
||||
{lastDecision?.short_score == null ? '—' : lastDecision.short_score.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="dlobKpi">
|
||||
<div className="dlobKpi__label">Loops</div>
|
||||
<div className="dlobKpi__value">{counters?.loops ?? '—'}</div>
|
||||
<div className="dlobKpi__sub muted">
|
||||
{counters ? `${counters.decisions ?? 0} decisions / ${counters.skips ?? 0} skips` : '—'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="botDash__layout">
|
||||
<div className="botPanel">
|
||||
<div className="botPanel__head">
|
||||
<div className="botPanel__title">Gates</div>
|
||||
<div className="muted">{lastSnapshot?.data_age_ms != null ? `${lastSnapshot.data_age_ms} ms age` : '—'}</div>
|
||||
</div>
|
||||
<div className="botGateGrid">
|
||||
{[
|
||||
['fresh', lastGates?.fresh],
|
||||
['spread_ok', lastGates?.spread_ok],
|
||||
['slippage_ok', lastGates?.slippage_ok],
|
||||
['depth_ok', lastGates?.depth_ok],
|
||||
['has_candles', lastGates?.has_candles],
|
||||
['all', lastGates?.all],
|
||||
].map(([label, value]) => (
|
||||
<div
|
||||
key={label}
|
||||
className={`botGate botGate--${gateTone(value as boolean | null | undefined)}`}
|
||||
>
|
||||
<span className="botGate__label">{label}</span>
|
||||
<span className="botGate__value">{value == null ? '—' : value ? 'pass' : 'fail'}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="botPanel__head">
|
||||
<div className="botPanel__title">Feature Snapshot</div>
|
||||
<div className="muted">{lastSnapshot?.query_latency_ms != null ? `${lastSnapshot.query_latency_ms} ms query` : '—'}</div>
|
||||
</div>
|
||||
<div className="botFeatureList">
|
||||
{renderFeatureRow('spread_bps', formatBps(lastFeatures?.spread_bps ?? null))}
|
||||
{renderFeatureRow('mark_vs_oracle', formatBps(lastFeatures?.mark_vs_oracle_bps ?? null), numericClass(lastFeatures?.mark_vs_oracle_bps ?? null))}
|
||||
{renderFeatureRow('mom_3s', formatBps(lastFeatures?.mom_3s ?? null), numericClass(lastFeatures?.mom_3s ?? null))}
|
||||
{renderFeatureRow('mom_10s', formatBps(lastFeatures?.mom_10s ?? null), numericClass(lastFeatures?.mom_10s ?? null))}
|
||||
{renderFeatureRow('mom_30s', formatBps(lastFeatures?.mom_30s ?? null), numericClass(lastFeatures?.mom_30s ?? null))}
|
||||
{renderFeatureRow('vol_30s', formatBps(lastFeatures?.vol_30s ?? null))}
|
||||
{renderFeatureRow('depth_bid_usd', formatUsd(lastFeatures?.depth_bid_usd ?? null), 'pos')}
|
||||
{renderFeatureRow('depth_ask_usd', formatUsd(lastFeatures?.depth_ask_usd ?? null), 'neg')}
|
||||
{renderFeatureRow('depth_imbalance', formatPct(lastFeatures?.depth_imbalance ?? null), numericClass(lastFeatures?.depth_imbalance ?? null))}
|
||||
{renderFeatureRow('buy_slippage', formatBps(lastFeatures?.buy_slippage_bps ?? null))}
|
||||
{renderFeatureRow('sell_slippage', formatBps(lastFeatures?.sell_slippage_bps ?? null))}
|
||||
{renderFeatureRow('last_error', state?.last_error || runtimeState?.error || '—', state?.last_error || runtimeState?.error ? 'neg' : '')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="botPanel">
|
||||
<div className="botPanel__head">
|
||||
<div className="botPanel__title">Event Feed</div>
|
||||
<div className="muted">{events.length ? `${events.length} rows` : '—'}</div>
|
||||
</div>
|
||||
{events.length ? (
|
||||
<div className="botEventList">
|
||||
{events.map((event) => (
|
||||
<div className={`botEvent botEvent--${event.type}`} key={event.id}>
|
||||
<div className="botEvent__head">
|
||||
<span className="botEvent__type">{event.type}</span>
|
||||
<span className="muted">{formatClock(event.ts)}</span>
|
||||
</div>
|
||||
<div className="botEvent__summary">{eventSummary(event)}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="botPanel__empty muted">No bot events yet.</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
import type { BotObserverData, BotObserverRuntimeState } from './useBotObserver';
|
||||
|
||||
function formatPct(v: number | null | undefined): string {
|
||||
if (v == null || !Number.isFinite(v)) return '—';
|
||||
return `${(v * 100).toFixed(0)}%`;
|
||||
}
|
||||
|
||||
function formatUsd(v: number | null | undefined): string {
|
||||
if (v == null || !Number.isFinite(v)) return '—';
|
||||
if (Math.abs(v) >= 1_000_000) return `$${(v / 1_000_000).toFixed(2)}M`;
|
||||
if (Math.abs(v) >= 1000) return `$${(v / 1000).toFixed(1)}K`;
|
||||
return `$${v.toFixed(2)}`;
|
||||
}
|
||||
|
||||
function formatAge(iso: string | null | undefined): string {
|
||||
if (!iso) return '—';
|
||||
const ts = Date.parse(iso);
|
||||
if (!Number.isFinite(ts)) return '—';
|
||||
const seconds = Math.max(0, Math.floor((Date.now() - ts) / 1000));
|
||||
if (seconds < 60) return `${seconds}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return `${minutes}m`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `${hours}h`;
|
||||
}
|
||||
|
||||
function gateTone(value: boolean | null | undefined): 'ok' | 'bad' | 'muted' {
|
||||
if (value === true) return 'ok';
|
||||
if (value === false) return 'bad';
|
||||
return 'muted';
|
||||
}
|
||||
|
||||
function stateTone(value: string | null | undefined): string {
|
||||
const normalized = String(value || '').trim().toLowerCase();
|
||||
if (normalized === 'long') return 'pos';
|
||||
if (normalized === 'short' || normalized === 'panic') return 'neg';
|
||||
return '';
|
||||
}
|
||||
|
||||
function resolveMachineState(runtimeState: BotObserverRuntimeState | null, desiredMode: string, killSwitch: boolean): string {
|
||||
if (killSwitch) return 'panic';
|
||||
const status = String(runtimeState?.status || runtimeState?.mode || desiredMode || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (['off', 'observe', 'paper', 'trade', 'panic'].includes(status)) return status;
|
||||
return 'off';
|
||||
}
|
||||
|
||||
export default function BotObserverSummaryCard({
|
||||
marketName,
|
||||
observer,
|
||||
}: {
|
||||
marketName: string;
|
||||
observer: BotObserverData;
|
||||
}) {
|
||||
const { bot, state, loading, error, warning } = observer;
|
||||
const runtimeState: BotObserverRuntimeState | null = state?.state || null;
|
||||
const machineState = resolveMachineState(runtimeState, bot?.mode || 'off', Boolean(bot?.kill_switch));
|
||||
const lastDecision = runtimeState?.last_decision || null;
|
||||
const lastSnapshot = runtimeState?.last_snapshot || null;
|
||||
const lastGates = runtimeState?.last_gates || null;
|
||||
const counters = runtimeState?.counters || null;
|
||||
|
||||
if (loading && !bot) {
|
||||
return <div className="botSummaryCard__empty muted">Loading bot…</div>;
|
||||
}
|
||||
|
||||
if (error && !bot) {
|
||||
return <div className="uiError botSummaryCard__error">{error}</div>;
|
||||
}
|
||||
|
||||
if (!bot) {
|
||||
if (warning === 'bot_control_plane_schema_missing') {
|
||||
return (
|
||||
<div className="botSummaryCard__empty">
|
||||
<div className="botSummaryCard__emptyTitle">Bot control plane missing</div>
|
||||
<div className="muted">Current Hasura environment does not publish bot tables yet.</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="botSummaryCard__empty">
|
||||
<div className="botSummaryCard__emptyTitle">No bot configured</div>
|
||||
<div className="muted">No observer found for {marketName}.</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="botSummaryCard">
|
||||
<div className="botSummaryCard__head">
|
||||
<div>
|
||||
<div className="botSummaryCard__title">Bot State Machine</div>
|
||||
<div className="botSummaryCard__subtitle muted">{bot.name}</div>
|
||||
</div>
|
||||
<div className={['botSummaryCard__side', stateTone(lastDecision?.side)].join(' ')}>
|
||||
{(lastDecision?.side || 'flat').toUpperCase()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error ? <div className="uiError botSummaryCard__error">{error}</div> : null}
|
||||
|
||||
{bot.market_name !== marketName ? (
|
||||
<div className="botSummaryCard__note muted">Chart: {marketName} • Bot: {bot.market_name}</div>
|
||||
) : null}
|
||||
|
||||
<div className="botStateRail">
|
||||
{['off', 'observe', 'paper', 'trade', 'panic'].map((stage) => (
|
||||
<div
|
||||
key={stage}
|
||||
className={[
|
||||
'botStateRail__node',
|
||||
machineState === stage ? 'botStateRail__node--active' : '',
|
||||
stage === 'panic' ? 'botStateRail__node--panic' : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
>
|
||||
{stage}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="botSummaryStats">
|
||||
<div className="botSummaryStats__row">
|
||||
<span className="botSummaryStats__label">Desired</span>
|
||||
<span className="botSummaryStats__value">{bot.mode}</span>
|
||||
</div>
|
||||
<div className="botSummaryStats__row">
|
||||
<span className="botSummaryStats__label">Runtime</span>
|
||||
<span className="botSummaryStats__value">{runtimeState?.status || runtimeState?.mode || '—'}</span>
|
||||
</div>
|
||||
<div className="botSummaryStats__row">
|
||||
<span className="botSummaryStats__label">Heartbeat</span>
|
||||
<span className="botSummaryStats__value">{formatAge(state?.last_heartbeat_at)}</span>
|
||||
</div>
|
||||
<div className="botSummaryStats__row">
|
||||
<span className="botSummaryStats__label">Data Age</span>
|
||||
<span className="botSummaryStats__value">
|
||||
{lastSnapshot?.data_age_ms != null ? `${lastSnapshot.data_age_ms} ms` : '—'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="botSummaryStats__row">
|
||||
<span className="botSummaryStats__label">Query</span>
|
||||
<span className="botSummaryStats__value">
|
||||
{lastSnapshot?.query_latency_ms != null ? `${lastSnapshot.query_latency_ms} ms` : '—'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="botSummaryStats__row">
|
||||
<span className="botSummaryStats__label">Confidence</span>
|
||||
<span className="botSummaryStats__value">{formatPct(lastDecision?.confidence ?? null)}</span>
|
||||
</div>
|
||||
<div className="botSummaryStats__row">
|
||||
<span className="botSummaryStats__label">Target</span>
|
||||
<span className="botSummaryStats__value">{formatUsd(lastDecision?.target_notional_usd ?? null)}</span>
|
||||
</div>
|
||||
<div className="botSummaryStats__row">
|
||||
<span className="botSummaryStats__label">Loops</span>
|
||||
<span className="botSummaryStats__value">{counters?.loops ?? '—'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="botGatePills">
|
||||
{[
|
||||
['fresh', lastGates?.fresh],
|
||||
['spread', lastGates?.spread_ok],
|
||||
['slippage', lastGates?.slippage_ok],
|
||||
['depth', lastGates?.depth_ok],
|
||||
].map(([label, value]) => (
|
||||
<span key={label} className={`botGatePill botGatePill--${gateTone(value as boolean | null | undefined)}`}>
|
||||
{label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{lastDecision?.skip_reason ? (
|
||||
<div className="botSummaryCard__footer muted">skip: {lastDecision.skip_reason}</div>
|
||||
) : runtimeState?.inactive_reason ? (
|
||||
<div className="botSummaryCard__footer muted">{runtimeState.inactive_reason}</div>
|
||||
) : state?.last_error ? (
|
||||
<div className="botSummaryCard__footer neg">{state.last_error}</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,290 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useInterval } from '../../app/hooks/useInterval';
|
||||
|
||||
export type BotConfigSummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
market_name: string;
|
||||
market_type: string;
|
||||
mode: string;
|
||||
kill_switch: boolean;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type BotObserverRuntimeState = {
|
||||
service?: string;
|
||||
version?: string;
|
||||
appVersion?: string;
|
||||
observe_only?: boolean;
|
||||
market_name?: string;
|
||||
market_type?: string;
|
||||
mode?: string;
|
||||
kill_switch?: boolean;
|
||||
status?: string;
|
||||
strategy_type?: string;
|
||||
loop_ms?: number;
|
||||
last_snapshot?: {
|
||||
query_latency_ms?: number | null;
|
||||
data_age_ms?: number | null;
|
||||
candles_count?: number | null;
|
||||
stats_age_ms?: number | null;
|
||||
depth_age_ms?: number | null;
|
||||
buy_slippage_age_ms?: number | null;
|
||||
sell_slippage_age_ms?: number | null;
|
||||
} | null;
|
||||
last_features?: {
|
||||
mark_price?: number | null;
|
||||
oracle_price?: number | null;
|
||||
mid_price?: number | null;
|
||||
spread_bps?: number | null;
|
||||
stats_imbalance?: number | null;
|
||||
depth_bid_usd?: number | null;
|
||||
depth_ask_usd?: number | null;
|
||||
depth_imbalance?: number | null;
|
||||
buy_slippage_bps?: number | null;
|
||||
sell_slippage_bps?: number | null;
|
||||
mark_vs_oracle_bps?: number | null;
|
||||
mom_3s?: number | null;
|
||||
mom_10s?: number | null;
|
||||
mom_30s?: number | null;
|
||||
vol_30s?: number | null;
|
||||
} | null;
|
||||
last_gates?: {
|
||||
fresh?: boolean;
|
||||
spread_ok?: boolean;
|
||||
slippage_ok?: boolean;
|
||||
depth_ok?: boolean;
|
||||
has_candles?: boolean;
|
||||
all?: boolean;
|
||||
} | null;
|
||||
last_decision?: {
|
||||
side?: string;
|
||||
confidence?: number | null;
|
||||
long_score?: number | null;
|
||||
short_score?: number | null;
|
||||
target_notional_usd?: number | null;
|
||||
horizon_s?: number | null;
|
||||
skip_reason?: string | null;
|
||||
} | null;
|
||||
counters?: {
|
||||
loops?: number;
|
||||
decisions?: number;
|
||||
skips?: number;
|
||||
errors?: number;
|
||||
} | null;
|
||||
inactive_reason?: string;
|
||||
error?: string;
|
||||
trade_requested_but_observer_only?: boolean;
|
||||
};
|
||||
|
||||
export type BotStateRow = {
|
||||
bot_id: string;
|
||||
last_heartbeat_at: string | null;
|
||||
last_action_at: string | null;
|
||||
last_error: string | null;
|
||||
state: BotObserverRuntimeState | null;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type BotEventRow = {
|
||||
id: number;
|
||||
ts: string;
|
||||
type: string;
|
||||
payload?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
export type BotObserverData = {
|
||||
bot: BotConfigSummary | null;
|
||||
resolvedBy: string | null;
|
||||
state: BotStateRow | null;
|
||||
events: BotEventRow[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
warning: string | null;
|
||||
lastUpdatedAt: string | null;
|
||||
};
|
||||
|
||||
function envString(name: string): string | undefined {
|
||||
const value = (import.meta as any).env?.[name];
|
||||
if (value == null) return undefined;
|
||||
const text = String(value).trim();
|
||||
return text || undefined;
|
||||
}
|
||||
|
||||
function getApiBase(): string {
|
||||
return envString('VITE_API_URL') || '/api';
|
||||
}
|
||||
|
||||
function buildApiUrl(pathname: string): string {
|
||||
const base = new URL(getApiBase(), window.location.origin);
|
||||
const basePath = base.pathname && base.pathname !== '/' ? base.pathname.replace(/\/$/, '') : '';
|
||||
const [pathOnly, searchOnly = ''] = String(pathname || '').split('?');
|
||||
base.pathname = `${basePath}${pathOnly.startsWith('/') ? pathOnly : `/${pathOnly}`}`;
|
||||
base.search = searchOnly ? `?${searchOnly}` : '';
|
||||
base.hash = '';
|
||||
return base.toString();
|
||||
}
|
||||
|
||||
async function apiRequest<T>(pathname: string): Promise<T> {
|
||||
const res = await fetch(buildApiUrl(pathname), {
|
||||
cache: 'no-store',
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const text = await res.text();
|
||||
let json: any = null;
|
||||
try {
|
||||
json = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
throw new Error(`Invalid API JSON for ${pathname}`);
|
||||
}
|
||||
if (!res.ok) throw new Error(json?.error || `API HTTP ${res.status}`);
|
||||
return json as T;
|
||||
}
|
||||
|
||||
function preferredBotId(): string | undefined {
|
||||
return envString('VITE_BOT_ID');
|
||||
}
|
||||
|
||||
function preferredBotName(): string | undefined {
|
||||
return envString('VITE_BOT_NAME');
|
||||
}
|
||||
|
||||
function resolveBot(bots: BotConfigSummary[], marketName: string): { bot: BotConfigSummary | null; by: string | null } {
|
||||
const configuredId = preferredBotId();
|
||||
if (configuredId) {
|
||||
const match = bots.find((entry) => entry.id === configuredId);
|
||||
if (match) return { bot: match, by: 'env:id' };
|
||||
}
|
||||
|
||||
const configuredName = preferredBotName();
|
||||
if (configuredName) {
|
||||
const match = bots.find((entry) => entry.name === configuredName);
|
||||
if (match) return { bot: match, by: 'env:name' };
|
||||
}
|
||||
|
||||
const match = bots.find((entry) => String(entry.market_name || '').trim().toUpperCase() === marketName.trim().toUpperCase());
|
||||
if (match) return { bot: match, by: 'market' };
|
||||
|
||||
return { bot: null, by: null };
|
||||
}
|
||||
|
||||
export function useBotObserver(marketName: string): BotObserverData {
|
||||
const mountedRef = useRef(true);
|
||||
const resolveInFlightRef = useRef(false);
|
||||
const detailsInFlightRef = useRef(false);
|
||||
const [bot, setBot] = useState<BotConfigSummary | null>(null);
|
||||
const [resolvedBy, setResolvedBy] = useState<string | null>(null);
|
||||
const [state, setState] = useState<BotStateRow | null>(null);
|
||||
const [events, setEvents] = useState<BotEventRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [warning, setWarning] = useState<string | null>(null);
|
||||
const [lastUpdatedAt, setLastUpdatedAt] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function refreshBotResolution() {
|
||||
if (resolveInFlightRef.current) return;
|
||||
resolveInFlightRef.current = true;
|
||||
try {
|
||||
const json = await apiRequest<{ ok?: boolean; bots?: BotConfigSummary[]; error?: string; warning?: string }>(
|
||||
'/v1/bots?limit=100'
|
||||
);
|
||||
const bots = Array.isArray(json?.bots) ? json.bots : [];
|
||||
const resolved = resolveBot(bots, marketName);
|
||||
if (!mountedRef.current) return;
|
||||
setBot((current) => {
|
||||
if (current?.id === resolved.bot?.id) return current;
|
||||
return resolved.bot;
|
||||
});
|
||||
setResolvedBy(resolved.by);
|
||||
if (!resolved.bot) {
|
||||
setState(null);
|
||||
setEvents([]);
|
||||
setLoading(false);
|
||||
}
|
||||
setWarning(typeof json?.warning === 'string' && json.warning ? json.warning : null);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
if (!mountedRef.current) return;
|
||||
setError(String((err as Error)?.message || err));
|
||||
setLoading(false);
|
||||
} finally {
|
||||
resolveInFlightRef.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshBotDetails(botId: string) {
|
||||
if (detailsInFlightRef.current) return;
|
||||
detailsInFlightRef.current = true;
|
||||
try {
|
||||
const [stateJson, eventsJson] = await Promise.all([
|
||||
apiRequest<{ ok?: boolean; state?: BotStateRow | null; error?: string; warning?: string }>(
|
||||
`/v1/bots/${botId}/state`
|
||||
),
|
||||
apiRequest<{ ok?: boolean; events?: BotEventRow[]; error?: string; warning?: string }>(
|
||||
`/v1/bots/${botId}/events?limit=24`
|
||||
),
|
||||
]);
|
||||
if (!mountedRef.current) return;
|
||||
setState(stateJson?.state || null);
|
||||
setEvents(Array.isArray(eventsJson?.events) ? eventsJson.events : []);
|
||||
setLastUpdatedAt(new Date().toISOString());
|
||||
setWarning(
|
||||
(typeof stateJson?.warning === 'string' && stateJson.warning) ||
|
||||
(typeof eventsJson?.warning === 'string' && eventsJson.warning) ||
|
||||
null
|
||||
);
|
||||
setError(null);
|
||||
setLoading(false);
|
||||
} catch (err) {
|
||||
if (!mountedRef.current) return;
|
||||
setError(String((err as Error)?.message || err));
|
||||
setLoading(false);
|
||||
} finally {
|
||||
detailsInFlightRef.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
setBot(null);
|
||||
setResolvedBy(null);
|
||||
setState(null);
|
||||
setEvents([]);
|
||||
setError(null);
|
||||
setWarning(null);
|
||||
setLastUpdatedAt(null);
|
||||
void refreshBotResolution();
|
||||
}, [marketName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!bot?.id) return;
|
||||
void refreshBotDetails(bot.id);
|
||||
}, [bot?.id]);
|
||||
|
||||
useInterval(() => {
|
||||
void refreshBotResolution();
|
||||
}, 5000);
|
||||
|
||||
useInterval(() => {
|
||||
if (!bot?.id) return;
|
||||
void refreshBotDetails(bot.id);
|
||||
}, bot?.id ? 1000 : null);
|
||||
|
||||
return {
|
||||
bot,
|
||||
resolvedBy,
|
||||
state,
|
||||
events,
|
||||
loading,
|
||||
error,
|
||||
warning,
|
||||
lastUpdatedAt,
|
||||
};
|
||||
}
|
||||
@@ -1,21 +1,18 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { Candle, ChartIndicators } from '../../lib/api';
|
||||
import type { TickerItem } from '../tickerbar/TickerBar';
|
||||
import Card from '../../ui/Card';
|
||||
import ChartLayersPanel from './ChartLayersPanel';
|
||||
import ChartSideToolbar from './ChartSideToolbar';
|
||||
import ChartToolbar from './ChartToolbar';
|
||||
import TradingChart from './TradingChart';
|
||||
import type { FibAnchor, FibRetracement } from './FibRetracementPrimitive';
|
||||
import { LineStyle, type IChartApi, type ISeriesApi, type UTCTimestamp } from 'lightweight-charts';
|
||||
import { LineStyle, type IChartApi } from 'lightweight-charts';
|
||||
import type { OverlayLayer } from './ChartPanel.types';
|
||||
|
||||
type Props = {
|
||||
candles: Candle[];
|
||||
indicators: ChartIndicators;
|
||||
dlobQuotes?: { bid: number | null; ask: number | null; mid: number | null } | null;
|
||||
tickerItems: TickerItem[];
|
||||
theme: 'day' | 'night';
|
||||
timeframe: string;
|
||||
bucketSeconds: number;
|
||||
seriesKey: string;
|
||||
@@ -24,10 +21,7 @@ type Props = {
|
||||
onToggleIndicators: () => void;
|
||||
showBuild: boolean;
|
||||
onToggleBuild: () => void;
|
||||
onResetViewReady?: ((handler: (() => void) | null) => void) | undefined;
|
||||
seriesLabel: string;
|
||||
hasMoreHistory?: boolean;
|
||||
onRequestHistoryBefore?: (beforeTime: number) => Promise<void> | void;
|
||||
};
|
||||
|
||||
type FibDragMode = 'move' | 'edit-b';
|
||||
@@ -53,8 +47,6 @@ export default function ChartPanel({
|
||||
candles,
|
||||
indicators,
|
||||
dlobQuotes,
|
||||
tickerItems,
|
||||
theme,
|
||||
timeframe,
|
||||
bucketSeconds,
|
||||
seriesKey,
|
||||
@@ -63,10 +55,7 @@ export default function ChartPanel({
|
||||
onToggleIndicators,
|
||||
showBuild,
|
||||
onToggleBuild,
|
||||
onResetViewReady,
|
||||
seriesLabel,
|
||||
hasMoreHistory = false,
|
||||
onRequestHistoryBefore,
|
||||
}: Props) {
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
const [activeTool, setActiveTool] = useState<'cursor' | 'fib-retracement'>('cursor');
|
||||
@@ -85,7 +74,6 @@ export default function ChartPanel({
|
||||
const [priceAutoScale, setPriceAutoScale] = useState(true);
|
||||
|
||||
const chartApiRef = useRef<IChartApi | null>(null);
|
||||
const candleSeriesRef = useRef<ISeriesApi<'Candlestick', UTCTimestamp> | null>(null);
|
||||
const activeToolRef = useRef(activeTool);
|
||||
const fibStartRef = useRef<FibAnchor | null>(fibStart);
|
||||
const pendingMoveRef = useRef<FibAnchor | null>(null);
|
||||
@@ -96,7 +84,6 @@ export default function ChartPanel({
|
||||
const selectPointerRef = useRef<number | null>(null);
|
||||
const selectedOverlayIdRef = useRef<string | null>(selectedOverlayId);
|
||||
const fibRef = useRef<FibRetracement | null>(fib);
|
||||
const resetChartViewRef = useRef<() => void>(() => {});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isFullscreen) return;
|
||||
@@ -140,12 +127,6 @@ export default function ChartPanel({
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (isEditableTarget(e.target)) return;
|
||||
|
||||
if (e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey && e.key.toLowerCase() === 'r') {
|
||||
e.preventDefault();
|
||||
resetChartViewRef.current();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.code === 'Space') {
|
||||
spaceDownRef.current = true;
|
||||
e.preventDefault();
|
||||
@@ -213,17 +194,6 @@ export default function ChartPanel({
|
||||
ts.setVisibleLogicalRange({ from: center - span / 2, to: center + span / 2 });
|
||||
}
|
||||
|
||||
function resetChartView() {
|
||||
const chart = chartApiRef.current;
|
||||
if (!chart) return;
|
||||
|
||||
chart.timeScale().resetTimeScale();
|
||||
candleSeriesRef.current?.priceScale().setAutoScale(true);
|
||||
setPriceAutoScale(true);
|
||||
}
|
||||
|
||||
resetChartViewRef.current = resetChartView;
|
||||
|
||||
function clamp01(v: number): number {
|
||||
if (!Number.isFinite(v)) return 1;
|
||||
return Math.max(0, Math.min(1, v));
|
||||
@@ -258,7 +228,7 @@ export default function ChartPanel({
|
||||
lineStyle: LineStyle.Dotted,
|
||||
},
|
||||
];
|
||||
}, [dlobQuotes?.ask, dlobQuotes?.bid, dlobQuotes?.mid, quotesOpacity, quotesVisible, theme]);
|
||||
}, [dlobQuotes?.ask, dlobQuotes?.bid, dlobQuotes?.mid, quotesOpacity, quotesVisible]);
|
||||
|
||||
function updateLayer(layerId: string, patch: Partial<OverlayLayer>) {
|
||||
setLayers((prev) => prev.map((l) => (l.id === layerId ? { ...l, ...patch } : l)));
|
||||
@@ -330,19 +300,12 @@ export default function ChartPanel({
|
||||
if (!fibEffectiveVisible) setSelectedOverlayId(null);
|
||||
}, [fib, fibEffectiveVisible, selectedOverlayId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onResetViewReady) return;
|
||||
onResetViewReady(() => resetChartViewRef.current());
|
||||
return () => onResetViewReady(null);
|
||||
}, [onResetViewReady]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isFullscreen ? <div className="chartBackdrop" onClick={() => setIsFullscreen(false)} /> : null}
|
||||
<Card className={cardClassName}>
|
||||
<div className="chartCard__toolbar">
|
||||
<ChartToolbar
|
||||
tickerItems={tickerItems}
|
||||
timeframe={timeframe}
|
||||
onTimeframeChange={onTimeframeChange}
|
||||
showIndicators={showIndicators}
|
||||
@@ -366,13 +329,12 @@ export default function ChartPanel({
|
||||
onToggleLayers={() => setLayersOpen((v) => !v)}
|
||||
onZoomIn={() => zoomTime(0.8)}
|
||||
onZoomOut={() => zoomTime(1.25)}
|
||||
onResetView={resetChartView}
|
||||
onResetView={() => chartApiRef.current?.timeScale().resetTimeScale()}
|
||||
onClearFib={clearFib}
|
||||
/>
|
||||
<div className="chartCard__chart">
|
||||
<TradingChart
|
||||
candles={candles}
|
||||
theme={theme}
|
||||
oracle={indicators.oracle}
|
||||
sma20={indicators.sma20}
|
||||
ema20={indicators.ema20}
|
||||
@@ -386,11 +348,8 @@ export default function ChartPanel({
|
||||
fibOpacity={fibEffectiveOpacity}
|
||||
fibSelected={fibSelected}
|
||||
priceAutoScale={priceAutoScale}
|
||||
hasMoreHistory={hasMoreHistory}
|
||||
onRequestHistoryBefore={onRequestHistoryBefore}
|
||||
onReady={({ chart, candles: candleSeries }) => {
|
||||
onReady={({ chart }) => {
|
||||
chartApiRef.current = chart;
|
||||
candleSeriesRef.current = candleSeries;
|
||||
}}
|
||||
onChartClick={(p) => {
|
||||
if (activeTool === 'fib-retracement') {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import Button from '../../ui/Button';
|
||||
import TickerBar, { type TickerItem } from '../tickerbar/TickerBar';
|
||||
|
||||
type Props = {
|
||||
tickerItems: TickerItem[];
|
||||
timeframe: string;
|
||||
onTimeframeChange: (tf: string) => void;
|
||||
showIndicators: boolean;
|
||||
@@ -16,10 +14,9 @@ type Props = {
|
||||
onToggleFullscreen: () => void;
|
||||
};
|
||||
|
||||
const timeframes = ['1s', '3s', '5s', '15s', '30s', '1m', '5m', '15m', '1h', '4h', '1D'] as const;
|
||||
const timeframes = ['3s', '5s', '15s', '30s', '1m', '5m', '15m', '1h', '4h', '1D'] as const;
|
||||
|
||||
export default function ChartToolbar({
|
||||
tickerItems,
|
||||
timeframe,
|
||||
onTimeframeChange,
|
||||
showIndicators,
|
||||
@@ -35,7 +32,6 @@ export default function ChartToolbar({
|
||||
return (
|
||||
<div className="chartToolbar">
|
||||
<div className="chartToolbar__group">
|
||||
<TickerBar items={tickerItems} className="tickerBar--toolbar" />
|
||||
{timeframes.map((tf) => (
|
||||
<Button
|
||||
key={tf}
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
import type {
|
||||
IPrimitivePaneRenderer,
|
||||
IPrimitivePaneView,
|
||||
ISeriesApi,
|
||||
ISeriesPrimitive,
|
||||
SeriesAttachedParameter,
|
||||
Time,
|
||||
} from 'lightweight-charts';
|
||||
|
||||
export type KeyboardCursorPoint = {
|
||||
price: number;
|
||||
color: string;
|
||||
};
|
||||
|
||||
export type KeyboardCursorState = {
|
||||
time: number;
|
||||
price: number;
|
||||
points: KeyboardCursorPoint[];
|
||||
};
|
||||
|
||||
type State = {
|
||||
cursor: KeyboardCursorState | null;
|
||||
series: ISeriesApi<'Candlestick', Time> | null;
|
||||
chart: SeriesAttachedParameter<Time>['chart'] | null;
|
||||
lineColor: string;
|
||||
};
|
||||
|
||||
class KeyboardCursorPaneRenderer implements IPrimitivePaneRenderer {
|
||||
private readonly _getState: () => State;
|
||||
|
||||
constructor(getState: () => State) {
|
||||
this._getState = getState;
|
||||
}
|
||||
|
||||
draw(target: any) {
|
||||
const { cursor, series, chart, lineColor } = this._getState();
|
||||
if (!cursor || !series || !chart) return;
|
||||
|
||||
const x = chart.timeScale().timeToCoordinate(cursor.time as any);
|
||||
const y = series.priceToCoordinate(cursor.price);
|
||||
if (x == null || y == null) return;
|
||||
|
||||
target.useBitmapCoordinateSpace(({ context, bitmapSize, horizontalPixelRatio, verticalPixelRatio }: any) => {
|
||||
context.save();
|
||||
try {
|
||||
const xPx = Math.round(x * horizontalPixelRatio);
|
||||
const yPx = Math.round(y * verticalPixelRatio);
|
||||
|
||||
context.strokeStyle = lineColor;
|
||||
context.lineWidth = Math.max(1, Math.round(1 * horizontalPixelRatio));
|
||||
context.setLineDash([Math.max(3, Math.round(6 * horizontalPixelRatio)), Math.max(3, Math.round(6 * horizontalPixelRatio))]);
|
||||
|
||||
context.beginPath();
|
||||
context.moveTo(xPx, 0);
|
||||
context.lineTo(xPx, bitmapSize.height);
|
||||
context.stroke();
|
||||
|
||||
context.beginPath();
|
||||
context.moveTo(0, yPx);
|
||||
context.lineTo(bitmapSize.width, yPx);
|
||||
context.stroke();
|
||||
context.setLineDash([]);
|
||||
|
||||
const outerR = Math.max(3, Math.round(4 * horizontalPixelRatio));
|
||||
const innerR = Math.max(2, Math.round(2.5 * horizontalPixelRatio));
|
||||
|
||||
for (const point of cursor.points) {
|
||||
if (!Number.isFinite(point.price)) continue;
|
||||
const pointY = series.priceToCoordinate(point.price);
|
||||
if (pointY == null) continue;
|
||||
const pointYPx = Math.round(pointY * verticalPixelRatio);
|
||||
|
||||
context.fillStyle = lineColor;
|
||||
context.beginPath();
|
||||
context.arc(xPx, pointYPx, outerR, 0, Math.PI * 2);
|
||||
context.fill();
|
||||
|
||||
context.fillStyle = point.color;
|
||||
context.beginPath();
|
||||
context.arc(xPx, pointYPx, innerR, 0, Math.PI * 2);
|
||||
context.fill();
|
||||
}
|
||||
} finally {
|
||||
context.restore();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class KeyboardCursorPaneView implements IPrimitivePaneView {
|
||||
private readonly _renderer: KeyboardCursorPaneRenderer;
|
||||
|
||||
constructor(getState: () => State) {
|
||||
this._renderer = new KeyboardCursorPaneRenderer(getState);
|
||||
}
|
||||
|
||||
zOrder() {
|
||||
return 'top';
|
||||
}
|
||||
|
||||
renderer() {
|
||||
return this._renderer;
|
||||
}
|
||||
}
|
||||
|
||||
export class KeyboardCursorPrimitive implements ISeriesPrimitive<Time> {
|
||||
private _param: SeriesAttachedParameter<Time> | null = null;
|
||||
private _series: ISeriesApi<'Candlestick', Time> | null = null;
|
||||
private _cursor: KeyboardCursorState | null = null;
|
||||
private _lineColor = 'rgba(96,165,250,0.92)';
|
||||
private readonly _paneView: KeyboardCursorPaneView;
|
||||
private readonly _paneViews: readonly IPrimitivePaneView[];
|
||||
|
||||
constructor() {
|
||||
this._paneView = new KeyboardCursorPaneView(() => ({
|
||||
cursor: this._cursor,
|
||||
series: this._series,
|
||||
chart: this._param?.chart ?? null,
|
||||
lineColor: this._lineColor,
|
||||
}));
|
||||
this._paneViews = [this._paneView];
|
||||
}
|
||||
|
||||
attached(param: SeriesAttachedParameter<Time>) {
|
||||
this._param = param;
|
||||
this._series = param.series as ISeriesApi<'Candlestick', Time>;
|
||||
}
|
||||
|
||||
detached() {
|
||||
this._param = null;
|
||||
this._series = null;
|
||||
}
|
||||
|
||||
paneViews() {
|
||||
return this._paneViews;
|
||||
}
|
||||
|
||||
setCursor(next: KeyboardCursorState | null) {
|
||||
this._cursor = next;
|
||||
this._param?.requestUpdate();
|
||||
}
|
||||
|
||||
setLineColor(next: string) {
|
||||
this._lineColor = String(next || '').trim() || 'rgba(96,165,250,0.92)';
|
||||
this._param?.requestUpdate();
|
||||
}
|
||||
}
|
||||
@@ -22,11 +22,9 @@ import {
|
||||
} from 'lightweight-charts';
|
||||
import type { Candle, SeriesPoint } from '../../lib/api';
|
||||
import { FibRetracementPrimitive, type FibAnchor, type FibRetracement } from './FibRetracementPrimitive';
|
||||
import { KeyboardCursorPrimitive, type KeyboardCursorPoint, type KeyboardCursorState } from './KeyboardCursorPrimitive';
|
||||
|
||||
type Props = {
|
||||
candles: Candle[];
|
||||
theme: 'day' | 'night';
|
||||
oracle?: SeriesPoint[];
|
||||
sma20?: SeriesPoint[];
|
||||
ema20?: SeriesPoint[];
|
||||
@@ -48,8 +46,6 @@ type Props = {
|
||||
fibOpacity?: number;
|
||||
fibSelected?: boolean;
|
||||
priceAutoScale?: boolean;
|
||||
hasMoreHistory?: boolean;
|
||||
onRequestHistoryBefore?: (beforeTime: number) => Promise<void> | void;
|
||||
onReady?: (api: { chart: IChartApi; candles: ISeriesApi<'Candlestick', UTCTimestamp> }) => void;
|
||||
onChartClick?: (p: FibAnchor & { target: 'chart' | 'fib' }) => void;
|
||||
onChartCrosshairMove?: (p: FibAnchor) => void;
|
||||
@@ -73,32 +69,6 @@ const BUILD_FLAT_COLOR = '#60a5fa';
|
||||
const BUILD_UP_SLICE = 'rgba(34,197,94,0.70)';
|
||||
const BUILD_DOWN_SLICE = 'rgba(239,68,68,0.70)';
|
||||
const BUILD_FLAT_SLICE = 'rgba(96,165,250,0.70)';
|
||||
const ORACLE_CURSOR_POINT = 'rgba(251,146,60,0.95)';
|
||||
const SMA_CURSOR_POINT = 'rgba(248,113,113,0.95)';
|
||||
const EMA_CURSOR_POINT = 'rgba(52,211,153,0.95)';
|
||||
const BB_UPPER_CURSOR_POINT = 'rgba(250,204,21,0.85)';
|
||||
const BB_LOWER_CURSOR_POINT = 'rgba(163,163,163,0.85)';
|
||||
const BB_MID_CURSOR_POINT = 'rgba(250,204,21,0.65)';
|
||||
|
||||
function chartPalette(theme: 'day' | 'night') {
|
||||
if (theme === 'day') {
|
||||
return {
|
||||
textColor: '#112036',
|
||||
gridColor: 'rgba(17,32,54,0.08)',
|
||||
crosshairColor: 'rgba(71,85,105,0.28)',
|
||||
scaleBorder: 'rgba(17,32,54,0.12)',
|
||||
volumeColor: 'rgba(17,32,54,0.16)',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
textColor: '#e6e9ef',
|
||||
gridColor: 'rgba(255,255,255,0.06)',
|
||||
crosshairColor: 'rgba(226,232,240,0.22)',
|
||||
scaleBorder: 'rgba(255,255,255,0.08)',
|
||||
volumeColor: 'rgba(255,255,255,0.15)',
|
||||
};
|
||||
}
|
||||
|
||||
function toTime(t: number): UTCTimestamp {
|
||||
return t as UTCTimestamp;
|
||||
@@ -515,7 +485,6 @@ class BuildSlicesPrimitive implements ISeriesPrimitive<Time> {
|
||||
|
||||
export default function TradingChart({
|
||||
candles,
|
||||
theme,
|
||||
oracle,
|
||||
sma20,
|
||||
ema20,
|
||||
@@ -529,8 +498,6 @@ export default function TradingChart({
|
||||
fibOpacity = 1,
|
||||
fibSelected = false,
|
||||
priceAutoScale = true,
|
||||
hasMoreHistory = false,
|
||||
onRequestHistoryBefore,
|
||||
onReady,
|
||||
onChartClick,
|
||||
onChartCrosshairMove,
|
||||
@@ -548,24 +515,14 @@ export default function TradingChart({
|
||||
const onChartClickRef = useRef<Props['onChartClick']>(onChartClick);
|
||||
const onChartCrosshairMoveRef = useRef<Props['onChartCrosshairMove']>(onChartCrosshairMove);
|
||||
const onPointerEventRef = useRef<Props['onPointerEvent']>(onPointerEvent);
|
||||
const onRequestHistoryBeforeRef = useRef<Props['onRequestHistoryBefore']>(onRequestHistoryBefore);
|
||||
const capturedOverlayPointerRef = useRef<number | null>(null);
|
||||
const buildSlicesPrimitiveRef = useRef<BuildSlicesPrimitive | null>(null);
|
||||
const keyboardCursorPrimitiveRef = useRef<KeyboardCursorPrimitive | null>(null);
|
||||
const buildSamplesRef = useRef<Map<number, BuildSample[]>>(new Map());
|
||||
const buildKeyRef = useRef<string | null>(null);
|
||||
const lastBuildCandleStartRef = useRef<number | null>(null);
|
||||
const hoverCandleTimeRef = useRef<number | null>(null);
|
||||
const [hoverCandleTime, setHoverCandleTime] = useState<number | null>(null);
|
||||
const [keyboardCursor, setKeyboardCursor] = useState<KeyboardCursorState | null>(null);
|
||||
const priceLinesRef = useRef<Map<string, any>>(new Map());
|
||||
const candlesRef = useRef<Candle[]>(candles);
|
||||
const hasMoreHistoryRef = useRef<boolean>(hasMoreHistory);
|
||||
const requestedHistoryBeforeRef = useRef<number | null>(null);
|
||||
const prevSeriesKeyRef = useRef<string | null>(null);
|
||||
const prevFirstTimeRef = useRef<number | null>(null);
|
||||
const prevCandlesLenRef = useRef<number>(0);
|
||||
const keyboardCursorRef = useRef<KeyboardCursorState | null>(keyboardCursor);
|
||||
const seriesRef = useRef<{
|
||||
candles?: ISeriesApi<'Candlestick'>;
|
||||
volume?: ISeriesApi<'Histogram'>;
|
||||
@@ -586,7 +543,6 @@ export default function TradingChart({
|
||||
const bbUpper = useMemo(() => toLineSeries(bb20?.upper), [bb20?.upper]);
|
||||
const bbLower = useMemo(() => toLineSeries(bb20?.lower), [bb20?.lower]);
|
||||
const bbMid = useMemo(() => toLineSeries(bb20?.mid), [bb20?.mid]);
|
||||
const palette = useMemo(() => chartPalette(theme), [theme]);
|
||||
const priceFormat = useMemo(() => {
|
||||
const sample = samplePriceFromCandles(candles);
|
||||
return sample == null ? { type: 'price' as const, precision: 2, minMove: 0.01 } : priceFormatForSample(sample);
|
||||
@@ -608,10 +564,6 @@ export default function TradingChart({
|
||||
onPointerEventRef.current = onPointerEvent;
|
||||
}, [onPointerEvent]);
|
||||
|
||||
useEffect(() => {
|
||||
onRequestHistoryBeforeRef.current = onRequestHistoryBefore;
|
||||
}, [onRequestHistoryBefore]);
|
||||
|
||||
useEffect(() => {
|
||||
fibRef.current = fib ?? null;
|
||||
}, [fib]);
|
||||
@@ -625,93 +577,6 @@ export default function TradingChart({
|
||||
priceAutoScaleRef.current = priceAutoScale;
|
||||
}, [priceAutoScale]);
|
||||
|
||||
useEffect(() => {
|
||||
candlesRef.current = candles;
|
||||
}, [candles]);
|
||||
|
||||
useEffect(() => {
|
||||
hasMoreHistoryRef.current = hasMoreHistory;
|
||||
}, [hasMoreHistory]);
|
||||
|
||||
useEffect(() => {
|
||||
keyboardCursorRef.current = keyboardCursor;
|
||||
}, [keyboardCursor]);
|
||||
|
||||
function setHoverTime(next: number | null) {
|
||||
if (hoverCandleTimeRef.current !== next) {
|
||||
hoverCandleTimeRef.current = next;
|
||||
setHoverCandleTime(next);
|
||||
}
|
||||
}
|
||||
|
||||
function findCandleIndexByTime(items: Candle[], time: number | null): number {
|
||||
if (time == null || !items.length) return -1;
|
||||
let lo = 0;
|
||||
let hi = items.length - 1;
|
||||
while (lo <= hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
const midTime = items[mid]!.time;
|
||||
if (midTime === time) return mid;
|
||||
if (midTime < time) lo = mid + 1;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return Math.max(0, Math.min(items.length - 1, lo));
|
||||
}
|
||||
|
||||
function ensureLogicalIndexVisible(index: number, alignRight = false) {
|
||||
const chart = chartRef.current;
|
||||
if (!chart) return;
|
||||
const range = chart.timeScale().getVisibleLogicalRange();
|
||||
if (!range) return;
|
||||
|
||||
const from = Number(range.from);
|
||||
const to = Number(range.to);
|
||||
const span = Math.max(5, to - from);
|
||||
const leftPad = Math.max(2, Math.floor(span * 0.12));
|
||||
const rightPad = Math.max(2, Math.floor(span * 0.12));
|
||||
|
||||
if (alignRight) {
|
||||
chart.timeScale().setVisibleLogicalRange({
|
||||
from: index - span + rightPad,
|
||||
to: index + rightPad,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (index < from + leftPad) {
|
||||
chart.timeScale().setVisibleLogicalRange({
|
||||
from: index - leftPad,
|
||||
to: index - leftPad + span,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (index > to - rightPad) {
|
||||
chart.timeScale().setVisibleLogicalRange({
|
||||
from: index + rightPad - span,
|
||||
to: index + rightPad,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function activateKeyboardCursor(index: number, options?: { alignRight?: boolean; scrollToRealTime?: boolean }) {
|
||||
const chart = chartRef.current;
|
||||
const items = candlesRef.current;
|
||||
if (!chart || !items.length) return;
|
||||
|
||||
const safeIndex = Math.max(0, Math.min(items.length - 1, Math.round(index)));
|
||||
const candle = items[safeIndex]!;
|
||||
|
||||
if (options?.scrollToRealTime) chart.timeScale().scrollToRealTime();
|
||||
ensureLogicalIndexVisible(safeIndex, Boolean(options?.alignRight));
|
||||
setKeyboardCursor({ time: candle.time, price: candle.close, points: [] });
|
||||
onChartCrosshairMoveRef.current?.({ logical: safeIndex, price: candle.close });
|
||||
}
|
||||
|
||||
function clearKeyboardCursor() {
|
||||
setKeyboardCursor(null);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
showBuildRef.current = showBuild;
|
||||
if (!showBuild && (hoverCandleTimeRef.current != null || hoverCandleTime != null)) {
|
||||
@@ -727,21 +592,21 @@ export default function TradingChart({
|
||||
const chart = createChart(containerRef.current, {
|
||||
layout: {
|
||||
background: { type: ColorType.Solid, color: 'rgba(0,0,0,0)' },
|
||||
textColor: palette.textColor,
|
||||
textColor: '#e6e9ef',
|
||||
fontFamily:
|
||||
'system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, sans-serif',
|
||||
},
|
||||
grid: {
|
||||
vertLines: { color: palette.gridColor },
|
||||
horzLines: { color: palette.gridColor },
|
||||
vertLines: { color: 'rgba(255,255,255,0.06)' },
|
||||
horzLines: { color: 'rgba(255,255,255,0.06)' },
|
||||
},
|
||||
crosshair: {
|
||||
mode: CrosshairMode.Normal,
|
||||
vertLine: { color: palette.crosshairColor, style: LineStyle.Dashed },
|
||||
horzLine: { color: palette.crosshairColor, style: LineStyle.Dashed },
|
||||
vertLine: { color: 'rgba(255,255,255,0.18)', style: LineStyle.Dashed },
|
||||
horzLine: { color: 'rgba(255,255,255,0.18)', style: LineStyle.Dashed },
|
||||
},
|
||||
rightPriceScale: { borderColor: palette.scaleBorder },
|
||||
timeScale: { borderColor: palette.scaleBorder, timeVisible: true, secondsVisible: false },
|
||||
rightPriceScale: { borderColor: 'rgba(255,255,255,0.08)' },
|
||||
timeScale: { borderColor: 'rgba(255,255,255,0.08)', timeVisible: true, secondsVisible: false },
|
||||
handleScale: { mouseWheel: true, pinch: true },
|
||||
handleScroll: { mouseWheel: true, pressedMouseMove: true, horzTouchDrag: true, vertTouchDrag: true },
|
||||
});
|
||||
@@ -755,10 +620,6 @@ export default function TradingChart({
|
||||
wickDownColor: '#ef4444',
|
||||
priceFormat,
|
||||
});
|
||||
const keyboardCursorPrimitive = new KeyboardCursorPrimitive();
|
||||
candleSeries.attachPrimitive(keyboardCursorPrimitive);
|
||||
keyboardCursorPrimitiveRef.current = keyboardCursorPrimitive;
|
||||
keyboardCursorPrimitive.setLineColor(palette.crosshairColor);
|
||||
|
||||
const fibPrimitive = new FibRetracementPrimitive();
|
||||
candleSeries.attachPrimitive(fibPrimitive);
|
||||
@@ -769,7 +630,7 @@ export default function TradingChart({
|
||||
const volumeSeries = chart.addSeries(HistogramSeries, {
|
||||
priceFormat: { type: 'volume' },
|
||||
priceScaleId: '',
|
||||
color: palette.volumeColor,
|
||||
color: 'rgba(255,255,255,0.15)',
|
||||
});
|
||||
volumeSeries.priceScale().applyOptions({
|
||||
scaleMargins: { top: 0.88, bottom: 0 },
|
||||
@@ -833,12 +694,6 @@ export default function TradingChart({
|
||||
if (logical == null) return;
|
||||
const price = candleSeries.coordinateToPrice(param.point.y);
|
||||
if (price == null) return;
|
||||
const clickedTime = typeof param?.time === 'number' ? Number(param.time) : null;
|
||||
const clickedIndex =
|
||||
clickedTime != null && Number.isFinite(clickedTime)
|
||||
? findCandleIndexByTime(candlesRef.current, clickedTime)
|
||||
: Math.max(0, Math.min(candlesRef.current.length - 1, Math.round(Number(logical))));
|
||||
const clickedCandle = candlesRef.current[clickedIndex] ?? null;
|
||||
|
||||
const currentFib = fibRef.current;
|
||||
let target: 'chart' | 'fib' = 'chart';
|
||||
@@ -867,11 +722,6 @@ export default function TradingChart({
|
||||
}
|
||||
}
|
||||
|
||||
if (clickedCandle) {
|
||||
const chart = chartRef.current;
|
||||
if (chart) ensureLogicalIndexVisible(clickedIndex);
|
||||
setKeyboardCursor({ time: clickedCandle.time, price: Number(price), points: [] });
|
||||
}
|
||||
onChartClickRef.current?.({ logical: Number(logical), price: Number(price), target });
|
||||
};
|
||||
chart.subscribeClick(onClick);
|
||||
@@ -879,14 +729,20 @@ export default function TradingChart({
|
||||
const onCrosshairMove = (param: any) => {
|
||||
if (!param?.point) {
|
||||
if (showBuildRef.current && hoverCandleTimeRef.current != null) {
|
||||
setHoverTime(null);
|
||||
hoverCandleTimeRef.current = null;
|
||||
setHoverCandleTime(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const t = typeof param?.time === 'number' ? Number(param.time) : null;
|
||||
const next = t != null && Number.isFinite(t) ? t : null;
|
||||
setHoverTime(next);
|
||||
if (showBuildRef.current) {
|
||||
const t = typeof param?.time === 'number' ? Number(param.time) : null;
|
||||
const next = t != null && Number.isFinite(t) ? t : null;
|
||||
if (hoverCandleTimeRef.current !== next) {
|
||||
hoverCandleTimeRef.current = next;
|
||||
setHoverCandleTime(next);
|
||||
}
|
||||
}
|
||||
|
||||
const logical = param.logical ?? chart.timeScale().coordinateToLogical(param.point.x);
|
||||
if (logical == null) return;
|
||||
@@ -896,27 +752,7 @@ export default function TradingChart({
|
||||
};
|
||||
chart.subscribeCrosshairMove(onCrosshairMove);
|
||||
|
||||
const onVisibleLogicalRangeChange = (range: { from: number; to: number } | null) => {
|
||||
if (!range) return;
|
||||
if (!hasMoreHistoryRef.current) return;
|
||||
const currentCandles = candlesRef.current;
|
||||
const oldestTime = currentCandles[0]?.time;
|
||||
if (!oldestTime) return;
|
||||
|
||||
const threshold = Math.min(40, Math.max(8, Math.floor(currentCandles.length * 0.1)));
|
||||
if (Number(range.from) > threshold) {
|
||||
requestedHistoryBeforeRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (requestedHistoryBeforeRef.current === oldestTime) return;
|
||||
requestedHistoryBeforeRef.current = oldestTime;
|
||||
void onRequestHistoryBeforeRef.current?.(oldestTime);
|
||||
};
|
||||
chart.timeScale().subscribeVisibleLogicalRangeChange(onVisibleLogicalRangeChange);
|
||||
|
||||
const container = containerRef.current;
|
||||
const focusContainer = () => containerRef.current?.focus({ preventScroll: true });
|
||||
const toAnchorFromPoint = (x: number, y: number): FibAnchor | null => {
|
||||
const logical = chart.timeScale().coordinateToLogical(x);
|
||||
if (logical == null) return null;
|
||||
@@ -951,7 +787,6 @@ export default function TradingChart({
|
||||
|
||||
const onOverlayPointer = (e: PointerEvent) => {
|
||||
if (!containerRef.current) return;
|
||||
focusContainer();
|
||||
const rect = containerRef.current.getBoundingClientRect();
|
||||
const x = e.clientX - rect.left;
|
||||
const y = e.clientY - rect.top;
|
||||
@@ -1010,25 +845,6 @@ export default function TradingChart({
|
||||
container?.addEventListener('pointercancel', onOverlayPointer, { capture: true });
|
||||
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
if (e.shiftKey && !e.ctrlKey) {
|
||||
const range = chart.timeScale().getVisibleLogicalRange();
|
||||
if (!range) return;
|
||||
|
||||
const rawDelta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
|
||||
if (!Number.isFinite(rawDelta) || rawDelta === 0) return;
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const span = Math.max(5, Number(range.to) - Number(range.from));
|
||||
const shift = (rawDelta / 120) * Math.max(1, span * 0.12);
|
||||
chart.timeScale().setVisibleLogicalRange({
|
||||
from: Number(range.from) + shift,
|
||||
to: Number(range.to) + shift,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!e.ctrlKey) return;
|
||||
if (!containerRef.current) return;
|
||||
e.preventDefault();
|
||||
@@ -1073,7 +889,6 @@ export default function TradingChart({
|
||||
|
||||
let pan: { pointerId: number; startPrice: number; startRange: { from: number; to: number } } | null = null;
|
||||
const onPointerDown = (e: PointerEvent) => {
|
||||
focusContainer();
|
||||
if (e.button !== 0) return;
|
||||
if (!e.ctrlKey) return;
|
||||
if (priceAutoScaleRef.current) return;
|
||||
@@ -1149,56 +964,6 @@ export default function TradingChart({
|
||||
container?.addEventListener('pointerup', stopPan, { capture: true });
|
||||
container?.addEventListener('pointercancel', stopPan, { capture: true });
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (!candlesRef.current.length) return;
|
||||
if (e.ctrlKey || e.metaKey) return;
|
||||
|
||||
const items = candlesRef.current;
|
||||
const lastIndex = items.length - 1;
|
||||
const hoveredIndex = findCandleIndexByTime(items, keyboardCursorRef.current?.time ?? hoverCandleTimeRef.current);
|
||||
const baseIndex = hoveredIndex >= 0 ? hoveredIndex : lastIndex;
|
||||
const step = e.shiftKey ? 10 : 1;
|
||||
|
||||
if (e.altKey) {
|
||||
if (!e.shiftKey && e.key.toLowerCase() === 'l') {
|
||||
e.preventDefault();
|
||||
activateKeyboardCursor(lastIndex, { alignRight: true, scrollToRealTime: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
activateKeyboardCursor(baseIndex - step);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'ArrowRight') {
|
||||
e.preventDefault();
|
||||
activateKeyboardCursor(baseIndex + step);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'Home') {
|
||||
e.preventDefault();
|
||||
activateKeyboardCursor(0);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'End') {
|
||||
e.preventDefault();
|
||||
activateKeyboardCursor(lastIndex, { alignRight: true, scrollToRealTime: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'Escape' && keyboardCursorRef.current != null) {
|
||||
e.preventDefault();
|
||||
clearKeyboardCursor();
|
||||
}
|
||||
};
|
||||
|
||||
container?.addEventListener('keydown', onKeyDown);
|
||||
|
||||
const ro = new ResizeObserver(() => {
|
||||
if (!containerRef.current) return;
|
||||
const { width, height } = containerRef.current.getBoundingClientRect();
|
||||
@@ -1209,7 +974,6 @@ export default function TradingChart({
|
||||
return () => {
|
||||
chart.unsubscribeClick(onClick);
|
||||
chart.unsubscribeCrosshairMove(onCrosshairMove);
|
||||
chart.timeScale().unsubscribeVisibleLogicalRangeChange(onVisibleLogicalRangeChange);
|
||||
container?.removeEventListener('pointerdown', onOverlayPointer, { capture: true });
|
||||
container?.removeEventListener('pointermove', onOverlayPointer, { capture: true });
|
||||
container?.removeEventListener('pointerup', onOverlayPointer, { capture: true });
|
||||
@@ -1219,7 +983,6 @@ export default function TradingChart({
|
||||
container?.removeEventListener('pointermove', onPointerMove, { capture: true });
|
||||
container?.removeEventListener('pointerup', stopPan, { capture: true });
|
||||
container?.removeEventListener('pointercancel', stopPan, { capture: true });
|
||||
container?.removeEventListener('keydown', onKeyDown);
|
||||
ro.disconnect();
|
||||
if (fibPrimitiveRef.current) {
|
||||
candleSeries.detachPrimitive(fibPrimitiveRef.current);
|
||||
@@ -1229,10 +992,6 @@ export default function TradingChart({
|
||||
volumeSeries.detachPrimitive(buildSlicesPrimitiveRef.current);
|
||||
buildSlicesPrimitiveRef.current = null;
|
||||
}
|
||||
if (keyboardCursorPrimitiveRef.current) {
|
||||
candleSeries.detachPrimitive(keyboardCursorPrimitiveRef.current);
|
||||
keyboardCursorPrimitiveRef.current = null;
|
||||
}
|
||||
const lines = priceLinesRef.current;
|
||||
for (const line of Array.from(lines.values())) {
|
||||
try {
|
||||
@@ -1248,38 +1007,6 @@ export default function TradingChart({
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
keyboardCursorPrimitiveRef.current?.setLineColor(palette.crosshairColor);
|
||||
}, [palette.crosshairColor]);
|
||||
|
||||
useEffect(() => {
|
||||
const chart = chartRef.current;
|
||||
const volumeSeries = seriesRef.current.volume;
|
||||
if (!chart) return;
|
||||
|
||||
chart.applyOptions({
|
||||
layout: {
|
||||
background: { type: ColorType.Solid, color: 'rgba(0,0,0,0)' },
|
||||
textColor: palette.textColor,
|
||||
fontFamily:
|
||||
'system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, sans-serif',
|
||||
},
|
||||
grid: {
|
||||
vertLines: { color: palette.gridColor },
|
||||
horzLines: { color: palette.gridColor },
|
||||
},
|
||||
crosshair: {
|
||||
mode: CrosshairMode.Normal,
|
||||
vertLine: { color: palette.crosshairColor, style: LineStyle.Dashed },
|
||||
horzLine: { color: palette.crosshairColor, style: LineStyle.Dashed },
|
||||
},
|
||||
rightPriceScale: { borderColor: palette.scaleBorder },
|
||||
timeScale: { borderColor: palette.scaleBorder, timeVisible: true, secondsVisible: false },
|
||||
});
|
||||
|
||||
volumeSeries?.applyOptions({ color: palette.volumeColor });
|
||||
}, [palette]);
|
||||
|
||||
useEffect(() => {
|
||||
const candlesSeries = seriesRef.current.candles;
|
||||
if (!candlesSeries) return;
|
||||
@@ -1325,7 +1052,6 @@ export default function TradingChart({
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
}, [priceLines]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1402,8 +1128,8 @@ export default function TradingChart({
|
||||
buildPrimitive?.setEnabled(showBuild);
|
||||
|
||||
if (showBuild) {
|
||||
const activeCursorTime = keyboardCursor?.time ?? hoverCandleTime;
|
||||
const hoverCandle = activeCursorTime == null ? null : candles.find((c) => c.time === activeCursorTime);
|
||||
const hoverTime = hoverCandleTime;
|
||||
const hoverCandle = hoverTime == null ? null : candles.find((c) => c.time === hoverTime);
|
||||
const hoverData = hoverCandle ? buildDeltaSeriesForCandle(hoverCandle, bs, map.get(hoverCandle.time)) : [];
|
||||
|
||||
if (hoverData.length) {
|
||||
@@ -1438,107 +1164,8 @@ export default function TradingChart({
|
||||
bucketSeconds,
|
||||
seriesKey,
|
||||
hoverCandleTime,
|
||||
keyboardCursor,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
const chart = chartRef.current;
|
||||
const nextFirstTime = candles[0]?.time ?? null;
|
||||
const nextLen = candles.length;
|
||||
const prevFirstTime = prevFirstTimeRef.current;
|
||||
const prevLen = prevCandlesLenRef.current;
|
||||
|
||||
if (chart && prevFirstTime != null && nextFirstTime != null && nextFirstTime < prevFirstTime && nextLen > prevLen) {
|
||||
const range = chart.timeScale().getVisibleLogicalRange();
|
||||
if (range) {
|
||||
const delta = nextLen - prevLen;
|
||||
chart.timeScale().setVisibleLogicalRange({
|
||||
from: Number(range.from) + delta,
|
||||
to: Number(range.to) + delta,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
prevFirstTimeRef.current = nextFirstTime;
|
||||
prevCandlesLenRef.current = nextLen;
|
||||
}, [candles]);
|
||||
|
||||
useEffect(() => {
|
||||
const chart = chartRef.current;
|
||||
if (!chart) return;
|
||||
if (!candles.length) {
|
||||
prevSeriesKeyRef.current = seriesKey;
|
||||
clearKeyboardCursor();
|
||||
return;
|
||||
}
|
||||
if (prevSeriesKeyRef.current === seriesKey) return;
|
||||
|
||||
prevSeriesKeyRef.current = seriesKey;
|
||||
requestedHistoryBeforeRef.current = null;
|
||||
clearKeyboardCursor();
|
||||
setHoverTime(null);
|
||||
chart.timeScale().fitContent();
|
||||
if (priceAutoScaleRef.current) {
|
||||
seriesRef.current.candles?.priceScale().setAutoScale(true);
|
||||
}
|
||||
}, [candles.length, seriesKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!keyboardCursor) return;
|
||||
const items = candlesRef.current;
|
||||
if (!items.length) {
|
||||
clearKeyboardCursor();
|
||||
return;
|
||||
}
|
||||
const index = findCandleIndexByTime(items, keyboardCursor.time);
|
||||
if (index < 0) {
|
||||
activateKeyboardCursor(items.length - 1, { alignRight: true });
|
||||
return;
|
||||
}
|
||||
ensureLogicalIndexVisible(index);
|
||||
}, [candles, keyboardCursor]);
|
||||
|
||||
useEffect(() => {
|
||||
const primitive = keyboardCursorPrimitiveRef.current;
|
||||
if (!primitive) return;
|
||||
if (!keyboardCursor) {
|
||||
primitive.setCursor(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const candle = candles.find((item) => item.time === keyboardCursor.time) ?? null;
|
||||
if (!candle) {
|
||||
primitive.setCursor(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const candlePointColor = candle.close >= candle.open ? '#22c55e' : '#ef4444';
|
||||
const points: KeyboardCursorPoint[] = [{ price: candle.close, color: candlePointColor }];
|
||||
|
||||
const oracleValue = oracle.find((item) => item.time === candle.time)?.value ?? null;
|
||||
if (oracleValue != null) points.push({ price: oracleValue, color: ORACLE_CURSOR_POINT });
|
||||
|
||||
if (showIndicators) {
|
||||
const smaValue = sma20?.find((item) => item.time === candle.time)?.value ?? null;
|
||||
const emaValue = ema20?.find((item) => item.time === candle.time)?.value ?? null;
|
||||
const bbUpperValue = bb20?.upper.find((item) => item.time === candle.time)?.value ?? null;
|
||||
const bbLowerValue = bb20?.lower.find((item) => item.time === candle.time)?.value ?? null;
|
||||
const bbMidValue = bb20?.mid.find((item) => item.time === candle.time)?.value ?? null;
|
||||
|
||||
if (smaValue != null) points.push({ price: smaValue, color: SMA_CURSOR_POINT });
|
||||
if (emaValue != null) points.push({ price: emaValue, color: EMA_CURSOR_POINT });
|
||||
if (bbUpperValue != null) points.push({ price: bbUpperValue, color: BB_UPPER_CURSOR_POINT });
|
||||
if (bbLowerValue != null) points.push({ price: bbLowerValue, color: BB_LOWER_CURSOR_POINT });
|
||||
if (bbMidValue != null) points.push({ price: bbMidValue, color: BB_MID_CURSOR_POINT });
|
||||
}
|
||||
|
||||
primitive.setCursor({
|
||||
time: candle.time,
|
||||
price: keyboardCursor.price,
|
||||
points,
|
||||
});
|
||||
}, [bb20, candles, ema20, keyboardCursor, oracle, showIndicators, sma20]);
|
||||
|
||||
useEffect(() => {
|
||||
const s = seriesRef.current;
|
||||
if (!s.candles) return;
|
||||
@@ -1586,5 +1213,5 @@ export default function TradingChart({
|
||||
ps.setVisibleRange({ from, to });
|
||||
}, [priceAutoScale]);
|
||||
|
||||
return <div className="tradingChart" ref={containerRef} tabIndex={0} aria-label="Trading chart" />;
|
||||
return <div className="tradingChart" ref={containerRef} />;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
applyLatestRowToCandles,
|
||||
buildChartIndicators,
|
||||
fetchChart,
|
||||
getChartLiveTable,
|
||||
mergeCandles,
|
||||
type Candle,
|
||||
type ChartIndicators,
|
||||
} from '../../lib/api';
|
||||
import { subscribeGraphqlWs } from '../../lib/graphqlWs';
|
||||
import type { Candle, ChartIndicators } from '../../lib/api';
|
||||
import { fetchChart } from '../../lib/api';
|
||||
import { useInterval } from '../../app/hooks/useInterval';
|
||||
|
||||
type Params = {
|
||||
symbol: string;
|
||||
@@ -22,196 +15,45 @@ type Result = {
|
||||
candles: Candle[];
|
||||
indicators: ChartIndicators;
|
||||
meta: { tf: string; bucketSeconds: number } | null;
|
||||
dataKey: string | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
hasMoreHistory: boolean;
|
||||
refresh: () => Promise<void>;
|
||||
requestHistoryBefore: (beforeTime: number) => Promise<void>;
|
||||
};
|
||||
|
||||
type HasuraLatestRow = {
|
||||
updated_at?: string | null;
|
||||
oracle_price?: unknown;
|
||||
mark_price?: unknown;
|
||||
mid_price?: unknown;
|
||||
source?: string | null;
|
||||
};
|
||||
|
||||
type SubscriptionData = Record<string, HasuraLatestRow[] | undefined>;
|
||||
|
||||
export function useChartData({ symbol, source, tf, limit, pollMs }: Params): Result {
|
||||
const [candles, setCandles] = useState<Candle[]>([]);
|
||||
const [indicators, setIndicators] = useState<ChartIndicators>({});
|
||||
const [meta, setMeta] = useState<{ tf: string; bucketSeconds: number } | null>(null);
|
||||
const [dataKey, setDataKey] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [hasMoreHistory, setHasMoreHistory] = useState(true);
|
||||
const inFlight = useRef(false);
|
||||
|
||||
const candlesRef = useRef<Candle[]>([]);
|
||||
const controllerRef = useRef<AbortController | null>(null);
|
||||
const requestIdRef = useRef(0);
|
||||
const loadingOlderRef = useRef(false);
|
||||
const requestedBeforeRef = useRef<number | null>(null);
|
||||
|
||||
const normalizedSource = useMemo(() => {
|
||||
const raw = String(source || '').trim();
|
||||
return raw || undefined;
|
||||
}, [source]);
|
||||
const queryKey = useMemo(() => JSON.stringify([symbol, normalizedSource ?? '', tf, limit]), [symbol, normalizedSource, tf, limit]);
|
||||
|
||||
useEffect(() => {
|
||||
candlesRef.current = candles;
|
||||
}, [candles]);
|
||||
|
||||
const replaceState = useCallback(
|
||||
(nextCandles: Candle[], nextMeta: { tf: string; bucketSeconds: number } | null, nextDataKey: string) => {
|
||||
candlesRef.current = nextCandles;
|
||||
setCandles(nextCandles);
|
||||
setIndicators(buildChartIndicators(nextCandles));
|
||||
setMeta(nextMeta);
|
||||
setDataKey(nextDataKey);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const fetchInitial = useCallback(async () => {
|
||||
controllerRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
const requestId = requestIdRef.current + 1;
|
||||
requestIdRef.current = requestId;
|
||||
controllerRef.current = controller;
|
||||
requestedBeforeRef.current = null;
|
||||
loadingOlderRef.current = false;
|
||||
const fetchOnce = useCallback(async () => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setHasMoreHistory(true);
|
||||
|
||||
try {
|
||||
const res = await fetchChart({
|
||||
symbol,
|
||||
source: normalizedSource,
|
||||
tf,
|
||||
limit,
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (controller.signal.aborted) return;
|
||||
if (requestId !== requestIdRef.current) return;
|
||||
replaceState(res.candles, res.meta, queryKey);
|
||||
setHasMoreHistory(res.candles.length > 0);
|
||||
const res = await fetchChart({ symbol, source, tf, limit });
|
||||
setCandles(res.candles);
|
||||
setIndicators(res.indicators);
|
||||
setMeta(res.meta);
|
||||
setError(null);
|
||||
} catch (e: any) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (requestId !== requestIdRef.current) return;
|
||||
setError(String(e?.message || e));
|
||||
} finally {
|
||||
if (requestId !== requestIdRef.current) return;
|
||||
if (controllerRef.current === controller) controllerRef.current = null;
|
||||
setLoading(false);
|
||||
inFlight.current = false;
|
||||
}
|
||||
}, [limit, normalizedSource, queryKey, replaceState, symbol, tf]);
|
||||
|
||||
const requestHistoryBefore = useCallback(
|
||||
async (beforeTime: number) => {
|
||||
const currentMeta = meta;
|
||||
if (!currentMeta) return;
|
||||
if (loadingOlderRef.current || !hasMoreHistory) return;
|
||||
if (!Number.isFinite(beforeTime)) return;
|
||||
|
||||
const cursor = Math.floor(beforeTime);
|
||||
if (requestedBeforeRef.current === cursor) return;
|
||||
requestedBeforeRef.current = cursor;
|
||||
loadingOlderRef.current = true;
|
||||
|
||||
try {
|
||||
const res = await fetchChart({
|
||||
symbol,
|
||||
source: normalizedSource,
|
||||
tf,
|
||||
limit,
|
||||
beforeTime: cursor,
|
||||
});
|
||||
const older = res.candles;
|
||||
if (!older.length) {
|
||||
setHasMoreHistory(false);
|
||||
return;
|
||||
}
|
||||
const merged = mergeCandles(older, candlesRef.current);
|
||||
replaceState(merged, currentMeta, queryKey);
|
||||
} catch (e: any) {
|
||||
requestedBeforeRef.current = null;
|
||||
setError(String(e?.message || e));
|
||||
} finally {
|
||||
loadingOlderRef.current = false;
|
||||
}
|
||||
},
|
||||
[hasMoreHistory, limit, meta, normalizedSource, queryKey, replaceState, symbol, tf]
|
||||
);
|
||||
}, [symbol, source, tf, limit]);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchInitial();
|
||||
}, [fetchInitial]);
|
||||
void fetchOnce();
|
||||
}, [fetchOnce]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => controllerRef.current?.abort();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!symbol || !meta) return;
|
||||
|
||||
const table = getChartLiveTable(symbol);
|
||||
const sourceClause = normalizedSource ? 'source: {_eq: $source}' : '';
|
||||
const query = `
|
||||
subscription ChartLive($market: String!${normalizedSource ? ', $source: String!' : ''}) {
|
||||
${table}(
|
||||
where: {
|
||||
market_name: {_eq: $market}
|
||||
is_indicative: {_eq: false}
|
||||
${sourceClause}
|
||||
}
|
||||
limit: 1
|
||||
) {
|
||||
updated_at
|
||||
oracle_price
|
||||
mark_price
|
||||
mid_price
|
||||
source
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const sub = subscribeGraphqlWs<SubscriptionData>({
|
||||
query,
|
||||
variables: {
|
||||
market: symbol,
|
||||
...(normalizedSource ? { source: normalizedSource } : {}),
|
||||
},
|
||||
pollMs,
|
||||
onError: (nextError) => setError(nextError),
|
||||
onData: (data) => {
|
||||
const row = data?.[table]?.[0];
|
||||
if (!row) return;
|
||||
const nextCandles = applyLatestRowToCandles(candlesRef.current, row, meta.bucketSeconds);
|
||||
if (nextCandles === candlesRef.current) return;
|
||||
replaceState(nextCandles, meta, queryKey);
|
||||
},
|
||||
});
|
||||
|
||||
return () => sub.unsubscribe();
|
||||
}, [meta, normalizedSource, pollMs, queryKey, replaceState, symbol]);
|
||||
useInterval(() => void fetchOnce(), pollMs);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
candles,
|
||||
indicators,
|
||||
meta,
|
||||
dataKey,
|
||||
loading,
|
||||
error,
|
||||
hasMoreHistory,
|
||||
refresh: fetchInitial,
|
||||
requestHistoryBefore,
|
||||
}),
|
||||
[candles, dataKey, error, fetchInitial, hasMoreHistory, indicators, loading, meta, requestHistoryBefore]
|
||||
() => ({ candles, indicators, meta, loading, error, refresh: fetchOnce }),
|
||||
[candles, indicators, meta, loading, error, fetchOnce]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
import type { DlobL2, OrderbookRow } from './useDlobL2';
|
||||
|
||||
export const DEFAULT_DLOB_DEPTH_BANDS_BPS = [5, 10, 20, 50, 100, 200] as const;
|
||||
export const DEFAULT_DLOB_SLIPPAGE_SIZES_USD = [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 5000, 10000, 50000] as const;
|
||||
|
||||
export type ComputedDlobDepthBandRow = {
|
||||
marketName: string;
|
||||
bandBps: number;
|
||||
midPrice: number | null;
|
||||
bestBid: number | null;
|
||||
bestAsk: number | null;
|
||||
bidUsd: number | null;
|
||||
askUsd: number | null;
|
||||
bidBase: number | null;
|
||||
askBase: number | null;
|
||||
imbalance: number | null;
|
||||
updatedAt: string | null;
|
||||
};
|
||||
|
||||
export type ComputedDlobSlippageRow = {
|
||||
marketName: string;
|
||||
side: 'buy' | 'sell';
|
||||
sizeUsd: number;
|
||||
midPrice: number | null;
|
||||
vwapPrice: number | null;
|
||||
worstPrice: number | null;
|
||||
filledUsd: number | null;
|
||||
filledBase: number | null;
|
||||
impactBps: number | null;
|
||||
levelsConsumed: number | null;
|
||||
fillPct: number | null;
|
||||
updatedAt: string | null;
|
||||
};
|
||||
|
||||
type OrderbookSide = 'buy' | 'sell';
|
||||
|
||||
function levelUsd(level: OrderbookRow): number {
|
||||
if (Number.isFinite(level.sizeUsd)) return level.sizeUsd;
|
||||
if (Number.isFinite(level.sizeBase) && Number.isFinite(level.price)) return level.sizeBase * level.price;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function canonicalBids(l2: DlobL2): OrderbookRow[] {
|
||||
return (Array.isArray(l2.bids) ? l2.bids : [])
|
||||
.slice()
|
||||
.sort((a, b) => b.price - a.price);
|
||||
}
|
||||
|
||||
function canonicalAsks(l2: DlobL2): OrderbookRow[] {
|
||||
return (Array.isArray(l2.asks) ? l2.asks.slice().reverse() : [])
|
||||
.slice()
|
||||
.sort((a, b) => a.price - b.price);
|
||||
}
|
||||
|
||||
function resolveBestBid(l2: DlobL2, bids: OrderbookRow[]): number | null {
|
||||
if (l2.bestBid != null && Number.isFinite(l2.bestBid)) return l2.bestBid;
|
||||
const price = bids[0]?.price;
|
||||
return Number.isFinite(price) ? price : null;
|
||||
}
|
||||
|
||||
function resolveBestAsk(l2: DlobL2, asks: OrderbookRow[]): number | null {
|
||||
if (l2.bestAsk != null && Number.isFinite(l2.bestAsk)) return l2.bestAsk;
|
||||
const price = asks[0]?.price;
|
||||
return Number.isFinite(price) ? price : null;
|
||||
}
|
||||
|
||||
function resolveMidPrice(l2: DlobL2, bestBid: number | null, bestAsk: number | null): number | null {
|
||||
if (l2.mid != null && Number.isFinite(l2.mid)) return l2.mid;
|
||||
if (bestBid != null && bestAsk != null) return (bestBid + bestAsk) / 2;
|
||||
return bestBid ?? bestAsk ?? null;
|
||||
}
|
||||
|
||||
function computeBandDepth(
|
||||
bids: OrderbookRow[],
|
||||
asks: OrderbookRow[],
|
||||
midPrice: number | null,
|
||||
bandBps: number
|
||||
): Pick<ComputedDlobDepthBandRow, 'bidUsd' | 'askUsd' | 'bidBase' | 'askBase' | 'imbalance'> {
|
||||
if (midPrice == null || !Number.isFinite(midPrice) || !(midPrice > 0)) {
|
||||
return {
|
||||
bidUsd: null,
|
||||
askUsd: null,
|
||||
bidBase: null,
|
||||
askBase: null,
|
||||
imbalance: null,
|
||||
};
|
||||
}
|
||||
|
||||
const minBidPrice = midPrice * (1 - bandBps / 10_000);
|
||||
const maxAskPrice = midPrice * (1 + bandBps / 10_000);
|
||||
|
||||
let bidBase = 0;
|
||||
let askBase = 0;
|
||||
let bidUsd = 0;
|
||||
let askUsd = 0;
|
||||
|
||||
for (const level of bids) {
|
||||
if (!Number.isFinite(level.price) || !Number.isFinite(level.sizeBase)) continue;
|
||||
if (level.price < minBidPrice) break;
|
||||
bidBase += level.sizeBase;
|
||||
bidUsd += levelUsd(level);
|
||||
}
|
||||
|
||||
for (const level of asks) {
|
||||
if (!Number.isFinite(level.price) || !Number.isFinite(level.sizeBase)) continue;
|
||||
if (level.price > maxAskPrice) break;
|
||||
askBase += level.sizeBase;
|
||||
askUsd += levelUsd(level);
|
||||
}
|
||||
|
||||
const denom = bidUsd + askUsd;
|
||||
return {
|
||||
bidUsd,
|
||||
askUsd,
|
||||
bidBase,
|
||||
askBase,
|
||||
imbalance: denom > 0 ? (bidUsd - askUsd) / denom : null,
|
||||
};
|
||||
}
|
||||
|
||||
function simulateFill(levels: OrderbookRow[], sizeUsd: number) {
|
||||
let remainingUsd = sizeUsd;
|
||||
let filledUsd = 0;
|
||||
let filledBase = 0;
|
||||
let worstPrice: number | null = null;
|
||||
let levelsConsumed = 0;
|
||||
|
||||
for (const level of levels) {
|
||||
const availableUsd = levelUsd(level);
|
||||
if (!(availableUsd > 0) || !Number.isFinite(level.price) || !(level.price > 0)) continue;
|
||||
if (remainingUsd <= 0) break;
|
||||
|
||||
levelsConsumed += 1;
|
||||
worstPrice = level.price;
|
||||
|
||||
const takeUsd = Math.min(remainingUsd, availableUsd);
|
||||
filledUsd += takeUsd;
|
||||
filledBase += takeUsd / level.price;
|
||||
remainingUsd -= takeUsd;
|
||||
}
|
||||
|
||||
return {
|
||||
filledUsd,
|
||||
filledBase,
|
||||
worstPrice,
|
||||
levelsConsumed,
|
||||
vwapPrice: filledBase > 0 ? filledUsd / filledBase : null,
|
||||
fillPct: sizeUsd > 0 ? (filledUsd / sizeUsd) * 100 : null,
|
||||
};
|
||||
}
|
||||
|
||||
function impactBps(side: OrderbookSide, midPrice: number | null, vwapPrice: number | null): number | null {
|
||||
if (midPrice == null || vwapPrice == null) return null;
|
||||
if (!(midPrice > 0) || !Number.isFinite(vwapPrice)) return null;
|
||||
if (side === 'buy') return ((vwapPrice / midPrice) - 1) * 10_000;
|
||||
return (1 - vwapPrice / midPrice) * 10_000;
|
||||
}
|
||||
|
||||
export function computeDepthBandsFromDlobL2(
|
||||
l2: DlobL2 | null | undefined,
|
||||
bandList: readonly number[] = DEFAULT_DLOB_DEPTH_BANDS_BPS
|
||||
): ComputedDlobDepthBandRow[] {
|
||||
if (!l2?.marketName) return [];
|
||||
|
||||
const bids = canonicalBids(l2);
|
||||
const asks = canonicalAsks(l2);
|
||||
const bestBid = resolveBestBid(l2, bids);
|
||||
const bestAsk = resolveBestAsk(l2, asks);
|
||||
const midPrice = resolveMidPrice(l2, bestBid, bestAsk);
|
||||
const updatedAt = l2.updatedAt ?? null;
|
||||
|
||||
return bandList
|
||||
.map((bandBps) => Number(bandBps))
|
||||
.filter((bandBps, idx, arr) => Number.isFinite(bandBps) && bandBps > 0 && arr.indexOf(bandBps) === idx)
|
||||
.sort((a, b) => a - b)
|
||||
.map((bandBps) => ({
|
||||
marketName: l2.marketName,
|
||||
bandBps,
|
||||
midPrice,
|
||||
bestBid,
|
||||
bestAsk,
|
||||
updatedAt,
|
||||
...computeBandDepth(bids, asks, midPrice, bandBps),
|
||||
}));
|
||||
}
|
||||
|
||||
export function computeSlippageFromDlobL2(
|
||||
l2: DlobL2 | null | undefined,
|
||||
sizeList: readonly number[] = DEFAULT_DLOB_SLIPPAGE_SIZES_USD
|
||||
): ComputedDlobSlippageRow[] {
|
||||
if (!l2?.marketName) return [];
|
||||
|
||||
const bids = canonicalBids(l2);
|
||||
const asks = canonicalAsks(l2);
|
||||
const bestBid = resolveBestBid(l2, bids);
|
||||
const bestAsk = resolveBestAsk(l2, asks);
|
||||
const midPrice = resolveMidPrice(l2, bestBid, bestAsk);
|
||||
const updatedAt = l2.updatedAt ?? null;
|
||||
|
||||
if (midPrice == null || !Number.isFinite(midPrice) || !(midPrice > 0)) return [];
|
||||
|
||||
const sizes = sizeList
|
||||
.map((sizeUsd) => Number(sizeUsd))
|
||||
.filter((sizeUsd, idx, arr) => Number.isFinite(sizeUsd) && sizeUsd > 0 && arr.indexOf(sizeUsd) === idx)
|
||||
.sort((a, b) => a - b);
|
||||
|
||||
const rows: ComputedDlobSlippageRow[] = [];
|
||||
|
||||
for (const sizeUsd of sizes) {
|
||||
const buyFill = simulateFill(asks, sizeUsd);
|
||||
rows.push({
|
||||
marketName: l2.marketName,
|
||||
side: 'buy',
|
||||
sizeUsd,
|
||||
midPrice,
|
||||
vwapPrice: buyFill.vwapPrice,
|
||||
worstPrice: buyFill.worstPrice,
|
||||
filledUsd: buyFill.filledUsd,
|
||||
filledBase: buyFill.filledBase,
|
||||
impactBps: impactBps('buy', midPrice, buyFill.vwapPrice),
|
||||
levelsConsumed: buyFill.levelsConsumed,
|
||||
fillPct: buyFill.fillPct,
|
||||
updatedAt,
|
||||
});
|
||||
|
||||
const sellFill = simulateFill(bids, sizeUsd);
|
||||
rows.push({
|
||||
marketName: l2.marketName,
|
||||
side: 'sell',
|
||||
sizeUsd,
|
||||
midPrice,
|
||||
vwapPrice: sellFill.vwapPrice,
|
||||
worstPrice: sellFill.worstPrice,
|
||||
filledUsd: sellFill.filledUsd,
|
||||
filledBase: sellFill.filledBase,
|
||||
impactBps: impactBps('sell', midPrice, sellFill.vwapPrice),
|
||||
levelsConsumed: sellFill.levelsConsumed,
|
||||
fillPct: sellFill.fillPct,
|
||||
updatedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
const HOT_MARKETS = new Set(['SOL-PERP', 'JTO-PERP', 'ADA-PERP']);
|
||||
|
||||
export type OrderbookTable = 'dlob_hot_snapshot_latest' | 'dlob_all_derived_latest';
|
||||
export type LatestDlobTable = 'dlob_hot_derived_latest' | 'dlob_all_derived_latest';
|
||||
|
||||
export function normalizeMarketName(marketName: string): string {
|
||||
return String(marketName || '').trim().toUpperCase();
|
||||
}
|
||||
|
||||
export function isHotMarket(marketName: string): boolean {
|
||||
return HOT_MARKETS.has(normalizeMarketName(marketName));
|
||||
}
|
||||
|
||||
export function getOrderbookTables(marketName: string): OrderbookTable[] {
|
||||
return isHotMarket(marketName) ? ['dlob_hot_snapshot_latest', 'dlob_all_derived_latest'] : ['dlob_all_derived_latest'];
|
||||
}
|
||||
|
||||
export function getOrderbookTable(marketName: string): OrderbookTable {
|
||||
return getOrderbookTables(marketName)[0];
|
||||
}
|
||||
|
||||
export function getLatestDlobTables(marketName: string): LatestDlobTable[] {
|
||||
return isHotMarket(marketName) ? ['dlob_hot_derived_latest', 'dlob_all_derived_latest'] : ['dlob_all_derived_latest'];
|
||||
}
|
||||
|
||||
export function getLatestDlobTable(marketName: string): LatestDlobTable {
|
||||
return getLatestDlobTables(marketName)[0];
|
||||
}
|
||||
|
||||
export function getChartSeriesTable(marketName: string): 'dlob_hot_derived_ts' | 'dlob_all_derived_ts' {
|
||||
return isHotMarket(marketName) ? 'dlob_hot_derived_ts' : 'dlob_all_derived_ts';
|
||||
}
|
||||
@@ -1,19 +1,134 @@
|
||||
import { useMemo } from 'react';
|
||||
import { computeDepthBandsFromDlobL2, type ComputedDlobDepthBandRow } from './dlobDerivedMetrics';
|
||||
import { useDlobL2 } from './useDlobL2';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { subscribeGraphqlWs } from '../../lib/graphqlWs';
|
||||
|
||||
const COMPUTED_DLOB_LEVELS = 512;
|
||||
export type DlobDepthBandRow = {
|
||||
marketName: string;
|
||||
bandBps: number;
|
||||
midPrice: number | null;
|
||||
bestBid: number | null;
|
||||
bestAsk: number | null;
|
||||
bidUsd: number | null;
|
||||
askUsd: number | null;
|
||||
bidBase: number | null;
|
||||
askBase: number | null;
|
||||
imbalance: number | null;
|
||||
updatedAt: string | null;
|
||||
};
|
||||
|
||||
export type DlobDepthBandRow = ComputedDlobDepthBandRow;
|
||||
function toNum(v: unknown): number | null {
|
||||
if (v == null) return null;
|
||||
if (typeof v === 'number') return Number.isFinite(v) ? v : null;
|
||||
if (typeof v === 'string') {
|
||||
const s = v.trim();
|
||||
if (!s) return null;
|
||||
const n = Number(s);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toInt(v: unknown): number | null {
|
||||
if (v == null) return null;
|
||||
if (typeof v === 'number') return Number.isFinite(v) ? Math.trunc(v) : null;
|
||||
if (typeof v === 'string') {
|
||||
const s = v.trim();
|
||||
if (!s) return null;
|
||||
const n = Number.parseInt(s, 10);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type HasuraRow = {
|
||||
market_name: string;
|
||||
band_bps: unknown;
|
||||
mid_price?: unknown;
|
||||
best_bid_price?: unknown;
|
||||
best_ask_price?: unknown;
|
||||
bid_usd?: unknown;
|
||||
ask_usd?: unknown;
|
||||
bid_base?: unknown;
|
||||
ask_base?: unknown;
|
||||
imbalance?: unknown;
|
||||
updated_at?: string | null;
|
||||
};
|
||||
|
||||
type SubscriptionData = {
|
||||
dlob_depth_bps_latest: HasuraRow[];
|
||||
};
|
||||
|
||||
export function useDlobDepthBands(
|
||||
marketName: string
|
||||
): { rows: DlobDepthBandRow[]; connected: boolean; error: string | null } {
|
||||
const { l2, connected, error } = useDlobL2(marketName, {
|
||||
levels: COMPUTED_DLOB_LEVELS,
|
||||
grouping: 'raw',
|
||||
});
|
||||
const [rows, setRows] = useState<DlobDepthBandRow[]>([]);
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const normalizedMarket = useMemo(() => (marketName || '').trim(), [marketName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!normalizedMarket) {
|
||||
setRows([]);
|
||||
setError(null);
|
||||
setConnected(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
const query = `
|
||||
subscription DlobDepthBands($market: String!) {
|
||||
dlob_depth_bps_latest(
|
||||
where: { market_name: { _eq: $market } }
|
||||
order_by: [{ band_bps: asc }]
|
||||
) {
|
||||
market_name
|
||||
band_bps
|
||||
mid_price
|
||||
best_bid_price
|
||||
best_ask_price
|
||||
bid_usd
|
||||
ask_usd
|
||||
bid_base
|
||||
ask_base
|
||||
imbalance
|
||||
updated_at
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const sub = subscribeGraphqlWs<SubscriptionData>({
|
||||
query,
|
||||
variables: { market: normalizedMarket },
|
||||
onStatus: ({ connected }) => setConnected(connected),
|
||||
onError: (e) => setError(e),
|
||||
onData: (data) => {
|
||||
const out: DlobDepthBandRow[] = [];
|
||||
for (const r of data?.dlob_depth_bps_latest || []) {
|
||||
if (!r?.market_name) continue;
|
||||
const bandBps = toInt(r.band_bps);
|
||||
if (bandBps == null || bandBps <= 0) continue;
|
||||
out.push({
|
||||
marketName: r.market_name,
|
||||
bandBps,
|
||||
midPrice: toNum(r.mid_price),
|
||||
bestBid: toNum(r.best_bid_price),
|
||||
bestAsk: toNum(r.best_ask_price),
|
||||
bidUsd: toNum(r.bid_usd),
|
||||
askUsd: toNum(r.ask_usd),
|
||||
bidBase: toNum(r.bid_base),
|
||||
askBase: toNum(r.ask_base),
|
||||
imbalance: toNum(r.imbalance),
|
||||
updatedAt: r.updated_at ?? null,
|
||||
});
|
||||
}
|
||||
setRows(out);
|
||||
},
|
||||
});
|
||||
|
||||
return () => sub.unsubscribe();
|
||||
}, [normalizedMarket]);
|
||||
|
||||
const rows = useMemo(() => computeDepthBandsFromDlobL2(l2), [l2]);
|
||||
return { rows, connected, error };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { subscribeGraphqlWs } from '../../lib/graphqlWs';
|
||||
import { getOrderbookTable, isHotMarket } from './dlobSource';
|
||||
|
||||
const ORDERBOOK_POLL_MS = 400;
|
||||
|
||||
export type OrderbookRow = {
|
||||
price: number;
|
||||
@@ -22,11 +19,12 @@ export type DlobL2 = {
|
||||
updatedAt: string | null;
|
||||
};
|
||||
|
||||
type ParsedLevel = {
|
||||
price: number;
|
||||
sizeBase: number;
|
||||
sizeUsd: number;
|
||||
};
|
||||
function envNumber(name: string): number | undefined {
|
||||
const raw = (import.meta as any).env?.[name];
|
||||
if (raw == null) return undefined;
|
||||
const n = Number(raw);
|
||||
return Number.isFinite(n) ? n : undefined;
|
||||
}
|
||||
|
||||
function toNum(v: unknown): number | null {
|
||||
if (v == null) return null;
|
||||
@@ -51,64 +49,38 @@ function normalizeJson(v: unknown): unknown {
|
||||
}
|
||||
}
|
||||
|
||||
const PRICE_PRECISION = 1_000_000;
|
||||
const BASE_PRECISION = 1_000_000_000;
|
||||
|
||||
function toScaledNum(v: unknown, precision: number): number | null {
|
||||
const n = toNum(v);
|
||||
if (n == null) return null;
|
||||
return n / precision;
|
||||
}
|
||||
|
||||
function parseNormalizedLevels(raw: unknown): ParsedLevel[] {
|
||||
function parseLevels(raw: unknown, pricePrecision: number, basePrecision: number): Array<{ price: number; size: number }> {
|
||||
const v = normalizeJson(raw);
|
||||
if (!Array.isArray(v)) return [];
|
||||
|
||||
const out: ParsedLevel[] = [];
|
||||
const out: Array<{ price: number; size: number }> = [];
|
||||
for (const item of v) {
|
||||
const price = toNum((item as any)?.price);
|
||||
const sizeBase = toNum((item as any)?.sizeBase ?? (item as any)?.size);
|
||||
if (price == null || sizeBase == null) continue;
|
||||
if (!Number.isFinite(price) || !Number.isFinite(sizeBase)) continue;
|
||||
out.push({ price, sizeBase, sizeUsd: sizeBase * price });
|
||||
const priceInt = toNum((item as any)?.price);
|
||||
const sizeInt = toNum((item as any)?.size);
|
||||
if (priceInt == null || sizeInt == null) continue;
|
||||
|
||||
const price = priceInt / pricePrecision;
|
||||
const size = sizeInt / basePrecision;
|
||||
if (!Number.isFinite(price) || !Number.isFinite(size)) continue;
|
||||
out.push({ price, size });
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseRawHotLevels(raw: unknown): ParsedLevel[] {
|
||||
const v = normalizeJson(raw);
|
||||
if (!Array.isArray(v)) return [];
|
||||
|
||||
const out: ParsedLevel[] = [];
|
||||
for (const item of v) {
|
||||
const price = toScaledNum((item as any)?.price, PRICE_PRECISION);
|
||||
const sizeBase = toScaledNum((item as any)?.size, BASE_PRECISION);
|
||||
if (price == null || sizeBase == null) continue;
|
||||
if (!Number.isFinite(price) || !Number.isFinite(sizeBase)) continue;
|
||||
out.push({ price, sizeBase, sizeUsd: sizeBase * price });
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function limitHotWindow(levels: ParsedLevel[], visibleLevels: number): ParsedLevel[] {
|
||||
const cap = Math.max(visibleLevels * 4, 24);
|
||||
return levels.slice(0, cap);
|
||||
}
|
||||
|
||||
function withTotals(levels: ParsedLevel[]): OrderbookRow[] {
|
||||
function withTotals(levels: Array<{ price: number; sizeBase: number }>): OrderbookRow[] {
|
||||
let totalBase = 0;
|
||||
let totalUsd = 0;
|
||||
|
||||
return levels.map((l) => {
|
||||
const sizeUsd = l.sizeBase * l.price;
|
||||
totalBase += l.sizeBase;
|
||||
totalUsd += l.sizeUsd;
|
||||
totalUsd += sizeUsd;
|
||||
|
||||
return {
|
||||
price: l.price,
|
||||
sizeBase: l.sizeBase,
|
||||
sizeUsd: l.sizeUsd,
|
||||
sizeUsd,
|
||||
totalBase,
|
||||
totalUsd,
|
||||
};
|
||||
@@ -116,29 +88,19 @@ function withTotals(levels: ParsedLevel[]): OrderbookRow[] {
|
||||
}
|
||||
|
||||
type HasuraDlobL2Row = {
|
||||
market_name: string;
|
||||
bids_norm?: unknown;
|
||||
asks_norm?: unknown;
|
||||
best_bid_price?: unknown;
|
||||
best_ask_price?: unknown;
|
||||
mid_price?: unknown;
|
||||
updated_at?: string | null;
|
||||
};
|
||||
|
||||
type HasuraHotSnapshotRow = {
|
||||
market_name: string;
|
||||
bids?: unknown;
|
||||
asks?: unknown;
|
||||
best_bid_price_raw?: unknown;
|
||||
best_ask_price_raw?: unknown;
|
||||
updated_at?: string | null;
|
||||
};
|
||||
|
||||
type SubscriptionData = Record<string, Array<HasuraDlobL2Row | HasuraHotSnapshotRow> | undefined>;
|
||||
type SubscriptionData = {
|
||||
dlob_l2_latest: HasuraDlobL2Row[];
|
||||
};
|
||||
|
||||
export function useDlobL2(
|
||||
marketName: string,
|
||||
opts?: { levels?: number; grouping?: string }
|
||||
opts?: { levels?: number }
|
||||
): { l2: DlobL2 | null; connected: boolean; error: string | null } {
|
||||
const [l2, setL2] = useState<DlobL2 | null>(null);
|
||||
const [connected, setConnected] = useState(false);
|
||||
@@ -146,54 +108,9 @@ export function useDlobL2(
|
||||
|
||||
const normalizedMarket = useMemo(() => (marketName || '').trim(), [marketName]);
|
||||
const levels = useMemo(() => Math.max(1, opts?.levels ?? 14), [opts?.levels]);
|
||||
const grouping = useMemo(() => String(opts?.grouping || 'drift').trim().toLowerCase(), [opts?.grouping]);
|
||||
|
||||
function resolveDriftGroupingStep(referencePrice: number | null): number {
|
||||
const px = referencePrice == null || !Number.isFinite(referencePrice) ? 0 : Math.abs(referencePrice);
|
||||
if (px >= 1000) return 0.1;
|
||||
if (px >= 100) return 0.01;
|
||||
if (px >= 10) return 0.001;
|
||||
if (px >= 1) return 0.0001;
|
||||
if (px >= 0.1) return 0.00001;
|
||||
return 0.000001;
|
||||
}
|
||||
|
||||
function resolveGroupingStep(mode: string, referencePrice: number | null): number | null {
|
||||
if (!mode || mode === 'raw' || mode === 'none' || mode === 'off') return null;
|
||||
if (mode === 'drift') return resolveDriftGroupingStep(referencePrice);
|
||||
const parsed = Number(mode);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function groupLevelsByStep(
|
||||
side: 'bid' | 'ask',
|
||||
input: ParsedLevel[],
|
||||
step: number | null
|
||||
): ParsedLevel[] {
|
||||
if (step == null || !Number.isFinite(step) || step <= 0) return input;
|
||||
const stepMicros = Math.max(1, Math.round(step * PRICE_PRECISION));
|
||||
const grouped = new Map<number, { sizeBase: number; sizeUsd: number }>();
|
||||
|
||||
for (const level of input) {
|
||||
const priceMicros = Math.round(level.price * PRICE_PRECISION);
|
||||
const bucketMicros =
|
||||
side === 'bid'
|
||||
? Math.floor(priceMicros / stepMicros) * stepMicros
|
||||
: Math.ceil(priceMicros / stepMicros) * stepMicros;
|
||||
const existing = grouped.get(bucketMicros) || { sizeBase: 0, sizeUsd: 0 };
|
||||
existing.sizeBase += level.sizeBase;
|
||||
existing.sizeUsd += level.sizeUsd;
|
||||
grouped.set(bucketMicros, existing);
|
||||
}
|
||||
|
||||
return Array.from(grouped.entries())
|
||||
.map(([bucketMicros, totals]) => ({
|
||||
price: bucketMicros / PRICE_PRECISION,
|
||||
sizeBase: totals.sizeBase,
|
||||
sizeUsd: totals.sizeUsd,
|
||||
}))
|
||||
.sort((a, b) => (side === 'bid' ? b.price - a.price : a.price - b.price));
|
||||
}
|
||||
const pricePrecision = useMemo(() => envNumber('VITE_DLOB_PRICE_PRECISION') ?? 1_000_000, []);
|
||||
const basePrecision = useMemo(() => envNumber('VITE_DLOB_BASE_PRECISION') ?? 1_000_000_000, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!normalizedMarket) {
|
||||
@@ -204,21 +121,13 @@ export function useDlobL2(
|
||||
}
|
||||
|
||||
setError(null);
|
||||
const table = getOrderbookTable(normalizedMarket);
|
||||
const hotMarket = isHotMarket(normalizedMarket);
|
||||
|
||||
const query = `
|
||||
subscription DlobL2($market: String!) {
|
||||
${table}(
|
||||
where: {
|
||||
market_name: {_eq: $market}
|
||||
is_indicative: {_eq: false}
|
||||
${hotMarket ? 'snapshot_kind: {_eq: "orderbook_l2"}' : ''}
|
||||
}
|
||||
limit: 1
|
||||
) {
|
||||
dlob_l2_latest(where: {market_name: {_eq: $market}}, limit: 1) {
|
||||
market_name
|
||||
${hotMarket ? 'bids asks best_bid_price_raw best_ask_price_raw' : 'bids_norm asks_norm best_bid_price best_ask_price mid_price'}
|
||||
bids
|
||||
asks
|
||||
updated_at
|
||||
}
|
||||
}
|
||||
@@ -227,63 +136,32 @@ export function useDlobL2(
|
||||
const sub = subscribeGraphqlWs<SubscriptionData>({
|
||||
query,
|
||||
variables: { market: normalizedMarket },
|
||||
pollMs: ORDERBOOK_POLL_MS,
|
||||
onStatus: ({ connected }) => setConnected(connected),
|
||||
onError: (e) => setError(e),
|
||||
onData: (data) => {
|
||||
const row = data?.[table]?.[0] as HasuraDlobL2Row | HasuraHotSnapshotRow | undefined;
|
||||
if (!row?.market_name) {
|
||||
setL2(null);
|
||||
return;
|
||||
}
|
||||
const row = data?.dlob_l2_latest?.[0];
|
||||
if (!row?.market_name) return;
|
||||
|
||||
const bestBidRaw = hotMarket
|
||||
? toScaledNum((row as HasuraHotSnapshotRow).best_bid_price_raw, PRICE_PRECISION)
|
||||
: toNum((row as HasuraDlobL2Row).best_bid_price);
|
||||
const bestAskRaw = hotMarket
|
||||
? toScaledNum((row as HasuraHotSnapshotRow).best_ask_price_raw, PRICE_PRECISION)
|
||||
: toNum((row as HasuraDlobL2Row).best_ask_price);
|
||||
const referencePrice =
|
||||
bestBidRaw != null && bestAskRaw != null ? (bestBidRaw + bestAskRaw) / 2 : bestBidRaw ?? bestAskRaw ?? null;
|
||||
const groupingStep = resolveGroupingStep(grouping, referencePrice);
|
||||
|
||||
const bidsSource = hotMarket
|
||||
? limitHotWindow(parseRawHotLevels((row as HasuraHotSnapshotRow).bids), levels)
|
||||
: parseNormalizedLevels((row as HasuraDlobL2Row).bids_norm);
|
||||
const asksSource = hotMarket
|
||||
? limitHotWindow(parseRawHotLevels((row as HasuraHotSnapshotRow).asks), levels)
|
||||
: parseNormalizedLevels((row as HasuraDlobL2Row).asks_norm);
|
||||
|
||||
const bidsSorted = groupLevelsByStep(
|
||||
'bid',
|
||||
bidsSource,
|
||||
groupingStep
|
||||
)
|
||||
const bidsSorted = parseLevels(row.bids, pricePrecision, basePrecision)
|
||||
.slice()
|
||||
.sort((a, b) => b.price - a.price)
|
||||
.slice(0, levels)
|
||||
.map((l) => ({ price: l.price, sizeBase: l.sizeBase, sizeUsd: l.sizeUsd }));
|
||||
.map((l) => ({ price: l.price, sizeBase: l.size }));
|
||||
|
||||
const asksSorted = groupLevelsByStep(
|
||||
'ask',
|
||||
asksSource,
|
||||
groupingStep
|
||||
)
|
||||
const asksSorted = parseLevels(row.asks, pricePrecision, basePrecision)
|
||||
.slice()
|
||||
.sort((a, b) => a.price - b.price)
|
||||
.slice(0, levels)
|
||||
.map((l) => ({ price: l.price, sizeBase: l.sizeBase, sizeUsd: l.sizeUsd }));
|
||||
.map((l) => ({ price: l.price, sizeBase: l.size }));
|
||||
|
||||
// We compute totals from best -> worse.
|
||||
// For UI we display asks with best ask closest to mid (at the bottom), so we reverse.
|
||||
const bids = withTotals(bidsSorted);
|
||||
const asks = withTotals(asksSorted).slice().reverse();
|
||||
|
||||
const bestBid = bestBidRaw ?? (bidsSorted.length ? bidsSorted[0].price : null);
|
||||
const bestAsk = bestAskRaw ?? (asksSorted.length ? asksSorted[0].price : null);
|
||||
const mid = hotMarket
|
||||
? bestBid != null && bestAsk != null
|
||||
? (bestBid + bestAsk) / 2
|
||||
: null
|
||||
: toNum((row as HasuraDlobL2Row).mid_price) ?? (bestBid != null && bestAsk != null ? (bestBid + bestAsk) / 2 : null);
|
||||
const bestBid = bidsSorted.length ? bidsSorted[0].price : null;
|
||||
const bestAsk = asksSorted.length ? asksSorted[0].price : null;
|
||||
const mid = bestBid != null && bestAsk != null ? (bestBid + bestAsk) / 2 : null;
|
||||
|
||||
setL2({
|
||||
marketName: row.market_name,
|
||||
@@ -298,7 +176,7 @@ export function useDlobL2(
|
||||
});
|
||||
|
||||
return () => sub.unsubscribe();
|
||||
}, [grouping, normalizedMarket, levels]);
|
||||
}, [normalizedMarket, levels, pricePrecision, basePrecision]);
|
||||
|
||||
return { l2, connected, error };
|
||||
}
|
||||
|
||||
@@ -1,17 +1,138 @@
|
||||
import { useMemo } from 'react';
|
||||
import { computeSlippageFromDlobL2, type ComputedDlobSlippageRow } from './dlobDerivedMetrics';
|
||||
import { useDlobL2 } from './useDlobL2';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { subscribeGraphqlWs } from '../../lib/graphqlWs';
|
||||
|
||||
const COMPUTED_DLOB_LEVELS = 512;
|
||||
export type DlobSlippageRow = {
|
||||
marketName: string;
|
||||
side: 'buy' | 'sell';
|
||||
sizeUsd: number;
|
||||
midPrice: number | null;
|
||||
vwapPrice: number | null;
|
||||
worstPrice: number | null;
|
||||
filledUsd: number | null;
|
||||
filledBase: number | null;
|
||||
impactBps: number | null;
|
||||
levelsConsumed: number | null;
|
||||
fillPct: number | null;
|
||||
updatedAt: string | null;
|
||||
};
|
||||
|
||||
export type DlobSlippageRow = ComputedDlobSlippageRow;
|
||||
function toNum(v: unknown): number | null {
|
||||
if (v == null) return null;
|
||||
if (typeof v === 'number') return Number.isFinite(v) ? v : null;
|
||||
if (typeof v === 'string') {
|
||||
const s = v.trim();
|
||||
if (!s) return null;
|
||||
const n = Number(s);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toInt(v: unknown): number | null {
|
||||
if (v == null) return null;
|
||||
if (typeof v === 'number') return Number.isFinite(v) ? Math.trunc(v) : null;
|
||||
if (typeof v === 'string') {
|
||||
const s = v.trim();
|
||||
if (!s) return null;
|
||||
const n = Number.parseInt(s, 10);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type HasuraRow = {
|
||||
market_name: string;
|
||||
side: string;
|
||||
size_usd: unknown;
|
||||
mid_price?: unknown;
|
||||
vwap_price?: unknown;
|
||||
worst_price?: unknown;
|
||||
filled_usd?: unknown;
|
||||
filled_base?: unknown;
|
||||
impact_bps?: unknown;
|
||||
levels_consumed?: unknown;
|
||||
fill_pct?: unknown;
|
||||
updated_at?: string | null;
|
||||
};
|
||||
|
||||
type SubscriptionData = {
|
||||
dlob_slippage_latest: HasuraRow[];
|
||||
};
|
||||
|
||||
export function useDlobSlippage(marketName: string): { rows: DlobSlippageRow[]; connected: boolean; error: string | null } {
|
||||
const { l2, connected, error } = useDlobL2(marketName, {
|
||||
levels: COMPUTED_DLOB_LEVELS,
|
||||
grouping: 'raw',
|
||||
});
|
||||
const [rows, setRows] = useState<DlobSlippageRow[]>([]);
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const normalizedMarket = useMemo(() => (marketName || '').trim(), [marketName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!normalizedMarket) {
|
||||
setRows([]);
|
||||
setError(null);
|
||||
setConnected(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
const query = `
|
||||
subscription DlobSlippage($market: String!) {
|
||||
dlob_slippage_latest(
|
||||
where: { market_name: { _eq: $market } }
|
||||
order_by: [{ side: asc }, { size_usd: asc }]
|
||||
) {
|
||||
market_name
|
||||
side
|
||||
size_usd
|
||||
mid_price
|
||||
vwap_price
|
||||
worst_price
|
||||
filled_usd
|
||||
filled_base
|
||||
impact_bps
|
||||
levels_consumed
|
||||
fill_pct
|
||||
updated_at
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const sub = subscribeGraphqlWs<SubscriptionData>({
|
||||
query,
|
||||
variables: { market: normalizedMarket },
|
||||
onStatus: ({ connected }) => setConnected(connected),
|
||||
onError: (e) => setError(e),
|
||||
onData: (data) => {
|
||||
const out: DlobSlippageRow[] = [];
|
||||
for (const r of data?.dlob_slippage_latest || []) {
|
||||
if (!r?.market_name) continue;
|
||||
const side = String(r.side || '').trim();
|
||||
if (side !== 'buy' && side !== 'sell') continue;
|
||||
const sizeUsd = toInt(r.size_usd);
|
||||
if (sizeUsd == null || sizeUsd <= 0) continue;
|
||||
out.push({
|
||||
marketName: r.market_name,
|
||||
side,
|
||||
sizeUsd,
|
||||
midPrice: toNum(r.mid_price),
|
||||
vwapPrice: toNum(r.vwap_price),
|
||||
worstPrice: toNum(r.worst_price),
|
||||
filledUsd: toNum(r.filled_usd),
|
||||
filledBase: toNum(r.filled_base),
|
||||
impactBps: toNum(r.impact_bps),
|
||||
levelsConsumed: toInt(r.levels_consumed),
|
||||
fillPct: toNum(r.fill_pct),
|
||||
updatedAt: r.updated_at ?? null,
|
||||
});
|
||||
}
|
||||
setRows(out);
|
||||
},
|
||||
});
|
||||
|
||||
return () => sub.unsubscribe();
|
||||
}, [normalizedMarket]);
|
||||
|
||||
const rows = useMemo(() => computeSlippageFromDlobL2(l2), [l2]);
|
||||
return { rows, connected, error };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { subscribeGraphqlWs } from '../../lib/graphqlWs';
|
||||
import { getLatestDlobTable } from './dlobSource';
|
||||
|
||||
const ORDERBOOK_STATS_POLL_MS = 400;
|
||||
|
||||
export type DlobStats = {
|
||||
marketName: string;
|
||||
@@ -35,23 +32,24 @@ function toNum(v: unknown): number | null {
|
||||
|
||||
type HasuraDlobStatsRow = {
|
||||
market_name: string;
|
||||
mark_price?: unknown;
|
||||
oracle_price?: unknown;
|
||||
best_bid_price?: unknown;
|
||||
best_ask_price?: unknown;
|
||||
mid_price?: unknown;
|
||||
spread_quote?: unknown;
|
||||
spread_bps?: unknown;
|
||||
depth_bid_base?: unknown;
|
||||
depth_ask_base?: unknown;
|
||||
depth_bid_quote?: unknown;
|
||||
depth_ask_quote?: unknown;
|
||||
imbalance?: unknown;
|
||||
mark_price?: string | null;
|
||||
oracle_price?: string | null;
|
||||
best_bid_price?: string | null;
|
||||
best_ask_price?: string | null;
|
||||
mid_price?: string | null;
|
||||
spread_abs?: string | null;
|
||||
spread_bps?: string | null;
|
||||
depth_bid_base?: string | null;
|
||||
depth_ask_base?: string | null;
|
||||
depth_bid_usd?: string | null;
|
||||
depth_ask_usd?: string | null;
|
||||
imbalance?: string | null;
|
||||
updated_at?: string | null;
|
||||
is_indicative?: boolean | null;
|
||||
};
|
||||
|
||||
type SubscriptionData = Record<string, HasuraDlobStatsRow[] | undefined>;
|
||||
type SubscriptionData = {
|
||||
dlob_stats_latest: HasuraDlobStatsRow[];
|
||||
};
|
||||
|
||||
export function useDlobStats(marketName: string): { stats: DlobStats | null; connected: boolean; error: string | null } {
|
||||
const [stats, setStats] = useState<DlobStats | null>(null);
|
||||
@@ -69,29 +67,24 @@ export function useDlobStats(marketName: string): { stats: DlobStats | null; con
|
||||
}
|
||||
|
||||
setError(null);
|
||||
const table = getLatestDlobTable(normalizedMarket);
|
||||
|
||||
const query = `
|
||||
subscription DlobStats($market: String!) {
|
||||
${table}(
|
||||
where: {market_name: {_eq: $market}, is_indicative: {_eq: false}}
|
||||
limit: 1
|
||||
) {
|
||||
dlob_stats_latest(where: {market_name: {_eq: $market}}, limit: 1) {
|
||||
market_name
|
||||
mark_price
|
||||
oracle_price
|
||||
best_bid_price
|
||||
best_ask_price
|
||||
mid_price
|
||||
spread_quote
|
||||
spread_abs
|
||||
spread_bps
|
||||
depth_bid_base
|
||||
depth_ask_base
|
||||
depth_bid_quote
|
||||
depth_ask_quote
|
||||
depth_bid_usd
|
||||
depth_ask_usd
|
||||
imbalance
|
||||
updated_at
|
||||
is_indicative
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -99,15 +92,11 @@ export function useDlobStats(marketName: string): { stats: DlobStats | null; con
|
||||
const sub = subscribeGraphqlWs<SubscriptionData>({
|
||||
query,
|
||||
variables: { market: normalizedMarket },
|
||||
pollMs: ORDERBOOK_STATS_POLL_MS,
|
||||
onStatus: ({ connected }) => setConnected(connected),
|
||||
onError: (e) => setError(e),
|
||||
onData: (data) => {
|
||||
const row = data?.[table]?.[0];
|
||||
if (!row?.market_name) {
|
||||
setStats(null);
|
||||
return;
|
||||
}
|
||||
const row = data?.dlob_stats_latest?.[0];
|
||||
if (!row?.market_name) return;
|
||||
setStats({
|
||||
marketName: row.market_name,
|
||||
markPrice: toNum(row.mark_price),
|
||||
@@ -115,12 +104,12 @@ export function useDlobStats(marketName: string): { stats: DlobStats | null; con
|
||||
bestBid: toNum(row.best_bid_price),
|
||||
bestAsk: toNum(row.best_ask_price),
|
||||
mid: toNum(row.mid_price),
|
||||
spreadAbs: toNum(row.spread_quote),
|
||||
spreadAbs: toNum(row.spread_abs),
|
||||
spreadBps: toNum(row.spread_bps),
|
||||
depthBidBase: toNum(row.depth_bid_base),
|
||||
depthAskBase: toNum(row.depth_ask_base),
|
||||
depthBidUsd: toNum(row.depth_bid_quote),
|
||||
depthAskUsd: toNum(row.depth_ask_quote),
|
||||
depthBidUsd: toNum(row.depth_bid_usd),
|
||||
depthAskUsd: toNum(row.depth_ask_usd),
|
||||
imbalance: toNum(row.imbalance),
|
||||
updatedAt: row.updated_at ?? null,
|
||||
});
|
||||
|
||||
@@ -9,7 +9,6 @@ export type TickerItem = {
|
||||
|
||||
type Props = {
|
||||
items: TickerItem[];
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function formatPct(v: number): string {
|
||||
@@ -17,9 +16,9 @@ function formatPct(v: number): string {
|
||||
return `${s}${v.toFixed(2)}%`;
|
||||
}
|
||||
|
||||
export default function TickerBar({ items, className }: Props) {
|
||||
export default function TickerBar({ items }: Props) {
|
||||
return (
|
||||
<div className={['tickerBar', className].filter(Boolean).join(' ')}>
|
||||
<div className="tickerBar">
|
||||
{items.map((t) => (
|
||||
<div key={t.key} className={['ticker', t.active ? 'ticker--active' : ''].filter(Boolean).join(' ')}>
|
||||
<span className="ticker__label">{t.label}</span>
|
||||
@@ -29,3 +28,4 @@ export default function TickerBar({ items, className }: Props) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
type Props = {
|
||||
header?: ReactNode;
|
||||
@@ -10,57 +9,10 @@ type Props = {
|
||||
};
|
||||
|
||||
export default function AppShell({ header, top, main, sidebar, rightbar }: Props) {
|
||||
const headerRef = useRef<HTMLDivElement | null>(null);
|
||||
const topRef = useRef<HTMLDivElement | null>(null);
|
||||
const [headerHeight, setHeaderHeight] = useState(0);
|
||||
const [topHeight, setTopHeight] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const observers: ResizeObserver[] = [];
|
||||
|
||||
const observeHeight = (
|
||||
element: HTMLDivElement | null,
|
||||
setHeight: (height: number) => void
|
||||
) => {
|
||||
if (!element) {
|
||||
setHeight(0);
|
||||
return;
|
||||
}
|
||||
|
||||
const update = () => setHeight(Math.ceil(element.getBoundingClientRect().height));
|
||||
update();
|
||||
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(element);
|
||||
observers.push(observer);
|
||||
};
|
||||
|
||||
observeHeight(headerRef.current, setHeaderHeight);
|
||||
observeHeight(topRef.current, setTopHeight);
|
||||
|
||||
return () => {
|
||||
for (const observer of observers) observer.disconnect();
|
||||
};
|
||||
}, [header, top]);
|
||||
|
||||
const shellStyle = {
|
||||
['--shell-header-height' as any]: `${headerHeight}px`,
|
||||
['--shell-top-height' as any]: `${topHeight}px`,
|
||||
['--shell-top-offset' as any]: `${headerHeight + topHeight}px`,
|
||||
} as CSSProperties;
|
||||
|
||||
return (
|
||||
<div className="shell" style={shellStyle}>
|
||||
{header ? (
|
||||
<div className="shellHeader" ref={headerRef}>
|
||||
{header}
|
||||
</div>
|
||||
) : null}
|
||||
{top ? (
|
||||
<div className="shellTop" ref={topRef}>
|
||||
{top}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="shell">
|
||||
{header ? <div className="shellHeader">{header}</div> : null}
|
||||
{top ? <div className="shellTop">{top}</div> : null}
|
||||
<div className="shellBody">
|
||||
<div className="shellMain">{main}</div>
|
||||
{sidebar ? <div className="shellSidebar">{sidebar}</div> : null}
|
||||
|
||||
@@ -1,62 +1,13 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import Button from '../ui/Button';
|
||||
|
||||
type Props = {
|
||||
user: string;
|
||||
theme: 'day' | 'night';
|
||||
onResetView?: (() => void) | null;
|
||||
onToggleTheme: () => void;
|
||||
onLogout: () => void;
|
||||
};
|
||||
|
||||
export default function AuthStatus({ user, theme, onResetView, onToggleTheme, onLogout }: Props) {
|
||||
const formatter = useMemo(
|
||||
() =>
|
||||
new Intl.DateTimeFormat(undefined, {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
}),
|
||||
[]
|
||||
);
|
||||
const [nowLabel, setNowLabel] = useState(() => formatter.format(new Date()));
|
||||
|
||||
useEffect(() => {
|
||||
const tick = () => setNowLabel(formatter.format(new Date()));
|
||||
tick();
|
||||
const timer = window.setInterval(tick, 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [formatter]);
|
||||
|
||||
export default function AuthStatus({ user, onLogout }: Props) {
|
||||
return (
|
||||
<div className="authStatus">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
type="button"
|
||||
title="Reset View (Alt+R)"
|
||||
aria-keyshortcuts="Alt+R"
|
||||
onClick={onResetView ?? undefined}
|
||||
disabled={!onResetView}
|
||||
>
|
||||
Reset View
|
||||
</Button>
|
||||
<button
|
||||
className={`themeSwitch themeSwitch--${theme}`}
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={theme === 'night'}
|
||||
aria-label={theme === 'day' ? 'Switch to Night theme' : 'Switch to Day theme'}
|
||||
title={theme === 'day' ? 'Switch to Night theme' : 'Switch to Day theme'}
|
||||
onClick={onToggleTheme}
|
||||
>
|
||||
<span className="themeSwitch__label themeSwitch__label--day">Day</span>
|
||||
<span className="themeSwitch__label themeSwitch__label--night">Night</span>
|
||||
<span className="themeSwitch__thumb" aria-hidden="true" />
|
||||
</button>
|
||||
<div className="authStatus__clock" aria-label="Bieżący czas">
|
||||
{nowLabel}
|
||||
</div>
|
||||
<div className="authStatus__user" aria-label="Zalogowany użytkownik">
|
||||
<div className="authStatus__userLabel">Zalogowany</div>
|
||||
<div className="authStatus__userName">{user}</div>
|
||||
|
||||
@@ -11,21 +11,6 @@ type LoginResponse = {
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type WhoamiResponse = {
|
||||
ok?: boolean;
|
||||
user?: string | null;
|
||||
};
|
||||
|
||||
async function readSessionUser(): Promise<string | null> {
|
||||
const res = await fetch('/whoami', {
|
||||
cache: 'no-store',
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const json = (await res.json().catch(() => null)) as WhoamiResponse | null;
|
||||
const user = typeof json?.user === 'string' ? json.user.trim() : '';
|
||||
return user || null;
|
||||
}
|
||||
|
||||
export default function LoginScreen({ onLoggedIn }: Props) {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
@@ -41,18 +26,17 @@ export default function LoginScreen({ onLoggedIn }: Props) {
|
||||
const res = await fetch('/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
const json = (await res.json().catch(() => null)) as LoginResponse | null;
|
||||
const ok = Boolean(res.ok && json?.ok);
|
||||
if (!ok) throw new Error(json?.error || 'invalid_credentials');
|
||||
const u = await readSessionUser();
|
||||
const u = typeof json?.user === 'string' ? json.user.trim() : '';
|
||||
if (!u) throw new Error('bad_response');
|
||||
setPassword('');
|
||||
onLoggedIn(u);
|
||||
} catch {
|
||||
setError('Logowanie nie utworzyło sesji. Sprawdź dane albo konfigurację dev proxy.');
|
||||
setError('Nieprawidłowy login lub hasło.');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
@@ -103,3 +87,4 @@ export default function LoginScreen({ onLoggedIn }: Props) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -24,10 +24,7 @@ export default function TopNav({ active = 'trade', onSelect, rightSlot }: Props)
|
||||
<div className="topNav__left">
|
||||
<div className="topNav__brand" aria-label="Trade">
|
||||
<div className="topNav__brandMark" aria-hidden="true" />
|
||||
<div className="topNav__brandText">
|
||||
<div className="topNav__brandName">Trade</div>
|
||||
<div className="topNav__brandMeta">by mpabi</div>
|
||||
</div>
|
||||
<div className="topNav__brandName">Trade</div>
|
||||
</div>
|
||||
<nav className="topNav__menu" aria-label="Primary">
|
||||
{navItems.map((it) => (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import { getChartSeriesTable, getLatestDlobTable } from '../features/market/dlobSource';
|
||||
import { bollingerBands, ema, macd, rsi, sma } from './indicators';
|
||||
|
||||
export type Candle = {
|
||||
time: number; // unix seconds
|
||||
open: number;
|
||||
@@ -28,289 +25,21 @@ export type ChartIndicators = {
|
||||
macd?: { macd: SeriesPoint[]; signal: SeriesPoint[] };
|
||||
};
|
||||
|
||||
type GraphqlError = { message: string };
|
||||
type HasuraDerivedTsRow = {
|
||||
event_ts: string;
|
||||
oracle_price?: number | string | null;
|
||||
mark_price?: number | string | null;
|
||||
mid_price?: number | string | null;
|
||||
};
|
||||
type HasuraLatestDlobRow = {
|
||||
updated_at?: string | null;
|
||||
oracle_price?: number | string | null;
|
||||
mark_price?: number | string | null;
|
||||
mid_price?: number | string | null;
|
||||
export type ChartResponse = {
|
||||
ok: boolean;
|
||||
symbol?: string;
|
||||
source?: string | null;
|
||||
tf?: string;
|
||||
bucketSeconds?: number;
|
||||
candles?: Candle[];
|
||||
indicators?: ChartIndicators;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function readEnv(name: string): string | undefined {
|
||||
const viteValue = (import.meta as any).env?.[name];
|
||||
if (viteValue != null && String(viteValue).trim()) return String(viteValue);
|
||||
const nodeValue = (globalThis as any)?.process?.env?.[name];
|
||||
if (nodeValue != null && String(nodeValue).trim()) return String(nodeValue);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getHasuraUrl(): string {
|
||||
const v = readEnv('VITE_HASURA_URL');
|
||||
return v ? String(v) : '/graphql';
|
||||
}
|
||||
|
||||
function getHasuraAuthHeaders(): Record<string, string> | undefined {
|
||||
const token = readEnv('VITE_HASURA_AUTH_TOKEN');
|
||||
if (token) return { authorization: `Bearer ${String(token)}` };
|
||||
const secret = readEnv('VITE_HASURA_ADMIN_SECRET');
|
||||
if (secret) return { 'x-hasura-admin-secret': String(secret) };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parseTimeframeToSeconds(tf: string): number {
|
||||
const raw = String(tf || '').trim();
|
||||
const match = raw.match(/^(\d+)([smhdSMHD])$/);
|
||||
if (!match) return 60;
|
||||
const value = Number(match[1]);
|
||||
const unit = match[2].toLowerCase();
|
||||
if (!Number.isFinite(value) || value <= 0) return 60;
|
||||
if (unit === 's') return value;
|
||||
if (unit === 'm') return value * 60;
|
||||
if (unit === 'h') return value * 3600;
|
||||
if (unit === 'd') return value * 86400;
|
||||
return 60;
|
||||
}
|
||||
|
||||
function toSeries(times: number[], values: Array<number | null>) {
|
||||
return times.map((time, i) => ({ time, value: values[i] ?? null }));
|
||||
}
|
||||
|
||||
function buildIndicators(candles: Candle[]): ChartIndicators {
|
||||
const times = candles.map((c) => c.time);
|
||||
const closes = candles.map((c) => c.close);
|
||||
const oracleValues = candles.map((c) => (c.oracle == null ? null : c.oracle));
|
||||
const sma20 = sma(closes, 20);
|
||||
const ema20 = ema(closes, 20);
|
||||
const bb20 = bollingerBands(closes, 20, 2);
|
||||
const rsi14 = rsi(closes, 14);
|
||||
const macdOut = macd(closes, 12, 26, 9);
|
||||
|
||||
return {
|
||||
oracle: toSeries(times, oracleValues),
|
||||
sma20: toSeries(times, sma20),
|
||||
ema20: toSeries(times, ema20),
|
||||
bb20: {
|
||||
upper: toSeries(times, bb20.upper),
|
||||
lower: toSeries(times, bb20.lower),
|
||||
mid: toSeries(times, bb20.mid),
|
||||
},
|
||||
rsi14: toSeries(times, rsi14),
|
||||
macd: {
|
||||
macd: toSeries(times, macdOut.macd),
|
||||
signal: toSeries(times, macdOut.signal),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function toNum(v: unknown): number | null {
|
||||
if (v == null) return null;
|
||||
if (typeof v === 'number') return Number.isFinite(v) ? v : null;
|
||||
if (typeof v === 'string') {
|
||||
const s = v.trim();
|
||||
if (!s) return null;
|
||||
const n = Number(s);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function aggregateRowsToCandles(
|
||||
rows: HasuraDerivedTsRow[],
|
||||
bucketSeconds: number,
|
||||
options?: { fillGaps?: boolean; limit?: number }
|
||||
): Candle[] {
|
||||
const buckets = new Map<number, Candle>();
|
||||
const sortedRows = rows.slice().sort((a, b) => Date.parse(a.event_ts) - Date.parse(b.event_ts));
|
||||
|
||||
for (const row of sortedRows) {
|
||||
const tsSec = Math.floor(Date.parse(row.event_ts) / 1000);
|
||||
if (!Number.isFinite(tsSec)) continue;
|
||||
const bucket = tsSec - (tsSec % bucketSeconds);
|
||||
const oracle = toNum(row.oracle_price);
|
||||
const close = toNum(row.mark_price) ?? toNum(row.mid_price) ?? oracle;
|
||||
if (close == null) continue;
|
||||
|
||||
const existing = buckets.get(bucket);
|
||||
if (!existing) {
|
||||
buckets.set(bucket, {
|
||||
time: bucket,
|
||||
open: close,
|
||||
high: close,
|
||||
low: close,
|
||||
close,
|
||||
volume: 1,
|
||||
oracle,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
existing.high = Math.max(existing.high, close);
|
||||
existing.low = Math.min(existing.low, close);
|
||||
existing.close = close;
|
||||
existing.volume = (existing.volume || 0) + 1;
|
||||
existing.oracle = oracle ?? existing.oracle ?? null;
|
||||
}
|
||||
|
||||
const sorted = Array.from(buckets.values()).sort((a, b) => a.time - b.time);
|
||||
if (!sorted.length) return [];
|
||||
|
||||
if (!options?.fillGaps) {
|
||||
return options?.limit ? sorted.slice(-options.limit) : sorted;
|
||||
}
|
||||
|
||||
const tail = options?.limit ? sorted.slice(-options.limit) : sorted;
|
||||
const candles: Candle[] = [];
|
||||
const firstBucket = tail[0]!.time;
|
||||
const lastBucket = tail[tail.length - 1]!.time;
|
||||
const byTime = new Map(tail.map((c) => [c.time, c]));
|
||||
let prev = tail[0]!;
|
||||
|
||||
for (let bucket = firstBucket; bucket <= lastBucket; bucket += bucketSeconds) {
|
||||
const current = byTime.get(bucket);
|
||||
if (current) {
|
||||
candles.push(current);
|
||||
prev = current;
|
||||
continue;
|
||||
}
|
||||
candles.push({
|
||||
time: bucket,
|
||||
open: prev.close,
|
||||
high: prev.close,
|
||||
low: prev.close,
|
||||
close: prev.close,
|
||||
volume: 0,
|
||||
oracle: prev.oracle ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return candles;
|
||||
}
|
||||
|
||||
export function mergeCandles(prev: Candle[], next: Candle[]): Candle[] {
|
||||
const map = new Map<number, Candle>();
|
||||
for (const candle of prev) map.set(candle.time, candle);
|
||||
for (const candle of next) map.set(candle.time, candle);
|
||||
return Array.from(map.values()).sort((a, b) => a.time - b.time);
|
||||
}
|
||||
|
||||
export function applyLatestRowToCandles(
|
||||
candles: Candle[],
|
||||
row: HasuraLatestDlobRow,
|
||||
bucketSeconds: number
|
||||
): Candle[] {
|
||||
const tsSec = Math.floor(Date.parse(String(row.updated_at || '')) / 1000);
|
||||
if (!Number.isFinite(tsSec)) return candles;
|
||||
const bucket = tsSec - (tsSec % bucketSeconds);
|
||||
const oracle = toNum(row.oracle_price);
|
||||
const close = toNum(row.mark_price) ?? toNum(row.mid_price) ?? oracle;
|
||||
if (close == null) return candles;
|
||||
|
||||
const next = candles.slice();
|
||||
const last = next[next.length - 1];
|
||||
if (!last || bucket > last.time) {
|
||||
next.push({
|
||||
time: bucket,
|
||||
open: last?.close ?? close,
|
||||
high: close,
|
||||
low: close,
|
||||
close,
|
||||
volume: 1,
|
||||
oracle,
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
if (bucket < last.time) return candles;
|
||||
|
||||
last.high = Math.max(last.high, close);
|
||||
last.low = Math.min(last.low, close);
|
||||
last.close = close;
|
||||
last.volume = (last.volume || 0) + 1;
|
||||
last.oracle = oracle ?? last.oracle ?? null;
|
||||
return next;
|
||||
}
|
||||
|
||||
export function buildChartIndicators(candles: Candle[]): ChartIndicators {
|
||||
return buildIndicators(candles);
|
||||
}
|
||||
|
||||
export function getChartLiveTable(marketName: string) {
|
||||
return getLatestDlobTable(marketName);
|
||||
}
|
||||
|
||||
async function fetchChartFromHasura(params: {
|
||||
symbol: string;
|
||||
source?: string;
|
||||
tf: string;
|
||||
limit: number;
|
||||
beforeTime?: number;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<{ candles: Candle[]; indicators: ChartIndicators; meta: { tf: string; bucketSeconds: number } }> {
|
||||
const bucketSeconds = parseTimeframeToSeconds(params.tf);
|
||||
const table = getChartSeriesTable(params.symbol);
|
||||
const maxPoints = Math.min(200_000, Math.max(5_000, params.limit * Math.max(1, bucketSeconds) * 3));
|
||||
const sourceFilter = params.source?.trim();
|
||||
const beforeTime = Number.isFinite(params.beforeTime) ? Number(params.beforeTime) : null;
|
||||
const beforeIso = beforeTime == null ? null : new Date(beforeTime * 1000).toISOString();
|
||||
const query = `
|
||||
query ChartSeries($symbol: String!, $limit: Int!${sourceFilter ? ', $source: String!' : ''}${beforeIso ? ', $before: timestamptz!' : ''}) {
|
||||
${table}(
|
||||
limit: $limit
|
||||
order_by: {event_ts: desc}
|
||||
where: {
|
||||
market_name: {_eq: $symbol}
|
||||
is_indicative: {_eq: false}
|
||||
${sourceFilter ? 'source: {_eq: $source}' : ''}
|
||||
${beforeIso ? 'event_ts: {_lt: $before}' : ''}
|
||||
}
|
||||
) {
|
||||
event_ts
|
||||
oracle_price
|
||||
mark_price
|
||||
mid_price
|
||||
}
|
||||
}
|
||||
`;
|
||||
const res = await fetch(getHasuraUrl(), {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
signal: params.signal,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...(getHasuraAuthHeaders() || {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
variables: {
|
||||
symbol: params.symbol,
|
||||
limit: maxPoints,
|
||||
...(sourceFilter ? { source: sourceFilter } : {}),
|
||||
...(beforeIso ? { before: beforeIso } : {}),
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`Hasura HTTP ${res.status}: ${text}`);
|
||||
|
||||
const json = JSON.parse(text) as { data?: Record<string, HasuraDerivedTsRow[]>; errors?: GraphqlError[] };
|
||||
if (Array.isArray(json.errors) && json.errors.length) {
|
||||
throw new Error(json.errors.map((e) => e.message).join(' | '));
|
||||
}
|
||||
const rows = json.data?.[table] || [];
|
||||
const candles = aggregateRowsToCandles(rows, bucketSeconds, { fillGaps: beforeIso == null, limit: params.limit });
|
||||
|
||||
return {
|
||||
candles,
|
||||
indicators: buildIndicators(candles),
|
||||
meta: { tf: params.tf, bucketSeconds },
|
||||
};
|
||||
function getApiBaseUrl(): string {
|
||||
const v = (import.meta as any).env?.VITE_API_URL;
|
||||
if (v) return String(v);
|
||||
return '/api';
|
||||
}
|
||||
|
||||
export async function fetchChart(params: {
|
||||
@@ -318,8 +47,50 @@ export async function fetchChart(params: {
|
||||
source?: string;
|
||||
tf: string;
|
||||
limit: number;
|
||||
beforeTime?: number;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<{ candles: Candle[]; indicators: ChartIndicators; meta: { tf: string; bucketSeconds: number } }> {
|
||||
return await fetchChartFromHasura(params);
|
||||
const base = getApiBaseUrl();
|
||||
const u = new URL(base, window.location.origin);
|
||||
u.pathname = u.pathname && u.pathname !== '/' ? u.pathname.replace(/\/$/, '') + '/v1/chart' : '/v1/chart';
|
||||
u.searchParams.set('symbol', params.symbol);
|
||||
u.searchParams.set('tf', params.tf);
|
||||
u.searchParams.set('limit', String(params.limit));
|
||||
if (params.source && params.source.trim()) u.searchParams.set('source', params.source.trim());
|
||||
|
||||
const res = await fetch(u.toString());
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`API HTTP ${res.status}: ${text}`);
|
||||
const json = JSON.parse(text) as ChartResponse;
|
||||
if (!json.ok) throw new Error(json.error || 'API: error');
|
||||
return {
|
||||
candles: (json.candles || []).map((c) => ({
|
||||
...c,
|
||||
time: Number(c.time),
|
||||
open: Number(c.open),
|
||||
high: Number(c.high),
|
||||
low: Number(c.low),
|
||||
close: Number(c.close),
|
||||
volume: c.volume == null ? undefined : Number(c.volume),
|
||||
oracle: c.oracle == null ? null : Number(c.oracle),
|
||||
flow:
|
||||
(c as any)?.flow && typeof (c as any).flow === 'object'
|
||||
? {
|
||||
up: Number((c as any).flow.up),
|
||||
down: Number((c as any).flow.down),
|
||||
flat: Number((c as any).flow.flat),
|
||||
}
|
||||
: undefined,
|
||||
flowRows: Array.isArray((c as any)?.flowRows)
|
||||
? (c as any).flowRows.map((x: any) => Number(x))
|
||||
: Array.isArray((c as any)?.flow_rows)
|
||||
? (c as any).flow_rows.map((x: any) => Number(x))
|
||||
: undefined,
|
||||
flowMoves: Array.isArray((c as any)?.flowMoves)
|
||||
? (c as any).flowMoves.map((x: any) => Number(x))
|
||||
: Array.isArray((c as any)?.flow_moves)
|
||||
? (c as any).flow_moves.map((x: any) => Number(x))
|
||||
: undefined,
|
||||
})),
|
||||
indicators: json.indicators || {},
|
||||
meta: { tf: String(json.tf || params.tf), bucketSeconds: Number(json.bucketSeconds || 0) },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
type HeadersMap = Record<string, string>;
|
||||
type GraphqlError = { message: string };
|
||||
|
||||
type SubscribeParams<T> = {
|
||||
query: string;
|
||||
@@ -7,29 +6,12 @@ type SubscribeParams<T> = {
|
||||
onData: (data: T) => void;
|
||||
onError?: (err: string) => void;
|
||||
onStatus?: (s: { connected: boolean }) => void;
|
||||
pollMs?: number;
|
||||
};
|
||||
|
||||
function envString(name: string): string | undefined {
|
||||
const viteValue = (import.meta as any).env?.[name];
|
||||
const viteString = viteValue == null ? '' : String(viteValue).trim();
|
||||
if (viteString) return viteString;
|
||||
const nodeValue = (globalThis as any)?.process?.env?.[name];
|
||||
const nodeString = nodeValue == null ? '' : String(nodeValue).trim();
|
||||
return nodeString || undefined;
|
||||
}
|
||||
|
||||
function envBool(name: string): boolean {
|
||||
const v = envString(name);
|
||||
if (!v) return false;
|
||||
return ['1', 'true', 'yes', 'on'].includes(v.toLowerCase());
|
||||
}
|
||||
|
||||
function envInt(name: string, fallback: number): number {
|
||||
const raw = envString(name);
|
||||
if (!raw) return fallback;
|
||||
const parsed = Number.parseInt(raw, 10);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
||||
const v = (import.meta as any).env?.[name];
|
||||
const s = v == null ? '' : String(v).trim();
|
||||
return s ? s : undefined;
|
||||
}
|
||||
|
||||
function resolveGraphqlHttpUrl(): string {
|
||||
@@ -78,59 +60,13 @@ export type SubscriptionHandle = {
|
||||
unsubscribe: () => void;
|
||||
};
|
||||
|
||||
async function fetchGraphqlOnce<T>(
|
||||
httpUrl: string,
|
||||
headers: HeadersMap | undefined,
|
||||
query: string,
|
||||
variables: Record<string, unknown> | undefined
|
||||
): Promise<T> {
|
||||
const operation = query.replace(/^\s*subscription\b/, 'query');
|
||||
const res = await fetch(httpUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...(headers || {}),
|
||||
},
|
||||
body: JSON.stringify({ query: operation, variables: variables ?? {} }),
|
||||
});
|
||||
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`Hasura HTTP ${res.status}: ${text}`);
|
||||
|
||||
let json: { data?: T; errors?: GraphqlError[] };
|
||||
try {
|
||||
json = JSON.parse(text);
|
||||
} catch {
|
||||
throw new Error(`Hasura invalid JSON: ${text}`);
|
||||
}
|
||||
|
||||
if (Array.isArray(json.errors) && json.errors.length) {
|
||||
throw new Error(json.errors.map((e) => e.message).join(' | '));
|
||||
}
|
||||
if (json.data == null) throw new Error('Hasura: empty response');
|
||||
return json.data;
|
||||
}
|
||||
|
||||
export function subscribeGraphqlWs<T>({
|
||||
query,
|
||||
variables,
|
||||
onData,
|
||||
onError,
|
||||
onStatus,
|
||||
pollMs: pollMsOverride,
|
||||
}: SubscribeParams<T>): SubscriptionHandle {
|
||||
const httpUrl = resolveGraphqlHttpUrl();
|
||||
export function subscribeGraphqlWs<T>({ query, variables, onData, onError, onStatus }: SubscribeParams<T>): SubscriptionHandle {
|
||||
const wsUrl = resolveGraphqlWsUrl();
|
||||
const headers = resolveAuthHeaders();
|
||||
const pollOnly = envBool('VITE_GRAPHQL_POLL_ONLY');
|
||||
const pollMs = Math.max(50, pollMsOverride ?? envInt('VITE_GRAPHQL_POLL_MS', 1000));
|
||||
let ws: WebSocket | null = null;
|
||||
let closed = false;
|
||||
let started = false;
|
||||
let polling = false;
|
||||
let reconnectTimer: number | null = null;
|
||||
let pollTimer: number | null = null;
|
||||
|
||||
const subId = '1';
|
||||
|
||||
@@ -141,30 +77,6 @@ export function subscribeGraphqlWs<T>({
|
||||
|
||||
const setConnected = (connected: boolean) => onStatus?.({ connected });
|
||||
|
||||
const clearReconnectTimer = () => {
|
||||
if (reconnectTimer != null) {
|
||||
window.clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const clearPollTimer = () => {
|
||||
if (pollTimer != null) {
|
||||
window.clearTimeout(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const closeSocket = () => {
|
||||
if (!ws) return;
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
ws = null;
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
if (!ws || started) return;
|
||||
started = true;
|
||||
@@ -177,40 +89,14 @@ export function subscribeGraphqlWs<T>({
|
||||
);
|
||||
};
|
||||
|
||||
const pollOnce = async () => {
|
||||
try {
|
||||
const data = await fetchGraphqlOnce<T>(httpUrl, headers, query, variables);
|
||||
if (closed) return;
|
||||
setConnected(true);
|
||||
onData(data);
|
||||
} catch (e) {
|
||||
if (closed) return;
|
||||
setConnected(false);
|
||||
emitError(e);
|
||||
} finally {
|
||||
if (!closed && polling) {
|
||||
pollTimer = window.setTimeout(() => void pollOnce(), pollMs);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const startPolling = () => {
|
||||
if (closed || polling) return;
|
||||
polling = true;
|
||||
clearReconnectTimer();
|
||||
closeSocket();
|
||||
started = false;
|
||||
void pollOnce();
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
if (closed) return;
|
||||
if (polling) return;
|
||||
started = false;
|
||||
try {
|
||||
ws = new WebSocket(wsUrl, 'graphql-ws');
|
||||
} catch (e) {
|
||||
startPolling();
|
||||
emitError(e);
|
||||
reconnectTimer = window.setTimeout(connect, 1000);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -235,14 +121,14 @@ export function subscribeGraphqlWs<T>({
|
||||
}
|
||||
|
||||
if (msg.type === 'connection_error') {
|
||||
startPolling();
|
||||
emitError(msg.payload || 'connection_error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'ka' || msg.type === 'complete') return;
|
||||
|
||||
if (msg.type === 'error') {
|
||||
startPolling();
|
||||
emitError(msg.payload || 'subscription_error');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -258,29 +144,25 @@ export function subscribeGraphqlWs<T>({
|
||||
|
||||
ws.onerror = () => {
|
||||
setConnected(false);
|
||||
startPolling();
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
setConnected(false);
|
||||
if (closed) return;
|
||||
startPolling();
|
||||
reconnectTimer = window.setTimeout(connect, 1000);
|
||||
};
|
||||
};
|
||||
|
||||
if (pollOnly) {
|
||||
startPolling();
|
||||
} else {
|
||||
connect();
|
||||
}
|
||||
connect();
|
||||
|
||||
return {
|
||||
unsubscribe: () => {
|
||||
closed = true;
|
||||
polling = false;
|
||||
setConnected(false);
|
||||
clearReconnectTimer();
|
||||
clearPollTimer();
|
||||
if (reconnectTimer != null) {
|
||||
window.clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
if (!ws) return;
|
||||
try {
|
||||
ws.send(JSON.stringify({ id: subId, type: 'stop' }));
|
||||
@@ -288,7 +170,12 @@ export function subscribeGraphqlWs<T>({
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
closeSocket();
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
ws = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -45,7 +45,6 @@ export async function hasuraRequest<T>(query: string, variables: Record<string,
|
||||
|
||||
const res = await fetch(getHasuraUrl(), {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers,
|
||||
body: JSON.stringify({ query, variables }),
|
||||
});
|
||||
@@ -68,9 +67,7 @@ export async function fetchLatestTicks(symbol: string, limit: number, source?: s
|
||||
u.searchParams.set('limit', String(limit));
|
||||
if (source && source.trim()) u.searchParams.set('source', source.trim());
|
||||
|
||||
const res = await fetch(u.toString(), {
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const res = await fetch(u.toString());
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`API HTTP ${res.status}: ${text}`);
|
||||
const json = JSON.parse(text) as { ok?: boolean; ticks?: any[]; error?: string };
|
||||
|
||||
@@ -1,366 +0,0 @@
|
||||
export type DiagramRuntimePublisher = {
|
||||
id: string;
|
||||
title: string;
|
||||
status: 'ok' | 'warn';
|
||||
health: {
|
||||
httpOk: boolean;
|
||||
gauge: number | null;
|
||||
};
|
||||
metrics: {
|
||||
transport: string;
|
||||
updateIntervalMs: number;
|
||||
perpMarkets: number;
|
||||
spotMarkets: number;
|
||||
totalMarkets: number;
|
||||
latestSlot: number | null;
|
||||
};
|
||||
endpoints: {
|
||||
health: string;
|
||||
metrics: string;
|
||||
};
|
||||
errors: string[];
|
||||
};
|
||||
|
||||
export type DiagramRuntimeResponse = {
|
||||
ok: boolean;
|
||||
version?: string;
|
||||
fetchedAt?: string;
|
||||
nodes?: {
|
||||
publisher?: DiagramRuntimePublisher;
|
||||
};
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type DiagramLayoutView = 'standard' | 'ultra';
|
||||
|
||||
export type DiagramLayoutState = Record<
|
||||
string,
|
||||
{
|
||||
position?: { x: number; y: number };
|
||||
size?: { width: number; height: number };
|
||||
parentId?: string | null;
|
||||
}
|
||||
>;
|
||||
|
||||
export type DiagramLayoutResponse = {
|
||||
ok: boolean;
|
||||
view: DiagramLayoutView;
|
||||
updatedAt?: string;
|
||||
layout?: DiagramLayoutState;
|
||||
currentRevisionId?: number | null;
|
||||
revisionId?: number | null;
|
||||
restoredFromRevisionId?: number | null;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type DiagramLayoutRevision = {
|
||||
id: number;
|
||||
view: DiagramLayoutView;
|
||||
updatedAt: string;
|
||||
action: string;
|
||||
entryCount: number;
|
||||
};
|
||||
|
||||
export type DiagramLayoutHistoryResponse = {
|
||||
ok: boolean;
|
||||
view: DiagramLayoutView;
|
||||
currentRevisionId?: number | null;
|
||||
revisions?: DiagramLayoutRevision[];
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type DiagramLayoutStoredRevision = DiagramLayoutRevision & {
|
||||
layout: DiagramLayoutState;
|
||||
};
|
||||
|
||||
type DiagramLayoutStoredView = {
|
||||
layout: DiagramLayoutState;
|
||||
updatedAt?: string;
|
||||
currentRevisionId: number | null;
|
||||
nextRevisionId: number;
|
||||
revisions: DiagramLayoutStoredRevision[];
|
||||
};
|
||||
|
||||
type DiagramLayoutStore = {
|
||||
views: Partial<Record<DiagramLayoutView, DiagramLayoutStoredView>>;
|
||||
};
|
||||
|
||||
type DiagramDebugEvent = {
|
||||
ts: string;
|
||||
view: DiagramLayoutView;
|
||||
event: string;
|
||||
nodeId?: string | null;
|
||||
viewport?: { x?: number; y?: number; zoom?: number };
|
||||
payload?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
const layoutStoreKey = 'trade-system-flow-layout-store:v1';
|
||||
const debugStoreKey = 'trade-system-flow-debug-log:v1';
|
||||
const maxRevisionCount = 32;
|
||||
const maxDebugEventCount = 200;
|
||||
|
||||
function canUseStorage() {
|
||||
return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
|
||||
}
|
||||
|
||||
function getIsoNow() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function cloneLayoutState(layout: DiagramLayoutState | undefined): DiagramLayoutState {
|
||||
return JSON.parse(JSON.stringify(layout || {})) as DiagramLayoutState;
|
||||
}
|
||||
|
||||
function emptyStoredView(): DiagramLayoutStoredView {
|
||||
return {
|
||||
layout: {},
|
||||
updatedAt: undefined,
|
||||
currentRevisionId: null,
|
||||
nextRevisionId: 1,
|
||||
revisions: [],
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeStoredView(value: unknown): DiagramLayoutStoredView {
|
||||
const raw = value && typeof value === 'object' ? (value as Partial<DiagramLayoutStoredView>) : {};
|
||||
const revisions = Array.isArray(raw.revisions)
|
||||
? raw.revisions
|
||||
.filter((entry): entry is DiagramLayoutStoredRevision => {
|
||||
return Boolean(
|
||||
entry &&
|
||||
typeof entry === 'object' &&
|
||||
Number.isInteger((entry as DiagramLayoutStoredRevision).id) &&
|
||||
typeof (entry as DiagramLayoutStoredRevision).updatedAt === 'string'
|
||||
);
|
||||
})
|
||||
.map((entry) => ({
|
||||
id: entry.id,
|
||||
view: entry.view,
|
||||
updatedAt: entry.updatedAt,
|
||||
action: entry.action,
|
||||
entryCount: Number.isFinite(entry.entryCount) ? Math.max(0, Math.trunc(entry.entryCount)) : 0,
|
||||
layout: cloneLayoutState(entry.layout),
|
||||
}))
|
||||
: [];
|
||||
|
||||
const nextRevisionId = Number.isInteger(raw.nextRevisionId)
|
||||
? Math.max(1, Number(raw.nextRevisionId))
|
||||
: revisions.reduce((maxId, entry) => Math.max(maxId, entry.id), 0) + 1;
|
||||
|
||||
return {
|
||||
layout: cloneLayoutState(raw.layout),
|
||||
updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : undefined,
|
||||
currentRevisionId: Number.isInteger(raw.currentRevisionId) ? Number(raw.currentRevisionId) : null,
|
||||
nextRevisionId,
|
||||
revisions,
|
||||
};
|
||||
}
|
||||
|
||||
function readLayoutStore(): DiagramLayoutStore {
|
||||
if (!canUseStorage()) return { views: {} };
|
||||
try {
|
||||
const raw = window.localStorage.getItem(layoutStoreKey);
|
||||
if (!raw) return { views: {} };
|
||||
const parsed = JSON.parse(raw) as Partial<DiagramLayoutStore>;
|
||||
const views = parsed?.views && typeof parsed.views === 'object' ? parsed.views : {};
|
||||
return {
|
||||
views: {
|
||||
standard: sanitizeStoredView(views.standard),
|
||||
ultra: sanitizeStoredView(views.ultra),
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return { views: {} };
|
||||
}
|
||||
}
|
||||
|
||||
function writeLayoutStore(store: DiagramLayoutStore) {
|
||||
if (!canUseStorage()) return;
|
||||
window.localStorage.setItem(layoutStoreKey, JSON.stringify(store));
|
||||
}
|
||||
|
||||
function readStoredView(view: DiagramLayoutView): DiagramLayoutStoredView {
|
||||
const store = readLayoutStore();
|
||||
return sanitizeStoredView(store.views[view]);
|
||||
}
|
||||
|
||||
function writeStoredView(view: DiagramLayoutView, next: DiagramLayoutStoredView) {
|
||||
const store = readLayoutStore();
|
||||
store.views = {
|
||||
...store.views,
|
||||
[view]: sanitizeStoredView(next),
|
||||
};
|
||||
writeLayoutStore(store);
|
||||
}
|
||||
|
||||
function appendRevision(
|
||||
view: DiagramLayoutView,
|
||||
storedView: DiagramLayoutStoredView,
|
||||
layout: DiagramLayoutState,
|
||||
action: string,
|
||||
updatedAt: string
|
||||
) {
|
||||
const revisionId = Math.max(1, storedView.nextRevisionId || 1);
|
||||
const layoutCopy = cloneLayoutState(layout);
|
||||
const revision: DiagramLayoutStoredRevision = {
|
||||
id: revisionId,
|
||||
view,
|
||||
updatedAt,
|
||||
action: action || 'manual-save',
|
||||
entryCount: Object.keys(layoutCopy).length,
|
||||
layout: layoutCopy,
|
||||
};
|
||||
|
||||
const revisions = [revision, ...storedView.revisions].slice(0, maxRevisionCount);
|
||||
return {
|
||||
revisionId,
|
||||
next: {
|
||||
layout: layoutCopy,
|
||||
updatedAt,
|
||||
currentRevisionId: revisionId,
|
||||
nextRevisionId: revisionId + 1,
|
||||
revisions,
|
||||
} satisfies DiagramLayoutStoredView,
|
||||
};
|
||||
}
|
||||
|
||||
function toHistoryRevisions(revisions: DiagramLayoutStoredRevision[], limit: number) {
|
||||
return revisions.slice(0, Math.max(1, limit)).map((entry) => ({
|
||||
id: entry.id,
|
||||
view: entry.view,
|
||||
updatedAt: entry.updatedAt,
|
||||
action: entry.action,
|
||||
entryCount: entry.entryCount,
|
||||
}));
|
||||
}
|
||||
|
||||
function readDebugEvents(): DiagramDebugEvent[] {
|
||||
if (!canUseStorage()) return [];
|
||||
try {
|
||||
const raw = window.localStorage.getItem(debugStoreKey);
|
||||
if (!raw) return [];
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? (parsed as DiagramDebugEvent[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeDebugEvents(events: DiagramDebugEvent[]) {
|
||||
if (!canUseStorage()) return;
|
||||
window.localStorage.setItem(debugStoreKey, JSON.stringify(events.slice(-maxDebugEventCount)));
|
||||
}
|
||||
|
||||
export async function fetchDiagramRuntime(): Promise<DiagramRuntimeResponse> {
|
||||
return {
|
||||
ok: true,
|
||||
version: 'frontend-local',
|
||||
fetchedAt: getIsoNow(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchDiagramLayout(view: DiagramLayoutView): Promise<DiagramLayoutResponse> {
|
||||
const storedView = readStoredView(view);
|
||||
return {
|
||||
ok: true,
|
||||
view,
|
||||
updatedAt: storedView.updatedAt,
|
||||
layout: cloneLayoutState(storedView.layout),
|
||||
currentRevisionId: storedView.currentRevisionId,
|
||||
};
|
||||
}
|
||||
|
||||
export async function saveDiagramLayout(
|
||||
view: DiagramLayoutView,
|
||||
layout: DiagramLayoutState,
|
||||
action?: string
|
||||
): Promise<DiagramLayoutResponse> {
|
||||
const storedView = readStoredView(view);
|
||||
const updatedAt = getIsoNow();
|
||||
const { revisionId, next } = appendRevision(view, storedView, layout, action || 'manual-save', updatedAt);
|
||||
writeStoredView(view, next);
|
||||
return {
|
||||
ok: true,
|
||||
view,
|
||||
updatedAt,
|
||||
layout: cloneLayoutState(next.layout),
|
||||
currentRevisionId: revisionId,
|
||||
revisionId,
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteDiagramLayout(view: DiagramLayoutView): Promise<DiagramLayoutResponse> {
|
||||
const storedView = readStoredView(view);
|
||||
const updatedAt = getIsoNow();
|
||||
const { revisionId, next } = appendRevision(view, storedView, {}, 'reset', updatedAt);
|
||||
writeStoredView(view, next);
|
||||
return {
|
||||
ok: true,
|
||||
view,
|
||||
updatedAt,
|
||||
layout: {},
|
||||
currentRevisionId: revisionId,
|
||||
revisionId,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchDiagramLayoutHistory(
|
||||
view: DiagramLayoutView,
|
||||
limit = 12
|
||||
): Promise<DiagramLayoutHistoryResponse> {
|
||||
const storedView = readStoredView(view);
|
||||
return {
|
||||
ok: true,
|
||||
view,
|
||||
currentRevisionId: storedView.currentRevisionId,
|
||||
revisions: toHistoryRevisions(storedView.revisions, limit),
|
||||
};
|
||||
}
|
||||
|
||||
export async function restoreDiagramLayoutRevision(
|
||||
view: DiagramLayoutView,
|
||||
revisionId: number
|
||||
): Promise<DiagramLayoutResponse> {
|
||||
const storedView = readStoredView(view);
|
||||
const revision = storedView.revisions.find((entry) => entry.id === revisionId);
|
||||
if (!revision) throw new Error(`Local layout revision ${revisionId} not found`);
|
||||
|
||||
const updatedAt = getIsoNow();
|
||||
const { revisionId: nextRevisionId, next } = appendRevision(
|
||||
view,
|
||||
storedView,
|
||||
revision.layout,
|
||||
'restore',
|
||||
updatedAt
|
||||
);
|
||||
writeStoredView(view, next);
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
view,
|
||||
updatedAt,
|
||||
layout: cloneLayoutState(revision.layout),
|
||||
currentRevisionId: nextRevisionId,
|
||||
revisionId: nextRevisionId,
|
||||
restoredFromRevisionId: revision.id,
|
||||
};
|
||||
}
|
||||
|
||||
export async function postDiagramDebugEvent(body: {
|
||||
view: DiagramLayoutView;
|
||||
event: string;
|
||||
nodeId?: string | null;
|
||||
viewport?: { x?: number; y?: number; zoom?: number };
|
||||
payload?: Record<string, unknown>;
|
||||
}): Promise<void> {
|
||||
const events = readDebugEvents();
|
||||
events.push({
|
||||
ts: getIsoNow(),
|
||||
view: body.view,
|
||||
event: body.event,
|
||||
nodeId: body.nodeId,
|
||||
viewport: body.viewport,
|
||||
payload: body.payload,
|
||||
});
|
||||
writeDebugEvents(events);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
const DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -14,8 +14,8 @@ function stripTrailingSlashes(p: string): string {
|
||||
return out || '/';
|
||||
}
|
||||
|
||||
function readApiReadToken(env: Record<string, string | undefined>): string | undefined {
|
||||
if (env.API_READ_TOKEN) return env.API_READ_TOKEN;
|
||||
function readApiReadToken(): string | undefined {
|
||||
if (process.env.API_READ_TOKEN) return process.env.API_READ_TOKEN;
|
||||
const p = path.join(ROOT, 'tokens', 'read.json');
|
||||
if (!fs.existsSync(p)) return undefined;
|
||||
try {
|
||||
@@ -27,22 +27,6 @@ function readApiReadToken(env: Record<string, string | undefined>): string | und
|
||||
}
|
||||
}
|
||||
|
||||
function readApiAdminSecret(env: Record<string, string | undefined>): string | undefined {
|
||||
if (Object.prototype.hasOwnProperty.call(env, 'API_PROXY_ADMIN_SECRET')) {
|
||||
const raw = String(env.API_PROXY_ADMIN_SECRET || '').trim();
|
||||
return raw || undefined;
|
||||
}
|
||||
const p = path.join(ROOT, 'tokens', 'api.json');
|
||||
if (!fs.existsSync(p)) return undefined;
|
||||
try {
|
||||
const raw = fs.readFileSync(p, 'utf8');
|
||||
const json = JSON.parse(raw) as { adminSecret?: string };
|
||||
return json?.adminSecret ? String(json.adminSecret) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function parseBasicAuth(value: string | undefined): BasicAuth | undefined {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) return undefined;
|
||||
@@ -54,11 +38,11 @@ function parseBasicAuth(value: string | undefined): BasicAuth | undefined {
|
||||
return { username, password };
|
||||
}
|
||||
|
||||
function readProxyBasicAuth(env: Record<string, string | undefined>): BasicAuth | undefined {
|
||||
const fromEnv = parseBasicAuth(env.API_PROXY_BASIC_AUTH);
|
||||
function readProxyBasicAuth(): BasicAuth | undefined {
|
||||
const fromEnv = parseBasicAuth(process.env.API_PROXY_BASIC_AUTH);
|
||||
if (fromEnv) return fromEnv;
|
||||
|
||||
const fileRaw = String(env.API_PROXY_BASIC_AUTH_FILE || '').trim();
|
||||
const fileRaw = String(process.env.API_PROXY_BASIC_AUTH_FILE || '').trim();
|
||||
if (!fileRaw) return undefined;
|
||||
|
||||
const p = path.isAbsolute(fileRaw) ? fileRaw : path.join(ROOT, fileRaw);
|
||||
@@ -75,6 +59,10 @@ function readProxyBasicAuth(env: Record<string, string | undefined>): BasicAuth
|
||||
}
|
||||
}
|
||||
|
||||
const apiReadToken = readApiReadToken();
|
||||
const proxyBasicAuth = readProxyBasicAuth();
|
||||
const apiProxyTarget = process.env.API_PROXY_TARGET || 'http://localhost:8787';
|
||||
|
||||
function parseUrl(v: string): URL | undefined {
|
||||
try {
|
||||
return new URL(v);
|
||||
@@ -83,6 +71,10 @@ function parseUrl(v: string): URL | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
const apiProxyTargetUrl = parseUrl(apiProxyTarget);
|
||||
const apiProxyTargetPath = stripTrailingSlashes(apiProxyTargetUrl?.pathname || '/');
|
||||
const apiProxyTargetEndsWithApi = apiProxyTargetPath.endsWith('/api');
|
||||
|
||||
function inferUiProxyTarget(apiTarget: string): string | undefined {
|
||||
try {
|
||||
const u = new URL(apiTarget);
|
||||
@@ -99,6 +91,15 @@ function inferUiProxyTarget(apiTarget: string): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
const uiProxyTarget =
|
||||
process.env.FRONTEND_PROXY_TARGET ||
|
||||
process.env.UI_PROXY_TARGET ||
|
||||
process.env.AUTH_PROXY_TARGET ||
|
||||
inferUiProxyTarget(apiProxyTarget) ||
|
||||
(apiProxyTargetUrl && apiProxyTargetPath === '/' ? stripTrailingSlashes(apiProxyTargetUrl.toString()) : undefined);
|
||||
|
||||
const graphqlProxyTarget = process.env.GRAPHQL_PROXY_TARGET || process.env.HASURA_PROXY_TARGET || uiProxyTarget;
|
||||
|
||||
function applyProxyBasicAuth(proxyReq: any) {
|
||||
if (!proxyBasicAuth) return false;
|
||||
const b64 = Buffer.from(`${proxyBasicAuth.username}:${proxyBasicAuth.password}`, 'utf8').toString('base64');
|
||||
@@ -118,122 +119,60 @@ function rewriteSetCookieForLocalDevHttp(proxyRes: any) {
|
||||
proxyRes.headers['set-cookie'] = Array.isArray(v) ? v.map(rewrite) : rewrite(String(v));
|
||||
}
|
||||
|
||||
function readDevProxyAuthUser(env: Record<string, string | undefined>): string | undefined {
|
||||
const raw = String(env.DEV_PROXY_AUTH_USER || env.VITE_DEV_AUTH_USER || '').trim();
|
||||
return raw || undefined;
|
||||
}
|
||||
const proxy: Record<string, any> = {
|
||||
'/api': {
|
||||
target: apiProxyTarget,
|
||||
changeOrigin: true,
|
||||
rewrite: (p: string) => (apiProxyTargetEndsWithApi ? p.replace(/^\/api/, '') : p),
|
||||
configure: (p: any) => {
|
||||
p.on('proxyReq', (proxyReq: any) => {
|
||||
if (applyProxyBasicAuth(proxyReq)) return;
|
||||
if (apiReadToken) proxyReq.setHeader('Authorization', `Bearer ${apiReadToken}`);
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = { ...process.env, ...loadEnv(mode, DIR, '') } as Record<string, string | undefined>;
|
||||
const apiReadToken = readApiReadToken(env);
|
||||
const apiAdminSecret = readApiAdminSecret(env);
|
||||
const proxyBasicAuth = readProxyBasicAuth(env);
|
||||
const devProxyAuthUser = readDevProxyAuthUser(env);
|
||||
const apiProxyTargetRaw = String(env.API_PROXY_TARGET || '').trim();
|
||||
const apiProxyTarget = apiProxyTargetRaw || undefined;
|
||||
const apiProxyTargetUrl = apiProxyTarget ? parseUrl(apiProxyTarget) : undefined;
|
||||
const apiProxyTargetPath = stripTrailingSlashes(apiProxyTargetUrl?.pathname || '/');
|
||||
const apiProxyTargetEndsWithApi = apiProxyTargetPath.endsWith('/api');
|
||||
const apiProxyStripPrefixRaw = String(env.API_PROXY_STRIP_PREFIX || (apiProxyTargetEndsWithApi ? '/api' : '')).trim();
|
||||
const apiProxyStripPrefix = apiProxyStripPrefixRaw ? stripTrailingSlashes(apiProxyStripPrefixRaw) : '';
|
||||
const uiProxyTarget =
|
||||
env.FRONTEND_PROXY_TARGET ||
|
||||
env.UI_PROXY_TARGET ||
|
||||
env.AUTH_PROXY_TARGET ||
|
||||
inferUiProxyTarget(apiProxyTarget) ||
|
||||
(apiProxyTargetUrl && apiProxyTargetPath === '/'
|
||||
? stripTrailingSlashes(apiProxyTargetUrl.toString())
|
||||
: undefined);
|
||||
const graphqlProxyTarget = env.GRAPHQL_PROXY_TARGET || env.HASURA_PROXY_TARGET || uiProxyTarget;
|
||||
const graphqlProxyPathRaw = String(env.GRAPHQL_PROXY_PATH || '').trim();
|
||||
const graphqlProxyPath = graphqlProxyPathRaw ? stripTrailingSlashes(graphqlProxyPathRaw) : '';
|
||||
const portRaw = env.VITE_DEV_PORT || env.DEV_PORT || '5173';
|
||||
const port = Number.parseInt(String(portRaw), 10);
|
||||
|
||||
function applyProxyBasicAuth(proxyReq: any) {
|
||||
if (!proxyBasicAuth) return false;
|
||||
const b64 = Buffer.from(`${proxyBasicAuth.username}:${proxyBasicAuth.password}`, 'utf8').toString('base64');
|
||||
proxyReq.setHeader('Authorization', `Basic ${b64}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
function applyDevProxyAuth(proxyReq: any) {
|
||||
if (!devProxyAuthUser) return false;
|
||||
proxyReq.setHeader('x-trade-user', devProxyAuthUser);
|
||||
return true;
|
||||
}
|
||||
|
||||
const proxy: Record<string, any> = {
|
||||
};
|
||||
|
||||
if (apiProxyTarget) {
|
||||
proxy['/api'] = {
|
||||
target: apiProxyTarget,
|
||||
if (graphqlProxyTarget) {
|
||||
for (const prefix of ['/graphql', '/graphql-ws']) {
|
||||
proxy[prefix] = {
|
||||
target: graphqlProxyTarget,
|
||||
changeOrigin: true,
|
||||
rewrite: (p: string) => {
|
||||
if (!apiProxyStripPrefix) return p;
|
||||
const rewritten = p.replace(new RegExp(`^${apiProxyStripPrefix}`), '');
|
||||
return rewritten || '/';
|
||||
},
|
||||
ws: true,
|
||||
configure: (p: any) => {
|
||||
p.on('proxyReq', (proxyReq: any) => {
|
||||
applyProxyBasicAuth(proxyReq);
|
||||
applyDevProxyAuth(proxyReq);
|
||||
if (apiAdminSecret) {
|
||||
proxyReq.setHeader('x-admin-secret', apiAdminSecret);
|
||||
return;
|
||||
}
|
||||
if (apiReadToken) proxyReq.setHeader('Authorization', `Bearer ${apiReadToken}`);
|
||||
});
|
||||
p.on('proxyReqWs', (proxyReq: any) => {
|
||||
applyProxyBasicAuth(proxyReq);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (graphqlProxyTarget) {
|
||||
for (const prefix of ['/graphql', '/graphql-ws']) {
|
||||
proxy[prefix] = {
|
||||
target: graphqlProxyTarget,
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
rewrite: (p: string) => (graphqlProxyPath ? p.replace(new RegExp(`^${prefix}`), graphqlProxyPath) : p),
|
||||
configure: (p: any) => {
|
||||
p.on('proxyReq', (proxyReq: any) => {
|
||||
applyProxyBasicAuth(proxyReq);
|
||||
applyDevProxyAuth(proxyReq);
|
||||
});
|
||||
p.on('proxyReqWs', (proxyReq: any) => {
|
||||
applyProxyBasicAuth(proxyReq);
|
||||
applyDevProxyAuth(proxyReq);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
if (uiProxyTarget) {
|
||||
for (const prefix of ['/whoami', '/auth', '/logout']) {
|
||||
proxy[prefix] = {
|
||||
target: uiProxyTarget,
|
||||
changeOrigin: true,
|
||||
configure: (p: any) => {
|
||||
p.on('proxyReq', (proxyReq: any) => {
|
||||
applyProxyBasicAuth(proxyReq);
|
||||
});
|
||||
p.on('proxyRes', (proxyRes: any) => {
|
||||
rewriteSetCookieForLocalDevHttp(proxyRes);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (uiProxyTarget) {
|
||||
for (const prefix of ['/whoami', '/auth', '/logout']) {
|
||||
proxy[prefix] = {
|
||||
target: uiProxyTarget,
|
||||
changeOrigin: true,
|
||||
configure: (p: any) => {
|
||||
p.on('proxyReq', (proxyReq: any) => {
|
||||
applyProxyBasicAuth(proxyReq);
|
||||
applyDevProxyAuth(proxyReq);
|
||||
});
|
||||
p.on('proxyRes', (proxyRes: any) => {
|
||||
rewriteSetCookieForLocalDevHttp(proxyRes);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: Number.isInteger(port) && port > 0 ? port : 5173,
|
||||
strictPort: true,
|
||||
proxy,
|
||||
},
|
||||
};
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
proxy,
|
||||
},
|
||||
});
|
||||
|
||||
153
doc/dlob-services.md
Normal file
153
doc/dlob-services.md
Normal file
@@ -0,0 +1,153 @@
|
||||
# Serwisy DLOB na VPS (k3s / `trade-staging`)
|
||||
|
||||
Ten dokument opisuje rolę serwisów “DLOB” uruchomionych w namespace `trade-staging` oraz ich przepływ danych.
|
||||
|
||||
## Czy `dlob-worker` pracuje na VPS?
|
||||
|
||||
Tak — wszystkie serwisy wymienione niżej działają **na VPS** jako Deploymenty w klastrze k3s, w namespace `trade-staging`.
|
||||
|
||||
## Czy na VPS jest GraphQL/WS dla stats i orderbook?
|
||||
|
||||
Tak — **GraphQL wystawia Hasura** (na VPS w k3s), a nie `dlob-server`.
|
||||
|
||||
- Dane L2 i liczone statsy są zapisane do Postgresa jako tabele `dlob_*_latest` i są dostępne przez Hasurę jako GraphQL (query + subscriptions).
|
||||
- Z zewnątrz korzystamy przez frontend (proxy) pod:
|
||||
- HTTP: `https://trade.rv32i.pl/graphql`
|
||||
- WS: `wss://trade.rv32i.pl/graphql` (subskrypcje, protokół `graphql-ws`)
|
||||
|
||||
`dlob-server` wystawia **REST** (np. `/l2`, `/l3`) w klastrze; to jest źródło danych dla workerów albo do debugowania.
|
||||
|
||||
## TL;DR: kto co robi
|
||||
|
||||
### `dlob-worker`
|
||||
- **Rola:** kolektor L2 + wyliczenie “basic stats”.
|
||||
- **Wejście:** HTTP L2 z `DLOB_HTTP_URL` (u nas obecnie `https://dlob.drift.trade`, ale można przełączyć na `http://dlob-server:6969`).
|
||||
- **Wyjście:** upsert do Hasury (Postgres) tabel:
|
||||
- `dlob_l2_latest` (raw snapshot L2, JSON leveli)
|
||||
- `dlob_stats_latest` (pochodne: best bid/ask, mid, spread, depth, imbalance, itp.)
|
||||
- **Częstotliwość:** `DLOB_POLL_MS` (u nas 500 ms).
|
||||
|
||||
### `dlob-slippage-worker`
|
||||
- **Rola:** symulacja slippage vs rozmiar zlecenia na podstawie L2.
|
||||
- **Wejście:** czyta z Hasury `dlob_l2_latest` (dla listy rynków).
|
||||
- **Wyjście:** upsert do Hasury tabeli `dlob_slippage_latest` (m.in. `impact_bps`, `vwap_price`, `worst_price`, `fill_pct`).
|
||||
- **Częstotliwość:** `DLOB_POLL_MS` (u nas 1000 ms); rozmiary w `DLOB_SLIPPAGE_SIZES_USD`.
|
||||
|
||||
### `dlob-depth-worker`
|
||||
- **Rola:** metryki “głębokości” w pasmach ±bps wokół mid.
|
||||
- **Wejście:** czyta z Hasury `dlob_l2_latest`.
|
||||
- **Wyjście:** upsert do Hasury tabeli `dlob_depth_bps_latest` (per `(market_name, band_bps)`).
|
||||
- **Częstotliwość:** `DLOB_POLL_MS` (u nas 1000 ms); pasma w `DLOB_DEPTH_BPS_BANDS`.
|
||||
|
||||
### `dlob-publisher`
|
||||
- **Rola:** utrzymuje “żywy” DLOB na podstawie subskrypcji on-chain i publikuje snapshoty do Redis.
|
||||
- **Wejście:** Solana RPC/WS (`ENDPOINT`, `WS_ENDPOINT` z secreta `trade-dlob-rpc`), Drift SDK; konfiguracja rynków np. `PERP_MARKETS_TO_LOAD`.
|
||||
- **Wyjście:** zapis/publish do `dlob-redis` (cache / pubsub / streamy), z którego korzysta serwer HTTP (i ewentualnie WS manager).
|
||||
|
||||
### `dlob-server`
|
||||
- **Rola:** HTTP API do danych DLOB (np. `/l2`, `/l3`) serwowane z cache Redis.
|
||||
- **Wejście:** `dlob-redis` + slot subscriber (do oceny “świeżości” danych).
|
||||
- **Wyjście:** endpoint HTTP w klastrze (Service `dlob-server:6969`), który może być źródłem dla `dlob-worker` (gdy `DLOB_HTTP_URL=http://dlob-server:6969`).
|
||||
|
||||
### `dlob-redis`
|
||||
- **Rola:** Redis (u nas single-node “cluster mode”) jako **cache i kanał komunikacji** między `dlob-publisher` a `dlob-server`.
|
||||
- **Uwagi:** to “klej” między komponentami publish/serve; bez niego publisher i server nie współpracują.
|
||||
|
||||
## Jak to się spina (przepływ danych)
|
||||
|
||||
1) `dlob-publisher` (on-chain) → publikuje snapshoty do `dlob-redis`.
|
||||
2) `dlob-server` → serwuje `/l2` i `/l3` z `dlob-redis` (HTTP w klastrze).
|
||||
3) `dlob-worker` → pobiera L2 (obecnie z `https://dlob.drift.trade`; opcjonalnie z `dlob-server`) i zapisuje “latest” do Hasury/DB.
|
||||
4) `dlob-slippage-worker` + `dlob-depth-worker` → liczą agregaty z `dlob_l2_latest` i zapisują do Hasury/DB (pod UI).
|
||||
|
||||
## Co to jest L1 / L2 / L3 (orderbook)
|
||||
|
||||
- `L1` (top-of-book): tylko najlepszy bid i najlepszy ask (czasem też spread).
|
||||
- `L2` (Level 2): **zagregowane poziomy cenowe** po stronie bid/ask — lista leveli `{ price, size }`, gdzie `size` to suma wolumenu na danej cenie (to jest typowy “orderbook UI” i baza pod spread/depth/imbalance).
|
||||
- `L3` (Level 3): **niezagregowane, pojedyncze zlecenia** (każde osobno, zwykle z dodatkowymi polami/identyfikatorami). Większy wolumen danych; przydatne do “pro” analiz i debugowania mikrostruktury.
|
||||
|
||||
W tym stacku:
|
||||
- `dlob-server` udostępnia REST endpointy `/l2` i `/l3`.
|
||||
- Hasura/DB trzyma “latest” snapshot L2 w `dlob_l2_latest` oraz metryki w `dlob_stats_latest` / `dlob_depth_bps_latest` / `dlob_slippage_latest`.
|
||||
|
||||
## Słownik pojęć (bid/ask/spread i metryki)
|
||||
|
||||
### Podstawy orderbooka
|
||||
|
||||
- **Bid**: zlecenia kupna (chęć kupna). W orderbooku “bid side”.
|
||||
- **Ask**: zlecenia sprzedaży (chęć sprzedaży). W orderbooku “ask side”.
|
||||
- **Best bid / best ask**: najlepsza (najwyższa) cena kupna i najlepsza (najniższa) cena sprzedaży na topie księgi (L1).
|
||||
- **Spread**: różnica pomiędzy `best_ask` a `best_bid`. Im mniejszy spread, tym “taniej” wejść/wyjść (mniej kosztów natychmiastowej realizacji).
|
||||
- **Mid price**: cena “po środku”: `(best_bid + best_ask) / 2`. Używana jako punkt odniesienia do bps i slippage.
|
||||
- **Level**: pojedynczy poziom cenowy w L2 (np. `price=100.00`, `size=12.3`).
|
||||
- **Size**: ilość/płynność na poziomie (zwykle w jednostkach “base asset”).
|
||||
- **Base / Quote**:
|
||||
- `base` = instrument bazowy (np. SOL),
|
||||
- `quote` = waluta wyceny (często USD).
|
||||
|
||||
## Kolory w UI (visualizer)
|
||||
|
||||
- `bid` / “buy side” = zielony (`.pos`, `#22c55e`)
|
||||
- `ask` / “sell side” = czerwony (`.neg`, `#ef4444`)
|
||||
- “flat” / brak zmiany = niebieski (`#60a5fa`) — używany m.in. w “brick stack” pod świecami
|
||||
|
||||
### Jednostki i skróty
|
||||
|
||||
- **bps (basis points)**: 1 bps = 0.01% = `0.0001`. Np. 25 bps = 0.25%.
|
||||
- **USD**: u nas wiele wartości jest przeliczanych do USD (np. `size_base * price`).
|
||||
|
||||
### Metryki “stats” (np. `dlob_stats_latest`)
|
||||
|
||||
- `spread_abs` (USD): `best_ask - best_bid`.
|
||||
- `spread_bps` (bps): `(spread_abs / mid_price) * 10_000`.
|
||||
- `depth_levels`: ile leveli (top‑N) z każdej strony braliśmy do liczenia “depth”.
|
||||
- `depth_bid_base` / `depth_ask_base`: suma `size` po top‑N levelach bid/ask (w base).
|
||||
- `depth_bid_usd` / `depth_ask_usd`: suma `size_base * price` po top‑N levelach (w USD).
|
||||
- `imbalance` ([-1..1]): miara asymetrii płynności:
|
||||
- `(depth_bid_usd - depth_ask_usd) / (depth_bid_usd + depth_ask_usd)`
|
||||
- >0 = relatywnie więcej płynności po bid, <0 = po ask.
|
||||
- `oracle_price`: cena z oracla (np. Pyth) jako punkt odniesienia.
|
||||
- `mark_price`: “mark” z rynku/perp (cena referencyjna dla rozliczeń); różni się od oracle/top-of-book.
|
||||
|
||||
### Metryki “depth bands” (np. `dlob_depth_bps_latest`)
|
||||
|
||||
- `band_bps`: szerokość pasma wokół `mid_price` (np. 5/10/20/50/100/200 bps).
|
||||
- `bid_usd` / `ask_usd`: płynność po danej stronie, ale **tylko z poziomów mieszczących się w oknie ±`band_bps`** wokół mid.
|
||||
- `imbalance`: jak wyżej, ale liczony per band.
|
||||
|
||||
### Metryki “slippage” (np. `dlob_slippage_latest`)
|
||||
|
||||
To jest symulacja “gdybym teraz zrobił market order o rozmiarze X” na podstawie L2.
|
||||
|
||||
- `size_usd`: docelowy rozmiar zlecenia w USD.
|
||||
- `vwap_price`: średnia cena realizacji (Volume Weighted Average Price) dla symulowanego fill.
|
||||
- `impact_bps`: koszt/odchylenie względem `mid_price` wyrażone w bps (zwykle na bazie `vwap` vs `mid`).
|
||||
- `worst_price`: najgorsza cena dotknięta podczas “zjadania” kolejnych leveli.
|
||||
- `filled_usd` / `filled_base`: ile realnie udało się wypełnić (może być < docelowego, jeśli brakuje płynności).
|
||||
- `fill_pct`: procent wypełnienia (100% = pełny fill).
|
||||
- `levels_consumed`: ile leveli zostało “zjedzonych” podczas fill.
|
||||
|
||||
### Metadane czasu (“świeżość”)
|
||||
|
||||
- `ts`: timestamp źródła (czas snapshotu).
|
||||
- `slot`: slot Solany, z którego pochodzi snapshot (monotoniczny “numer czasu” chaina).
|
||||
- `updated_at`: kiedy nasz worker zapisał/odświeżył rekord w DB (do oceny, czy dane są świeże).
|
||||
|
||||
## Szybka diagnostyka na VPS
|
||||
|
||||
```bash
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n trade-staging get deploy | grep -E 'dlob-(worker|slippage-worker|depth-worker|publisher|server|redis)'
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n trade-staging logs deploy/dlob-worker --tail=80
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n trade-staging logs deploy/dlob-publisher --tail=80
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n trade-staging logs deploy/dlob-server --tail=80
|
||||
```
|
||||
|
||||
## Ważna uwaga (źródło L2 w `dlob-worker`)
|
||||
|
||||
Jeśli chcesz, żeby `dlob-worker` polegał na **naszym** stacku (własny RPC + `dlob-publisher` + `dlob-server`), ustaw:
|
||||
|
||||
- `DLOB_HTTP_URL=http://dlob-server:6969`
|
||||
|
||||
Aktualnie w `trade-staging` jest ustawione:
|
||||
|
||||
- `DLOB_HTTP_URL=https://dlob.drift.trade`
|
||||
150
doc/gitea-k3s-rv32i.md
Normal file
150
doc/gitea-k3s-rv32i.md
Normal file
@@ -0,0 +1,150 @@
|
||||
# Gitea na k3s (Traefik + cert-manager + Let’s Encrypt) dla `rv32i.pl`
|
||||
|
||||
Ten dokument instaluje Gitea w k3s:
|
||||
- Ingress: Traefik
|
||||
- TLS: cert-manager + Let’s Encrypt (`ClusterIssuer` = `letsencrypt-prod`)
|
||||
- Host: `rv32i.pl`
|
||||
- Secret TLS: `rv32i-pl-tls`
|
||||
|
||||
## Ważne (hasła/sekrety)
|
||||
|
||||
Nie wstawiam i nie zalecam trzymania haseł w plikach w repo (`doc/`), bo to zwykle kończy się wyciekiem (git history, backupy, screeny).
|
||||
|
||||
Zamiast tego:
|
||||
- trzymamy hasła w **Kubernetes Secret** (w klastrze),
|
||||
- a w dokumentacji zostawiamy **placeholderey** i komendy, które proszą o hasło interaktywnie.
|
||||
|
||||
Jeśli mimo wszystko chcesz „na sztywno” wpisać hasła do pliku, podaj je jawnie w wiadomości — ale to jest zła praktyka.
|
||||
|
||||
## 0) Wymagania
|
||||
|
||||
1) `cert-manager` działa, a `ClusterIssuer` jest gotowy:
|
||||
```bash
|
||||
sudo k3s kubectl get clusterissuer letsencrypt-prod
|
||||
```
|
||||
|
||||
2) DNS wskazuje na VPS:
|
||||
```bash
|
||||
dig +short rv32i.pl A
|
||||
```
|
||||
Oczekiwane: `77.90.8.171`
|
||||
|
||||
3) Porty 80/443 są otwarte z internetu (firewall/ACL u providera).
|
||||
|
||||
## 1) Instalacja Helm (jeśli nie masz)
|
||||
|
||||
```bash
|
||||
helm version || true
|
||||
curl -fsSL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | sudo bash
|
||||
helm version
|
||||
```
|
||||
|
||||
## 2) Namespace
|
||||
|
||||
```bash
|
||||
sudo k3s kubectl create namespace gitea
|
||||
```
|
||||
|
||||
## 3) Secret z kontem admina (bez wpisywania hasła do historii)
|
||||
|
||||
Ten krok tworzy w klastrze sekret `gitea-admin` z loginem/hasłem/email admina.
|
||||
|
||||
```bash
|
||||
read -rp "Gitea admin username: " GITEA_ADMIN_USER
|
||||
read -rsp "Gitea admin password: " GITEA_ADMIN_PASS; echo
|
||||
read -rp "Gitea admin email: " GITEA_ADMIN_EMAIL
|
||||
|
||||
sudo k3s kubectl -n gitea create secret generic gitea-admin \
|
||||
--from-literal=username="$GITEA_ADMIN_USER" \
|
||||
--from-literal=password="$GITEA_ADMIN_PASS" \
|
||||
--from-literal=email="$GITEA_ADMIN_EMAIL"
|
||||
```
|
||||
|
||||
## 4) Helm values (Ingress + TLS + Postgres w klastrze)
|
||||
|
||||
Utwórz plik `gitea-values.yaml` na VPS (nie musi być w repo):
|
||||
|
||||
```bash
|
||||
cat <<'YAML' > gitea-values.yaml
|
||||
ingress:
|
||||
enabled: true
|
||||
className: traefik
|
||||
annotations:
|
||||
cert-manager.io/cluster-issuer: letsencrypt-prod
|
||||
hosts:
|
||||
- host: rv32i.pl
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
tls:
|
||||
- secretName: rv32i-pl-tls
|
||||
hosts:
|
||||
- rv32i.pl
|
||||
|
||||
gitea:
|
||||
admin:
|
||||
existingSecret: gitea-admin
|
||||
config:
|
||||
server:
|
||||
DOMAIN: rv32i.pl
|
||||
ROOT_URL: https://rv32i.pl/
|
||||
PROTOCOL: http
|
||||
|
||||
persistence:
|
||||
enabled: true
|
||||
storageClass: local-path
|
||||
size: 10Gi
|
||||
|
||||
postgresql:
|
||||
enabled: true
|
||||
primary:
|
||||
persistence:
|
||||
enabled: true
|
||||
storageClass: local-path
|
||||
size: 10Gi
|
||||
YAML
|
||||
```
|
||||
|
||||
## 5) Instalacja Gitea
|
||||
|
||||
```bash
|
||||
helm repo add gitea-charts https://dl.gitea.com/charts/
|
||||
helm repo update
|
||||
|
||||
helm upgrade --install gitea gitea-charts/gitea \
|
||||
-n gitea \
|
||||
-f gitea-values.yaml
|
||||
```
|
||||
|
||||
## 6) Sprawdzenie
|
||||
|
||||
```bash
|
||||
sudo k3s kubectl -n gitea get pods -o wide
|
||||
sudo k3s kubectl -n gitea get ingress -o wide
|
||||
sudo k3s kubectl -n gitea get certificate -o wide
|
||||
sudo k3s kubectl -n gitea get order,challenge
|
||||
```
|
||||
|
||||
Wejdź na:
|
||||
- `https://rv32i.pl`
|
||||
|
||||
Jeśli `Certificate` nie robi się `Ready=True`, to najczęściej:
|
||||
- port 80 nie dochodzi z internetu (Let’s Encrypt HTTP-01),
|
||||
- Ingress nie ma `className: traefik`,
|
||||
- DNS nie wskazuje na VPS.
|
||||
|
||||
## 7) (Opcjonalnie) dostęp do haseł po czasie
|
||||
|
||||
Jeśli chcesz podejrzeć login/email z sekretu (hasło też da się odczytać, ale rób to ostrożnie):
|
||||
```bash
|
||||
sudo k3s kubectl -n gitea get secret gitea-admin -o jsonpath='{.data.username}' | base64 -d; echo
|
||||
sudo k3s kubectl -n gitea get secret gitea-admin -o jsonpath='{.data.email}' | base64 -d; echo
|
||||
```
|
||||
|
||||
## 8) Uwaga o Git przez SSH
|
||||
|
||||
Na VPS port 22 zajmuje systemowy OpenSSH. Na start korzystaj z klonowania przez HTTPS.
|
||||
Jeśli chcesz klonować przez SSH z Gitei:
|
||||
- najprościej wystawić Gitea SSH na innym porcie (np. 2222) i zrobić NodePort/LoadBalancer,
|
||||
- albo zmapować port przez Traefik TCP (wymaga dodatkowej konfiguracji).
|
||||
|
||||
167
doc/k8s-migracja.md
Normal file
167
doc/k8s-migracja.md
Normal file
@@ -0,0 +1,167 @@
|
||||
# Plan migracji na Kubernetes (mikroserwisy + CI/CD)
|
||||
|
||||
## 1) Co jest dziś w repo (stan wejściowy)
|
||||
|
||||
Ten projekt już ma podział “mikroserwisowy” w Docker Compose:
|
||||
|
||||
- **DB stack** (`devops/db/docker-compose.yml`)
|
||||
- `postgres` (TimescaleDB, port 5432)
|
||||
- `hasura` (GraphQL Engine, port 8080)
|
||||
- `pgadmin` (narzędzie dev, port 5050)
|
||||
- **App stack** (`devops/app/docker-compose.yml`)
|
||||
- `api` = **trade-api** (Node, port 8787, `devops/api/Dockerfile`)
|
||||
- `frontend` = **trade-frontend** (Node + statyczny build visualizera, port 8081, `devops/app/frontend/Dockerfile`)
|
||||
- `ingestor` = worker (Node, `devops/ingestor/Dockerfile`) – opcjonalnie, profil `ingest`
|
||||
- **One-shot bootstrap** (`devops/tools/bootstrap/docker-compose.yml`)
|
||||
- `db-init` (aplikuje SQL `devops/db/initdb/001_init.sql`)
|
||||
- `db-version` / `db-backfill` (migracje “wersji” ticków)
|
||||
- `hasura-bootstrap` (Node script `devops/db/hasura-bootstrap.mjs`: track tabel + permissions + funkcje)
|
||||
|
||||
Konfiguracja i sekrety dziś są w `tokens/*.json` (gitignored) i są montowane jako pliki do kontenerów.
|
||||
|
||||
## 2) Docelowa architektura na K8s
|
||||
|
||||
Minimalny sensowny podział na K8s (1 namespace lub 2):
|
||||
|
||||
- **timescaledb** (stanowe) → `StatefulSet` + `PVC` + `Service`
|
||||
- **hasura** → `Deployment` + `Service`
|
||||
- **trade-api** → `Deployment` + `Service`
|
||||
- **trade-frontend** → `Deployment` + `Service` + `Ingress`
|
||||
- **trade-ingestor** → `Deployment` (1 replika) albo `CronJob` (jeśli chcesz uruchamiać okresowo)
|
||||
- **bootstrap / migracje** → `Job` (odpalane ręcznie albo jako część release’u)
|
||||
|
||||
Opcjonalnie:
|
||||
- `pgadmin` tylko na dev/staging (nieprodukcyjnie).
|
||||
|
||||
## 3) Proponowane zasoby Kubernetes (mapowanie 1:1 z Compose)
|
||||
|
||||
### 3.1 timescaledb (Postgres)
|
||||
- `StatefulSet` z `volumeClaimTemplates` (dane w PVC)
|
||||
- `Service` typu `ClusterIP` (np. `timescaledb:5432`)
|
||||
- Init schematu:
|
||||
- *na pierwszy start* można nadal użyć mechanizmu `/docker-entrypoint-initdb.d` (ConfigMap z SQL),
|
||||
- *dla istniejących wolumenów* potrzebny jest osobny `Job` (odpowiednik `db-init` z compose).
|
||||
|
||||
### 3.2 Hasura
|
||||
- `Deployment` + `Service` (`hasura:8080`)
|
||||
- `Secret` na:
|
||||
- `HASURA_GRAPHQL_ADMIN_SECRET`
|
||||
- klucz JWT (`HASURA_GRAPHQL_JWT_SECRET` / `HASURA_JWT_KEY`)
|
||||
- connection string do Postgresa (albo osobno hasło)
|
||||
- Bootstrap metadanych:
|
||||
- `Job` uruchamiający `devops/db/hasura-bootstrap.mjs` (odpowiednik `hasura-bootstrap`).
|
||||
|
||||
### 3.3 trade-api
|
||||
- `Deployment` + `Service` (`trade-api:8787`)
|
||||
- `readinessProbe`/`livenessProbe`: `GET /healthz` (już istnieje)
|
||||
- Konfiguracja:
|
||||
- env: `HASURA_GRAPHQL_URL`, `TICKS_TABLE`, `CANDLES_FUNCTION`, `APP_VERSION`, `BUILD_TIMESTAMP`
|
||||
- sekret plikowy (jak dziś): `tokens/hasura.json` + `tokens/api.json` → `Secret` montowany do `/app/tokens/*`
|
||||
|
||||
### 3.4 trade-frontend
|
||||
- `Deployment` + `Service` (`trade-frontend:8081`)
|
||||
- `Ingress` wystawiający UI na zewnątrz (TLS opcjonalnie)
|
||||
- `readinessProbe`/`livenessProbe`: `GET /healthz` (już istnieje)
|
||||
- Sekrety plikowe:
|
||||
- `tokens/frontend.json` (basic auth do UI)
|
||||
- `tokens/read.json` (read token do proxy `/api/*`)
|
||||
- oba jako `Secret` montowany do `/tokens/*`
|
||||
- `API_UPSTREAM`: `http://trade-api:8787` (Service DNS)
|
||||
|
||||
### 3.5 trade-ingestor
|
||||
- `Deployment` (zwykle `replicas: 1`)
|
||||
- Sekrety:
|
||||
- RPC do Drift (np. `tokens/heliusN.json` / `rpcUrl` / `heliusApiKey`)
|
||||
- write token do API (`tokens/alg.json`)
|
||||
- Konfiguracja:
|
||||
- `MARKET_NAME`, `INTERVAL_MS`, `SOURCE`, `INGEST_API_URL=http://trade-api:8787`
|
||||
- Uwaga: worker wymaga egress do internetu (Helius RPC + Drift).
|
||||
|
||||
### 3.6 Jobs: db-init / db-version / db-backfill / hasura-bootstrap
|
||||
Bezpieczny pattern:
|
||||
- uruchamiane manualnie (kubectl) albo jako “hook” w Helm (pre/post-install)
|
||||
- odpalane w tym samym namespace co DB/Hasura (żeby DNS działał prosto)
|
||||
|
||||
## 4) Sekrety i konfiguracja (z `tokens/` → K8s)
|
||||
|
||||
Rekomendacja: rozdziel na 2 typy:
|
||||
|
||||
- **Secret** (nie commitować w git):
|
||||
- `tokens/hasura.json` (adminSecret, jwtKey)
|
||||
- `tokens/api.json` (api adminSecret)
|
||||
- `tokens/frontend.json` (basic auth)
|
||||
- `tokens/read.json` (read token)
|
||||
- `tokens/alg.json` (write token)
|
||||
- `tokens/heliusN.json` (RPC token / url)
|
||||
- **ConfigMap**:
|
||||
- wersja i parametry nie-wrażliwe: `APP_VERSION`, `BUILD_TIMESTAMP`, `TICKS_TABLE`, `CANDLES_FUNCTION`, `MARKET_NAME`, `INTERVAL_MS`
|
||||
|
||||
Jeśli chcesz GitOps bez trzymania sekretów “na piechotę”, wybierz jedno:
|
||||
- **Sealed Secrets** (zaszyfrowane sekrety w repo),
|
||||
- **External Secrets Operator** (Vault / AWS / GCP / Azure),
|
||||
- “na start” manualne `kubectl create secret ...` per środowisko.
|
||||
|
||||
## 5) Wersjonowanie (v1, v2…) i cutover bez wyłączania DB
|
||||
|
||||
W `scripts/ops/` jest workflow wersjonowania Compose:
|
||||
- nowa wersja `api+frontend(+ingestor)` działa równolegle
|
||||
- pisze do **nowej tabeli** (`drift_ticks_vN`) i używa **nowej funkcji** (`get_drift_candles_vN`)
|
||||
|
||||
Na K8s najprościej odwzorować to tak:
|
||||
- Helm release name albo suffix w nazwach zasobów: `trade-v1`, `trade-v2`, …
|
||||
- wspólne DB/Hasura pozostają bez zmian
|
||||
- `Job` “version-init”:
|
||||
- odpala SQL migracji (odpowiednik `db-version`)
|
||||
- odpala `hasura-bootstrap` z `TICKS_TABLE` i `CANDLES_FUNCTION` ustawionymi na vN
|
||||
- “cutover”:
|
||||
- startujesz `trade-ingestor` vN
|
||||
- stopujesz `trade-ingestor` v1
|
||||
- po czasie robisz `db-backfill` (opcjonalnie) i sprzątasz stare zasoby
|
||||
|
||||
## 6) CI/CD “na gita” (build → deploy po pushu)
|
||||
|
||||
### Opcja A (polecana): GitOps (Argo CD / Flux)
|
||||
1) CI (GitHub Actions / GitLab CI) buduje obrazy:
|
||||
- `trade-api`
|
||||
- `trade-frontend`
|
||||
- `trade-ingestor`
|
||||
2) CI publikuje je do registry (np. GHCR)
|
||||
3) CD (ArgoCD/Flux) automatycznie synchronizuje manifesty/Helm z repo i robi rollout
|
||||
|
||||
Tagowanie obrazów:
|
||||
- `:sha-<shortsha>` dla każdego commita
|
||||
- opcjonalnie `:vN` dla release’ów
|
||||
|
||||
Aktualizacja tagów:
|
||||
- ArgoCD Image Updater / Flux Image Automation **albo**
|
||||
- CI robi commit do `k8s/` (np. podmienia tag w `values.yaml`)
|
||||
|
||||
### Opcja B (prostsza na start): “kubectl apply” z CI
|
||||
1) CI buduje i pushuje obrazy
|
||||
2) CI wykonuje `helm upgrade --install` albo `kubectl apply -k ...`
|
||||
3) Dostęp do klastra przez sekret w repo (kubeconfig / token)
|
||||
|
||||
## 7) Proponowana sekwencja migracji (checklista)
|
||||
|
||||
1) **Decyzje**: gdzie stoi klaster (EKS/GKE/AKS/k3s), jakie registry, jaki Ingress, jak trzymamy sekrety.
|
||||
2) **K8s “base”**: namespace, storage class, ingress controller, certy (jeśli TLS).
|
||||
3) **DB**: wdroż Timescale (StatefulSet + PVC), odpal `db-init` job.
|
||||
4) **Hasura**: wdroż Hasurę, odpal `hasura-bootstrap` job.
|
||||
5) **API**: wdroż `trade-api`, sprawdź `/healthz`.
|
||||
6) **Tokeny**: wygeneruj read/write tokeny (obecnym mechanizmem API) i wgraj je jako Secrets.
|
||||
7) **Frontend**: wdroż `trade-frontend` + Ingress, sprawdź `/healthz` i UI.
|
||||
8) **Ingestor**: wdroż `trade-ingestor` (1 replika), potwierdź że ticki wpadają.
|
||||
9) **CI/CD**: dodaj workflow build+push i deploy (GitOps albo kubectl).
|
||||
10) **Staging → Prod**: rollout na staging, potem prod.
|
||||
|
||||
## 8) Pytania, które domykają plan
|
||||
|
||||
1) Jaki “git”: **GitHub czy GitLab**?
|
||||
2) Gdzie ma stać K8s: cloud (EKS/GKE/AKS) czy on-prem/k3s?
|
||||
3) DB w klastrze (StatefulSet) czy zewnętrzny managed Postgres/Timescale?
|
||||
4) Czy “po pushu” ma:
|
||||
- tylko robić rollout na `main`,
|
||||
- czy tworzyć **preview env per branch/PR**,
|
||||
- czy startować **nową wersję vN równolegle** (jak `scripts/ops/`)?
|
||||
5) Jaki dostęp z zewnątrz: domena + TLS, czy wystarczy port-forward / internal?
|
||||
|
||||
356
doc/migration.md
Normal file
356
doc/migration.md
Normal file
@@ -0,0 +1,356 @@
|
||||
# Migracja `trade` do k3s + GitOps (pull) na Gitea + CI/CD
|
||||
|
||||
Ten dokument opisuje plan migracji obecnego stacka (Docker Compose) do k3s z CD w modelu **pull-based** (GitOps): klaster sam synchronizuje „desired state” z repo na Gitei, a CI jedynie buduje/publikuje obrazy i aktualizuje repo deploymentu.
|
||||
|
||||
## Status (VPS / k3s)
|
||||
|
||||
Na VPS jest już uruchomione (k3s single-node):
|
||||
|
||||
- Ingress: Traefik (80/443)
|
||||
- TLS: cert-manager + `ClusterIssuer/letsencrypt-prod`
|
||||
- Gitea (Ingress `https://rv32i.pl`) + registry (`https://rv32i.pl/v2/`)
|
||||
- Argo CD w namespace `argocd`
|
||||
- Gitea Actions runner w namespace `gitea-actions` (act_runner + DinD)
|
||||
- GitOps repo `trade/trade-deploy` podpięte do Argo:
|
||||
- `Application/argocd/trade-staging` (auto-sync)
|
||||
- `namespace/trade-staging`: Postgres/Timescale + Hasura + pgAdmin + Job `hasura-bootstrap`
|
||||
- `namespace/trade-staging`: `trade-api` + `trade-ingestor` (obrazy z registry `rv32i.pl`)
|
||||
- `namespace/trade-staging`: `trade-frontend` + Ingress `trade.rv32i.pl` (basic auth, TLS OK)
|
||||
|
||||
Szybka weryfikacja (VPS):
|
||||
|
||||
```bash
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n trade-staging get deploy trade-api trade-ingestor -o wide
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n trade-staging logs deploy/trade-ingestor --tail=40
|
||||
```
|
||||
|
||||
### Tokeny `trade-api` (read/write)
|
||||
|
||||
Endpointy w `trade-api` są chronione tokenami z tabeli `api_tokens`:
|
||||
- `GET /v1/ticks`, `GET /v1/chart` → scope `read`
|
||||
- `POST /v1/ingest/tick` → scope `write`
|
||||
|
||||
W `staging` tokeny są przechowywane jako K8s Secrets (bez commitowania do gita):
|
||||
- `trade-staging/Secret/trade-ingestor-tokens`: `alg.json` (write) + `heliusN.json` (RPC)
|
||||
- `trade-staging/Secret/trade-read-token`: `read.json` (read)
|
||||
- `trade-staging/Secret/trade-frontend-tokens`: `frontend.json` (basic auth) + `read.json` (proxy do API)
|
||||
|
||||
### Dostęp: Argo CD UI (bez konfliktu z lokalnym Hasurą na 8080)
|
||||
|
||||
Port-forward uruchamiasz „na żądanie” (to nie jest stały serwis). Jeśli lokalnie masz Hasurę na `8080`, użyj `8090`.
|
||||
|
||||
Na VPS:
|
||||
|
||||
```bash
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n argocd port-forward --address 127.0.0.1 svc/argocd-server 8090:443
|
||||
```
|
||||
|
||||
Na swoim komputerze:
|
||||
|
||||
```bash
|
||||
ssh -L 8090:127.0.0.1:8090 user@rv32i.pl
|
||||
```
|
||||
|
||||
UI: `https://localhost:8090`
|
||||
|
||||
### Argo CD: username / hasło
|
||||
|
||||
- Username: `admin`
|
||||
- Hasło startowe (pobierz na VPS; nie commituj / nie wklejaj do gita):
|
||||
|
||||
```bash
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath='{.data.password}' | base64 -d; echo
|
||||
```
|
||||
|
||||
Po pierwszym logowaniu ustaw własne hasło i (opcjonalnie) usuń `argocd-initial-admin-secret`.
|
||||
|
||||
### Runner: log (czy CI działa)
|
||||
|
||||
Na VPS:
|
||||
|
||||
```bash
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n gitea-actions logs deploy/gitea-act-runner -c runner --tail=80
|
||||
```
|
||||
|
||||
### Portainer (Kubernetes UI): `portainer.rv32i.pl`
|
||||
|
||||
Portainer jest wdrażany przez Argo CD jako osobna aplikacja `portainer` (namespace `portainer`) z Ingressem i cert-managerem.
|
||||
|
||||
Wymagania:
|
||||
- DNS: rekord A `portainer.rv32i.pl` → `77.90.8.171`
|
||||
|
||||
Weryfikacja na VPS:
|
||||
|
||||
```bash
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n argocd get application portainer -o wide
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n portainer get pods,svc,ingress,certificate -o wide
|
||||
```
|
||||
|
||||
Jeśli cert-manager „utknie” na HTTP-01 z powodu cache NXDOMAIN w klastrze, pomocne jest zrestartowanie CoreDNS:
|
||||
|
||||
```bash
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n kube-system rollout restart deploy/coredns
|
||||
```
|
||||
|
||||
Jeśli Portainer pokaże ekran `timeout.html` (setup/login timed out), zrestartuj deployment i od razu dokończ inicjalizację:
|
||||
|
||||
```bash
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n portainer rollout restart deploy/portainer
|
||||
```
|
||||
|
||||
### Frontend UI: `trade.rv32i.pl`
|
||||
|
||||
Frontend jest wdrożony w `trade-staging` i ma Ingress na `trade.rv32i.pl` (Traefik + cert-manager).
|
||||
|
||||
Wymagania:
|
||||
- DNS: rekord A `trade.rv32i.pl` → `77.90.8.171`
|
||||
|
||||
Weryfikacja na VPS:
|
||||
|
||||
```bash
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n trade-staging get deploy trade-frontend -o wide
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n trade-staging get ingress trade-frontend -o wide
|
||||
KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl -n trade-staging get certificate trade-rv32i-pl-tls -o wide
|
||||
```
|
||||
|
||||
Status na dziś:
|
||||
- `Certificate/trade-rv32i-pl-tls` = `Ready=True` (Let’s Encrypt)
|
||||
|
||||
## 0) Stan wejściowy (co dziś jest w repo)
|
||||
|
||||
Projekt ma już logiczny podział „mikroserwisowy”:
|
||||
|
||||
- **DB stack**: `devops/db/docker-compose.yml`
|
||||
- TimescaleDB/Postgres (`postgres`, port 5432)
|
||||
- Hasura (`hasura`, port 8080)
|
||||
- pgAdmin (`pgadmin`, port 5050) – raczej tylko dev/staging
|
||||
- **App stack**: `devops/app/docker-compose.yml`
|
||||
- `trade-api` (`api`, port 8787; health: `GET /healthz`)
|
||||
- `trade-frontend` (`frontend`, port 8081; health: `GET /healthz`)
|
||||
- `trade-ingestor` (`ingestor`, profil `ingest`) – worker ingestujący ticki
|
||||
- **One-shot bootstrap**: `devops/tools/bootstrap/docker-compose.yml`
|
||||
- `db-init`, `db-version`, `db-backfill` (SQL)
|
||||
- `hasura-bootstrap` (track tabel + permissions)
|
||||
|
||||
Sekrety/konfiguracja lokalnie są dziś w `tokens/*.json` (gitignored) i są montowane jako pliki do kontenerów.
|
||||
|
||||
## 1) Cel migracji
|
||||
|
||||
- Przeniesienie usług do k3s (Kubernetes) bez zmiany logiki aplikacji.
|
||||
- Wdrożenia przez GitOps (**pull**, bez „kubectl apply” z CI).
|
||||
- Powtarzalność: jedna ścieżka build → deploy, jednoznaczne tagi/digests.
|
||||
- Minimalny downtime: możliwość uruchamiania wersji równolegle (v1/v2…), jak w `scripts/ops/*`.
|
||||
|
||||
## 2) Założenia i decyzje do podjęcia (checklista)
|
||||
|
||||
Ustal na start (zaznacz jedną opcję, resztę możesz doprecyzować później):
|
||||
|
||||
1) **CD (pull)**: Argo CD czy Flux
|
||||
- Argo CD + (opcjonalnie) Image Updater – popularny i „klikany”
|
||||
- Flux + Image Automation – bardzo „git-first”
|
||||
2) **Registry obrazów**: Gitea Registry czy osobne (Harbor / registry:2)
|
||||
3) **Sekrety w GitOps**: manualne seedy (na start) czy docelowo SOPS/SealedSecrets/ExternalSecrets
|
||||
4) **DB**: w klastrze (StatefulSet + PVC) czy zewnętrzny Postgres/Timescale
|
||||
5) **Środowiska**: `staging` + `prod`? (opcjonalnie preview per branch/PR)
|
||||
6) **Ingress/TLS**: Traefik + cert-manager + Let’s Encrypt (lub inny wariant)
|
||||
|
||||
## 3) Docelowa architektura na k3s (mapowanie 1:1)
|
||||
|
||||
Minimalny, praktyczny podział zasobów:
|
||||
|
||||
- `timescaledb` (Postgres/Timescale): `StatefulSet` + `PVC` + `Service`
|
||||
- `hasura`: `Deployment` + `Service`
|
||||
- `trade-api`: `Deployment` + `Service`
|
||||
- `trade-frontend`: `Deployment` + `Service` + `Ingress`
|
||||
- `trade-ingestor`: `Deployment` (zwykle `replicas: 1`) albo `CronJob` (jeśli ingest ma być okresowy)
|
||||
- migracje/bootstrap:
|
||||
- `Job` dla `db-init`/`db-version`/`db-backfill`
|
||||
- `Job` dla `hasura-bootstrap`
|
||||
|
||||
Ważne:
|
||||
- `trade-api` i `trade-frontend` mają gotowe endpointy `/healthz` do `readinessProbe`/`livenessProbe`.
|
||||
- `trade-ingestor` potrzebuje egress do internetu (RPC do Helius/Drift).
|
||||
|
||||
## 4) Podział repozytoriów (rekomendowane)
|
||||
|
||||
Żeby GitOps było czyste i proste:
|
||||
|
||||
1) Repo aplikacji: **`trade`** (to repo)
|
||||
- kod i Dockerfile: `devops/api/Dockerfile`, `devops/ingestor/Dockerfile`, `devops/app/frontend/Dockerfile`
|
||||
2) Repo deploymentu: **`trade-deploy`** (nowe repo na Gitei)
|
||||
- manifesty K8s (Helm chart albo Kustomize)
|
||||
- overlays per środowisko: `staging/`, `prod/`
|
||||
|
||||
Zasada: CI nie wykonuje deploya do klastra; CI tylko aktualizuje `trade-deploy`, a CD w klastrze to „pulluje”.
|
||||
|
||||
## 5) CI na Gitei (build → push)
|
||||
|
||||
Do wyboru:
|
||||
- **Gitea Actions** + `act_runner` (najbliżej GitHub Actions)
|
||||
- alternatywnie Woodpecker/Drone, jeśli już masz w infra
|
||||
|
||||
Zakres CI:
|
||||
- zbuduj i wypchnij obrazy:
|
||||
- `trade-api`
|
||||
- `trade-frontend`
|
||||
- `trade-ingestor`
|
||||
- taguj deterministycznie, np.:
|
||||
- `sha-<shortsha>` (zawsze)
|
||||
- opcjonalnie `vN` na release
|
||||
- po push obrazu: zaktualizuj `trade-deploy` (tag/digest) lub zostaw to automatyzacji obrazów (patrz niżej).
|
||||
|
||||
## 6) CD (pull) z klastra: GitOps
|
||||
|
||||
Wariant A (najprostszy operacyjnie): **CI robi commit do `trade-deploy`**
|
||||
- CI po zbudowaniu obrazu aktualizuje `values.yaml`/`kustomization.yaml` w `trade-deploy` (tag lub digest) i robi commit/push.
|
||||
- Argo CD / Flux wykrywa zmianę i robi rollout.
|
||||
|
||||
Wariant B (bardziej „autopilot”): **automatyczna aktualizacja obrazów**
|
||||
- Argo CD Image Updater albo Flux Image Automation obserwuje registry i sam aktualizuje repo `trade-deploy`.
|
||||
- CI tylko buduje/pushuje obrazy.
|
||||
|
||||
## 7) Sekrety: `tokens/*.json` → Kubernetes Secret (plikowy mount)
|
||||
|
||||
Docelowo w K8s montujesz te same pliki co w Compose:
|
||||
|
||||
- `tokens/hasura.json` → dla `trade-api` (admin do Hasury)
|
||||
- `tokens/api.json` → dla `trade-api` (admin secret do tokenów API)
|
||||
- `tokens/read.json` → dla `trade-frontend` (proxy do API)
|
||||
- `tokens/frontend.json` → dla `trade-frontend` (basic auth)
|
||||
- `tokens/alg.json` → dla `trade-ingestor` (write token)
|
||||
- `tokens/heliusN.json` (lub `rpcUrl`) → dla `trade-ingestor`
|
||||
|
||||
Nie commituj sekretów do gita. W GitOps wybierz jedną drogę:
|
||||
- start: ręczne `kubectl create secret ...` na środowisko
|
||||
- docelowo: SOPS (age) / SealedSecrets / ExternalSecrets (Vault itp.)
|
||||
|
||||
## 8) Plan wdrożenia (kolejność kroków)
|
||||
|
||||
### Etap 1: Klaster i narzędzia bazowe
|
||||
1) Namespace’y (np. `trade`, `gitea`, `argocd`/`flux-system`).
|
||||
2) StorageClass (na start `local-path`, docelowo rozważ Longhorn).
|
||||
3) Ingress controller (Traefik w k3s) + cert-manager + ClusterIssuer.
|
||||
4) Registry obrazów (Gitea Registry / Harbor / registry:2).
|
||||
5) GitOps controller (Argo CD albo Flux) podpięty do `trade-deploy`.
|
||||
|
||||
### Etap 2: DB + Hasura
|
||||
6) Deploy TimescaleDB (StatefulSet + PVC + Service).
|
||||
7) Uruchom `Job` `db-init` (idempotent) – odpowiednik `devops/tools/bootstrap:db-init`.
|
||||
8) Deploy Hasura (Deployment + Service + Secret na admin/jwt/db-url).
|
||||
9) Uruchom `Job` `hasura-bootstrap` – odpowiednik `devops/tools/bootstrap:hasura-bootstrap`.
|
||||
|
||||
### Etap 3: App stack
|
||||
10) Deploy `trade-api` (Deployment + Service, env `HASURA_GRAPHQL_URL`, `TICKS_TABLE`, `CANDLES_FUNCTION`).
|
||||
11) Sprawdź `GET /healthz` po Service DNS i (opcjonalnie) z zewnątrz.
|
||||
12) Wygeneruj i wgraj tokeny:
|
||||
- read token dla frontendu (`tokens/read.json`)
|
||||
- write token dla ingestora (`tokens/alg.json`)
|
||||
13) Deploy `trade-frontend` + Ingress (TLS opcjonalnie); ustaw `API_UPSTREAM=http://trade-api:8787`.
|
||||
14) Deploy `trade-ingestor` (`replicas: 1`); potwierdź, że ticki wpadają.
|
||||
|
||||
### Etap 4: CI/CD end-to-end
|
||||
15) Skonfiguruj runnera CI (Gitea Actions / Woodpecker).
|
||||
16) Workflow CI: build+push obrazów (i ewentualny commit do `trade-deploy`).
|
||||
17) Zasady promocji: staging → prod (np. tylko tag/release).
|
||||
|
||||
### Etap 4b: Workflow zmian (dev → staging) + snapshoty/rollback
|
||||
|
||||
Rekomendacja: nie robimy “ręcznych” zmian na VPS (żeby nie tworzyć snowflake’a). Każdy deploy ma być **snapshoot’em**, do którego można wrócić: *git commit w `trade-deploy` + pin do obrazu* (`sha-<shortsha>` albo digest; bez `latest`).
|
||||
|
||||
Standardowy flow:
|
||||
1) Zmiany robisz lokalnie (nie musisz odpalać lokalnego Dockera; na start wystarczy szybki build/typecheck).
|
||||
2) Push do gita (PR/merge).
|
||||
3) CI buduje i pushuje obrazy, a następnie aktualizuje `trade-deploy` (tag/digest + ewentualnie `BUILD_TIMESTAMP`).
|
||||
4) Argo CD (auto-sync) wdraża do `trade-staging`.
|
||||
5) Testujesz na VPS (UI/API/ingestor).
|
||||
|
||||
Rollback (szybki, preferowany):
|
||||
- cofasz zmianę w `trade-deploy` (`git revert` / powrót do poprzedniej rewizji w Argo) → Argo wraca do poprzedniego snapshoot’a.
|
||||
|
||||
Rollback (bezpieczny dla “dużych” zmian, np. ingest/schema):
|
||||
- użyj wersjonowania vN (osobna tabela/funkcja/porty) + cutover ingestora; jeśli zmiana nie siądzie, robisz cut back vN → v1 (dane w starej tabeli zostają).
|
||||
|
||||
## 9) Wersjonowanie v1/v2… (równoległe wdrożenia + cutover)
|
||||
|
||||
Repo ma już pattern wersjonowania w Compose (`scripts/ops/*` + `devops/versions/vN.env`).
|
||||
|
||||
Odwzorowanie na K8s:
|
||||
- osobne release’y Helm (np. `trade-v1`, `trade-v2`) albo osobne namespace’y
|
||||
- wspólny DB/Hasura bez zmian
|
||||
- `Job` „version-init”:
|
||||
- uruchamia SQL `db-version` (tworzy `drift_ticks_vN` i funkcje)
|
||||
- uruchamia `hasura-bootstrap` z `TICKS_TABLE`/`CANDLES_FUNCTION` ustawionymi na vN
|
||||
- cutover:
|
||||
- start `trade-ingestor` vN
|
||||
- stop `trade-ingestor` v1
|
||||
- (opcjonalnie) `db-backfill` jako osobny job
|
||||
|
||||
## 10) Definition of Done (DoD)
|
||||
|
||||
- `trade-api` i `trade-frontend` działają na k3s (proby `Ready=True`, brak crashloopów).
|
||||
- `trade-ingestor` zapisuje ticki do właściwej tabeli, a UI pokazuje wykres.
|
||||
- Deploy jest sterowany przez GitOps (zmiana w `trade-deploy` → rollout bez ręcznego `kubectl apply`).
|
||||
- Sekrety są poza gitem (manualnie lub przez wybraną metodę GitOps).
|
||||
|
||||
## 11) Referencje w repo
|
||||
|
||||
- Compose: `devops/db/docker-compose.yml`, `devops/app/docker-compose.yml`, `devops/tools/bootstrap/docker-compose.yml`
|
||||
- Workflow end-to-end: `doc/workflow-api-ingest.md`
|
||||
- Szkic migracji K8s: `doc/k8s-migracja.md`
|
||||
- Gitea na k3s (Traefik/TLS): `doc/gitea-k3s-rv32i.md`
|
||||
|
||||
## 12) Metoda „superproject” (subrepo) – plan refaktoru repozytoriów
|
||||
|
||||
Cel: utrzymać osobne repo dla usług (API/ingestor/frontend) i osobne repo GitOps (`trade-deploy`), a do tego mieć jedno repo „główne” (superproject) spinające wszystko (np. jako **git submodules**).
|
||||
|
||||
### Wybór repo głównego
|
||||
|
||||
Rekomendacja: **`trade/trade-infra` jako repo główne (superproject)**:
|
||||
- jest neutralne (infra/ops), nie miesza kodu aplikacji z manifestami GitOps,
|
||||
- pozwala trzymać jedną „zafiksowaną” wersję całego systemu (SHAs submodułów),
|
||||
- nie wymaga zmiany Argo CD (który nadal może śledzić `trade/trade-deploy`).
|
||||
|
||||
### Docelowy podział ról repo
|
||||
|
||||
- `trade/trade-api` – kod + Dockerfile dla `trade-api`
|
||||
- `trade/trade-ingestor` – kod + Dockerfile dla `trade-ingestor`
|
||||
- `trade/trade-frontend` – kod + Dockerfile dla `trade-frontend` (apps/visualizer + serwer)
|
||||
- `trade/trade-deploy` – GitOps: Kustomize/Helm dla k3s (Argo CD pull)
|
||||
- `trade/trade-doc` – dokumentacja całego projektu (`doc/`), w tym log działań
|
||||
- `trade/trade-infra` – superproject + narzędzia/ops (np. makefile, skrypty, checklisty)
|
||||
|
||||
### Proponowany układ w superprojekcie
|
||||
|
||||
Przykład (ścieżki w `trade/trade-infra`):
|
||||
|
||||
```text
|
||||
trade-infra/
|
||||
api/ -> submodule: trade-api
|
||||
ingestor/ -> submodule: trade-ingestor
|
||||
frontend/ -> submodule: trade-frontend
|
||||
deploy/ -> submodule: trade-deploy
|
||||
doc/ -> submodule: trade-doc
|
||||
```
|
||||
|
||||
### Plan wdrożenia refaktoru (po akceptacji)
|
||||
|
||||
1) Zainicjalizować `trade/trade-infra` jako superproject i dodać submodule do wszystkich subrepo.
|
||||
2) Wyciąć obecny kod do subrepo:
|
||||
- API: `services/api/*` + `devops/api/Dockerfile` → `trade-api/`
|
||||
- Frontend: `apps/visualizer/*` + `services/frontend/*` + `devops/app/frontend/*` → `trade-frontend/`
|
||||
- Ingestor: `scripts/ingest-drift-oracle.ts` (+ minimalny zestaw zależności i Dockerfile) → `trade-ingestor/`
|
||||
3) Przenieść dokumentację do `trade-doc` (w tym log: `doc/steps.md`) i zostawić w pozostałych repo linki do docs.
|
||||
4) Ujednolicić nazwy obrazów i tagowanie:
|
||||
- `rv32i.pl/trade/trade-api:<tag>`
|
||||
- `rv32i.pl/trade/trade-ingestor:<tag>`
|
||||
- `rv32i.pl/trade/trade-frontend:<tag>`
|
||||
5) CI/CD (Gitea Actions) per repo usługi:
|
||||
- build → push do registry,
|
||||
- aktualizacja `trade-deploy` (commit/PR z bumpem tagu/digesta),
|
||||
- staging auto-sync w Argo (prod manual).
|
||||
6) Walidacja end-to-end na k3s:
|
||||
- rollout `trade-staging`,
|
||||
- UI `https://trade.rv32i.pl`,
|
||||
- ingest ticków (`trade-ingestor` → `trade-api`).
|
||||
|
||||
Uwaga: lokalnie repo nie ma historii commitów, więc refaktor będzie startem „od zera” w nowych repo (initial commit per subrepo).
|
||||
158
doc/stats.md
Normal file
158
doc/stats.md
Normal file
@@ -0,0 +1,158 @@
|
||||
# DLOB stats — definicje i wizualizacja
|
||||
|
||||
Ten dokument opisuje metryki liczone z orderbooka DLOB (Drift Limit Order Book) oraz propozycje, jak je prezentować w naszej wizualizacji (warstwami/panelami).
|
||||
|
||||
## Źródła danych (tabele)
|
||||
|
||||
### `dlob_l2_latest` (snapshot L2, “surowy”)
|
||||
|
||||
Snapshot top‑N leveli orderbooka per market.
|
||||
|
||||
- `bids` / `asks`: tablice poziomów `{ price, size }` (wartości zwykle w “skalowanych intach” wg `PRICE_PRECISION` i `BASE_PRECISION`).
|
||||
- `best_bid_price` / `best_ask_price`, `mark_price`, `oracle_price`: w praktyce do szybkiego odczytu top‑of‑book (ale najdokładniej liczyć z `bids/asks`).
|
||||
- `ts`, `slot`: czas/slot źródłowego snapshota z DLOB.
|
||||
- `updated_at`: kiedy worker zapisał snapshot do DB (do oceny “świeżości”).
|
||||
|
||||
Z tego źródła robimy: orderbook UI (paski/heat), mikro‑ceny, symulacje fill.
|
||||
|
||||
### `dlob_stats_latest` (agregat z L2 pod UI)
|
||||
|
||||
Pochodne metryki liczone na podstawie `dlob_l2_latest` (lub równoważnego L2), trzymane jako “latest” per market.
|
||||
|
||||
Metryki:
|
||||
|
||||
- `best_bid_price`, `best_ask_price` (USD): najlepszy bid/ask.
|
||||
- `mid_price` (USD): `(best_bid_price + best_ask_price) / 2`.
|
||||
- `spread_abs` (USD): `best_ask_price - best_bid_price`.
|
||||
- `spread_bps` (bps): `(spread_abs / mid_price) * 10_000` (1 bps = 0.01%).
|
||||
- `depth_levels` (liczba): ile leveli z każdej strony weszło do “depth”.
|
||||
- `depth_bid_base`, `depth_ask_base` (base asset): suma size (w jednostkach bazowych) po top‑N levelach.
|
||||
- `depth_bid_usd`, `depth_ask_usd` (USD): suma `size_base * price` po top‑N levelach.
|
||||
- `imbalance` ([-1..1]): `(depth_bid_usd - depth_ask_usd) / (depth_bid_usd + depth_ask_usd)`; >0 = relatywnie większa płynność po bid.
|
||||
- `mark_price`, `oracle_price` (USD): ceny referencyjne (mark i oracle).
|
||||
- `ts`, `slot`, `updated_at`: metadane czasu/świeżości.
|
||||
|
||||
To jest najszybsze źródło do overlay na wykresie i do KPI w headerze.
|
||||
|
||||
### `dlob_depth_bps_latest` (płynność w pasmach wokół mid)
|
||||
|
||||
Metryki głębokości, ale nie “top‑N leveli” tylko “okno odległości od ceny” w bps.
|
||||
|
||||
Klucz:
|
||||
|
||||
- `(market_name, band_bps)` np. 5/10/20/50/100/200 bps.
|
||||
|
||||
Interpretacja:
|
||||
|
||||
- Dla danego `band_bps` sumujemy płynność tylko z poziomów, które mieszczą się w oknie ±`band_bps` wokół `mid_price`.
|
||||
|
||||
Metryki:
|
||||
|
||||
- `bid_base`, `ask_base` (base asset): suma size w oknie.
|
||||
- `bid_usd`, `ask_usd` (USD): suma `size_base * price` w oknie.
|
||||
- `imbalance` ([-1..1]): jak wyżej, ale per band.
|
||||
- `mid_price`, `best_bid_price`, `best_ask_price` (USD): do kontekstu wyliczeń.
|
||||
- `ts`, `slot`, `updated_at`, `raw`: metadane/diagnostyka.
|
||||
|
||||
To jest najlepsze źródło do wykresów “jak gruby jest orderbook blisko ceny”.
|
||||
|
||||
### `dlob_slippage_latest` (symulacja slippage vs rozmiar)
|
||||
|
||||
Symulacja wykonania zlecenia rynkowego po L2.
|
||||
|
||||
Klucz:
|
||||
|
||||
- `(market_name, side, size_usd)` gdzie `side ∈ {buy,sell}` a `size_usd` to predefiniowane progi (np. 100/500/1000/…).
|
||||
|
||||
Metryki:
|
||||
|
||||
- `impact_bps` (bps): wpływ wykonania vs `mid_price` (zwykle `vwap` względem mid).
|
||||
- `vwap_price` (USD): średnia cena wykonania.
|
||||
- `worst_price` (USD): najgorszy poziom dotknięty podczas fill.
|
||||
- `filled_usd`, `filled_base`: ile realnie weszło w fill (gdy brak płynności, może być < docelowego).
|
||||
- `fill_pct` (%): 100% = pełny fill.
|
||||
- `levels_consumed`: ile leveli zostało “zjedzone”.
|
||||
- `mid_price`, `ts`, `slot`, `updated_at`, `raw`: metadane/diagnostyka.
|
||||
|
||||
To jest idealne do “Dynamic Slippage” w formularzu i do wykresu slippage‑vs‑size.
|
||||
|
||||
## Jak nanieść na wizualizację (warstwy/panele)
|
||||
|
||||
Poniżej propozycja warstw, pogrupowanych tak, żeby serie w jednej warstwie były w tej samej “domenie” (jednostki i semantyka).
|
||||
|
||||
### Warstwa 1: Cena / Quotes (oś Y = USD, overlay na głównym wykresie)
|
||||
|
||||
Źródło: `dlob_stats_latest`.
|
||||
|
||||
- Linie: `mark_price` i `oracle_price` (referencje).
|
||||
- Linie: `best_bid_price` i `best_ask_price` (top‑of‑book).
|
||||
- Opcjonalnie: `mid_price` jako linia przerywana.
|
||||
- Opcjonalnie: “spread band” (wypełnienie między bid i ask).
|
||||
|
||||
Efekt: w jednym miejscu widać gdzie jest rynek + jak szeroki jest spread.
|
||||
|
||||
### Warstwa 2: Spread (panel pod wykresem, oś Y = bps)
|
||||
|
||||
Źródło: `dlob_stats_latest`.
|
||||
|
||||
- Linia: `spread_bps`.
|
||||
- Tooltip/secondary: `spread_abs` (USD) jako dodatkowa informacja (zwykle bez drugiej osi, żeby nie mieszać skali).
|
||||
|
||||
Efekt: szybkie “koszt wejścia/wyjścia” i jego zmienność.
|
||||
|
||||
### Warstwa 3: Płynność top‑N + imbalance (panel, oś Y = USD + opcjonalnie linia imbalance)
|
||||
|
||||
Źródło: `dlob_stats_latest`.
|
||||
|
||||
- Area: `depth_bid_usd` i `depth_ask_usd` (dwie serie, zielona/czerwona).
|
||||
- Opcjonalnie: linia `imbalance` (druga oś, zakres [-1..1]) albo jako wskaźnik liczbowy.
|
||||
|
||||
Efekt: ile jest płynności “najbliżej” top‑of‑book (w definicji top‑N leveli).
|
||||
|
||||
### Warstwa 4: Płynność jako funkcja odległości (bps bands) (panel)
|
||||
|
||||
Źródło: `dlob_depth_bps_latest`.
|
||||
|
||||
Dwa czytelne warianty prezentacji:
|
||||
|
||||
1) Fan chart / multi‑line:
|
||||
- Linie `bid_usd(band_bps)` i `ask_usd(band_bps)` dla kilku bandów (np. 10/50/200).
|
||||
|
||||
2) Stacked:
|
||||
- Słupki/area pokazujące “ile dodaje kolejne pasmo” (np. 0–10, 10–20, 20–50 bps), osobno dla bid i ask.
|
||||
|
||||
Efekt: “jak szybko rośnie płynność, gdy odchodzę od mid”.
|
||||
|
||||
### Warstwa 5: Slippage vs size (osobny panel XY, nie timeline)
|
||||
|
||||
Źródło: `dlob_slippage_latest`.
|
||||
|
||||
- Oś X: `size_usd`.
|
||||
- Oś Y: `impact_bps`.
|
||||
- Dwie krzywe: `buy` i `sell`.
|
||||
- Marker: aktualny “Order Value” z formularza (punkt na krzywej).
|
||||
|
||||
Efekt: bardzo czytelna krzywa kosztu wykonania względem rozmiaru.
|
||||
|
||||
### Warstwa 6: Heat / “paski” orderbooka (widok orderbook albo overlay z ograniczeniem)
|
||||
|
||||
Źródło: `dlob_l2_latest`.
|
||||
|
||||
- Paski (zielone/czerwone) per poziom ceny, intensywność ∝ `size` (jak na Drift UI).
|
||||
- To najlepiej działa jako:
|
||||
- osobny panel “Orderbook” (snapshot), albo
|
||||
- “edge overlay” przy prawej krawędzi wykresu (bez historii).
|
||||
|
||||
Efekt: “gdzie stoją ściany” i jak się zmieniają.
|
||||
|
||||
## Uwaga o historii (“latest” vs wykres w czasie)
|
||||
|
||||
Tabele `*_latest` są świetne do live UI i subscriptions, ale **nie przechowują historii** do rysowania timeline (np. spread przez ostatnie 24h).
|
||||
|
||||
Jeśli chcemy historię:
|
||||
|
||||
- opcja A: dodać osobne tabele time‑series (np. `dlob_stats_ts`, `dlob_depth_bps_ts`, `dlob_slippage_ts`) i zasilać je workerem,
|
||||
- opcja B: rozszerzyć ingest ticków (`drift_ticks`) o dodatkowe pola/nową tabelę eventów dla metryk orderbooka.
|
||||
|
||||
Wtedy warstwy 2–5 mogą być prawdziwymi wykresami “w czasie”, a nie tylko bieżącym odczytem.
|
||||
|
||||
231
doc/steps.md
Normal file
231
doc/steps.md
Normal file
@@ -0,0 +1,231 @@
|
||||
# steps.md
|
||||
|
||||
Log działań wykonywanych w ramach migracji `trade` → k3s + Gitea + GitOps (pull).
|
||||
Uwaga: **nie zapisuję sekretów** (hasła, tokeny, prywatne klucze) – jeśli pojawiają się w outputach narzędzi, są pomijane/redagowane.
|
||||
|
||||
## 2026-01-05
|
||||
|
||||
### Repo: inwentaryzacja i plan
|
||||
- Przejrzano strukturę repo (`apps/`, `devops/`, `services/`, `doc/`) i istniejące Compose stacki:
|
||||
- DB: `devops/db/docker-compose.yml`
|
||||
- App: `devops/app/docker-compose.yml`
|
||||
- Bootstrap (one-shot): `devops/tools/bootstrap/docker-compose.yml`
|
||||
- Sprawdzono Dockerfile:
|
||||
- API: `devops/api/Dockerfile`
|
||||
- Frontend: `devops/app/frontend/Dockerfile`
|
||||
- Ingestor: `devops/ingestor/Dockerfile`
|
||||
- Sprawdzono skrypty wersjonowania Compose (v1/v2…): `scripts/ops/*` + env: `devops/versions/v1.env`.
|
||||
- Dodano dokument planu migracji: `doc/migration.md`.
|
||||
|
||||
### Gitea: repo GitOps (MCP Gitea)
|
||||
- Utworzono repo `trade/trade-deploy` (public, `main`, auto-init).
|
||||
- Dodano szkielet Kustomize:
|
||||
- `kustomize/base/` (placeholder ConfigMap)
|
||||
- `kustomize/overlays/staging/` (`namespace: trade-staging`)
|
||||
- `kustomize/overlays/prod/` (`namespace: trade-prod`)
|
||||
- Dodano bootstrap manifesty Argo CD Application:
|
||||
- `bootstrap/argocd/application-trade-staging.yaml` (auto-sync + CreateNamespace)
|
||||
- `bootstrap/argocd/application-trade-prod.yaml` (CreateNamespace, bez auto-sync)
|
||||
- Dodano DB stack do `trade-deploy` (manifests + bootstrap):
|
||||
- Postgres/Timescale: `kustomize/base/postgres/*` + init SQL: `kustomize/base/initdb/001_init.sql`
|
||||
- Hasura: `kustomize/base/hasura/*` + job `hasura-bootstrap` (track tables/functions)
|
||||
- Staging: `kustomize/overlays/staging/pgadmin.yaml` + patch Hasury (console/dev mode)
|
||||
- Zaktualizowano `README.md` w `trade-deploy` o wymagane sekrety i port-forward.
|
||||
|
||||
### VPS: audyt stanu (MCP SSH)
|
||||
- Host: `qstack` (Debian), k3s działa; dostęp do klastra uzyskany przez `KUBECONFIG=/etc/rancher/k3s/k3s.yaml` (bez sudo).
|
||||
- Ingress: Traefik działa (LB na `77.90.8.171`, porty 80/443).
|
||||
- TLS: cert-manager działa; `ClusterIssuer/letsencrypt-prod` jest `Ready=True`.
|
||||
- Gitea jest zainstalowana w k3s (Helm release `gitea` w namespace `gitea`), Ingress na `rv32i.pl`, cert `rv32i-pl-tls` jest `Ready=True`.
|
||||
- GitOps controller (Argo CD / Flux): **nie znaleziono** (brak namespace `argocd` i `flux-system`).
|
||||
- Wdrożenia aplikacji `trade-*` w k3s: **nie znaleziono** (brak deploy/podów z nazwą `trade`).
|
||||
- Registry: endpoint `https://rv32i.pl/v2/` odpowiada (401 bez autoryzacji).
|
||||
|
||||
### Gitea: audyt stanu (MCP Gitea)
|
||||
- Zalogowany użytkownik: `u1` (admin).
|
||||
- Organizacja `trade` istnieje; są utworzone repozytoria (puste, bez commitów/branchy):
|
||||
- `trade/trade-api`
|
||||
- `trade/trade-frontend`
|
||||
- `trade/trade-ingestor`
|
||||
- `trade/trade-infra`
|
||||
- Repo `trade-deploy` (manifesty GitOps): **nie znaleziono**.
|
||||
|
||||
### VPS: Argo CD (MCP SSH)
|
||||
- Zainstalowano Argo CD przez Helm: release `argocd` w namespace `argocd` (`argo/argo-cd`).
|
||||
- Utworzono `Application` dla staging z `trade-deploy`:
|
||||
- zastosowano `bootstrap/argocd/application-trade-staging.yaml`
|
||||
- Argo utworzyło namespace `trade-staging` i zsynchronizowało placeholder ConfigMap `trade-deploy-info`.
|
||||
- Uwaga: jeśli port `8080` jest zajęty lokalnie (np. przez Hasurę), do port-forward użyj innego portu (np. `8090:443`).
|
||||
|
||||
### VPS: Gitea Actions runner (MCP SSH)
|
||||
- Wykryto wymaganie: `sudo` wymaga hasła, więc runner postawiony w k3s (bez instalacji binarki na hoście).
|
||||
- Utworzono namespace `gitea-actions` oraz zasoby dla `act_runner` (DinD sidecar + runner):
|
||||
- manifest w `trade-deploy`: `bootstrap/gitea-actions/act-runner.yaml`
|
||||
- sekret `act-runner-registration-token` utworzony w klastrze z tokena rejestracyjnego pobranego z Gitei (API admin; token nie trafia do gita)
|
||||
- Naprawiono start Dockera w sidecar:
|
||||
- początkowo próba po unix-sockecie powodowała konflikt (`docker.sock` jako katalog)
|
||||
- finalnie ustawiono `DOCKER_HOST=tcp://127.0.0.1:2375` (runner ↔ dind po localhost), co uruchomiło runnera poprawnie.
|
||||
|
||||
### Uwaga: seed sekretów (blokada narzędzia)
|
||||
- Przy próbie seedowania sekretów do `trade-staging` przez MCP SSH pojawił się trwały timeout na każde polecenie (`ssh-mcp/exec`), więc ten krok został opisany w `trade-deploy/README.md` do wykonania ręcznie na VPS.
|
||||
|
||||
### VPS: dostęp SSH kluczem (wymagane hasło)
|
||||
- Użytkownik poprosił o używanie naszego klucza prywatnego dla VPS: `k/qstack/qstack`.
|
||||
- Klucz jest zaszyfrowany hasłem (passphrase). Bez podania passphrase nie da się go użyć w trybie nieinteraktywnym (`ssh`/`ssh-keygen` zwraca błąd o niepoprawnym passphrase / brak `ssh-askpass`).
|
||||
- Żeby kontynuować automatyzację z tej sesji są 2 opcje:
|
||||
1) dostarczyć passphrase poza czatem (np. lokalnie w pliku w `tokens/`, gitignored) i używać `SSH_ASKPASS`, albo
|
||||
2) wygenerować osobny klucz bez passphrase jako “deploy key” tylko do automatyzacji i dodać jego publiczną część do `~user/.ssh/authorized_keys` na VPS.
|
||||
|
||||
### Następne kroki (do zrobienia)
|
||||
- Wybrać GitOps controller (Argo CD vs Flux) i zainstalować w k3s.
|
||||
- Utworzyć repo `trade-deploy` i dodać strukturę Helm/Kustomize (staging/prod).
|
||||
- Postawić runner CI (Gitea Actions `act_runner` lub alternatywa) i dodać pipeline build+push obrazów.
|
||||
- Dopiero potem: manifesty K8s dla `trade-api`/`trade-frontend`/`trade-ingestor` + DB/Hasura + joby migracji.
|
||||
|
||||
## 2026-01-06
|
||||
|
||||
### VPS: SSH kluczem projektu (passphrase)
|
||||
- Użyto klucza prywatnego `k/qstack/qstack` do połączenia z VPS przez `ssh` (z `SSH_ASKPASS` czytającym passphrase z `tokens/vps-ssh.json`, plik gitignored).
|
||||
- Skrypt `tokens/ssh-askpass.sh` był tworzony tymczasowo i został usunięty po użyciu (żeby nie ryzykować przypadkowego commita).
|
||||
|
||||
### Doprecyzowanie dostępu i bezpieczeństwo repo
|
||||
- Dopisano w `doc/migration.md` bieżący status VPS/k3s oraz komendy do Argo CD (port-forward na `8090`) i logów runnera.
|
||||
- Zaktualizowano `.gitignore`, żeby ignorować sekrety/klucze lokalne: `tokens/*`, `k/`, `argo/pass`, `gitea/token`.
|
||||
|
||||
### k3s: seed sekretów (staging)
|
||||
- Utworzono sekrety w namespace `trade-staging` (wartości wygenerowane losowo, nie logowane):
|
||||
- `trade-postgres` (`POSTGRES_*`)
|
||||
- `trade-hasura` (`HASURA_GRAPHQL_ADMIN_SECRET`, `HASURA_JWT_KEY`)
|
||||
- `trade-pgadmin` (`PGADMIN_DEFAULT_*`)
|
||||
|
||||
### Argo CD: deploy DB stack (staging)
|
||||
- Wymuszono refresh aplikacji Argo `trade-staging` (annotation `argocd.argoproj.io/refresh=hard`).
|
||||
- Status: `trade-staging` = `Synced` / `Healthy`.
|
||||
- Workloady w `trade-staging` działają:
|
||||
- `StatefulSet/postgres` = `postgres-0 Running`
|
||||
- `Deployment/hasura` = `Running`
|
||||
- `Deployment/pgadmin` = `Running`
|
||||
- `Job/hasura-bootstrap` = `Completed` (log: `[hasura-bootstrap] ok`)
|
||||
|
||||
### Portainer: dlaczego nie widać k3s (wyjaśnienie)
|
||||
- Portainer uruchomiony jako kontener Docker domyślnie widzi tylko środowisko Docker; k3s używa `containerd`, więc nie zobaczysz „podów” w `docker ps` ani w Portainerze jako kontenerów Dockera.
|
||||
- Żeby Portainer widział „wnętrze” k3s trzeba dodać środowisko typu `Kubernetes` w Portainer UI albo postawić Portainera bezpośrednio w klastrze (rekomendowane).
|
||||
|
||||
### Portainer (opcja A): wdrożenie w k3s + Ingress `portainer.rv32i.pl`
|
||||
- Dodano do GitOps repo `trade/trade-deploy` paczkę Kustomize: `kustomize/infra/portainer` (Namespace+RBAC+PVC+Deployment+Service+Ingress).
|
||||
- Dodano Argo CD `Application` dla Portainera: `bootstrap/argocd/application-portainer.yaml`.
|
||||
- Zastosowano `Application` na VPS i potwierdzono status: `portainer` = `Synced` / `Healthy`.
|
||||
- Ingress utworzony na host `portainer.rv32i.pl` (Traefik).
|
||||
- cert-manager utworzył `Certificate/portainer-rv32i-pl-tls`, ale ACME jest `pending` dopóki DNS `portainer.rv32i.pl` nie wskazuje na `77.90.8.171` (brak rekordu A w momencie sprawdzania).
|
||||
|
||||
### Portainer: DNS + TLS + odblokowanie „New Portainer installation timed out”
|
||||
- Potwierdzono, że rekord A `portainer.rv32i.pl` istnieje na autorytatywnych DNS (`dns*.home.pl`) i rozwiązuje się na publicznych resolverach.
|
||||
- Zrestartowano `Deployment/portainer` w namespace `portainer`, żeby odblokować ekran inicjalizacji (komunikat “timed out for security purposes”).
|
||||
- cert-manager miał „zawieszone” HTTP-01 self-check przez cache NXDOMAIN w klastrze; zrestartowano `Deployment/coredns` w `kube-system`, po czym certyfikat stał się `Ready=True` (`Certificate/portainer-rv32i-pl-tls`).
|
||||
|
||||
### Registry: token do Gitea Packages + docker login
|
||||
- Na VPS (z poziomu poda Gitei) wygenerowano token `read:package,write:package` dla użytkownika `u1`:
|
||||
- polecenie: `gitea admin user generate-access-token --username u1 --scopes "read:package,write:package" --raw`
|
||||
- token zapisany lokalnie w `tokens/gitea-registry.token` (gitignored; wartość nie jest logowana).
|
||||
- Wykonano `docker login rv32i.pl` (bez logowania tokena).
|
||||
- Zaktualizowano `.dockerignore`, żeby nie wysyłać do build context katalogów z sekretami/kluczami (`tokens/*`, `k/`, `gitea/`, `argo/`).
|
||||
|
||||
### Obrazy: build + push (trade-api, trade-ingestor)
|
||||
- Zbudowano i wypchnięto obrazy do Gitea registry:
|
||||
- `rv32i.pl/trade/trade-api:k3s-20260106013603`
|
||||
- `rv32i.pl/trade/trade-ingestor:k3s-20260106013603`
|
||||
- Tag zapisany lokalnie w `tokens/last-image-tag.txt` (gitignored).
|
||||
|
||||
### GitOps: manifesty k3s dla API + ingestor (trade-deploy)
|
||||
- Dodano do repo `trade/trade-deploy`:
|
||||
- `kustomize/base/api/deployment.yaml` + `kustomize/base/api/service.yaml`
|
||||
- `kustomize/base/ingestor/deployment.yaml`
|
||||
- aktualizacja `kustomize/base/kustomization.yaml` (dopięcie nowych zasobów).
|
||||
- Konfiguracja:
|
||||
- `trade-api` używa `HASURA_GRAPHQL_URL=http://hasura:8080/v1/graphql` i sekretów `trade-hasura` + `trade-api` (admin).
|
||||
- `trade-ingestor` startuje w trybie `INGEST_VIA=hasura` (bez tokenów API) i używa `trade-hasura` + `trade-ingestor-tokens` (RPC).
|
||||
|
||||
### k3s: seedy sekretów + weryfikacja (staging)
|
||||
- Utworzono w `trade-staging`:
|
||||
- `Secret/gitea-registry` (imagePullSecret do `rv32i.pl`)
|
||||
- `Secret/trade-api` (`API_ADMIN_SECRET`, wygenerowany losowo; nie logowany)
|
||||
- `Secret/trade-ingestor-tokens` (plik `heliusN.json`; wartość nie logowana)
|
||||
- Argo CD `Application/trade-staging` po refresh: `Synced` / `Healthy`.
|
||||
- Pody w `trade-staging` uruchomione: `trade-api` i `trade-ingestor` (`Running`).
|
||||
- Logi:
|
||||
- `trade-api` startuje i maskuje sekrety (`***`).
|
||||
- `trade-ingestor` pobiera ceny i ingestuje ticki; URL RPC jest redagowany (`api-key=***`).
|
||||
|
||||
### Ingest przez API + tokeny read/write
|
||||
- Zmieniono `trade-ingestor` na `INGEST_VIA=api` (pisze do `trade-api` zamiast bezpośrednio do Hasury); manifest w `trade/trade-deploy`: `kustomize/base/ingestor/deployment.yaml`.
|
||||
- Utworzono tokeny w `trade-api`:
|
||||
- `write` (dla ingestora) oraz `read` (dla klientów UI/odczytu)
|
||||
- tokeny zapisane jako K8s Secrets (wartości nie logowane):
|
||||
- `trade-staging/Secret/trade-ingestor-tokens`: `alg.json` (write) + `heliusN.json` (RPC)
|
||||
- `trade-staging/Secret/trade-read-token`: `read.json` (read)
|
||||
- Wymuszono rollout `Deployment/trade-ingestor` i potwierdzono w logach:
|
||||
- `ingestVia: "api"`, `writeUrl: "http://trade-api:8787/v1/ingest/tick"`, `auth: "bearer"`.
|
||||
- Potwierdzono, że `trade-api /v1/ticks` działa z tokenem `read` (bez ujawniania tokena).
|
||||
|
||||
### Frontend: deploy na k3s (staging) + Ingress `trade.rv32i.pl`
|
||||
- Zbudowano i wypchnięto obraz do Gitea registry:
|
||||
- `rv32i.pl/trade/trade-frontend:k3s-20260106013603`
|
||||
- Dodano manifesty do `trade/trade-deploy`:
|
||||
- `kustomize/base/frontend/deployment.yaml` + `kustomize/base/frontend/service.yaml`
|
||||
- staging: `kustomize/overlays/staging/frontend-ingress.yaml` (host `trade.rv32i.pl`)
|
||||
- aktualizacje `kustomize/base/kustomization.yaml` i `kustomize/overlays/staging/kustomization.yaml`.
|
||||
- Utworzono sekret `trade-staging/Secret/trade-frontend-tokens` (pliki `frontend.json` + `read.json`; wartości nie logowane).
|
||||
- Argo CD `Application/trade-staging`: `Synced` / `Healthy`; `Deployment/trade-frontend` = `Running`, `/healthz` działa.
|
||||
- TLS dla `trade.rv32i.pl` jest `pending` dopóki DNS `trade.rv32i.pl` nie wskazuje na `77.90.8.171` (w razie cache NXDOMAIN: restart `kube-system/coredns` jak wcześniej).
|
||||
|
||||
### DNS: `trade.rv32i.pl` (weryfikacja)
|
||||
- Sprawdzono rekord A `trade.rv32i.pl` na autorytatywnych DNS (`dns*.home.pl`) oraz na publicznych resolverach: **brak odpowiedzi** (rekord nie był jeszcze widoczny na NS), więc cert-manager trzyma `trade-rv32i-pl-tls` w stanie `pending` (NXDOMAIN).
|
||||
- Uwaga: jeśli w panelu DNS dodasz rekord i nadal masz `NXDOMAIN`, sprawdź czy host nie ma literówki (np. `rade` zamiast `trade`) i czy rekord jest zapisany jako A/CNAME dla właściwej nazwy `trade.rv32i.pl`.
|
||||
|
||||
### DNS/TLS: `trade.rv32i.pl` (finalizacja)
|
||||
- Użytkownik potwierdził rekord A `trade.rv32i.pl` → `77.90.8.171` na autorytatywnych DNS (`dns.home.pl`).
|
||||
- Na VPS potwierdzono:
|
||||
- `Ingress/trade-frontend` ma host `trade.rv32i.pl`.
|
||||
- `Certificate/trade-rv32i-pl-tls` = `Ready=True`.
|
||||
- `https://trade.rv32i.pl` odpowiada `HTTP 401` (basic auth) – czyli Ingress + TLS działają.
|
||||
|
||||
### Weryfikacja wdrożenia (MCP SSH)
|
||||
- `argocd/Application`: `trade-staging` i `portainer` = `Synced` / `Healthy`.
|
||||
- `trade-staging`: wszystkie workloady `Running` (Postgres/Hasura/pgAdmin/trade-api/trade-ingestor/trade-frontend).
|
||||
- `trade-ingestor` ma `INGEST_VIA=api` oraz `INGEST_API_URL=http://trade-api:8787` (ingest przez API z tokenem write).
|
||||
|
||||
### Portainer: odblokowanie ekranu `timeout.html`
|
||||
- Zrestartowano `Deployment/portainer` w namespace `portainer`, żeby ponownie pojawił się kreator inicjalizacji (admin user/password).
|
||||
|
||||
### Gitea: lista repo w organizacji `trade`
|
||||
- `trade/trade-api`
|
||||
- `trade/trade-deploy`
|
||||
- `trade/trade-doc`
|
||||
- `trade/trade-frontend`
|
||||
- `trade/trade-infra`
|
||||
- `trade/trade-ingestor`
|
||||
|
||||
## 2026-01-06
|
||||
|
||||
### Zmiana: log działań w `doc/`
|
||||
- Przeniesiono log działań z `steps.md` → `doc/steps.md` (zgodnie z nową zasadą: wszystko projektowe ląduje w `doc/`).
|
||||
|
||||
### Superproject: decyzja + plan (do akceptacji)
|
||||
- Zaproponowano `trade/trade-infra` jako repo główne (superproject) spinające subrepo (API/ingestor/frontend/deploy/doc).
|
||||
- Plan refaktoru opisany w `doc/migration.md` (sekcja „Metoda superproject”).
|
||||
- Użytkownik zaakceptował `trade/trade-infra` jako superproject; do decyzji pozostało: `submodules` vs `subtree` (rekomendacja: submodules, jeśli chcemy zachować niezależne repo + pinowanie wersji).
|
||||
|
||||
## 2026-01-10
|
||||
|
||||
### V2: GraphQL + WS (Hasura) + DLOB stats (staging)
|
||||
- `trade/trade-deploy`:
|
||||
- Podbito obraz frontendu do `gitea.mpabi.pl/trade/trade-frontend:sha-f85e6da` (UI proxy’uje Hasurę pod `/graphql` + WS pod `/graphql-ws`).
|
||||
- W Hasurze włączono `HASURA_GRAPHQL_UNAUTHORIZED_ROLE=public` (UI bez tokena; bootstrap nadaje ograniczone `select`).
|
||||
- W schemacie Postgresa dodano tabele pod statystyki DLOB: `public.dlob_l2_latest` i `public.dlob_stats_latest` (w `kustomize/base/initdb/001_init.sql`).
|
||||
- Dodano job migracji DB dla istniejących wolumenów: `kustomize/base/postgres/job-migrate.yaml` (Argo hook; uruchamia `psql -f 001_init.sql`).
|
||||
- `kustomize/base/hasura/job-bootstrap.yaml` działa jako Argo hook (re-run na sync) i trackuje tabele/permissions DLOB.
|
||||
- Dodano `dlob-worker` w k3s: `kustomize/base/dlob-worker/*` (Deployment + script jako ConfigMap); worker polluje `https://dlob.drift.trade/l2` i upsertuje do Hasury dla `PUMP/SOL/BONK/BTC/ETH` perps.
|
||||
- `apps/visualizer` (frontend na laptopie, dev mode):
|
||||
- `apps/visualizer/__start` odpala Vite z proxy do `https://trade.mpabi.pl` + ustawia `VITE_HASURA_WS_URL=/graphql-ws`.
|
||||
- `apps/visualizer/src/lib/graphqlWs.ts` wspiera względny `VITE_HASURA_WS_URL` (np. `/graphql-ws`) i normalizuje go do pełnego `ws(s)://...`.
|
||||
- `apps/visualizer/src/lib/hasura.ts` domyślnie używa `/graphql` (zgodnie z flow: dev UI → staging przez proxy).
|
||||
194
doc/workflow-api-ingest.md
Normal file
194
doc/workflow-api-ingest.md
Normal file
@@ -0,0 +1,194 @@
|
||||
# Workflow: init bazy + app stack + ingest przez API (tokeny + basic auth)
|
||||
|
||||
Docelowy podział na 3 compose’y:
|
||||
1) `devops/db/docker-compose.yml` → **Postgres/TimescaleDB + Hasura + pgAdmin** (DB stack)
|
||||
2) `devops/tools/bootstrap/docker-compose.yml` → **one-shot tools** (init SQL + Hasura metadata)
|
||||
3) `devops/app/docker-compose.yml` → **API + frontend (+ opcjonalny ingestor)** (app stack)
|
||||
|
||||
## TL;DR (local, end-to-end)
|
||||
1) `npm install`
|
||||
2) DB: `docker compose -f devops/db/docker-compose.yml up -d`
|
||||
3) Schema/metadata: `docker compose -f devops/tools/bootstrap/docker-compose.yml run --rm db-init` + `docker compose -f devops/tools/bootstrap/docker-compose.yml run --rm hasura-bootstrap`
|
||||
4) Tokeny: skopiuj `tokens/*.example.json` → `tokens/*.json` + ustaw RPC w `tokens/heliusN.json` (albo po prostu `cp tokens/helius.json tokens/heliusN.json`)
|
||||
5) API: `docker compose -f devops/app/docker-compose.yml up -d api` + `curl -sS http://localhost:8787/healthz`
|
||||
6) Tokeny (revocable): `npm run token:api -- --scopes write --out tokens/alg.json` + `npm run token:api -- --scopes read --out tokens/read.json`
|
||||
7) Frontend: `docker compose -f devops/app/docker-compose.yml up -d frontend`
|
||||
8) Ingestor: `docker compose -f devops/app/docker-compose.yml --profile ingest up -d`
|
||||
9) DLOB worker (Hasura stats/subscriptions): `docker compose -f devops/app/docker-compose.yml --profile dlob up -d dlob-worker`
|
||||
|
||||
Uwaga: ceny w `drift_ticks` są `NUMERIC` (Hasura zwykle zwraca/oczekuje stringów dla `numeric`); `trade-api` normalizuje je do `number` w `/v1/chart`.
|
||||
|
||||
## DLOB worker (Drift DLOB → Hasura) + GraphQL subscriptions
|
||||
|
||||
Cel: UI dostaje “global stats” (best bid/ask/spread/depth) przez **GraphQL + WS** (Hasura subscriptions), bez wystawiania sekretów do przeglądarki.
|
||||
|
||||
- Worker: `dlob-worker` pobiera snapshoty orderbooka z `https://dlob.drift.trade/l2` i upsertuje do Hasury.
|
||||
- Tabele:
|
||||
- `dlob_l2_latest` (raw L2 snapshot)
|
||||
- `dlob_stats_latest` (wyliczone statystyki)
|
||||
- UI: subskrybuje `dlob_stats_latest` po `/graphql` (proxy w `trade-frontend` obsługuje też WS upgrade).
|
||||
|
||||
Start lokalnie:
|
||||
```bash
|
||||
docker compose -f devops/app/docker-compose.yml --profile dlob up -d --build dlob-worker
|
||||
```
|
||||
|
||||
Opcjonalne env:
|
||||
- `DLOB_MARKETS=PUMP-PERP,SOL-PERP,BONK-PERP,BTC-PERP,ETH-PERP`
|
||||
- `DLOB_POLL_MS=500`
|
||||
- `DLOB_DEPTH=10`
|
||||
|
||||
Uwaga: UI nie potrzebuje sekretów Hasury, bo w `devops/db/docker-compose.yml` jest `HASURA_GRAPHQL_UNAUTHORIZED_ROLE=public`, a `hasura-bootstrap` nadaje roli `public` tylko `select` na tabelach DLOB.
|
||||
|
||||
## Migracja (bez kasowania danych)
|
||||
Szybka sekwencja do migracji schematu + odpalenia stacka (bez `down -v`) jest w `r1.txt`.
|
||||
|
||||
## Wersjonowanie API/UI (v2, v3...) bez ruszania DB/Hasury
|
||||
Cel: uruchamiasz nową wersję `api+frontend(+ingestor)` równolegle, na **nowych tabelach**, na **nowych portach**, a potem robisz cutover ingestora.
|
||||
|
||||
Konwencja:
|
||||
- v1: tabela `drift_ticks`, funkcja `get_drift_candles`, porty `8787/8081`
|
||||
- vN: tabela `drift_ticks_vN`, funkcja `get_drift_candles_vN`, porty `8787+(N-1)` i `8081+(N-1)`
|
||||
- wspólne: Postgres/Hasura/pgAdmin + `api_tokens` (tokeny) zostają bez wersjonowania
|
||||
|
||||
Skrypty: `scripts/ops/` (tworzą też env w `devops/versions/vN.env`)
|
||||
- `bash scripts/ops/version-init.sh 2` migracja DB + create `drift_ticks_v2` + track w Hasurze
|
||||
- `bash scripts/ops/version-up.sh 2` start `api+frontend` v2 (host: `8788/8082`)
|
||||
- `bash scripts/ops/version-ingestor-up.sh 2` start ingestor v2 (pisze do v2 API → `drift_ticks_v2`)
|
||||
- `bash scripts/ops/version-cutover.sh 1 2` start v2 ingestor, potem stop v1 ingestor
|
||||
- `bash scripts/ops/version-backfill.sh 1 2` backfill ALL: `drift_ticks` → `drift_ticks_v2`
|
||||
- `bash scripts/ops/version-down.sh 1` usuń stare kontenery v1 (DB bez zmian)
|
||||
- `bash scripts/ops/version-check.sh 2` healthz/ticks/chart dla v2
|
||||
|
||||
## Reset (UWAGA: kasuje dane z bazy)
|
||||
Jeśli uruchomisz `docker compose -f devops/db/docker-compose.yml down -v`, Postgres/Timescale traci cały wolumen (czyli rekordy z `drift_ticks`).
|
||||
|
||||
## Dane logowania (dev)
|
||||
- Postgres: `postgres://admin:pass@localhost:5432/crypto`
|
||||
- Hasura: `http://localhost:8080` (admin secret: `tokens/hasura.json` → `adminSecret`)
|
||||
- pgAdmin: `http://localhost:5050` (login: `admin@example.com`, hasło: `admin`)
|
||||
- Frontend UI: `http://localhost:8081` (basic auth: `tokens/frontend.json` → `username`/`password`)
|
||||
|
||||
## 0) Start DB stack
|
||||
Z root repo:
|
||||
```bash
|
||||
docker compose -f devops/db/docker-compose.yml up -d
|
||||
```
|
||||
Ten krok tworzy wspólną sieć Dockera `trade-net`, przez którą app stack łączy się do Hasury.
|
||||
|
||||
## 1) Init / upgrade schematu bazy (idempotent)
|
||||
Użyj zwłaszcza, jeśli masz istniejący wolumen Postgresa:
|
||||
```bash
|
||||
docker compose -f devops/tools/bootstrap/docker-compose.yml run --rm db-init
|
||||
```
|
||||
To jest też krok, który trzeba odpalić po zmianach w `devops/db/initdb/001_init.sql` (np. migracja `DOUBLE PRECISION` → `NUMERIC`).
|
||||
|
||||
## 2) Hasura metadata bootstrap (track tabel + permissions)
|
||||
```bash
|
||||
docker compose -f devops/tools/bootstrap/docker-compose.yml run --rm hasura-bootstrap
|
||||
```
|
||||
|
||||
## 3) Skonfiguruj API + frontend
|
||||
Utwórz lokalne pliki (gitignored) w `tokens/`:
|
||||
- `tokens/hasura.json` z `tokens/hasura.example.json` (URL + admin secret dla Hasury, używane przez `trade-api`)
|
||||
- `tokens/api.json` z `tokens/api.example.json` (sekret admina do tworzenia/revoke tokenów API)
|
||||
- `tokens/frontend.json` z `tokens/frontend.example.json` (basic auth do UI)
|
||||
- `tokens/heliusN.json` (RPC dla Drift; albo `heliusApiKey`, albo pełny `rpcUrl`)
|
||||
|
||||
Jeśli odpalasz lokalne skrypty (`npm run token:*`, `npm run ingest:*`) wykonaj też:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
## 4) Start API (trade-api)
|
||||
```bash
|
||||
docker compose -f devops/app/docker-compose.yml up -d api
|
||||
```
|
||||
|
||||
- API: `http://localhost:8787`
|
||||
|
||||
Healthcheck:
|
||||
```bash
|
||||
curl -sS http://localhost:8787/healthz
|
||||
```
|
||||
|
||||
## 5) Wygeneruj tokeny (revocable)
|
||||
**Write token** dla ingestora (domyślnie zapisuje do `tokens/alg.json`):
|
||||
```bash
|
||||
npm run token:api -- --name algo1 --scopes write --out tokens/alg.json
|
||||
```
|
||||
|
||||
Jeśli wcześniej uruchomiłeś `frontend` bez pliku `tokens/read.json`, Docker mógł utworzyć katalog `tokens/read.json`.
|
||||
Usuń go przed generacją tokena:
|
||||
```bash
|
||||
rm -rf tokens/read.json
|
||||
```
|
||||
|
||||
**Read token** dla frontendu (proxy wstrzykuje go serwerowo; nie trafia do JS):
|
||||
```bash
|
||||
npm run token:api -- --name reader-ui --scopes read --out tokens/read.json
|
||||
```
|
||||
|
||||
## 6) Start frontend (UI)
|
||||
```bash
|
||||
docker compose -f devops/app/docker-compose.yml up -d frontend
|
||||
```
|
||||
|
||||
- Frontend: `http://localhost:8081` (basic auth)
|
||||
|
||||
Dev mode (Vite + proxy `/api` z tokenem z `tokens/read.json`):
|
||||
```bash
|
||||
npm run visualizer:dev
|
||||
```
|
||||
- Dev UI: `http://localhost:5173`
|
||||
|
||||
## 7) Uruchom kontener ingestora, który wysyła ticki do API
|
||||
W ramach app stack (profil `ingest`):
|
||||
```bash
|
||||
docker compose -f devops/app/docker-compose.yml --profile ingest up -d
|
||||
```
|
||||
|
||||
Alternatywnie (bez Dockera) możesz odpalić ingest lokalnie:
|
||||
```bash
|
||||
npm run ingest:oracle -- --ingest-via api --market-name PUMP-PERP --interval-ms 1000 --source drift_oracle
|
||||
```
|
||||
Wymaga: `tokens/heliusN.json` (RPC) + `tokens/alg.json` (write token do API) + działającego `trade-api`.
|
||||
|
||||
Override (przykład):
|
||||
```bash
|
||||
MARKET_NAME=PUMP-PERP INTERVAL_MS=250 SOURCE=drift_oracle \
|
||||
docker compose -f devops/app/docker-compose.yml --profile ingest up -d
|
||||
```
|
||||
|
||||
## 8) Sprawdź, czy rekordy wpadają
|
||||
Przez API (wymaga read tokena):
|
||||
```bash
|
||||
curl -sS "http://localhost:8787/v1/ticks?symbol=PUMP-PERP&limit=5" \
|
||||
-H "Authorization: Bearer $(node -p 'require("./tokens/read.json").token')"
|
||||
```
|
||||
|
||||
W UI: `http://localhost:8081` → wykres powinien się aktualizować.
|
||||
|
||||
Sprawdź agregacje + wskaźniki (candles + indicators z backendu):
|
||||
```bash
|
||||
curl -sS "http://localhost:8787/v1/chart?symbol=PUMP-PERP&tf=1m&limit=120" \
|
||||
-H "Authorization: Bearer $(node -p 'require("./tokens/read.json").token')"
|
||||
```
|
||||
|
||||
## Checklist (copy/paste)
|
||||
- `npm install` zainstaluj zależności do `npm run token:*` / `npm run ingest:*`
|
||||
- `cp tokens/hasura.example.json tokens/hasura.json` skopiuj konfigurację Hasury
|
||||
- `cp tokens/api.example.json tokens/api.json` skopiuj konfigurację API (adminSecret)
|
||||
- `cp tokens/frontend.example.json tokens/frontend.json` skopiuj basic auth do UI
|
||||
- `cp tokens/helius.json tokens/heliusN.json` ustaw RPC dla Drift (fallback jest też `tokens/helius.json`)
|
||||
- `docker compose -f devops/db/docker-compose.yml up -d` uruchom Postgres/Timescale + Hasura + pgAdmin
|
||||
- `docker compose -f devops/tools/bootstrap/docker-compose.yml run --rm db-init` zastosuj schemat PG (tabele/indeksy/hypertable)
|
||||
- `docker compose -f devops/tools/bootstrap/docker-compose.yml run --rm hasura-bootstrap` track tabel + permissions w Hasurze
|
||||
- `docker compose -f devops/app/docker-compose.yml up -d api` uruchom API
|
||||
- `curl -sS http://localhost:8787/healthz` sprawdź czy API działa
|
||||
- `npm run token:api -- --name algo1 --scopes write --out tokens/alg.json` wygeneruj write token dla ingestora
|
||||
- `npm run token:api -- --name reader-ui --scopes read --out tokens/read.json` wygeneruj read token dla UI/curl
|
||||
- `docker compose -f devops/app/docker-compose.yml up -d frontend` uruchom frontend
|
||||
- `docker compose -f devops/app/docker-compose.yml --profile ingest up -d` uruchom ingestora (Drift → API → DB)
|
||||
- `curl -sS "http://localhost:8787/v1/ticks?symbol=PUMP-PERP&limit=5" -H "Authorization: Bearer $(node -p 'require("./tokens/read.json").token')"` sprawdź czy ticki wpadają
|
||||
- `curl -sS "http://localhost:8787/v1/chart?symbol=PUMP-PERP&tf=1m&limit=120" -H "Authorization: Bearer $(node -p 'require("./tokens/read.json").token')"` sprawdź candles + wskaźniki z backendu
|
||||
99
doc/workflow.md
Normal file
99
doc/workflow.md
Normal file
@@ -0,0 +1,99 @@
|
||||
# Workflow pracy w projekcie `trade` (dev → staging na VPS) + snapshot/rollback
|
||||
|
||||
Ten plik jest “source of truth” dla sposobu pracy nad zmianami w `trade`.
|
||||
Cel: **zero ręcznych zmian na VPS**, każdy deploy jest **snapshoot’em**, do którego można wrócić.
|
||||
|
||||
## Dla agenta / po restarcie sesji
|
||||
|
||||
1) Przeczytaj ten plik: `doc/workflow.md`.
|
||||
2) Kontekst funkcjonalny: `README.md`, `info.md`.
|
||||
3) Kontekst stacka: `doc/workflow-api-ingest.md` oraz `devops/*/README.md`.
|
||||
4) Stan VPS/k3s + GitOps: `doc/migration.md` i log zmian: `doc/steps.md`.
|
||||
|
||||
## Zasady (must-have)
|
||||
|
||||
- **Nie edytujemy “na żywo” VPS** (żadnych ręcznych poprawek w kontenerach/plikach na serwerze) → tylko Git + CI + Argo.
|
||||
- **Sekrety nie trafiają do gita**: `tokens/*.json` są gitignored; w dokumentacji/logach redagujemy hasła/tokeny.
|
||||
- **Brak `latest`**: obrazy w deployu są przypięte do `sha-<shortsha>` albo digesta.
|
||||
- **Każda zmiana = snapshot**: “wersja” to commit w repo deploy + przypięte obrazy.
|
||||
|
||||
## Domyślne środowisko pracy (ważne)
|
||||
|
||||
- **Frontend**: domyślnie pracujemy lokalnie (Vite) i łączymy się z backendem na VPS (staging) przez proxy. Deploy frontendu na VPS robimy tylko jeśli jest to wyraźnie powiedziane (“wdrażam na VPS”).
|
||||
- **Backend (trade-api + ingestor)**: zmiany backendu weryfikujemy/wdrażamy na VPS (staging), bo tam działa ingestor i tam są dane. Nie traktujemy lokalnego uruchomienia backendu jako domyślnego (tylko na wyraźną prośbę do debugowania).
|
||||
|
||||
## Standardowy flow zmian (polecany)
|
||||
|
||||
1) Zmiana w kodzie lokalnie.
|
||||
- Nie musisz odpalać lokalnego Dockera; na start rób szybkie walidacje (build/typecheck).
|
||||
2) Commit + push (najlepiej przez PR).
|
||||
3) CI:
|
||||
- build → push obrazów (tag `sha-*` lub digest),
|
||||
- aktualizacja `trade-deploy` (bump obrazu/rewizji).
|
||||
4) Argo CD (auto-sync na staging) wdraża nowy snapshot w `trade-staging`.
|
||||
5) Test na VPS:
|
||||
- API: `/healthz`, `/v1/ticks`, `/v1/chart`
|
||||
- UI: `trade.mpabi.pl`
|
||||
- Ingest: logi `trade-ingestor` + napływ ticków do tabeli.
|
||||
|
||||
## Snapshoty i rollback (playbook)
|
||||
|
||||
### Rollback szybki (preferowany)
|
||||
|
||||
- Cofnij snapshot w repo deploy:
|
||||
- `git revert` commita, który podbił obrazy, **albo**
|
||||
- w Argo cofnij do poprzedniej rewizji (ten sam efekt).
|
||||
|
||||
Efekt: Argo wraca do poprzedniego “dobrego” zestawu obrazów i konfiguracji.
|
||||
|
||||
### Rollback bezpieczny dla “dużych” zmian (schema/ingest)
|
||||
|
||||
Jeśli zmiana dotyka danych/ingestu, rób ją jako nową wersję vN:
|
||||
- nowa tabela: `drift_ticks_vN`
|
||||
- nowa funkcja: `get_drift_candles_vN`
|
||||
- osobny deploy API/UI (inne porty/sufiksy), a ingest przełączany “cutover”.
|
||||
|
||||
W razie problemów: robisz “cut back” vN → v1 (stare dane zostają nietknięte).
|
||||
|
||||
## Lokalne uruchomienie (opcjonalne, do debugowania)
|
||||
|
||||
Dokładna instrukcja: `doc/workflow-api-ingest.md`.
|
||||
|
||||
Skrót:
|
||||
```bash
|
||||
npm install
|
||||
docker compose -f devops/db/docker-compose.yml up -d
|
||||
docker compose -f devops/tools/bootstrap/docker-compose.yml run --rm db-init
|
||||
docker compose -f devops/tools/bootstrap/docker-compose.yml run --rm hasura-bootstrap
|
||||
docker compose -f devops/app/docker-compose.yml up -d --build api
|
||||
npm run token:api -- --scopes write --out tokens/alg.json
|
||||
npm run token:api -- --scopes read --out tokens/read.json
|
||||
docker compose -f devops/app/docker-compose.yml up -d --build frontend
|
||||
docker compose -f devops/app/docker-compose.yml --profile ingest up -d --build
|
||||
```
|
||||
|
||||
### Frontend dev (Vite) z backendem na VPS (staging)
|
||||
|
||||
Jeśli chcesz szybko iterować nad UI bez deploya, możesz odpalić lokalny Vite i podpiąć go do backendu na VPS przez istniejący proxy `/api` na `trade.mpabi.pl`.
|
||||
|
||||
- Vite trzyma `VITE_API_URL=/api` (default) i proxy’uje `/api/*` do VPS.
|
||||
- UI ma też GraphQL (Hasura) pod `/graphql` (HTTP + WS subscriptions) – w dev proxy’ujemy `/graphql` i `/graphql-ws` do VPS, żeby subscriptions działały na `http://localhost:5173`.
|
||||
- Auth w staging jest w trybie `session` (`/auth/login`, cookie `trade_session`), więc w dev proxy’ujemy też `/whoami`, `/auth/*`, `/logout`.
|
||||
- Dev proxy usuwa `Secure` z `Set-Cookie`, żeby cookie działało na `http://localhost:5173`.
|
||||
- Na VPS `trade-frontend` proxy’uje dalej do `trade-api` i wstrzykuje read-token **server-side** (token nie trafia do przeglądarki).
|
||||
|
||||
Przykład:
|
||||
|
||||
```bash
|
||||
cd apps/visualizer
|
||||
bash __start
|
||||
```
|
||||
|
||||
Jeśli staging ma dodatkowy basic auth (np. Traefik `basicAuth`), dodaj:
|
||||
`API_PROXY_BASIC_AUTH='USER:PASS'` albo `API_PROXY_BASIC_AUTH_FILE=tokens/frontend.json` (pola `username`/`password`).
|
||||
|
||||
## Definicja “done” dla zmiany
|
||||
|
||||
- Jest snapshot (commit w deploy) i można wrócić jednym ruchem.
|
||||
- Staging działa (API/ingest/UI) i ma podstawowe smoke-checki.
|
||||
- Sekrety nie zostały dodane do repo ani do logów/komentarzy.
|
||||
@@ -16,6 +16,8 @@ const STARTED_AT = new Date().toISOString();
|
||||
|
||||
const STATIC_DIR = process.env.STATIC_DIR || '/srv';
|
||||
const BASIC_AUTH_FILE = process.env.BASIC_AUTH_FILE || '/tokens/frontend.json';
|
||||
const API_READ_TOKEN_FILE = process.env.API_READ_TOKEN_FILE || '/tokens/read.json';
|
||||
const API_UPSTREAM = process.env.API_UPSTREAM || process.env.API_URL || 'http://api:8787';
|
||||
const HASURA_UPSTREAM = process.env.HASURA_UPSTREAM || 'http://hasura:8080';
|
||||
const HASURA_GRAPHQL_PATH = process.env.HASURA_GRAPHQL_PATH || '/v1/graphql';
|
||||
const GRAPHQL_CORS_ORIGIN = process.env.GRAPHQL_CORS_ORIGIN || process.env.CORS_ORIGIN || '*';
|
||||
@@ -66,6 +68,13 @@ function loadBasicAuth() {
|
||||
return { username, password };
|
||||
}
|
||||
|
||||
function loadApiReadToken() {
|
||||
const j = readJson(API_READ_TOKEN_FILE);
|
||||
const token = (j?.token || '').toString();
|
||||
if (!token) throw new Error(`Invalid API_READ_TOKEN_FILE: ${API_READ_TOKEN_FILE}`);
|
||||
return token;
|
||||
}
|
||||
|
||||
function send(res, status, headers, body) {
|
||||
res.statusCode = status;
|
||||
for (const [k, v] of Object.entries(headers || {})) res.setHeader(k, v);
|
||||
@@ -359,6 +368,56 @@ function readBody(req, limitBytes = 1024 * 16) {
|
||||
});
|
||||
}
|
||||
|
||||
function proxyApi(req, res, apiReadToken) {
|
||||
const upstreamBase = new URL(API_UPSTREAM);
|
||||
const inUrl = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
|
||||
|
||||
const prefix = '/api';
|
||||
const strippedPath = inUrl.pathname === prefix ? '/' : inUrl.pathname.startsWith(prefix + '/') ? inUrl.pathname.slice(prefix.length) : null;
|
||||
if (strippedPath == null) {
|
||||
send(res, 404, { 'content-type': 'text/plain; charset=utf-8' }, 'not_found');
|
||||
return;
|
||||
}
|
||||
|
||||
const target = new URL(upstreamBase.toString());
|
||||
target.pathname = strippedPath || '/';
|
||||
target.search = inUrl.search;
|
||||
|
||||
const isHttps = target.protocol === 'https:';
|
||||
const lib = isHttps ? https : http;
|
||||
|
||||
const headers = stripHopByHopHeaders(req.headers);
|
||||
delete headers.authorization; // basic auth from client must not leak upstream
|
||||
headers.host = target.host;
|
||||
headers.authorization = `Bearer ${apiReadToken}`;
|
||||
|
||||
const upstreamReq = lib.request(
|
||||
{
|
||||
protocol: target.protocol,
|
||||
hostname: target.hostname,
|
||||
port: target.port || (isHttps ? 443 : 80),
|
||||
method: req.method,
|
||||
path: target.pathname + target.search,
|
||||
headers,
|
||||
},
|
||||
(upstreamRes) => {
|
||||
const outHeaders = stripHopByHopHeaders(upstreamRes.headers);
|
||||
res.writeHead(upstreamRes.statusCode || 502, outHeaders);
|
||||
upstreamRes.pipe(res);
|
||||
}
|
||||
);
|
||||
|
||||
upstreamReq.on('error', (err) => {
|
||||
if (!res.headersSent) {
|
||||
send(res, 502, { 'content-type': 'text/plain; charset=utf-8' }, `bad_gateway: ${err?.message || err}`);
|
||||
} else {
|
||||
res.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
req.pipe(upstreamReq);
|
||||
}
|
||||
|
||||
function withCors(res) {
|
||||
res.setHeader('access-control-allow-origin', GRAPHQL_CORS_ORIGIN);
|
||||
res.setHeader('access-control-allow-methods', 'GET,POST,OPTIONS');
|
||||
@@ -581,6 +640,26 @@ async function handler(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
if (req.url?.startsWith('/api') && (req.url === '/api' || req.url.startsWith('/api/'))) {
|
||||
if (AUTH_MODE !== 'off' && AUTH_MODE !== 'none' && AUTH_MODE !== 'disabled') {
|
||||
const user = resolveAuthenticatedUser(req);
|
||||
if (!user) {
|
||||
unauthorized(res);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let token;
|
||||
try {
|
||||
token = loadApiReadToken();
|
||||
} catch (e) {
|
||||
send(res, 500, { 'content-type': 'text/plain; charset=utf-8' }, String(e?.message || e));
|
||||
return;
|
||||
}
|
||||
proxyApi(req, res, token);
|
||||
return;
|
||||
}
|
||||
|
||||
serveStatic(req, res);
|
||||
}
|
||||
|
||||
@@ -624,9 +703,11 @@ server.listen(PORT, () => {
|
||||
service: 'trade-frontend',
|
||||
port: PORT,
|
||||
staticDir: STATIC_DIR,
|
||||
apiUpstream: API_UPSTREAM,
|
||||
hasuraUpstream: HASURA_UPSTREAM,
|
||||
basicAuthFile: BASIC_AUTH_FILE,
|
||||
basicAuthMode: BASIC_AUTH_MODE,
|
||||
apiReadTokenFile: API_READ_TOKEN_FILE,
|
||||
authUserHeader: AUTH_USER_HEADER,
|
||||
authMode: AUTH_MODE,
|
||||
htpasswdFile: HTPASSWD_FILE,
|
||||
|
||||
Reference in New Issue
Block a user