client.profitAndLoss reads an account's profit and loss (PnL) in USD. Spot PnL uses each asset's
weighted average cost: buying raises the cost of the holding, selling realizes the proceeds minus
the average cost of what was sold, and every fee is a realized expense. Every trade is valued at
the USD price at its execution time. Deposits, withdrawals, and transfers are never PnL: deposited
coins have no known cost, and a transfer between the main account and its subaccounts carries its
cost along. Figures follow settled trades and transfers within seconds; asOf says when they were
last published. Tree-shaken builds reach the same service with profitAndLossService(core) from @polyester/sdk/services/profit-and-loss.
API keys need the read-pnl policy action, which grants no balance or trade read. Every subaccount
role includes the read_pnl permission. No method changes anything.
Every method is account-scoped, so each input accepts an optional account field ("main", "active", or { subaccountId }). The default is the active subaccount. With no active
subaccount, or with "main", a session or main-account API key reads the main account together
with every subaccount it owns, and a subaccount API key reads its own subaccount. A main-account API
key can name a subaccount its main account owns. See Account scoping for how the default resolves.
Methods
Every window ends now and starts at 00:00 UTC:
get(input, options?)
Returns the account's PnL over window, by product and by market, and the assets it holds now with
their entry price and unrealized PnL.
const pnl = await client.profitAndLoss.get({ window: "days_30" });
console.log(pnl.pnlUsd, pnl.realizedPnlUsd, pnl.unrealizedPnlUsd, pnl.notices);
for (const holding of pnl.holdings) {
console.log(
holding.assetId,
holding.positionQuantity,
holding.entryPriceUsd,
holding.unrealizedPnlUsd
);
}pnlUsd is realizedPnlUsd plus unrealizedPnlChangeUsd, the change in unrealized PnL from the
window's start to now, with transfers neutral. A holding's unrealizedPnlUsd values the quantity
with a known cost at markPriceUsd, minus costUsd; untrackedQuantity, such as deposited coins,
never counts toward PnL.
listDaily(input, options?)
Returns { days, nextPageToken, asOf }: one entry per UTC day of the range, oldest first, days
without activity included.
const DAY = 86_400_000;
const today = Math.floor(Date.now() / DAY) * DAY;
let pageToken = "";
do {
const page = await client.profitAndLoss.listDaily({
startTime: today - 29 * DAY,
endTime: today + DAY,
pageToken,
});
for (const day of page.days) console.log(day.day, day.pnlUsd, day.endEquityUsd, day.netFlowUsd);
pageToken = page.nextPageToken;
} while (pageToken !== "");An empty nextPageToken means there are no more days. A day's pnlUsd is its realized PnL plus
the change in unrealized PnL from the previous day's close to its close, with transfers neutral. startEquityUsd is everything the account owns at the 00:00 UTC that starts the day, funds
reserved by open orders and pending withdrawals included, and equals the previous day's endEquityUsd. netFlowUsd is deposits and transfers in minus withdrawals and transfers out, each
valued when it settled. Transfers between the main account and its own subaccounts count for a
single subaccount and cancel out for the main account. Today has no unrealizedPnlAtCloseUsd or endEquityUsd until it closes.
getTradingStatistics(input, options?)
Returns the trade count, volume, fees, and realized PnL over window, with the time-weighted
return, maximum drawdown, and Sharpe ratio of its closed days. Takes the same input as get. product and symbolId filter the trading figures; the return figures always cover the whole
account.
const stats = await client.profitAndLoss.getTradingStatistics({ window: "days_30" });
console.log(stats.tradeCount, stats.volumeUsd, stats.returnPct, stats.maxDrawdownPct, stats.sharpe);The return figures use closed UTC days only, from the account's first deposit on; returnDays says how many. For days_7 and days_30 they cover the 7 or 30 closed days ending at the latest
00:00 UTC whose prices are final, for lifetime every closed day, and for today none, so returnPct is null for today.
returnPctcompounds the daily returns, so deposits and withdrawals are not gains or losses. A day's return is(end - start - flow) / (start + flow / 2)of its equity and net flow; a day that starts with no equity starts at its first deposit, with return(end - flow) / flow. It is a percent, such as"1.25"for 1.25%.maxDrawdownPctis the largest fall of the compounded return from a previous peak, at day closes, in percent and never negative.sharpeis the annualized Sharpe ratio of the daily returns: their mean divided by their sample standard deviation, times the square root of 365, with no risk-free rate. It isnullwith thesharpe_insufficient_daysnotice below 7 daily returns, and also when the returns do not vary.
All three are null when a day's equity or net flow is not available, or when the window has no
closed day.
Missing prices and notices
A figure that needs a price that is not available is null, never "0". Each reply, and each day
of listDaily, carries notices, which say what its figures leave out:
A day's startEquityUsd and endEquityUsd are also null after a day with unclassified_transfer or quantity_shortfall. A notice this SDK build does not know reads "unspecified".
Errors carry no service detail. An invalid window, day range, limit, pageToken, or subaccount
throws ValidationError; an account the caller cannot read throws PermissionError or ResourceNotFoundError; ServiceUnavailableError means retry the same request.
Shapes
USD amounts and quantities are decimal strings, signed unless noted, and times are epoch milliseconds.
import type {
DailyProfitAndLoss,
HoldingProfitAndLoss,
ListDailyProfitAndLossResult,
MarketProfitAndLoss,
ProductProfitAndLoss,
ProfitAndLoss,
ProfitAndLossNotice,
ProfitAndLossWindow,
TradingStatistics,
} from "@polyester/sdk";
interface ProfitAndLoss {
windowStart: number; // inclusive
asOf: number; // when the figures were last published; trades settled just before may be missing
markTime: number; // time of the prices that value holdings now: the close of the latest whole minute
pnlUsd: string | null; // realizedPnlUsd plus unrealizedPnlChangeUsd
realizedPnlUsd: string; // the window's trades, after fees
unrealizedPnlChangeUsd: string | null; // from the window's start to now, net of transfers
unrealizedPnlUsd: string | null; // of the holdings now
feesUsd: string; // net of rebates; negative when rebates exceed fees
volumeUsd: string; // never negative
products: ProductProfitAndLoss[];
markets: MarketProfitAndLoss[]; // ordered by symbolId
holdings: HoldingProfitAndLoss[]; // ordered by assetId
notices: (ProfitAndLossNotice | "unspecified")[];
}
interface ProductProfitAndLoss {
product: "spot" | "unspecified";
realizedPnlUsd: string;
feesUsd: string;
volumeUsd: string;
}
interface MarketProfitAndLoss extends ProductProfitAndLoss {
symbolId: number;
tradeCount: string; // fills in the market in the window
}
interface HoldingProfitAndLoss {
assetId: number;
positionQuantity: string; // whole units: quantity with a known cost plus untrackedQuantity
untrackedQuantity: string; // quantity of unknown cost, such as deposited coins
costUsd: string; // cost of the quantity with a known cost, fees in the asset included
entryPriceUsd: string | null; // costUsd per unit; null when no quantity has a known cost
markPriceUsd: string | null; // current USD price per unit
unrealizedPnlUsd: string | null; // null when markPriceUsd is
}
interface ListDailyProfitAndLossResult {
days: DailyProfitAndLoss[]; // oldest first
nextPageToken: string; // "" when there are no more
asOf: number;
}
interface DailyProfitAndLoss {
day: number; // 00:00 UTC of the day
pnlUsd: string | null;
realizedPnlUsd: string;
unrealizedPnlAtCloseUsd: string | null; // null for today before it closes
feesUsd: string;
volumeUsd: string;
tradeCount: string;
notices: (ProfitAndLossNotice | "unspecified")[];
startEquityUsd: string | null; // never negative
endEquityUsd: string | null; // null for today
netFlowUsd: string | null;
}
interface TradingStatistics {
windowStart: number;
asOf: number;
tradeCount: string;
volumeUsd: string;
feesUsd: string;
realizedPnlUsd: string;
notices: (ProfitAndLossNotice | "unspecified")[];
returnPct: string | null; // time-weighted, over closed days; null for today
maxDrawdownPct: string | null;
sharpe: string | null; // annualized; null below 7 daily returns
returnDays: number; // daily returns the return figures use; today never counts
}tradeCount is a 64-bit count of fills, returned as a decimal string.
Related
- Balances for balances and portfolio equity history.
- Trades for the account's fills.
- API keys for the
read-pnlpolicy action.