Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions terminal/src/app/components/BalanceAnalysis.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<Card mb="md">
Expand Down Expand Up @@ -49,14 +54,22 @@ const BalanceAnalysis: FC<{
</Grid.Col>
</Grid>
<Grid mb="lg">
<Grid.Col span={6}>Risk beta (BTC)</Grid.Col>
<Grid.Col span={6}>
<Tooltip
label={`${bot.pair || "Selected symbol"} sensitivity to BTC, using completed 15-minute returns over the past 24 hours.`}
multiline
w={280}
>
<span>Symbol risk beta (BTC)</span>
</Tooltip>
</Grid.Col>
<Grid.Col span={6} ta="right">
<Box c="primary.8" component="div">
<strong>
{loadingBeta
? "Calculating..."
: beta === null
? "—"
? "Unavailable"
: beta.toFixed(2)}
</strong>
</Box>
Expand Down
8 changes: 7 additions & 1 deletion terminal/src/app/components/OrderBookAnalysis.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -35,6 +36,11 @@ const OrderBookAnalysis = ({
/>
<SymbolCvdCard symbol={symbol} enabled={enabled} />
</SimpleGrid>
<Grid mt="md">
<Grid.Col span={{ base: 12, md: 6 }}>
<SymbolTradesCard symbol={symbol} enabled={enabled} />
</Grid.Col>
</Grid>
</>
);
};
Expand Down
172 changes: 172 additions & 0 deletions terminal/src/app/components/SymbolTradesCard.tsx
Original file line number Diff line number Diff line change
@@ -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 });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle contract-query failures and provide a retry path

If the contract request fails on initial load, successful trade responses still cannot produce a summary because contract remains undefined. Only the trade query's loading and error states are rendered, so the card becomes blank without explaining the failure. Polling trades does not retry the separate contract query. Include the contract query's loading/error states and provide a way to retry it so a transient contract-request failure does not leave the chart unavailable for the rest of the mounted session.

Useful? React with 👍 / 👎.


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}<br>Price: %{y}<br>Notional: %{customdata:,.0f} USDT<extra></extra>",
};
});
}, [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 <Text>Enter a symbol</Text>;

return (
<Box>
<Box mb="sm">
<Title order={5}>Market trades</Title>
<Text c="dimmed" mb={0}>
Executed taker trades on the contract in the last 5 minutes. Marker
size is USDT notional.
</Text>
</Box>
{summary && (
<Group mb="sm" gap="lg">
<Text mb={0}>
Buy: <strong>{formatUsdt(summary.buy)}</strong> USDT
</Text>
<Text mb={0}>
Sell: <strong>{formatUsdt(summary.sell)}</strong> USDT
</Text>
<Text mb={0}>
Delta: <strong>{formatUsdt(summary.delta)}</strong> USDT
</Text>
<Text mb={0} c="dimmed">
{summary.trades.length} trades
</Text>
</Group>
)}
<Box mih={CHART_HEIGHT}>
{!summary && isFetching && (
<Text role="status">Loading {symbol} trades…</Text>
)}
{isError && (
<Text role="alert">{symbol} trades could not be refreshed.</Text>
)}
{summary && !summary.trades.length && (
<Text>No trades for {symbol} in the last 5 minutes.</Text>
)}
{!!summary?.trades.length && (
<LivePlotlyChart data={data} layout={layout} />
)}
</Box>
<Text c="dimmed" mt="sm" mb={0}>
Smaller horizontal gaps mean trades happen more frequently.
<br />
Larger vertical changes between dots mean larger price moves. Check the
y-axis to judge their size.
<br />
Positive delta: buyers eating sellers&apos; offers (buy pressure), with more
USDT traded by buyers taking offers than sellers taking bids.
</Text>
</Box>
);
};

export default SymbolTradesCard;
96 changes: 79 additions & 17 deletions terminal/src/app/components/tests/BalanceAnalysis.test.tsx
Original file line number Diff line number Diff line change
@@ -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());

Expand All @@ -24,41 +28,99 @@ const accountData = {
total_deposit: 0,
};

function renderBalanceAnalysis(bot: Partial<Bot>) {
const store = makeStore();

store.dispatch(resetBot(bot));
render(
<Provider store={store}>
<BalanceAnalysis accountData={accountData} />
</Provider>,
);
return store;
}

describeBlock("BalanceAnalysis risk beta", () => {
testCase("shows BTC beta calculated from 15-minute spot returns", () => {
useRiskBeta.mockReturnValue({
beta: 0.4567,
isLoading: false,
});

render(
<BalanceAnalysis
accountData={accountData}
marketType={MarketType.SPOT}
/>,
);
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(
<BalanceAnalysis
accountData={accountData}
marketType={MarketType.FUTURES}
/>,
);
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,
);
});
Expand Down
3 changes: 3 additions & 0 deletions terminal/src/app/components/tests/BotChartTabs.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ vi.mock("../ChartContainer", () => ({
vi.mock("../SpreadAndDepthCard", () => ({
default: () => <div>Shared order book charts</div>,
}));
vi.mock("../SymbolTradesCard", () => ({
default: () => <div>Market trades card</div>,
}));
vi.mock("../LivePlotlyChart", () => ({
default: () => <div>Stored CVD chart</div>,
}));
Expand Down
Loading
Loading