# Profit and loss

Read an account's profit and loss in USD over a window, per UTC day, and as trading statistics with return, drawdown, and Sharpe ratio.

`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](https://testnet.polyester.com/docs/sdk/typescript/guides/accounts-and-balances) for how the default resolves.

## Methods

| Method                 | Summary                                                                         |
| ---------------------- | ------------------------------------------------------------------------------- |
| `get`                  | PnL over a window by product and market, and current holdings.                  |
| `listDaily`            | PnL per UTC day, oldest first, with start and end equity and net flow.          |
| `getTradingStatistics` | Trade count, volume, fees, and realized PnL, with return, drawdown, and Sharpe. |

Every window ends now and starts at 00:00 UTC:

| `window`   | Starts                                                         |
| ---------- | -------------------------------------------------------------- |
| `today`    | 00:00 UTC today.                                               |
| `days_7`   | 00:00 UTC six days ago: today and the 6 days before it.        |
| `days_30`  | 00:00 UTC 29 days ago: today and the 29 days before it.        |
| `lifetime` | 00:00 UTC of the day of the account's first trade or transfer. |

### `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.

```ts
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
	);
}
```

| Field      | Type                  | Required | Notes                                                                 |
| ---------- | --------------------- | -------- | --------------------------------------------------------------------- |
| `window`   | `ProfitAndLossWindow` | yes      | `today`, `days_7`, `days_30`, or `lifetime`.                          |
| `product`  | `"spot"`              | no       | Only this product; omit for every product.                            |
| `symbolId` | `number`              | no       | Filters `markets` only; the totals and `holdings` cover every market. |
| `account`  | `AccountScope`        | no       | Scope override.                                                       |

`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.

```ts
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 !== "");
```

| Field       | Type           | Required | Notes                                                                              |
| ----------- | -------------- | -------- | ---------------------------------------------------------------------------------- |
| `startTime` | `number`       | yes      | First day, inclusive: 00:00 UTC of a day, in epoch ms.                             |
| `endTime`   | `number`       | yes      | Day after the last one, exclusive: 00:00 UTC, at most 366 days after `startTime`.  |
| `limit`     | `number`       | no       | Days per page, at most 366; `0` or omitted uses 31.                                |
| `pageToken` | `string`       | no       | The previous `nextPageToken`, with the same `account`, `startTime`, and `endTime`. |
| `account`   | `AccountScope` | no       | Scope override.                                                                    |

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.

```ts
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`.

- `returnPct` compounds 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%.
- `maxDrawdownPct` is the largest fall of the compounded return from a previous peak, at day closes, in percent and never negative.
- `sharpe` is 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 is `null` with the `sharpe_insufficient_days` notice 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:

| Notice                     | Meaning                                                                                                                                     |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `price_unavailable`        | Some trades or transfers had no USD price at the time, so their effect is not in the USD figures. Their quantities still count.             |
| `mark_unavailable`         | A current or window-start price is not available yet for some holdings: their unrealized PnL, and every figure that includes it, is `null`. |
| `unclassified_transfer`    | Some balance changes have an unrecognized reason and are not counted.                                                                       |
| `quantity_shortfall`       | Some sales exceeded the quantity PnL knows the account held.                                                                                |
| `equity_unavailable`       | The equity at a day's start or end is not available, so the equity figures and the returns that need them are `null`.                       |
| `flow_unvalued`            | Some deposits, withdrawals, or transfers had no USD price, so the day's net flow and the returns that need it are `null`.                   |
| `sharpe_insufficient_days` | Fewer than 7 daily returns in the window, so `sharpe` is `null`.                                                                            |

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.

```ts
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](https://testnet.polyester.com/docs/sdk/typescript/reference/balances) for balances and portfolio equity history.
- [Trades](https://testnet.polyester.com/docs/sdk/typescript/reference/trades) for the account's fills.
- [API keys](https://testnet.polyester.com/docs/sdk/typescript/reference/api-keys) for the `read-pnl` policy action.
