diff --git a/terminal/src/app/components/BalanceAnalysis.tsx b/terminal/src/app/components/BalanceAnalysis.tsx index e4833d143..c99f0f858 100644 --- a/terminal/src/app/components/BalanceAnalysis.tsx +++ b/terminal/src/app/components/BalanceAnalysis.tsx @@ -1,15 +1,20 @@ -import { Box, Card, Grid, Title } from "@mantine/core"; +import { Box, Card, Grid, Title, Tooltip } from "@mantine/core"; import { type FC } from "react"; +import { selectBot } from "../../features/bots/botSlice"; import { type BalanceData } from "../../features/features.types"; -import { type MarketType } from "../../utils/enums"; import { roundDecimals } from "../../utils/math"; +import { useAppSelector } from "../hooks"; import { useRiskBeta } from "../hooks/useRiskBeta"; const BalanceAnalysis: FC<{ accountData: BalanceData; - marketType: MarketType; -}> = ({ accountData, marketType }) => { - const { beta, isLoading: loadingBeta } = useRiskBeta(accountData, marketType); +}> = ({ accountData }) => { + const { bot } = useAppSelector(selectBot); + + const { beta, isLoading: loadingBeta } = useRiskBeta( + bot.pair, + bot.market_type, + ); return ( @@ -49,14 +54,22 @@ const BalanceAnalysis: FC<{ - Risk beta (BTC) + + + Symbol risk beta (BTC) + + {loadingBeta ? "Calculating..." : beta === null - ? "—" + ? "Unavailable" : beta.toFixed(2)} diff --git a/terminal/src/app/components/OrderBookAnalysis.tsx b/terminal/src/app/components/OrderBookAnalysis.tsx index 403aaf88f..d1d62ca94 100644 --- a/terminal/src/app/components/OrderBookAnalysis.tsx +++ b/terminal/src/app/components/OrderBookAnalysis.tsx @@ -1,8 +1,9 @@ -import { Alert, SimpleGrid } from "@mantine/core"; +import { Alert, Grid, SimpleGrid } from "@mantine/core"; import { getApiErrorMessage } from "../../utils/api"; import { useMicrostructureData } from "../hooks/useMicrostructureData"; import SpreadAndDepthCard from "./SpreadAndDepthCard"; import SymbolCvdCard from "./SymbolCvdCard"; +import SymbolTradesCard from "./SymbolTradesCard"; const OrderBookAnalysis = ({ enabled, @@ -35,6 +36,11 @@ const OrderBookAnalysis = ({ /> + + + + + ); }; diff --git a/terminal/src/app/components/SymbolTradesCard.tsx b/terminal/src/app/components/SymbolTradesCard.tsx new file mode 100644 index 000000000..31dbc96d0 --- /dev/null +++ b/terminal/src/app/components/SymbolTradesCard.tsx @@ -0,0 +1,172 @@ +import { Box, Group, Text, Title } from "@mantine/core"; +import { useEffect, useMemo, useState } from "react"; +import { + useFuturesContractQuery, + useFuturesTradesQuery, +} from "../../features/kucoinApiSlice"; +import { + summarizeRecentTrades, + TRADES_POLL_INTERVAL_MS, + TRADES_WINDOW_MS, +} from "../../features/kucoinTrades"; +import LivePlotlyChart from "./LivePlotlyChart"; + +type SymbolTradesCardProps = { + symbol: string; + enabled: boolean; +}; + +const BUY_COLOR = "#198754"; + +const SELL_COLOR = "#dc3545"; + +const CHART_HEIGHT = 300; + +const formatUsdt = (value: number) => + value.toLocaleString(undefined, { maximumFractionDigits: 0 }); + +const SymbolTradesCard = ({ symbol, enabled }: SymbolTradesCardProps) => { + const skip = !enabled || !symbol; + + const { + currentData: trades, + isFetching, + isError, + } = useFuturesTradesQuery(symbol, { + skip, + pollingInterval: TRADES_POLL_INTERVAL_MS, + refetchOnMountOrArgChange: true, + }); + + const { currentData: contract } = useFuturesContractQuery(symbol, { skip }); + + const [now, setNow] = useState(Date.now); + + // Advance the window only when a poll returns different trades. RTK Query + // keeps the same array when nothing changed, so a quiet contract stays still. + useEffect(() => { + setNow(Date.now()); + }, [trades]); + + // Slow tick so old trades still expire from a quiet contract. + useEffect(() => { + const interval = setInterval(() => setNow(Date.now()), 30_000); + + return () => clearInterval(interval); + }, []); + + const summary = useMemo( + () => + trades && contract + ? summarizeRecentTrades(trades, contract.multiplier, now) + : undefined, + [trades, contract, now], + ); + + const data = useMemo(() => { + const points = summary?.trades ?? []; + + return ["buy", "sell"].map((side) => { + const sidePoints = points.filter((trade) => trade.side === side); + + return { + type: "scatter", + mode: "lines+markers", + line: { color: side === "buy" ? BUY_COLOR : SELL_COLOR, width: 1.5 }, + name: side === "buy" ? "Buy (taker)" : "Sell (taker)", + x: sidePoints.map(({ timestamp }) => new Date(timestamp).toISOString()), + y: sidePoints.map(({ price }) => price), + ids: sidePoints.map(({ tradeId }) => tradeId), + customdata: sidePoints.map(({ notional }) => notional), + marker: { + color: side === "buy" ? BUY_COLOR : SELL_COLOR, + opacity: 0.75, + size: sidePoints.map(({ notional }) => + Math.min(28, Math.max(6, Math.sqrt(notional) / 2)), + ), + }, + hovertemplate: + "%{x|%H:%M:%S}
Price: %{y}
Notional: %{customdata:,.0f} USDT", + }; + }); + }, [summary]); + + const layout = useMemo( + () => ({ + autosize: true, + height: CHART_HEIGHT, + showlegend: true, + legend: { orientation: "h", y: 1.12 }, + margin: { t: 20, l: 80, r: 20, b: 50 }, + xaxis: { + type: "date", + range: [ + new Date(now - TRADES_WINDOW_MS).toISOString(), + new Date(now).toISOString(), + ], + title: { text: "Last 5 minutes" }, + }, + yaxis: { + autorange: true, + title: { text: "Price (USDT)", standoff: 16 }, + automargin: true, + }, + }), + [now], + ); + + if (skip) return Enter a symbol; + + return ( + + + Market trades + + Executed taker trades on the contract in the last 5 minutes. Marker + size is USDT notional. + + + {summary && ( + + + Buy: {formatUsdt(summary.buy)} USDT + + + Sell: {formatUsdt(summary.sell)} USDT + + + Delta: {formatUsdt(summary.delta)} USDT + + + {summary.trades.length} trades + + + )} + + {!summary && isFetching && ( + Loading {symbol} trades… + )} + {isError && ( + {symbol} trades could not be refreshed. + )} + {summary && !summary.trades.length && ( + No trades for {symbol} in the last 5 minutes. + )} + {!!summary?.trades.length && ( + + )} + + + Smaller horizontal gaps mean trades happen more frequently. +
+ Larger vertical changes between dots mean larger price moves. Check the + y-axis to judge their size. +
+ Positive delta: buyers eating sellers' offers (buy pressure), with more + USDT traded by buyers taking offers than sellers taking bids. +
+
+ ); +}; + +export default SymbolTradesCard; diff --git a/terminal/src/app/components/tests/BalanceAnalysis.test.tsx b/terminal/src/app/components/tests/BalanceAnalysis.test.tsx index ce098de5b..787fe00b4 100644 --- a/terminal/src/app/components/tests/BalanceAnalysis.test.tsx +++ b/terminal/src/app/components/tests/BalanceAnalysis.test.tsx @@ -1,12 +1,16 @@ import "@testing-library/jest-dom"; +import { Provider } from "react-redux"; import { describe as describeBlock, expect as expectValue, it as testCase, vi, } from "vitest"; +import { type Bot } from "../../../features/bots/botInitialState"; +import { resetBot, setField } from "../../../features/bots/botSlice"; +import { makeStore } from "../../store"; import { MarketType } from "../../../utils/enums"; -import { render, screen as rtlScreen } from "../../../utils/render"; +import { act, render, screen as rtlScreen } from "../../../utils/render"; const useRiskBeta = vi.hoisted(() => vi.fn()); @@ -24,6 +28,18 @@ const accountData = { total_deposit: 0, }; +function renderBalanceAnalysis(bot: Partial) { + const store = makeStore(); + + store.dispatch(resetBot(bot)); + render( + + + , + ); + return store; +} + describeBlock("BalanceAnalysis risk beta", () => { testCase("shows BTC beta calculated from 15-minute spot returns", () => { useRiskBeta.mockReturnValue({ @@ -31,34 +47,80 @@ describeBlock("BalanceAnalysis risk beta", () => { isLoading: false, }); - render( - , - ); + renderBalanceAnalysis({ pair: "ETHUSDT", market_type: MarketType.SPOT }); - expectValue(rtlScreen.getByText("Risk beta (BTC)")).toBeInTheDocument(); + expectValue( + rtlScreen.getByText("Symbol risk beta (BTC)"), + ).toBeInTheDocument(); expectValue(rtlScreen.getByText("0.46")).toBeInTheDocument(); - expectValue(useRiskBeta).toHaveBeenCalledWith(accountData, MarketType.SPOT); + expectValue(useRiskBeta).toHaveBeenCalledWith("ETHUSDT", MarketType.SPOT); }); - testCase("shows beta for live futures positions", () => { + testCase("shows beta for the selected futures symbol", () => { useRiskBeta.mockReturnValue({ beta: -1.2345, isLoading: false, }); - render( - , - ); + renderBalanceAnalysis({ + pair: "HAEDALUSDTM", + market_type: MarketType.FUTURES, + }); expectValue(rtlScreen.getByText("-1.23")).toBeInTheDocument(); expectValue(useRiskBeta).toHaveBeenCalledWith( - accountData, + "HAEDALUSDTM", + MarketType.FUTURES, + ); + }); + + testCase.each([ + { beta: null, isLoading: true, label: "Calculating..." }, + { beta: null, isLoading: false, label: "Unavailable" }, + ])( + "shows $label while beta cannot be displayed", + ({ beta, isLoading, label }) => { + useRiskBeta.mockReturnValue({ beta, isLoading }); + + renderBalanceAnalysis({ + pair: "HAEDALUSDTM", + market_type: MarketType.FUTURES, + }); + + expectValue(rtlScreen.getByText(label)).toBeInTheDocument(); + }, + ); + + testCase("follows bot replacement and symbol edits in botSlice", () => { + useRiskBeta.mockReturnValue({ beta: 1, isLoading: false }); + + const store = renderBalanceAnalysis({ + pair: "ETHUSDT", + market_type: MarketType.SPOT, + }); + + expectValue(useRiskBeta).toHaveBeenLastCalledWith( + "ETHUSDT", + MarketType.SPOT, + ); + + act(() => { + store.dispatch( + resetBot({ pair: "HAEDALUSDTM", market_type: MarketType.FUTURES }), + ); + }); + + expectValue(useRiskBeta).toHaveBeenLastCalledWith( + "HAEDALUSDTM", + MarketType.FUTURES, + ); + + act(() => { + store.dispatch(setField({ name: "pair", value: "ETHUSDTM" })); + }); + + expectValue(useRiskBeta).toHaveBeenLastCalledWith( + "ETHUSDTM", MarketType.FUTURES, ); }); diff --git a/terminal/src/app/components/tests/BotChartTabs.test.tsx b/terminal/src/app/components/tests/BotChartTabs.test.tsx index 2fbf10f5b..032ed20b3 100644 --- a/terminal/src/app/components/tests/BotChartTabs.test.tsx +++ b/terminal/src/app/components/tests/BotChartTabs.test.tsx @@ -25,6 +25,9 @@ vi.mock("../ChartContainer", () => ({ vi.mock("../SpreadAndDepthCard", () => ({ default: () =>
Shared order book charts
, })); +vi.mock("../SymbolTradesCard", () => ({ + default: () =>
Market trades card
, +})); vi.mock("../LivePlotlyChart", () => ({ default: () =>
Stored CVD chart
, })); diff --git a/terminal/src/app/components/tests/SymbolTradesCard.test.tsx b/terminal/src/app/components/tests/SymbolTradesCard.test.tsx new file mode 100644 index 000000000..6f89dbb55 --- /dev/null +++ b/terminal/src/app/components/tests/SymbolTradesCard.test.tsx @@ -0,0 +1,89 @@ +import "@testing-library/jest-dom"; +import { vi } from "vitest"; +import { + useFuturesContractQuery, + useFuturesTradesQuery, +} from "../../../features/kucoinApiSlice"; +import { render, screen as testingScreen } from "../../../utils/render"; +import SymbolTradesCard from "../SymbolTradesCard"; + +vi.mock("../../../features/kucoinApiSlice", () => ({ + useFuturesTradesQuery: vi.fn(), + useFuturesContractQuery: vi.fn(), +})); +vi.mock("../LivePlotlyChart", () => ({ + default: (props: { data: unknown }) => ( +
{JSON.stringify(props.data)}
+ ), +})); + +const respond = (trades: unknown, extra: Record = {}) => { + vi.mocked(useFuturesTradesQuery).mockReturnValue({ + currentData: trades, + refetch: vi.fn(), + isFetching: false, + isError: false, + ...extra, + } as ReturnType); + vi.mocked(useFuturesContractQuery).mockReturnValue({ + refetch: vi.fn(), + currentData: { symbol: "SOLUSDTM", multiplier: 1 }, + } as ReturnType); +}; + +describe("symbol market trades", () => { + it("summarizes taker buy and sell notional from the last 5 minutes only", () => { + const now = Date.now(); + + respond([ + { tradeId: "a", side: "buy", price: 10, size: 5, timestamp: now - 2_000 }, + { + tradeId: "b", + side: "sell", + price: 10, + size: 2, + timestamp: now - 1_000, + }, + { + tradeId: "c", + side: "buy", + price: 10, + size: 99, + timestamp: now - 400_000, + }, + ]); + + render(); + + expect(testingScreen.getByText("2 trades")).toBeInTheDocument(); + expect(testingScreen.getByTestId("chart")).toBeInTheDocument(); + }); + + it("says when the contract had no trades in the last 5 minutes", () => { + respond([ + { + tradeId: "old", + side: "buy", + price: 10, + size: 5, + timestamp: Date.now() - 400_000, + }, + ]); + + render(); + + expect( + testingScreen.getByText("No trades for SOLUSDTM in the last 5 minutes."), + ).toBeInTheDocument(); + }); + + it("shows an alert when the trade request fails", () => { + respond(undefined, { isError: true }); + + render(); + + expect(testingScreen.getByRole("alert")).toHaveTextContent( + "SOLUSDTM trades could not be refreshed.", + ); + }); +}); diff --git a/terminal/src/app/hooks/useRiskBeta.test.ts b/terminal/src/app/hooks/useRiskBeta.test.ts index 9159e20f9..0f780a2a5 100644 --- a/terminal/src/app/hooks/useRiskBeta.test.ts +++ b/terminal/src/app/hooks/useRiskBeta.test.ts @@ -1,20 +1,32 @@ +import { act, renderHook, waitFor } from "@testing-library/react"; import { afterEach as afterEachTest, + beforeEach as beforeEachTest, describe as describeBlock, expect as expectValue, it as testCase, vi, } from "vitest"; -import { ExchangeId } from "../../utils/enums"; -import { loadCandles } from "./useRiskBeta"; +import { ExchangeId, MarketType } from "../../utils/enums"; +import { FIFTEEN_MINUTES_MS } from "../../utils/riskBeta"; +import { loadCandles, useRiskBeta } from "./useRiskBeta"; + +const useGetSettingsQuery = vi.hoisted(() => vi.fn()); + +vi.mock("../../features/autotradeApiSlice", () => ({ + useGetSettingsQuery, +})); const completedBefore = 1_710_000_900_000; const signal = new AbortController().signal; -describeBlock("15-minute beta candle requests", () => { - afterEachTest(() => vi.unstubAllGlobals()); +afterEachTest(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); +describeBlock("15-minute beta candle requests", () => { testCase("reads Binance's close at index four", async () => { const fetchMock = vi.fn().mockResolvedValue({ ok: true, @@ -89,3 +101,152 @@ describeBlock("15-minute beta candle requests", () => { expectValue(fetchMock.mock.calls[0][0]).toContain("granularity=15"); }); }); + +describeBlock("selected symbol beta", () => { + function futuresRows(beta: number) { + let close = 100; + + return Array.from({ length: 97 }, (_, index) => { + if (index > 0) close *= 1 + beta * [0.01, -0.02, 0.02, -0.01][index % 4]; + return [ + completedBefore - (97 - index) * FIFTEEN_MINUTES_MS, + 0, + 0, + 0, + close, + ]; + }); + } + + const response = (beta: number) => ({ + ok: true, + json: async () => ({ data: futuresRows(beta) }), + }); + + beforeEachTest(() => { + vi.spyOn(Date, "now").mockReturnValue(completedBefore); + useGetSettingsQuery.mockReturnValue({ + data: { exchange_id: ExchangeId.KUCOIN, fiat: "USDT" }, + isLoading: false, + }); + }); + + testCase( + "calculates HAEDAL beta on a new-bot page from its candles", + async () => { + const fetchMock = vi.fn(async (url: string) => + response(url.includes("symbol=HAEDALUSDTM") ? 1.5 : 1), + ); + + vi.stubGlobal("fetch", fetchMock); + + const { result } = renderHook(() => + useRiskBeta("HAEDALUSDTM", MarketType.FUTURES), + ); + + expectValue(result.current.isLoading).toBe(true); + await waitFor(() => expectValue(result.current.isLoading).toBe(false)); + expectValue(result.current.beta).toBeCloseTo(1.5, 10); + expectValue( + fetchMock.mock.calls.map(([url]) => + new URL(url, "http://localhost").searchParams.get("symbol"), + ), + ).toEqual(["XBTUSDTM", "HAEDALUSDTM"]); + }, + ); + + testCase( + "BTC has beta one and shares the benchmark candle request", + async () => { + const fetchMock = vi.fn(async () => response(1)); + + vi.stubGlobal("fetch", fetchMock); + + const { result } = renderHook(() => + useRiskBeta("XBTUSDTM", MarketType.FUTURES), + ); + + await waitFor(() => expectValue(result.current.isLoading).toBe(false)); + expectValue(result.current.beta).toBe(1); + expectValue(fetchMock).toHaveBeenCalledTimes(1); + }, + ); + + testCase( + "recalculates when selecting another symbol and ignores stale responses", + async () => { + let resolveOldRequest!: (value: ReturnType) => void; + + const oldRequest = new Promise>((resolve) => { + resolveOldRequest = resolve; + }); + + const fetchMock = vi.fn((url: string, _options: RequestInit) => { + if (url.includes("symbol=HAEDALUSDTM")) return oldRequest; + return Promise.resolve( + response(url.includes("symbol=ETHUSDTM") ? -0.5 : 1), + ); + }); + + vi.stubGlobal("fetch", fetchMock); + + const { result, rerender } = renderHook( + ({ symbol }) => useRiskBeta(symbol, MarketType.FUTURES), + { initialProps: { symbol: "HAEDALUSDTM" } }, + ); + + const oldSignal = fetchMock.mock.calls[0][1].signal; + + rerender({ symbol: "ETHUSDTM" }); + + expectValue(oldSignal?.aborted).toBe(true); + await waitFor(() => expectValue(result.current.isLoading).toBe(false)); + expectValue(result.current.beta).toBeCloseTo(-0.5, 10); + + await act(async () => resolveOldRequest(response(3))); + expectValue(result.current.beta).toBeCloseTo(-0.5, 10); + }, + ); + + testCase("uses the selected KuCoin spot pair's quote currency", async () => { + const fetchMock = vi.fn(async (url: string) => ({ + ok: true, + json: async () => ({ + data: futuresRows(url.includes("symbol=ETH-USDC") ? 1.5 : 1).map( + ([timestamp, , , , close]) => [timestamp / 1000, 0, close, 0, 0], + ), + }), + })); + + vi.stubGlobal("fetch", fetchMock); + + const { result } = renderHook(() => + useRiskBeta("ETH-USDC", MarketType.SPOT), + ); + + await waitFor(() => expectValue(result.current.isLoading).toBe(false)); + expectValue(result.current.beta).toBeCloseTo(1.5, 10); + expectValue(fetchMock.mock.calls[0][0]).toContain("symbol=BTC-USDC"); + }); + + testCase.each(["failed request", "insufficient history"])( + "reports unavailable for %s", + async (reason) => { + vi.stubGlobal( + "fetch", + vi.fn(async () => ({ + ok: reason !== "failed request", + status: 503, + json: async () => ({ data: futuresRows(1).slice(-10) }), + })), + ); + + const { result } = renderHook(() => + useRiskBeta("HAEDALUSDTM", MarketType.FUTURES), + ); + + await waitFor(() => expectValue(result.current.isLoading).toBe(false)); + expectValue(result.current.beta).toBeNull(); + }, + ); +}); diff --git a/terminal/src/app/hooks/useRiskBeta.ts b/terminal/src/app/hooks/useRiskBeta.ts index 1eca1eb4e..ee02ea393 100644 --- a/terminal/src/app/hooks/useRiskBeta.ts +++ b/terminal/src/app/hooks/useRiskBeta.ts @@ -1,30 +1,14 @@ import { useEffect, useState } from "react"; import { useGetSettingsQuery } from "../../features/autotradeApiSlice"; -import { useGetBotsQuery } from "../../features/bots/botsApiSlice"; -import { type BalanceData } from "../../features/features.types"; -import { buildBackUrl } from "../../utils/api"; -import { BotStatus, ExchangeId, MarketType } from "../../utils/enums"; -import { getToken } from "../../utils/login"; +import { ExchangeId, MarketType } from "../../utils/enums"; import { floorToMultiple } from "../../utils/math"; import { calculateRiskBeta, FIFTEEN_MINUTES_MS, RISK_BETA_CANDLE_COUNT, type CandleClose, - type RiskExposure, } from "../../utils/riskBeta"; -async function fetchJson(url: string, signal: AbortSignal, token?: string) { - const response = await fetch(url, { - signal, - headers: token ? { Authorization: `Bearer ${token}` } : undefined, - }); - - if (!response.ok) - throw new Error(`Risk beta data request failed: ${response.status}`); - return response.json(); -} - export async function loadCandles( symbol: string, exchange: ExchangeId, @@ -65,10 +49,15 @@ export async function loadCandles( url = `/binance/api/v3/klines?${params}`; } - const response = await fetchJson(url, signal); + const response = await fetch(url, { signal }); + + if (!response.ok) + throw new Error(`Risk beta data request failed: ${response.status}`); + + const payload = await response.json(); const rows = - exchange === ExchangeId.BINANCE && !futures ? response : response.data; + exchange === ExchangeId.BINANCE && !futures ? payload : payload.data; if (!Array.isArray(rows)) throw new Error("Invalid candlestick response"); return rows.map((row: unknown) => { @@ -82,25 +71,30 @@ export async function loadCandles( }); } -export function useRiskBeta(accountData: BalanceData, marketType: MarketType) { +export function useRiskBeta(symbol: string, marketType: MarketType) { const { data: settings, isLoading: loadingSettings } = useGetSettingsQuery(); - const { data: activeBots, isLoading: loadingBots } = useGetBotsQuery( - { status: BotStatus.ACTIVE }, - { skip: marketType !== MarketType.FUTURES }, - ); + const exchange = settings?.exchange_id; + + const fiat = settings?.fiat; const [beta, setBeta] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { - if (loadingSettings || (marketType === MarketType.FUTURES && loadingBots)) { + setBeta(null); + if (loadingSettings) { setIsLoading(true); return; } - if (!settings || (marketType === MarketType.FUTURES && !activeBots)) { - setBeta(null); + if ( + !symbol || + !exchange || + !fiat || + (marketType === MarketType.FUTURES && + (exchange !== ExchangeId.KUCOIN || !symbol.endsWith("USDTM"))) + ) { setIsLoading(false); return; } @@ -109,127 +103,39 @@ export function useRiskBeta(accountData: BalanceData, marketType: MarketType) { const completedBefore = floorToMultiple(Date.now(), FIFTEEN_MINUTES_MS); - const exchange = settings.exchange_id; + const futures = marketType === MarketType.FUTURES; - const fiat = accountData.fiat_currency; + const benchmarkSymbol = futures + ? "XBTUSDTM" + : exchange === ExchangeId.KUCOIN + ? `BTC-${symbol.split("-")[1] ?? fiat}` + : `BTC${fiat}`; - setBeta(null); setIsLoading(true); - async function calculate() { - if ( - marketType === MarketType.FUTURES && - (exchange !== ExchangeId.KUCOIN || fiat !== "USDT") - ) { - return null; - } - - const benchmarkSymbol = - marketType === MarketType.FUTURES - ? "XBTUSDTM" - : exchange === ExchangeId.KUCOIN - ? `BTC-${fiat}` - : `BTC${fiat}`; - - const benchmark = await loadCandles( - benchmarkSymbol, - exchange, - completedBefore, - controller.signal, - marketType === MarketType.FUTURES, - ); - - let exposures: RiskExposure[]; - - if (marketType === MarketType.FUTURES) { - const pairs = [ - ...new Set( - activeBots!.bots.ids - .map((id) => activeBots!.bots.entities[id]) - .filter((bot) => bot?.market_type === MarketType.FUTURES) - .map((bot) => bot!.pair), + const benchmarkRequest = loadCandles( + benchmarkSymbol, + exchange, + completedBefore, + controller.signal, + futures, + ); + + Promise.all([ + benchmarkRequest, + symbol === benchmarkSymbol + ? benchmarkRequest + : loadCandles( + symbol, + exchange, + completedBefore, + controller.signal, + futures, ), - ]; - - exposures = ( - await Promise.all( - pairs.map(async (pair) => { - const positionResponse = await fetchJson( - `${buildBackUrl()}/order/kucoin/futures/position/${encodeURIComponent(pair)}`, - controller.signal, - getToken(), - ); - - if (positionResponse.error) - throw new Error("Position request failed"); - - const position = positionResponse.data; - - if (!position?.is_open || !position.current_qty) return null; - if (position.is_inverse || position.settle_currency !== fiat) { - throw new Error("Unsupported futures position"); - } - - const [contractResponse, candles] = await Promise.all([ - fetchJson( - `/kucoin-futures/api/v1/contracts/${encodeURIComponent(pair)}`, - controller.signal, - ), - pair === benchmarkSymbol - ? Promise.resolve(benchmark) - : loadCandles( - pair, - exchange, - completedBefore, - controller.signal, - true, - ), - ]); - - const multiplier = Number(contractResponse.data?.multiplier); - - if (!Number.isFinite(multiplier) || multiplier <= 0) { - throw new Error("Invalid futures contract multiplier"); - } - return { - quantity: Number(position.current_qty) * multiplier, - candles, - }; - }), - ) - ).filter((exposure): exposure is RiskExposure => exposure !== null); - } else { - exposures = await Promise.all( - Object.entries(accountData.balances) - .filter(([asset, quantity]) => asset !== fiat && quantity > 0) - .map(async ([asset, quantity]) => ({ - quantity, - candles: - asset === "BTC" - ? benchmark - : await loadCandles( - exchange === ExchangeId.KUCOIN - ? `${asset}-${fiat}` - : `${asset}${fiat}`, - exchange, - completedBefore, - controller.signal, - ), - })), - ); - } - - return calculateRiskBeta( - benchmark, - exposures, - accountData.estimated_total_fiat, - completedBefore, - ); - } - - calculate() - .then((value) => { - if (!controller.signal.aborted) setBeta(value); + ]) + .then(([benchmark, asset]) => { + if (!controller.signal.aborted) + setBeta(calculateRiskBeta(benchmark, asset, completedBefore)); }) .catch(() => { if (!controller.signal.aborted) setBeta(null); @@ -239,14 +145,7 @@ export function useRiskBeta(accountData: BalanceData, marketType: MarketType) { }); return () => controller.abort(); - }, [ - accountData, - activeBots, - loadingBots, - loadingSettings, - marketType, - settings, - ]); + }, [symbol, marketType, exchange, fiat, loadingSettings]); return { beta, isLoading }; } diff --git a/terminal/src/app/pages/BotDetail.tsx b/terminal/src/app/pages/BotDetail.tsx index 717b95280..246b5fe2e 100644 --- a/terminal/src/app/pages/BotDetail.tsx +++ b/terminal/src/app/pages/BotDetail.tsx @@ -96,12 +96,7 @@ export const BotDetail: FC<{}> = () => {
- {accountData && ( - - )} + {accountData && } diff --git a/terminal/src/app/pages/FuturesBotDetail.tsx b/terminal/src/app/pages/FuturesBotDetail.tsx index 2550d9a05..32f86f90c 100644 --- a/terminal/src/app/pages/FuturesBotDetail.tsx +++ b/terminal/src/app/pages/FuturesBotDetail.tsx @@ -143,12 +143,7 @@ export const FuturesBotDetail: FC<{}> = () => { - {accountData && ( - - )} + {accountData && } diff --git a/terminal/src/app/pages/tests/FuturesBotDetail.test.tsx b/terminal/src/app/pages/tests/FuturesBotDetail.test.tsx index 6aab67d37..452fbc0d1 100644 --- a/terminal/src/app/pages/tests/FuturesBotDetail.test.tsx +++ b/terminal/src/app/pages/tests/FuturesBotDetail.test.tsx @@ -127,9 +127,7 @@ vi.mock("../../components/BotDetailTabs", () => { return { default: BotDetailTabs }; }); vi.mock("../../components/BalanceAnalysis", () => { - const BalanceAnalysis = (_props: any) => ( -
- ); + const BalanceAnalysis = () =>
; BalanceAnalysis.displayName = "BalanceAnalysis"; return { default: BalanceAnalysis }; @@ -327,7 +325,7 @@ describe("FuturesBotDetail page", () => { - + { const state = store.getState().bot.bot; - expect(state.pair).toBe("KOMAUSDTM"); + expect(state.pair).toBe("HAEDALUSDTM"); expect(state.market_type).toBe(MarketType.FUTURES); }); diff --git a/terminal/src/features/kucoinApiSlice.ts b/terminal/src/features/kucoinApiSlice.ts index e2b21eb5e..dd1bc6e36 100644 --- a/terminal/src/features/kucoinApiSlice.ts +++ b/terminal/src/features/kucoinApiSlice.ts @@ -6,6 +6,7 @@ import { type KucoinOrderBook, type ObiSnapshot, } from "./kucoinLiquidity"; +import type { KucoinMarketTrade } from "./kucoinTrades"; export interface KucoinFuturesTicker24 { sequence: number; @@ -196,6 +197,33 @@ export const kucoinApiSlice = createApi({ return allPercentageChanges; }, }), + futuresTrades: build.query({ + // KuCoin returns only the latest ~100 public trades, newest data first. + query: (symbol) => ({ url: "/trade/history", params: { symbol } }), + transformResponse: (response: { + code: string; + data?: { + tradeId: string; + side: "buy" | "sell"; + price: string; + size: number; + ts: number | string; + }[]; + }) => { + if (response.code !== "200000" || !response.data) { + throw new Error("KuCoin trade history request failed"); + } + + return response.data.map((trade) => ({ + tradeId: trade.tradeId, + side: trade.side, + price: Number(trade.price), + size: Number(trade.size), + // KuCoin Futures trade timestamps are Unix nanoseconds. + timestamp: Number(trade.ts) / 1_000_000, + })); + }, + }), futuresContract: build.query({ query: (symbol) => ({ url: `/contracts/${symbol}`, @@ -213,4 +241,5 @@ export const { useBtcCloseSeriesQuery, useFuturesRankingsQuery, useFuturesContractQuery, + useFuturesTradesQuery, } = kucoinApiSlice; diff --git a/terminal/src/features/kucoinTrades.test.ts b/terminal/src/features/kucoinTrades.test.ts new file mode 100644 index 000000000..5abc2a960 --- /dev/null +++ b/terminal/src/features/kucoinTrades.test.ts @@ -0,0 +1,56 @@ +import { summarizeRecentTrades, type KucoinMarketTrade } from "./kucoinTrades"; + +const NOW = 1_000_000; + +const trade = ( + overrides: Partial = {}, +): KucoinMarketTrade => ({ + tradeId: "1", + side: "buy", + price: 100, + size: 10, + timestamp: NOW - 1_000, + ...overrides, +}); + +describe("recent market trades", () => { + it("values trades as price x contracts x multiplier", () => { + const { trades, buy } = summarizeRecentTrades([trade()], 0.1, NOW); + + expect(trades[0].notional).toBeCloseTo(100); + expect(buy).toBeCloseTo(100); + }); + + it("keeps only the last 5 minutes of trades", () => { + const { trades } = summarizeRecentTrades( + [ + trade({ tradeId: "old", timestamp: NOW - 300_001 }), + trade({ tradeId: "edge", timestamp: NOW - 300_000 }), + trade({ tradeId: "future", timestamp: NOW + 1 }), + ], + 1, + NOW, + ); + + expect(trades.map(({ tradeId }) => tradeId)).toEqual(["edge"]); + }); + + it("reports aggressive buy minus sell as the delta, oldest trade first", () => { + const summary = summarizeRecentTrades( + [ + trade({ tradeId: "sell", side: "sell", size: 4, timestamp: NOW - 500 }), + trade({ tradeId: "buy", side: "buy", size: 10, timestamp: NOW - 900 }), + ], + 1, + NOW, + ); + + expect(summary.buy).toBe(1000); + expect(summary.sell).toBe(400); + expect(summary.delta).toBe(600); + expect(summary.trades.map(({ tradeId }) => tradeId)).toEqual([ + "buy", + "sell", + ]); + }); +}); diff --git a/terminal/src/features/kucoinTrades.ts b/terminal/src/features/kucoinTrades.ts new file mode 100644 index 000000000..ae53ff03c --- /dev/null +++ b/terminal/src/features/kucoinTrades.ts @@ -0,0 +1,49 @@ +export const TRADES_WINDOW_MS = 5 * 60_000; + +export const TRADES_POLL_INTERVAL_MS = 5_000; + +export interface KucoinMarketTrade { + tradeId: string; + side: "buy" | "sell"; + price: number; + /** Contracts, not base-asset units. */ + size: number; + /** Milliseconds since the Unix epoch. */ + timestamp: number; +} + +export interface KucoinTradesSummary { + trades: (KucoinMarketTrade & { notional: number })[]; + buy: number; + sell: number; + delta: number; +} + +/** + * Keep trades from the last window and value them in USDT. + * Notional is price x contracts x multiplier, the same formula the stored CVD uses. + */ +export const summarizeRecentTrades = ( + trades: KucoinMarketTrade[], + multiplier: number, + now: number, + windowMs = TRADES_WINDOW_MS, +): KucoinTradesSummary => { + const recent = trades + .filter(({ timestamp }) => timestamp >= now - windowMs && timestamp <= now) + .sort((left, right) => left.timestamp - right.timestamp) + .map((trade) => ({ + ...trade, + notional: trade.price * trade.size * multiplier, + })); + + const buy = recent + .filter(({ side }) => side === "buy") + .reduce((total, { notional }) => total + notional, 0); + + const sell = recent + .filter(({ side }) => side === "sell") + .reduce((total, { notional }) => total + notional, 0); + + return { trades: recent, buy, sell, delta: buy - sell }; +}; diff --git a/terminal/src/utils/riskBeta.test.ts b/terminal/src/utils/riskBeta.test.ts index 54cfb328e..9da05743d 100644 --- a/terminal/src/utils/riskBeta.test.ts +++ b/terminal/src/utils/riskBeta.test.ts @@ -11,72 +11,76 @@ import { const completedBefore = 100 * FIFTEEN_MINUTES_MS; -const btcCandles: CandleClose[] = Array.from({ length: 97 }, (_, index) => ({ - timestamp: (index + 3) * FIFTEEN_MINUTES_MS, - close: 100 + index + (index % 3) * 2, -})); +function candlesWithBeta(beta: number): CandleClose[] { + let close = 100; -describeBlock("BTC risk beta from completed 15-minute returns", () => { - testCase( - "a BTC-only holding has beta one and ignores a forming candle", - () => { - const formingCandle = { - timestamp: completedBefore, - close: 999999, - }; + return Array.from({ length: 97 }, (_, index) => { + if (index > 0) close *= 1 + beta * [0.01, -0.02, 0.02, -0.01][index % 4]; + return { timestamp: (index + 3) * FIFTEEN_MINUTES_MS, close }; + }); +} - const result = calculateRiskBeta( - [...btcCandles, formingCandle], - [{ quantity: 1, candles: [...btcCandles, formingCandle] }], - btcCandles.at(-1)!.close, - completedBefore, - ); +const btcCandles = candlesWithBeta(1); - expectValue(result).toBe(1); - }, - ); +describeBlock( + "symbol beta against BTC from completed 15-minute returns", + () => { + testCase.each([1, 1.5, -2, 0])( + "calculates beta %s from the asset's own returns", + (beta) => { + expectValue( + calculateRiskBeta(btcCandles, candlesWithBeta(beta), completedBefore), + ).toBeCloseTo(beta, 10); + }, + ); - testCase( - "cash has zero beta and a short BTC position has negative beta", - () => { - expectValue(calculateRiskBeta(btcCandles, [], 200, completedBefore)).toBe( - 0, - ); + testCase("excludes a forming candle from both series", () => { expectValue( calculateRiskBeta( - btcCandles, - [{ quantity: -1, candles: btcCandles }], - 300, + [...btcCandles, { timestamp: completedBefore, close: 999999 }], + [...candlesWithBeta(1.5), { timestamp: completedBefore, close: 1 }], completedBefore, ), - ).toBeLessThan(0); - }, - ); + ).toBeCloseTo(1.5, 10); + }); - testCase( - "requires aligned, consecutive candles with benchmark variance", - () => { - const shiftedCandles = btcCandles.map(({ timestamp, close }) => ({ - timestamp: timestamp + 60_000, - close, - })); + testCase( + "sorts candles and uses only matching consecutive intervals", + () => { + const asset = candlesWithBeta(1.5).filter((_, index) => index !== 50); + expectValue( + calculateRiskBeta([...btcCandles].reverse(), asset, completedBefore), + ).toBeCloseTo(1.5, 10); + }, + ); + + testCase("requires at least twenty aligned returns", () => { expectValue( - calculateRiskBeta( - btcCandles, - [{ quantity: 1, candles: shiftedCandles }], - 200, - completedBefore, - ), + calculateRiskBeta(btcCandles, btcCandles.slice(-20), completedBefore), ).toBeNull(); expectValue( - calculateRiskBeta( - btcCandles.map((candle) => ({ ...candle, close: 100 })), - [], - 200, - completedBefore, - ), - ).toBeNull(); - }, - ); -}); + calculateRiskBeta(btcCandles, btcCandles.slice(-21), completedBefore), + ).toBe(1); + }); + + testCase( + "returns unavailable for misaligned candles or a flat benchmark", + () => { + expectValue( + calculateRiskBeta( + btcCandles, + btcCandles.map((candle) => ({ + ...candle, + timestamp: candle.timestamp + 60000, + })), + completedBefore, + ), + ).toBeNull(); + expectValue( + calculateRiskBeta(candlesWithBeta(0), btcCandles, completedBefore), + ).toBeNull(); + }, + ); + }, +); diff --git a/terminal/src/utils/riskBeta.ts b/terminal/src/utils/riskBeta.ts index 6882862eb..289f49392 100644 --- a/terminal/src/utils/riskBeta.ts +++ b/terminal/src/utils/riskBeta.ts @@ -3,11 +3,6 @@ export interface CandleClose { close: number; } -export interface RiskExposure { - quantity: number; - candles: CandleClose[]; -} - export const FIFTEEN_MINUTES_MS = 15 * 60 * 1000; export const RISK_BETA_CANDLE_COUNT = 97; @@ -16,12 +11,9 @@ const MIN_RETURNS = 20; export function calculateRiskBeta( benchmarkCandles: CandleClose[], - exposures: RiskExposure[], - accountValue: number, + assetCandles: CandleClose[], completedBefore: number, ): number | null { - if (!Number.isFinite(accountValue) || accountValue <= 0) return null; - const completedCloses = (candles: CandleClose[]) => new Map( candles @@ -38,52 +30,38 @@ export function calculateRiskBeta( const benchmark = completedCloses(benchmarkCandles); - const prices = exposures.map(({ candles }) => completedCloses(candles)); + const asset = completedCloses(assetCandles); const timestamps = [...benchmark.keys()] - .filter((timestamp) => prices.every((series) => series.has(timestamp))) + .filter((timestamp) => asset.has(timestamp)) .sort((left, right) => left - right) .slice(-RISK_BETA_CANDLE_COUNT); if (timestamps.length < MIN_RETURNS + 1) return null; - const latest = timestamps[timestamps.length - 1]; - - const latestPrices = prices.map((series) => series.get(latest)!); - - const portfolioReturns: number[] = []; + const assetReturns: number[] = []; const benchmarkReturns: number[] = []; let previousTimestamp: number | undefined; - let previousValue: number | undefined; + let previousAssetPrice: number | undefined; let previousBenchmark: number | undefined; for (const timestamp of timestamps) { - const value = - accountValue + - exposures.reduce( - (change, exposure, index) => - change + - exposure.quantity * - (prices[index].get(timestamp)! - latestPrices[index]), - 0, - ); - - if (value <= 0) return null; + const assetPrice = asset.get(timestamp)!; const benchmarkPrice = benchmark.get(timestamp)!; if ( previousTimestamp === timestamp - FIFTEEN_MINUTES_MS && - previousValue !== undefined && + previousAssetPrice !== undefined && previousBenchmark !== undefined ) { - portfolioReturns.push(value / previousValue - 1); + assetReturns.push(assetPrice / previousAssetPrice - 1); benchmarkReturns.push(benchmarkPrice / previousBenchmark - 1); } previousTimestamp = timestamp; - previousValue = value; + previousAssetPrice = assetPrice; previousBenchmark = benchmarkPrice; } @@ -94,8 +72,7 @@ export function calculateRiskBeta( const benchmarkMean = benchmarkReturns.reduce((sum, value) => sum + value, 0) / count; - const portfolioMean = - portfolioReturns.reduce((sum, value) => sum + value, 0) / count; + const assetMean = assetReturns.reduce((sum, value) => sum + value, 0) / count; const variance = benchmarkReturns.reduce( (sum, value) => sum + (value - benchmarkMean) ** 2, @@ -106,9 +83,11 @@ export function calculateRiskBeta( const covariance = benchmarkReturns.reduce( (sum, value, index) => - sum + (value - benchmarkMean) * (portfolioReturns[index] - portfolioMean), + sum + (value - benchmarkMean) * (assetReturns[index] - assetMean), 0, ); - return Math.round((covariance / variance) * 10000) / 10000; + const beta = covariance / variance; + + return Number.isFinite(beta) ? beta : null; }