# Historical analysis

> Markdown export of the Gearbox Protocol documentation page for agents and retrieval systems.

Canonical page: https://docs.gearbox.finance/developers/historical-analysis
Source file: content/developers/historical-analysis.mdx
Section router: https://docs.gearbox.finance/developers/llms.txt
Section full export: https://docs.gearbox.finance/developers/llms-full.txt

One call to `sdk.positions.offchain.list` returns a wallet’s current positions. Use the selected `position` for today’s values and the two history calls below for changes over time.

| What you need | Where to get it |
| --- | --- |
| Holdings and debt now | `collaterals[].collateral` per token, `totalValue` for all holdings, `totalDebt` including fees and interest |
| Equity now | Holdings minus debt: subtract the two `.value` fields for underlying, or the two `.valueUsd` fields for USD |
| Borrowing rate now | `borrowApy` (base rate including the interest fee), `borrowRate?.totalOnDebt` (including quotas), both in basis points |
| PnL now | `pnl?.organic` (before rewards), `pnl?.total` (including priced rewards) |
| Historical collateral value, debt, and base rate | [`sdk.positions.charts`](#read-historical-charts) returns `totalValueUnderlying`, `debt`, and `borrowApy` series |
| Gain since the initial deposit | Equity minus the opening deposit. If there were later flows, add withdrawals and subtract top-ups. Get the amounts from [`sdk.positions.transactions`](#compare-with-the-initial-deposit) and value each in underlying and USD on its date. |

For the monetary fields on `position`, `.value` uses token base units and `.valueUsd` is in dollars (or `null` if unpriced). Individual balances use the held token. Totals and PnL use the market underlying.

The USD field on `pnl` values the underlying gain at the snapshot price. It can differ from the dollar gain since deposit.

## Connect SDK

Follow [Connect SDK](https://docs.gearbox.finance/developers/sdk-setup). Set `offchain.baseUrl` to `https://api.gearbox.foundation` and use `offchain` or `both` mode.

## Find the account

Start with the owner’s wallet address (`owner`):

```typescript
const { data, meta } = await sdk.positions.offchain.list({
  wallet: owner,
  filter: { kind: "strategy" },
});

const accounts = data.filter(p => p.kind === "strategy");
console.table(accounts, ["chainId", "name", "creditAccount"]);
```

Choose the `chainId` and `creditAccount` from the same row. If the list is empty, check `meta.chains` for failed reads. A closed account may require your saved account address and receipts.

```typescript
import { formatUnits, isAddressEqual } from "viem";

const position = accounts.find(p =>
  p.chainId === chainId && isAddressEqual(p.creditAccount, creditAccount)
);
if (!position) throw new Error("Credit Account not found");
if (position.error) throw new Error(position.error);
const snapshot = meta.chains.find(chain => chain.chainId === chainId);
if (snapshot?.status !== "success") throw new Error("Could not read positions");

const { totalValue, totalDebt } = position;
const equityRaw = totalValue.value - totalDebt.value;
const equity = formatUnits(equityRaw, totalDebt.token.decimals);
const assetsUsd = totalValue.valueUsd;
const debtUsd = totalDebt.valueUsd;
const equityUsd = assetsUsd === null || debtUsd === null
  ? null
  : assetsUsd - debtUsd;
```

See [Monitor](https://docs.gearbox.finance/developers/monitor-position#find-your-leveraged-position) for the other position fields, including leverage and health factor.

## Read historical charts

For a one-month chart, request:

```typescript
const history = await sdk.positions.charts(
  position,
  ["totalValueUnderlying", "debt", "borrowApy", "pnl"],
  "1m",
);
```

Align each series’ `values` with `history.data.timestamps` by index. Holdings, debt, and PnL are in whole underlying tokens. For a [USD equity chart](https://docs.gearbox.finance/developers/token-amounts-and-usd#historical-values), multiply each point’s holdings minus debt by the underlying price at that timestamp. Check series status and keep missing points as gaps.

For per-token balances or a rate history including quota costs, record `position.collaterals` and `position.borrowRate?.totalOnDebt` over time.

## Compare with the initial deposit

Find the `open` transaction and read the contributed tokens from `assets`:

```typescript
const activity = await sdk.positions.transactions(position);
const indexed = activity.meta.chains.find(chain => chain.chainId === chainId);
if (indexed?.status !== "success") throw new Error("History unavailable");

const transactions = activity.data.filter(tx => tx.timestamp <= snapshot.timestamp);
const opening = transactions.find(tx => tx.kind === "open");
if (!opening?.assets.length) throw new Error("Opening contribution unavailable");

for (const { token, value } of opening.assets) {
  console.log(formatUnits(value, token.decimals), token.symbol);
}
```

Use the transfer amount directly when the token is the market underlying. Use its transaction-time USD value if available. When a required valuation is missing, the [receipt-block pricing code](https://docs.gearbox.finance/developers/token-amounts-and-usd#price-a-deposit-at-its-block) takes the SDK transaction hash, token address, and raw amount.

### Account for later deposits and withdrawals

In the same `transactions` array, count `deposit` and `addCollateral` assets as contributions, and `withdraw` and `withdrawCollateral` assets as withdrawals.

Include wallet-funded repayments and exclude internal debt changes. If an `other` transaction has unclear direction, use your application’s funding records or leave PnL unavailable. Use history for the same ownership period as the opening, with indexed coverage through the equity snapshot.

On Ethereum, [this wallet](https://etherscan.io/address/0x686e2d1Eb5aaB8769664d740CdfF5F6D6B6cD89C) opened [its Credit Account](https://etherscan.io/address/0xec1fcf6fdb21c24065a23fea57dd668ca0f4bdd6) with 3.46 wstETH and later added WETH. The table uses the oracle price at each deposit’s block. Figures are rounded.

| | WETH | USD |
| --- | ---: | ---: |
| [Opening deposit](https://etherscan.io/tx/0x39e6f3254cad4a44aed157e446e2c710d0964b1188d0076cb92e8c66f1cffd01) | 4.25 | 9,366 |
| [Later deposit](https://etherscan.io/tx/0x7213c48c052f11d354fced557e9e27fb2947eb2a81551f097d08e175547ab0eb) | 1.72 | 3,812 |
| Equity at block 26,492,488 | 6.72 | 11,051 |
| **Gain or loss** | **+0.75** | **−2,127** |

The owner gained WETH while losing dollar value.
