From 93dd0f39210554e16fd6dfd424ea0b149ecbd38e Mon Sep 17 00:00:00 2001 From: carkod Date: Sun, 29 Nov 2026 16:13:56 +0000 Subject: [PATCH 1/2] Add PnL estimation --- docs/fastest-movers.md | 3 - terminal/src/app/components/PnlAnalysis.tsx | 64 ++++++++ .../app/components/tests/PnlAnalysis.test.tsx | 92 +++++++++++ terminal/src/app/pages/BotDetail.tsx | 2 + terminal/src/app/pages/FuturesBotDetail.tsx | 2 + .../src/features/bots/estimatedPnl.test.ts | 145 ++++++++++++++++++ terminal/src/features/bots/estimatedPnl.ts | 80 ++++++++++ 7 files changed, 385 insertions(+), 3 deletions(-) create mode 100644 terminal/src/app/components/PnlAnalysis.tsx create mode 100644 terminal/src/app/components/tests/PnlAnalysis.test.tsx create mode 100644 terminal/src/features/bots/estimatedPnl.test.ts create mode 100644 terminal/src/features/bots/estimatedPnl.ts diff --git a/docs/fastest-movers.md b/docs/fastest-movers.md index 1ea01ea10..9f15ae762 100644 --- a/docs/fastest-movers.md +++ b/docs/fastest-movers.md @@ -27,6 +27,3 @@ ranking list, provided the three-hour move is at least +3% for gainers or at mos in the same list does not trigger a later alert merely by crossing this threshold. The threshold filters notifications; dashboard rankings retain all qualifying one-hour movers. - -Each alert includes a Dashboard trade link to `/bots/futures/new/`, -using the configured `FRONTEND_DOMAIN`, matching Binquant strategy alerts. diff --git a/terminal/src/app/components/PnlAnalysis.tsx b/terminal/src/app/components/PnlAnalysis.tsx new file mode 100644 index 000000000..ea9c05ddb --- /dev/null +++ b/terminal/src/app/components/PnlAnalysis.tsx @@ -0,0 +1,64 @@ +import { Card, Grid, Text, Title } from "@mantine/core"; +import { selectBot } from "../../features/bots/botSlice"; +import { estimateBotExitPnl } from "../../features/bots/estimatedPnl"; +import { useFuturesContractQuery } from "../../features/kucoinApiSlice"; +import { MarketType } from "../../utils/enums"; +import { useAppSelector, useSymbolData } from "../hooks"; + +export default function PnlAnalysis() { + const { bot, previewStopLossSettings, previewTrailingSettings } = + useAppSelector(selectBot); + + const { futuresLeverage } = useSymbolData(); + + const isFutures = bot.market_type === MarketType.FUTURES; + + const { currentData: contract } = useFuturesContractQuery(bot.pair, { + skip: !isFutures || !bot.pair || !bot.deal?.base_order_size, + }); + + const estimates = estimateBotExitPnl(bot, { + contractMultiplier: contract?.multiplier, + futuresLeverage, + previewStopLossSettings, + previewTrailingSettings, + }); + + const currency = isFutures ? "USDT" : bot.quote_asset; + + return ( + + + Estimated PnL + + {[ + { label: "Stop loss", value: estimates.stopLoss }, + { label: "Take profit", value: estimates.takeProfit }, + ].map(({ label, value }) => ( + + {label} + + + {value === null + ? "Unavailable" + : `${value > 0 ? "+" : ""}${value.toFixed(2)} ${currency}`} + + + + ))} + + Based on base order size and entry price. Excludes fees and slippage. + {bot.trailing && " Take profit estimates PnL at trailing activation."} + + + ); +} diff --git a/terminal/src/app/components/tests/PnlAnalysis.test.tsx b/terminal/src/app/components/tests/PnlAnalysis.test.tsx new file mode 100644 index 000000000..1317377e0 --- /dev/null +++ b/terminal/src/app/components/tests/PnlAnalysis.test.tsx @@ -0,0 +1,92 @@ +import { Provider } from "react-redux"; +import { vi } from "vitest"; +import { singleBot, type Bot } from "../../../features/bots/botInitialState"; +import { resetBot, setField } from "../../../features/bots/botSlice"; +import { EntryMode, MarketType } from "../../../utils/enums"; +import { act, render, screen } from "../../../utils/render"; +import { SymbolContext } from "../../hooks"; +import { makeStore } from "../../store"; +import PnlAnalysis from "../PnlAnalysis"; + +const contractQuery = vi.hoisted(() => vi.fn()); + +vi.mock("../../../features/kucoinApiSlice", async () => ({ + ...(await vi.importActual("../../../features/kucoinApiSlice")), + useFuturesContractQuery: contractQuery, +})); + +function renderPnl(bot: Partial = {}) { + contractQuery.mockReturnValue({ currentData: { multiplier: 0.01 } }); + + const store = makeStore(); + + store.dispatch( + resetBot({ + ...singleBot, + market_type: MarketType.FUTURES, + fiat_order_size: 100, + entry_mode: EntryMode.CONDITIONAL_LIMIT, + entry_price: 100, + futures_leverage: 2, + stop_loss: 5, + take_profit: 10, + ...bot, + }), + ); + render( + + + + + , + ); + return store; +} + +it("updates both estimates as order size and exit settings change", () => { + const store = renderPnl(); + + expect(screen.getByRole("heading", { name: "Estimated PnL" })).toBeTruthy(); + expect(screen.getByText("-10.00 USDT")).toBeTruthy(); + expect(screen.getByText("+20.00 USDT")).toBeTruthy(); + + act(() => { + store.dispatch(setField({ name: "fiat_order_size", value: 200 })); + store.dispatch(setField({ name: "stop_loss", value: 2 })); + store.dispatch(setField({ name: "take_profit", value: 3 })); + }); + + expect(screen.getByText("-8.00 USDT")).toBeTruthy(); + expect(screen.getByText("+12.00 USDT")).toBeTruthy(); +}); + +it("updates saved-contract estimates when the conditional entry price changes", () => { + const store = renderPnl({ + pair: "BTCUSDTM", + deal: { ...singleBot.deal, base_order_size: 200 }, + }); + + expect(screen.getByText("+20.00 USDT")).toBeTruthy(); + + act(() => { + store.dispatch(setField({ name: "entry_price", value: 50 })); + }); + + expect(screen.getByText("-5.00 USDT")).toBeTruthy(); + expect(screen.getByText("+10.00 USDT")).toBeTruthy(); +}); + +it("shows unavailable until an order size is entered", () => { + renderPnl({ fiat_order_size: 0 }); + + expect(screen.getAllByText("Unavailable")).toHaveLength(2); +}); diff --git a/terminal/src/app/pages/BotDetail.tsx b/terminal/src/app/pages/BotDetail.tsx index 246b5fe2e..80ca21d7c 100644 --- a/terminal/src/app/pages/BotDetail.tsx +++ b/terminal/src/app/pages/BotDetail.tsx @@ -15,6 +15,7 @@ import BotChartTabs from "../components/BotChartTabs"; import BotDetailTabs from "../components/BotDetailTabs"; import BotInfo from "../components/BotInfo"; import LogsInfo from "../components/LogsInfo"; +import PnlAnalysis from "../components/PnlAnalysis"; import { useAppDispatch, useAppSelector } from "../hooks"; import { SymbolProvider } from "../providers/SymbolProvider"; import { SpinnerContext } from "../spinner-context"; @@ -97,6 +98,7 @@ export const BotDetail: FC<{}> = () => { {accountData && } + diff --git a/terminal/src/app/pages/FuturesBotDetail.tsx b/terminal/src/app/pages/FuturesBotDetail.tsx index 32f86f90c..af3377b77 100644 --- a/terminal/src/app/pages/FuturesBotDetail.tsx +++ b/terminal/src/app/pages/FuturesBotDetail.tsx @@ -15,6 +15,7 @@ import BotChartTabs from "../components/BotChartTabs"; import BotDetailTabs from "../components/BotDetailTabs"; import BotInfo from "../components/BotInfo"; import LogsInfo from "../components/LogsInfo"; +import PnlAnalysis from "../components/PnlAnalysis"; import { useAppDispatch, useAppSelector } from "../hooks"; import { SymbolProvider } from "../providers/SymbolProvider"; import { SpinnerContext } from "../spinner-context"; @@ -144,6 +145,7 @@ export const FuturesBotDetail: FC<{}> = () => { {accountData && } + diff --git a/terminal/src/features/bots/estimatedPnl.test.ts b/terminal/src/features/bots/estimatedPnl.test.ts new file mode 100644 index 000000000..fb17f6a34 --- /dev/null +++ b/terminal/src/features/bots/estimatedPnl.test.ts @@ -0,0 +1,145 @@ +import { + BotPosition, + EntryMode, + MarketType, + QuoteAsset, +} from "../../utils/enums"; +import { singleBot, type Bot } from "./botInitialState"; +import { estimateBotExitPnl } from "./estimatedPnl"; + +const makeBot = (overrides: Partial = {}): Bot => ({ + ...singleBot, + fiat_order_size: 100, + fiat: "USDT", + quote_asset: QuoteAsset.USDT, + market_type: MarketType.FUTURES, + stop_loss: 6.5, + take_profit: 10, + ...overrides, + deal: { + ...singleBot.deal, + current_price: 100, + ...overrides.deal, + }, +}); + +describe("estimated exit PnL", () => { + it.each([BotPosition.LONG, BotPosition.SHORT])( + "sizes a new %s futures position from margin and leverage", + (position) => { + expect( + estimateBotExitPnl(makeBot({ position, futures_leverage: 3 })), + ).toEqual({ + stopLoss: expect.closeTo(-19.5, 8), + takeProfit: expect.closeTo(30, 8), + }); + }, + ); + + it("uses symbol leverage until the bot has an override", () => { + expect(estimateBotExitPnl(makeBot(), { futuresLeverage: 2 })).toEqual({ + stopLoss: expect.closeTo(-13, 8), + takeProfit: expect.closeTo(20, 8), + }); + }); + + it("values saved contracts with their multiplier without applying leverage again", () => { + const bot = makeBot({ + futures_leverage: 5, + deal: { ...singleBot.deal, base_order_size: 200, opening_price: 100 }, + }); + + expect(estimateBotExitPnl(bot, { contractMultiplier: 0.01 })).toEqual({ + stopLoss: expect.closeTo(-13, 8), + takeProfit: expect.closeTo(20, 8), + }); + expect(estimateBotExitPnl(bot)).toEqual({ + stopLoss: null, + takeProfit: null, + }); + }); + + it("uses filled entry and saved exit prices rather than the live market price", () => { + const bot = makeBot({ + position: BotPosition.SHORT, + deal: { + ...singleBot.deal, + current_price: 200, + opening_price: 100, + base_order_size: 20, + stop_loss_price: 104, + take_profit_price: 88, + }, + }); + + expect(estimateBotExitPnl(bot, { contractMultiplier: 0.1 })).toEqual({ + stopLoss: expect.closeTo(-8, 8), + takeProfit: expect.closeTo(24, 8), + }); + expect( + estimateBotExitPnl(bot, { + contractMultiplier: 0.1, + previewStopLossSettings: true, + previewTrailingSettings: true, + }), + ).toEqual({ + stopLoss: expect.closeTo(-13, 8), + takeProfit: expect.closeTo(20, 8), + }); + }); + + it("uses the conditional entry price when valuing saved contracts", () => { + const bot = makeBot({ + entry_mode: EntryMode.CONDITIONAL_LIMIT, + entry_price: 50, + deal: { ...singleBot.deal, base_order_size: 20, current_price: 100 }, + }); + + expect(estimateBotExitPnl(bot, { contractMultiplier: 0.1 })).toEqual({ + stopLoss: expect.closeTo(-6.5, 8), + takeProfit: expect.closeTo(10, 8), + }); + }); + + it("uses spot order spend before entry and filled asset quantity after entry", () => { + const bot = makeBot({ market_type: MarketType.SPOT }); + + expect(estimateBotExitPnl(bot)).toEqual({ + stopLoss: expect.closeTo(-6.5, 8), + takeProfit: expect.closeTo(10, 8), + }); + bot.deal = { ...bot.deal, opening_price: 100, opening_qty: 2 }; + expect(estimateBotExitPnl(bot)).toEqual({ + stopLoss: expect.closeTo(-13, 8), + takeProfit: expect.closeTo(20, 8), + }); + bot.deal = { ...bot.deal, opening_qty: 0, base_order_size: 200 }; + expect(estimateBotExitPnl(bot)).toEqual({ + stopLoss: expect.closeTo(-13, 8), + takeProfit: expect.closeTo(20, 8), + }); + }); + + it("estimates the trailing activation threshold when trailing is enabled", () => { + expect( + estimateBotExitPnl(makeBot({ trailing: true, trailing_profit: 5 })), + ).toEqual({ + stopLoss: expect.closeTo(-6.5, 8), + takeProfit: expect.closeTo(5, 8), + }); + }); + + it("shows unavailable for disabled exits or missing price and size", () => { + expect(estimateBotExitPnl(makeBot({ stop_loss: 0 }))).toEqual({ + stopLoss: null, + takeProfit: expect.closeTo(10, 8), + }); + expect(estimateBotExitPnl(makeBot({ fiat_order_size: 0 }))).toEqual({ + stopLoss: null, + takeProfit: null, + }); + expect( + estimateBotExitPnl(makeBot({ deal: { ...singleBot.deal } })), + ).toEqual({ stopLoss: null, takeProfit: null }); + }); +}); diff --git a/terminal/src/features/bots/estimatedPnl.ts b/terminal/src/features/bots/estimatedPnl.ts new file mode 100644 index 000000000..b79974e5a --- /dev/null +++ b/terminal/src/features/bots/estimatedPnl.ts @@ -0,0 +1,80 @@ +import { entryReferencePrice } from "../../utils/charting/editing"; +import { BotPosition, MarketType } from "../../utils/enums"; +import type { Bot } from "./botInitialState"; + +/** Gross exit PnL in the pair's quote currency, before fees and slippage. */ +export function estimateBotExitPnl( + bot: Bot, + { + contractMultiplier = null, + futuresLeverage = 1, + previewStopLossSettings = false, + previewTrailingSettings = false, + }: { + contractMultiplier?: number | null; + futuresLeverage?: number; + previewStopLossSettings?: boolean; + previewTrailingSettings?: boolean; + } = {}, +): { stopLoss: number | null; takeProfit: number | null } { + const unavailable = { stopLoss: null, takeProfit: null }; + + const entryPrice = entryReferencePrice(bot, bot.deal?.current_price ?? 0); + + if (!Number.isFinite(entryPrice) || entryPrice <= 0) return unavailable; + + const baseOrderSize = bot.deal?.base_order_size ?? 0; + + let quantity: number; + + if (bot.market_type === MarketType.FUTURES) { + if (baseOrderSize > 0) { + if (!Number.isFinite(contractMultiplier) || contractMultiplier <= 0) + return unavailable; + // The saved base order is already a leveraged contract quantity. + quantity = baseOrderSize * contractMultiplier; + } else { + quantity = + (bot.fiat_order_size * (bot.futures_leverage ?? futuresLeverage)) / + entryPrice; + } + } else if (bot.deal?.opening_qty > 0) { + quantity = bot.deal.opening_qty; + } else if (baseOrderSize > 0) { + quantity = baseOrderSize / entryPrice; + } else { + if (bot.fiat !== bot.quote_asset) return unavailable; + quantity = bot.fiat_order_size / entryPrice; + } + + if (!Number.isFinite(quantity) || quantity <= 0) return unavailable; + + const direction = bot.position === BotPosition.SHORT ? -1 : 1; + + const profitPercentage = bot.trailing ? bot.trailing_profit : bot.take_profit; + + const storedProfitPrice = bot.trailing + ? bot.deal?.trailing_profit_price + : bot.deal?.take_profit_price; + + const stopPrice = previewStopLossSettings + ? entryPrice * (1 - (direction * bot.stop_loss) / 100) + : bot.deal?.stop_loss_price || + entryPrice * (1 - (direction * bot.stop_loss) / 100); + + const profitPrice = previewTrailingSettings + ? entryPrice * (1 + (direction * profitPercentage) / 100) + : storedProfitPrice || + entryPrice * (1 + (direction * profitPercentage) / 100); + + return { + stopLoss: + bot.stop_loss > 0 && Number.isFinite(stopPrice) && stopPrice > 0 + ? (stopPrice - entryPrice) * quantity * direction + : null, + takeProfit: + profitPercentage > 0 && Number.isFinite(profitPrice) && profitPrice > 0 + ? (profitPrice - entryPrice) * quantity * direction + : null, + }; +} From 9e22a0b75d21962413826f684ba22c3e578e2b6d Mon Sep 17 00:00:00 2001 From: carkod Date: Sun, 29 Nov 2026 18:06:21 +0000 Subject: [PATCH 2/2] Fix base order size interactions not updating PnL section of account breakdown --- terminal/src/app/components/BaseOrderTab.tsx | 55 +++++-- .../components/tests/BaseOrderTab.test.tsx | 136 +++++++++++++++++- .../app/components/tests/PnlAnalysis.test.tsx | 22 ++- .../src/features/bots/estimatedPnl.test.ts | 39 +++++ terminal/src/features/bots/estimatedPnl.ts | 11 +- 5 files changed, 242 insertions(+), 21 deletions(-) diff --git a/terminal/src/app/components/BaseOrderTab.tsx b/terminal/src/app/components/BaseOrderTab.tsx index 5a3aef7a2..887edcfb3 100644 --- a/terminal/src/app/components/BaseOrderTab.tsx +++ b/terminal/src/app/components/BaseOrderTab.tsx @@ -76,14 +76,17 @@ const BaseOrderTab: FC<{ const entryPriceEditedRef = useRef(false); + const fiatOrderSizeEditedRef = useRef(false); + const initializedSymbolRef = useRef(null); const { register, + getValues, setValue, watch, reset, - formState: { errors, touchedFields }, + formState: { errors }, } = useForm({ mode: "onTouched", reValidateMode: "onBlur", @@ -114,19 +117,31 @@ const BaseOrderTab: FC<{ }; const addAvailableFiat = () => { - if (fiatAvailable) { - dispatch(setField({ name: "fiat_order_size", value: fiatAvailable })); + if (fiatAvailable > 0) { + fiatOrderSizeEditedRef.current = true; + setValue("fiat_order_size", fiatAvailable, { + shouldDirty: true, + shouldTouch: true, + shouldValidate: true, + }); } }; useEffect(() => { - const { unsubscribe } = watch((v, { name }) => { - if (v && v?.[name]) { - if (typeof v === "boolean") { - dispatch(setToggle({ name, value: v[name] })); - } else { - dispatch(setField({ name, value: v[name] })); - } + const { unsubscribe } = watch((values, { name }) => { + const value = name ? values[name] : undefined; + + if ( + !name || + value === undefined || + (typeof value === "number" && !Number.isFinite(value)) + ) { + return; + } + if (typeof value === "boolean") { + dispatch(setToggle({ name, value })); + } else { + dispatch(setField({ name, value })); } }); @@ -154,10 +169,10 @@ const BaseOrderTab: FC<{ isBusyBot, ]); useEffect(() => { - if (!touchedFields.fiat_order_size) { + if (getValues("fiat_order_size") !== bot.fiat_order_size) { setValue("fiat_order_size", bot.fiat_order_size); } - }, [bot.fiat_order_size, setValue, touchedFields.fiat_order_size]); + }, [bot.fiat_order_size, getValues, setValue]); useEffect(() => { if (!symbol || id) { initializedSymbolRef.current = null; @@ -188,7 +203,7 @@ const BaseOrderTab: FC<{ dispatch(setField({ name: "quote_asset", value: quoteAsset })); } if ( - !touchedFields.fiat_order_size && + !fiatOrderSizeEditedRef.current && bot.fiat_order_size === 0 && bot.status === BotStatus.INACTIVE && isNewRoute @@ -226,7 +241,6 @@ const BaseOrderTab: FC<{ loadingSettings, quoteAsset, setSpinner, - touchedFields.fiat_order_size, ]); return ( @@ -280,6 +294,19 @@ const BaseOrderTab: FC<{ {...register("fiat_order_size", { required: "Fiat order size is required", valueAsNumber: true, + onChange: () => { + fiatOrderSizeEditedRef.current = true; + }, + onBlur: (event) => { + const value = event.target.valueAsNumber; + + dispatch( + setField({ + name: "fiat_order_size", + value: Number.isFinite(value) ? value : 0, + }), + ); + }, })} id="fiat_order_size" /> diff --git a/terminal/src/app/components/tests/BaseOrderTab.test.tsx b/terminal/src/app/components/tests/BaseOrderTab.test.tsx index 64b92b883..930e9b629 100644 --- a/terminal/src/app/components/tests/BaseOrderTab.test.tsx +++ b/terminal/src/app/components/tests/BaseOrderTab.test.tsx @@ -29,6 +29,7 @@ import { import { SymbolContext } from "../../hooks"; import { makeStore } from "../../store"; import BaseOrderTab from "../BaseOrderTab"; +import PnlAnalysis from "../PnlAnalysis"; const settingsResponse = vi.hoisted(() => ({ data: { fiat: "USDT", base_order_size: 123 }, @@ -44,6 +45,11 @@ vi.mock("../../../features/autotradeApiSlice", async () => { }; }); +vi.mock("../../../features/kucoinApiSlice", async () => ({ + ...(await vi.importActual("../../../features/kucoinApiSlice")), + useFuturesContractQuery: () => ({ currentData: { multiplier: 1 } }), +})); + const symbolContextValue = { symbolsList: ["BTCUSDT", "ETHUSDT"], quoteAsset: "USDT", @@ -53,7 +59,10 @@ const symbolContextValue = { isLoading: false, }; -function renderLeverage(botOverrides: Partial = {}) { +function renderLeverage( + botOverrides: Partial = {}, + fiatAvailable?: number, +) { const store = makeStore(); store.dispatch( @@ -74,7 +83,8 @@ function renderLeverage(botOverrides: Partial = {}) { - + + @@ -85,6 +95,128 @@ function renderLeverage(botOverrides: Partial = {}) { } describe("BaseOrderTab", () => { + it("updates preview PnLs after the margin input loses focus", async () => { + const user = userEvent.setup(); + + const store = renderLeverage({ + pair: "ARCUSDTM", + futures_leverage: 5, + fiat_order_size: 74.15, + stop_loss: 3, + take_profit: 6, + deal: { + ...singleBot.deal, + current_price: 0.027665, + base_order_size: 13401, + }, + }); + + const margin = testingScreen.getByRole("spinbutton", { + name: /Fiat order size/, + }); + + expect(testingScreen.getByText("-11.12 USDT")).toBeInTheDocument(); + await user.clear(margin); + await user.type(margin, "37.075"); + await user.tab(); + + expect(store.getState().bot.bot.fiat_order_size).toBe(37.075); + expect(margin).toHaveValue(37.075); + expect(testingScreen.getByText("-5.56 USDT")).toBeInTheDocument(); + expect(testingScreen.getByText("+11.12 USDT")).toBeInTheDocument(); + }); + + it("clears the preview estimates when margin is zero", async () => { + const user = userEvent.setup(); + + const store = renderLeverage({ + fiat_order_size: 74.15, + deal: { ...singleBot.deal, current_price: 0.027665 }, + }); + + const margin = testingScreen.getByRole("spinbutton", { + name: /Fiat order size/, + }); + + await user.clear(margin); + await user.type(margin, "0"); + await user.tab(); + + expect(store.getState().bot.bot.fiat_order_size).toBe(0); + expect(testingScreen.getAllByText("Unavailable")).toHaveLength(2); + }); + + it("preserves zero after replacing the automatically filled margin", async () => { + const user = userEvent.setup(); + + const store = renderLeverage( + { + fiat_order_size: 0, + deal: { ...singleBot.deal, current_price: 0.027665 }, + }, + 74.15, + ); + + const margin = testingScreen.getByRole("spinbutton", { + name: /Fiat order size/, + }); + + expect(margin).toHaveValue(74.15); + await user.clear(margin); + await user.type(margin, "0"); + await user.tab(); + + expect(margin).toHaveValue(0); + expect(store.getState().bot.bot.fiat_order_size).toBe(0); + expect(testingScreen.getAllByText("Unavailable")).toHaveLength(2); + }); + + it("clears the preview on blur when the margin input is emptied", async () => { + const user = userEvent.setup(); + + const store = renderLeverage({ + fiat_order_size: 74.15, + deal: { ...singleBot.deal, current_price: 0.027665 }, + }); + + await user.clear( + testingScreen.getByRole("spinbutton", { name: /Fiat order size/ }), + ); + await user.tab(); + + expect(store.getState().bot.bot.fiat_order_size).toBe(0); + expect(testingScreen.getAllByText("Unavailable")).toHaveLength(2); + }); + + it("fills Max and updates preview PnLs after the margin has been edited and blurred", async () => { + const user = userEvent.setup(); + + const store = renderLeverage( + { + futures_leverage: 5, + fiat_order_size: 74.15, + stop_loss: 3, + take_profit: 6, + deal: { ...singleBot.deal, current_price: 0.027665 }, + }, + 100, + ); + + const margin = testingScreen.getByRole("spinbutton", { + name: /Fiat order size/, + }); + + await user.clear(margin); + await user.type(margin, "37.075"); + await user.tab(); + await user.click(testingScreen.getByRole("button", { name: "Max" })); + + expect(margin).toHaveValue(100); + expect(store.getState().bot.bot.fiat_order_size).toBe(100); + expect(testingScreen.getByText("-15.00 USDT")).toBeInTheDocument(); + expect(testingScreen.getByText("+30.00 USDT")).toBeInTheDocument(); + }); + it("defaults to immediate with a null price and hides conditional fields", () => { const store = renderLeverage(); diff --git a/terminal/src/app/components/tests/PnlAnalysis.test.tsx b/terminal/src/app/components/tests/PnlAnalysis.test.tsx index 1317377e0..679304efb 100644 --- a/terminal/src/app/components/tests/PnlAnalysis.test.tsx +++ b/terminal/src/app/components/tests/PnlAnalysis.test.tsx @@ -2,7 +2,7 @@ import { Provider } from "react-redux"; import { vi } from "vitest"; import { singleBot, type Bot } from "../../../features/bots/botInitialState"; import { resetBot, setField } from "../../../features/bots/botSlice"; -import { EntryMode, MarketType } from "../../../utils/enums"; +import { BotStatus, EntryMode, MarketType } from "../../../utils/enums"; import { act, render, screen } from "../../../utils/render"; import { SymbolContext } from "../../hooks"; import { makeStore } from "../../store"; @@ -71,6 +71,7 @@ it("updates both estimates as order size and exit settings change", () => { it("updates saved-contract estimates when the conditional entry price changes", () => { const store = renderPnl({ + status: BotStatus.PENDING, pair: "BTCUSDTM", deal: { ...singleBot.deal, base_order_size: 200 }, }); @@ -85,6 +86,25 @@ it("updates saved-contract estimates when the conditional entry price changes", expect(screen.getByText("+10.00 USDT")).toBeTruthy(); }); +it("halves ARC stop-loss PnL when preview margin is halved at 5x leverage", () => { + const store = renderPnl({ + pair: "ARCUSDTM", + entry_price: 0.027665, + futures_leverage: 5, + fiat_order_size: 74.15, + stop_loss: 3, + deal: { ...singleBot.deal, base_order_size: 13401 }, + }); + + expect(screen.getByText("-11.12 USDT")).toBeTruthy(); + + act(() => { + store.dispatch(setField({ name: "fiat_order_size", value: 37.075 })); + }); + + expect(screen.getByText("-5.56 USDT")).toBeTruthy(); +}); + it("shows unavailable until an order size is entered", () => { renderPnl({ fiat_order_size: 0 }); diff --git a/terminal/src/features/bots/estimatedPnl.test.ts b/terminal/src/features/bots/estimatedPnl.test.ts index fb17f6a34..6e4f07d2e 100644 --- a/terminal/src/features/bots/estimatedPnl.test.ts +++ b/terminal/src/features/bots/estimatedPnl.test.ts @@ -1,5 +1,6 @@ import { BotPosition, + BotStatus, EntryMode, MarketType, QuoteAsset, @@ -45,6 +46,7 @@ describe("estimated exit PnL", () => { it("values saved contracts with their multiplier without applying leverage again", () => { const bot = makeBot({ + status: BotStatus.ACTIVE, futures_leverage: 5, deal: { ...singleBot.deal, base_order_size: 200, opening_price: 100 }, }); @@ -61,6 +63,7 @@ describe("estimated exit PnL", () => { it("uses filled entry and saved exit prices rather than the live market price", () => { const bot = makeBot({ + status: BotStatus.ACTIVE, position: BotPosition.SHORT, deal: { ...singleBot.deal, @@ -90,6 +93,7 @@ describe("estimated exit PnL", () => { it("uses the conditional entry price when valuing saved contracts", () => { const bot = makeBot({ + status: BotStatus.PENDING, entry_mode: EntryMode.CONDITIONAL_LIMIT, entry_price: 50, deal: { ...singleBot.deal, base_order_size: 20, current_price: 100 }, @@ -108,6 +112,7 @@ describe("estimated exit PnL", () => { stopLoss: expect.closeTo(-6.5, 8), takeProfit: expect.closeTo(10, 8), }); + bot.status = BotStatus.ACTIVE; bot.deal = { ...bot.deal, opening_price: 100, opening_qty: 2 }; expect(estimateBotExitPnl(bot)).toEqual({ stopLoss: expect.closeTo(-13, 8), @@ -120,6 +125,40 @@ describe("estimated exit PnL", () => { }); }); + it("recalculates an unstarted futures order from edited margin despite a saved size", () => { + const bot = makeBot({ + pair: "ARCUSDTM", + futures_leverage: 5, + fiat_order_size: 74.15, + stop_loss: 3, + deal: { + ...singleBot.deal, + base_order_size: 13401, + current_price: 0.027665, + }, + }); + + expect(estimateBotExitPnl(bot).stopLoss).toBeCloseTo(-11.1225, 8); + bot.fiat_order_size = 37.075; + expect(estimateBotExitPnl(bot).stopLoss).toBeCloseTo(-5.56125, 8); + }); + + it("keeps submitted contract exposure when the margin field changes", () => { + const bot = makeBot({ + status: BotStatus.PENDING, + futures_leverage: 5, + deal: { ...singleBot.deal, base_order_size: 200, current_price: 100 }, + }); + + expect( + estimateBotExitPnl(bot, { contractMultiplier: 0.01 }).stopLoss, + ).toBeCloseTo(-13, 8); + bot.fiat_order_size = 50; + expect( + estimateBotExitPnl(bot, { contractMultiplier: 0.01 }).stopLoss, + ).toBeCloseTo(-13, 8); + }); + it("estimates the trailing activation threshold when trailing is enabled", () => { expect( estimateBotExitPnl(makeBot({ trailing: true, trailing_profit: 5 })), diff --git a/terminal/src/features/bots/estimatedPnl.ts b/terminal/src/features/bots/estimatedPnl.ts index b79974e5a..a56ebfc79 100644 --- a/terminal/src/features/bots/estimatedPnl.ts +++ b/terminal/src/features/bots/estimatedPnl.ts @@ -1,5 +1,5 @@ import { entryReferencePrice } from "../../utils/charting/editing"; -import { BotPosition, MarketType } from "../../utils/enums"; +import { BotPosition, BotStatus, MarketType } from "../../utils/enums"; import type { Bot } from "./botInitialState"; /** Gross exit PnL in the pair's quote currency, before fees and slippage. */ @@ -25,10 +25,13 @@ export function estimateBotExitPnl( const baseOrderSize = bot.deal?.base_order_size ?? 0; + const isOrderPreview = + bot.status === BotStatus.INACTIVE && !bot.orders?.length; + let quantity: number; if (bot.market_type === MarketType.FUTURES) { - if (baseOrderSize > 0) { + if (!isOrderPreview && baseOrderSize > 0) { if (!Number.isFinite(contractMultiplier) || contractMultiplier <= 0) return unavailable; // The saved base order is already a leveraged contract quantity. @@ -38,9 +41,9 @@ export function estimateBotExitPnl( (bot.fiat_order_size * (bot.futures_leverage ?? futuresLeverage)) / entryPrice; } - } else if (bot.deal?.opening_qty > 0) { + } else if (!isOrderPreview && bot.deal?.opening_qty > 0) { quantity = bot.deal.opening_qty; - } else if (baseOrderSize > 0) { + } else if (!isOrderPreview && baseOrderSize > 0) { quantity = baseOrderSize / entryPrice; } else { if (bot.fiat !== bot.quote_asset) return unavailable;