Skip to content
This repository has been archived by the owner on Aug 15, 2023. It is now read-only.

Commit

Permalink
Fix spot uPnL calculation (#100)
Browse files Browse the repository at this point in the history
* fix: include exchange btc balance in spot upnl
Co-authored-by: Sebastien Verreault <sebver@pm.me>
  • Loading branch information
sebastienverreault authored May 19, 2022
1 parent 0dcccf7 commit fd88ad0
Showing 1 changed file with 20 additions and 17 deletions.
37 changes: 20 additions & 17 deletions dealer/src/servers/exporter/exporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ export async function exporter() {
// load funding rates to be up-to-date
await dealer.fetchAndLoadFundingRates()

let btcBalanceOnExchange = 0
let averageOpenPrice = 0
let swapPosInCt = 0
const liabilityInUsd = await dealer.getLiabilityInUsd()
Expand Down Expand Up @@ -552,6 +553,7 @@ export async function exporter() {
}
if (ogBal.btcTotalBalance) {
Metrics.set(metrics["btcTotalBalance"], ogBal.btcTotalBalance)
btcBalanceOnExchange += ogBal.btcTotalBalance
}
} else {
Metrics.set(metrics["notionalLever"], 0)
Expand All @@ -569,9 +571,25 @@ export async function exporter() {
Metrics.set(metrics["liabilityInUsd"], liabilityInUsd)
Metrics.set(metrics["liabilityInBtc"], liabilityInBtc)

// Funding Account Balance
const fundingAccountBalance = await dealer.getFundingAccountBalance()
Metrics.set(
metrics["fundingAccountBtcFreeBalance"],
fundingAccountBalance.btcFreeBalance,
)
Metrics.set(
metrics["fundingAccountBtcUsedBalance"],
fundingAccountBalance.btcUsedBalance,
)
Metrics.set(
metrics["fundingAccountBtcTotalBalance"],
fundingAccountBalance.btcTotalBalance,
)
btcBalanceOnExchange += fundingAccountBalance.btcTotalBalance

// Spot uPnl
const openSpotQuantityInBtc = Math.abs(liabilityInBtc)
const spotOpenPrice = Math.abs(liabilityInUsd / liabilityInBtc)
const openSpotQuantityInBtc = Math.abs(liabilityInBtc) + btcBalanceOnExchange
const spotOpenPrice = Math.abs(liabilityInUsd) / openSpotQuantityInBtc
const spotUPnlInUsd = (spotPrice - spotOpenPrice) * openSpotQuantityInBtc
Metrics.set(metrics["spotUPnlInUsd"], spotUPnlInUsd)

Expand Down Expand Up @@ -631,21 +649,6 @@ export async function exporter() {
fundingFeesMetrics.fundingFeesIncomeCount,
)

// Funding Account Balance
const fundingAccountBalance = await dealer.getFundingAccountBalance()
Metrics.set(
metrics["fundingAccountBtcFreeBalance"],
fundingAccountBalance.btcFreeBalance,
)
Metrics.set(
metrics["fundingAccountBtcUsedBalance"],
fundingAccountBalance.btcUsedBalance,
)
Metrics.set(
metrics["fundingAccountBtcTotalBalance"],
fundingAccountBalance.btcTotalBalance,
)

// Funding Yields
const fundingYieldMetrics = await dealer.getAnnualFundingYieldMetrics()
Metrics.set(metrics["fundingYield1d"], fundingYieldMetrics.fundingYield1d)
Expand Down

0 comments on commit fd88ad0

Please sign in to comment.