@gainsnetwork/sdk 0.2.73-rc2 → 1.0.0-rc10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/lib/backend/globalTrades/index.d.ts +11 -0
- package/lib/backend/globalTrades/index.js +69 -0
- package/lib/backend/index.d.ts +3 -0
- package/lib/backend/index.js +28 -0
- package/lib/backend/tradingVariables/backend.types.d.ts +318 -0
- package/lib/backend/tradingVariables/backend.types.js +2 -0
- package/lib/backend/tradingVariables/converter.d.ts +34 -0
- package/lib/backend/tradingVariables/converter.js +338 -0
- package/lib/backend/tradingVariables/index.d.ts +5 -0
- package/lib/backend/tradingVariables/index.js +96 -0
- package/lib/backend/tradingVariables/types.d.ts +113 -0
- package/lib/backend/tradingVariables/types.js +14 -0
- package/lib/constants.d.ts +0 -5
- package/lib/constants.js +0 -5
- package/lib/contracts/types/generated/GFarmTradingStorageV5.d.ts +1911 -0
- package/lib/contracts/types/generated/GFarmTradingStorageV5.js +2 -0
- package/lib/contracts/types/generated/GNSBorrowingFees.d.ts +1067 -0
- package/lib/contracts/types/generated/GNSBorrowingFees.js +2 -0
- package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.d.ts +979 -0
- package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.js +2 -0
- package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.d.ts +1058 -0
- package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.js +2 -0
- package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +2134 -293
- package/lib/contracts/types/generated/GNSNftRewardsV6.d.ts +533 -0
- package/lib/contracts/types/generated/GNSNftRewardsV6.js +2 -0
- package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.d.ts +613 -0
- package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.js +2 -0
- package/lib/contracts/types/generated/GNSPairInfosV6_1.d.ts +911 -0
- package/lib/contracts/types/generated/GNSPairInfosV6_1.js +2 -0
- package/lib/contracts/types/generated/GNSPairsStorageV6.d.ts +660 -0
- package/lib/contracts/types/generated/GNSPairsStorageV6.js +2 -0
- package/lib/contracts/types/generated/GNSTrading.d.ts +758 -0
- package/lib/contracts/types/generated/GNSTrading.js +2 -0
- package/lib/contracts/types/generated/GNSTradingCallbacks.d.ts +875 -0
- package/lib/contracts/types/generated/GNSTradingCallbacks.js +2 -0
- package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.d.ts +806 -0
- package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.js +2 -0
- package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.d.ts +821 -0
- package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.js +2 -0
- package/lib/contracts/types/generated/GNSTradingStorage.d.ts +1387 -0
- package/lib/contracts/types/generated/GNSTradingStorage.js +2 -0
- package/lib/contracts/types/generated/GToken.d.ts +78 -107
- package/lib/contracts/types/generated/GTokenV6_3_2.d.ts +1838 -0
- package/lib/contracts/types/generated/GTokenV6_3_2.js +2 -0
- package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.d.ts +83 -0
- package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.js +2691 -0
- package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.d.ts +88 -0
- package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.js +1654 -0
- package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.d.ts +113 -0
- package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.js +1742 -0
- package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.d.ts +124 -0
- package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.js +1784 -0
- package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.d.ts +90 -53
- package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +4496 -430
- package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.d.ts +100 -0
- package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.js +1116 -0
- package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.d.ts +100 -0
- package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.js +1003 -0
- package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.d.ts +98 -0
- package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.js +1485 -0
- package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.d.ts +117 -0
- package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.js +1265 -0
- package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.d.ts +82 -0
- package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.js +1273 -0
- package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.d.ts +82 -0
- package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.js +1326 -0
- package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.d.ts +113 -0
- package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.js +1428 -0
- package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.d.ts +96 -0
- package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.js +2241 -0
- package/lib/contracts/types/generated/factories/GNSTrading__factory.d.ts +95 -0
- package/lib/contracts/types/generated/factories/GNSTrading__factory.js +1071 -0
- package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.d.ts +110 -0
- package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.js +2682 -0
- package/lib/contracts/types/generated/factories/GToken__factory.d.ts +7 -0
- package/lib/contracts/types/generated/factories/GToken__factory.js +69 -142
- package/lib/contracts/types/index.d.ts +2 -1
- package/lib/contracts/types/index.js +1 -0
- package/lib/contracts/utils/openTrades.d.ts +1 -0
- package/lib/contracts/utils/openTrades.js +94 -56
- package/lib/contracts/utils/pairs.js +0 -5
- package/lib/index.d.ts +2 -0
- package/lib/index.js +5 -0
- package/lib/markets/collateral/converter.d.ts +5 -0
- package/lib/markets/collateral/converter.js +11 -0
- package/lib/markets/collateral/index.d.ts +1 -0
- package/lib/markets/collateral/index.js +17 -0
- package/lib/markets/collateral/types.d.ts +7 -0
- package/lib/markets/collateral/types.js +2 -0
- package/lib/markets/holdingFees/index.d.ts +46 -0
- package/lib/markets/holdingFees/index.js +105 -0
- package/lib/markets/holdingFees/types.d.ts +23 -0
- package/lib/markets/holdingFees/types.js +5 -0
- package/lib/markets/index.d.ts +5 -0
- package/lib/markets/index.js +5 -0
- package/lib/markets/leverage/builder.d.ts +12 -0
- package/lib/markets/leverage/builder.js +25 -0
- package/lib/markets/leverage/getMarketLeverageRestrictions.d.ts +7 -0
- package/lib/markets/leverage/getMarketLeverageRestrictions.js +38 -0
- package/lib/markets/leverage/index.d.ts +3 -0
- package/lib/markets/leverage/index.js +19 -0
- package/lib/markets/leverage/types.d.ts +15 -0
- package/lib/markets/leverage/types.js +2 -0
- package/lib/markets/oi/converter.d.ts +62 -0
- package/lib/markets/oi/converter.js +102 -0
- package/lib/markets/oi/fetcher.d.ts +58 -0
- package/lib/markets/oi/fetcher.js +181 -0
- package/lib/markets/oi/index.d.ts +49 -0
- package/lib/markets/oi/index.js +77 -0
- package/lib/markets/oi/types.d.ts +73 -0
- package/lib/markets/oi/types.js +6 -0
- package/lib/markets/oi/validation.d.ts +80 -0
- package/lib/markets/oi/validation.js +172 -0
- package/lib/markets/price/builder.d.ts +25 -0
- package/lib/markets/price/builder.js +69 -0
- package/lib/markets/price/index.d.ts +6 -0
- package/lib/markets/price/index.js +22 -0
- package/lib/markets/price/marketPrice.d.ts +13 -0
- package/lib/markets/price/marketPrice.js +35 -0
- package/lib/markets/price/types.d.ts +23 -0
- package/lib/markets/price/types.js +5 -0
- package/lib/trade/counterTrade/index.d.ts +2 -0
- package/lib/trade/counterTrade/index.js +18 -0
- package/lib/trade/counterTrade/types.d.ts +7 -0
- package/lib/trade/counterTrade/types.js +2 -0
- package/lib/trade/counterTrade/validateCounterTrade.d.ts +10 -0
- package/lib/trade/counterTrade/validateCounterTrade.js +29 -0
- package/lib/trade/effectiveLeverage/builder.d.ts +23 -0
- package/lib/trade/effectiveLeverage/builder.js +30 -0
- package/lib/trade/effectiveLeverage/getTradeNewEffectiveLeverage.d.ts +23 -0
- package/lib/trade/effectiveLeverage/getTradeNewEffectiveLeverage.js +64 -0
- package/lib/trade/effectiveLeverage/index.d.ts +3 -0
- package/lib/trade/effectiveLeverage/index.js +22 -0
- package/lib/trade/effectiveLeverage/types.d.ts +33 -0
- package/lib/trade/effectiveLeverage/types.js +2 -0
- package/lib/trade/fees/borrowing/builder.d.ts +14 -0
- package/lib/trade/fees/borrowing/builder.js +34 -0
- package/lib/trade/fees/borrowing/index.d.ts +26 -3
- package/lib/trade/fees/borrowing/index.js +72 -22
- package/lib/trade/fees/borrowingV2/builder.d.ts +6 -0
- package/lib/trade/fees/borrowingV2/builder.js +24 -0
- package/lib/trade/fees/borrowingV2/converter.d.ts +75 -0
- package/lib/trade/fees/borrowingV2/converter.js +132 -0
- package/lib/trade/fees/borrowingV2/fetcher.d.ts +75 -0
- package/lib/trade/fees/borrowingV2/fetcher.js +185 -0
- package/lib/trade/fees/borrowingV2/index.d.ts +48 -0
- package/lib/trade/fees/borrowingV2/index.js +112 -0
- package/lib/trade/fees/borrowingV2/types.d.ts +95 -0
- package/lib/trade/fees/borrowingV2/types.js +5 -0
- package/lib/trade/fees/converter.d.ts +48 -0
- package/lib/trade/fees/converter.js +114 -0
- package/lib/trade/fees/fundingFees/builder.d.ts +9 -0
- package/lib/trade/fees/fundingFees/builder.js +35 -0
- package/lib/trade/fees/fundingFees/converter.d.ts +102 -0
- package/lib/trade/fees/fundingFees/converter.js +196 -0
- package/lib/trade/fees/fundingFees/fetcher.d.ts +66 -0
- package/lib/trade/fees/fundingFees/fetcher.js +150 -0
- package/lib/trade/fees/fundingFees/index.d.ts +124 -0
- package/lib/trade/fees/fundingFees/index.js +309 -0
- package/lib/trade/fees/fundingFees/pairContext.d.ts +33 -0
- package/lib/trade/fees/fundingFees/pairContext.js +17 -0
- package/lib/trade/fees/fundingFees/types.d.ts +77 -0
- package/lib/trade/fees/fundingFees/types.js +5 -0
- package/lib/trade/fees/holdingFees/index.d.ts +46 -0
- package/lib/trade/fees/holdingFees/index.js +105 -0
- package/lib/trade/fees/holdingFees/types.d.ts +23 -0
- package/lib/trade/fees/holdingFees/types.js +5 -0
- package/lib/trade/fees/index.d.ts +9 -2
- package/lib/trade/fees/index.js +69 -16
- package/lib/trade/fees/tiers/converter.d.ts +54 -0
- package/lib/trade/fees/tiers/converter.js +81 -0
- package/lib/trade/fees/tiers/index.d.ts +18 -0
- package/lib/trade/fees/tiers/index.js +45 -1
- package/lib/trade/fees/trading/builder.d.ts +18 -0
- package/lib/trade/fees/trading/builder.js +20 -0
- package/lib/trade/fees/trading/converter.d.ts +32 -0
- package/lib/trade/fees/trading/converter.js +47 -0
- package/lib/trade/fees/trading/holdingFees.d.ts +28 -0
- package/lib/trade/fees/trading/holdingFees.js +66 -0
- package/lib/trade/fees/trading/holdingFeesStructured.d.ts +28 -0
- package/lib/trade/fees/trading/holdingFeesStructured.js +66 -0
- package/lib/trade/fees/trading/index.d.ts +62 -0
- package/lib/trade/fees/trading/index.js +155 -0
- package/lib/trade/fees/trading/types.d.ts +48 -0
- package/lib/trade/fees/trading/types.js +5 -0
- package/lib/trade/index.d.ts +5 -2
- package/lib/trade/index.js +5 -2
- package/lib/trade/liquidation/builder.d.ts +25 -0
- package/lib/trade/liquidation/builder.js +59 -0
- package/lib/trade/liquidation/converter.d.ts +23 -0
- package/lib/trade/liquidation/converter.js +46 -0
- package/lib/trade/liquidation/index.d.ts +29 -0
- package/lib/trade/liquidation/index.js +218 -0
- package/lib/trade/liquidation/types.d.ts +43 -0
- package/lib/trade/liquidation/types.js +2 -0
- package/lib/trade/pnl/builder.d.ts +16 -0
- package/lib/trade/pnl/builder.js +44 -0
- package/lib/trade/pnl/converter.d.ts +47 -0
- package/lib/trade/pnl/converter.js +72 -0
- package/lib/trade/pnl/index.d.ts +91 -0
- package/lib/trade/pnl/index.js +303 -0
- package/lib/trade/pnl/types.d.ts +79 -0
- package/lib/trade/pnl/types.js +5 -0
- package/lib/trade/priceImpact/close/builder.d.ts +23 -0
- package/lib/trade/priceImpact/close/builder.js +45 -0
- package/lib/trade/priceImpact/close/index.d.ts +22 -0
- package/lib/trade/priceImpact/close/index.js +134 -0
- package/lib/trade/priceImpact/close/types.d.ts +47 -0
- package/lib/trade/priceImpact/close/types.js +5 -0
- package/lib/trade/priceImpact/cumulVol/builder.d.ts +22 -0
- package/lib/trade/priceImpact/cumulVol/builder.js +43 -0
- package/lib/trade/priceImpact/cumulVol/converter.d.ts +31 -0
- package/lib/trade/priceImpact/cumulVol/converter.js +59 -0
- package/lib/trade/priceImpact/cumulVol/index.d.ts +108 -0
- package/lib/trade/priceImpact/cumulVol/index.js +235 -0
- package/lib/trade/priceImpact/index.d.ts +21 -0
- package/lib/trade/priceImpact/index.js +79 -0
- package/lib/trade/priceImpact/open/builder.d.ts +21 -0
- package/lib/trade/priceImpact/open/builder.js +43 -0
- package/lib/trade/priceImpact/open/index.d.ts +23 -0
- package/lib/trade/priceImpact/open/index.js +79 -0
- package/lib/trade/priceImpact/open/types.d.ts +45 -0
- package/lib/trade/priceImpact/open/types.js +5 -0
- package/lib/trade/priceImpact/skew/builder.d.ts +12 -0
- package/lib/trade/priceImpact/skew/builder.js +28 -0
- package/lib/trade/priceImpact/skew/converter.d.ts +46 -0
- package/lib/trade/priceImpact/skew/converter.js +81 -0
- package/lib/trade/priceImpact/skew/fetcher.d.ts +60 -0
- package/lib/trade/priceImpact/skew/fetcher.js +169 -0
- package/lib/trade/priceImpact/skew/index.d.ts +53 -0
- package/lib/trade/priceImpact/skew/index.js +148 -0
- package/lib/trade/priceImpact/skew/types.d.ts +44 -0
- package/lib/trade/priceImpact/skew/types.js +5 -0
- package/lib/trade/spread.d.ts +5 -18
- package/lib/trade/spread.js +17 -106
- package/lib/trade/types.d.ts +109 -14
- package/lib/trade/types.js +0 -5
- package/lib/trade/utils.d.ts +18 -0
- package/lib/trade/utils.js +30 -0
- package/lib/vault/index.d.ts +3 -1
- package/lib/vault/index.js +2 -2
- package/package.json +2 -1
- package/lib/trade/liquidation.d.ts +0 -12
- package/lib/trade/liquidation.js +0 -55
- package/lib/trade/pnl.d.ts +0 -10
- package/lib/trade/pnl.js +0 -33
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @dev PnL calculation module
|
|
4
|
+
* @dev Provides functions matching v10 contract implementations
|
|
5
|
+
*/
|
|
6
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
7
|
+
if (k2 === undefined) k2 = k;
|
|
8
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
9
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
10
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
11
|
+
}
|
|
12
|
+
Object.defineProperty(o, k2, desc);
|
|
13
|
+
}) : (function(o, m, k, k2) {
|
|
14
|
+
if (k2 === undefined) k2 = k;
|
|
15
|
+
o[k2] = m[k];
|
|
16
|
+
}));
|
|
17
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
18
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
19
|
+
};
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
exports.getPriceForTargetPnlPercentage = exports.getPnl = exports.getComprehensivePnl = exports.getTradeValue = exports.getPnlPercent = exports.getTradeRealizedPnlCollateral = void 0;
|
|
22
|
+
const borrowing_1 = require("../fees/borrowing");
|
|
23
|
+
const trading_1 = require("../fees/trading");
|
|
24
|
+
const liquidation_1 = require("../liquidation");
|
|
25
|
+
/**
|
|
26
|
+
* @dev Gets trade realized PnL components from TradeFeesData
|
|
27
|
+
* @dev Mirrors contract's getTradeRealizedPnlCollateral function
|
|
28
|
+
* @param tradeFeesData Trade fees data containing realized components
|
|
29
|
+
* @returns Tuple of [realizedPnlCollateral, realizedTradingFeesCollateral, totalRealizedPnlCollateral]
|
|
30
|
+
*/
|
|
31
|
+
const getTradeRealizedPnlCollateral = (tradeFeesData) => {
|
|
32
|
+
const realizedPnlCollateral = tradeFeesData.realizedPnlCollateral;
|
|
33
|
+
const realizedTradingFeesCollateral = tradeFeesData.realizedTradingFeesCollateral;
|
|
34
|
+
const totalRealizedPnlCollateral = realizedPnlCollateral - realizedTradingFeesCollateral;
|
|
35
|
+
return {
|
|
36
|
+
realizedPnlCollateral,
|
|
37
|
+
realizedTradingFeesCollateral,
|
|
38
|
+
totalRealizedPnlCollateral,
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
exports.getTradeRealizedPnlCollateral = getTradeRealizedPnlCollateral;
|
|
42
|
+
/**
|
|
43
|
+
* @dev Calculates PnL percentage for a position
|
|
44
|
+
* @dev Mirrors contract's getPnlPercent function
|
|
45
|
+
* @param openPrice Trade open price
|
|
46
|
+
* @param currentPrice Current market price
|
|
47
|
+
* @param long Whether position is long
|
|
48
|
+
* @param leverage Position leverage
|
|
49
|
+
* @returns PnL percentage (e.g., 10 = 10% profit, -50 = 50% loss)
|
|
50
|
+
*/
|
|
51
|
+
const getPnlPercent = (openPrice, currentPrice, long, leverage) => {
|
|
52
|
+
if (openPrice === 0)
|
|
53
|
+
return -100;
|
|
54
|
+
const priceDiff = long ? currentPrice - openPrice : openPrice - currentPrice;
|
|
55
|
+
const pnlPercent = (priceDiff / openPrice) * 100 * leverage;
|
|
56
|
+
// Cap at -100% loss
|
|
57
|
+
return Math.max(pnlPercent, -100);
|
|
58
|
+
};
|
|
59
|
+
exports.getPnlPercent = getPnlPercent;
|
|
60
|
+
/**
|
|
61
|
+
* @dev Calculates trade value from collateral and PnL
|
|
62
|
+
* @dev Mirrors contract's getTradeValuePure function
|
|
63
|
+
* @param collateral Trade collateral amount
|
|
64
|
+
* @param pnlPercent PnL percentage
|
|
65
|
+
* @param totalFees Total fees to deduct
|
|
66
|
+
* @returns Trade value after PnL and fees
|
|
67
|
+
*/
|
|
68
|
+
const getTradeValue = (collateral, pnlPercent, totalFees) => {
|
|
69
|
+
const pnlCollateral = collateral * (pnlPercent / 100);
|
|
70
|
+
const value = collateral + pnlCollateral - totalFees;
|
|
71
|
+
return Math.max(0, value);
|
|
72
|
+
};
|
|
73
|
+
exports.getTradeValue = getTradeValue;
|
|
74
|
+
/**
|
|
75
|
+
* @dev Comprehensive PnL calculation including all fees
|
|
76
|
+
* @param trade The trade to calculate PnL for
|
|
77
|
+
* @param marketPrice Current market price (without price impact)
|
|
78
|
+
* @param executionPrice Price after all impacts (spread, skew, volume)
|
|
79
|
+
* @param tradeInfo Trade info with version and timestamps
|
|
80
|
+
* @param context Context with all fee parameters
|
|
81
|
+
* @returns Detailed PnL breakdown
|
|
82
|
+
*/
|
|
83
|
+
const getComprehensivePnl = (trade, marketPrice, executionPrice, tradeInfo, context) => {
|
|
84
|
+
var _a;
|
|
85
|
+
// Calculate both raw PnL (market price) and impact-adjusted PnL (execution price)
|
|
86
|
+
let rawPnlPercent = (0, exports.getPnlPercent)(trade.openPrice, marketPrice, trade.long, trade.leverage);
|
|
87
|
+
let impactPnlPercent = (0, exports.getPnlPercent)(trade.openPrice, executionPrice, trade.long, trade.leverage);
|
|
88
|
+
if (!context.tradeData) {
|
|
89
|
+
throw new Error("Trade data is undefined");
|
|
90
|
+
}
|
|
91
|
+
// Calculate position size
|
|
92
|
+
const positionSizeCollateral = trade.collateralAmount * trade.leverage;
|
|
93
|
+
// Calculate holding fees - always use getTradePendingHoldingFeesCollateral
|
|
94
|
+
const pendingHoldingFees = (0, trading_1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, context.tradeData.tradeFeesData, marketPrice, {
|
|
95
|
+
contractsVersion: context.core.contractsVersion,
|
|
96
|
+
currentTimestamp: context.core.currentTimestamp,
|
|
97
|
+
collateralPriceUsd: context.core.collateralPriceUsd,
|
|
98
|
+
borrowingV1: context.borrowingV1,
|
|
99
|
+
borrowingV2: context.borrowingV2,
|
|
100
|
+
funding: context.funding,
|
|
101
|
+
initialAccFees: context.tradeData.initialAccFees,
|
|
102
|
+
});
|
|
103
|
+
const borrowingFeeV1 = pendingHoldingFees.borrowingFeeCollateral_old;
|
|
104
|
+
const borrowingFeeV2 = pendingHoldingFees.borrowingFeeCollateral;
|
|
105
|
+
const fundingFee = pendingHoldingFees.fundingFeeCollateral;
|
|
106
|
+
// Calculate closing fees
|
|
107
|
+
const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(trade.collateralIndex, trade.user, trade.pairIndex, positionSizeCollateral, trade.isCounterTrade || false, {
|
|
108
|
+
fee: context.trading.fee,
|
|
109
|
+
globalTradeFeeParams: context.trading.globalTradeFeeParams,
|
|
110
|
+
collateralPriceUsd: context.core.collateralPriceUsd,
|
|
111
|
+
traderFeeMultiplier: context.trading.traderFeeMultiplier,
|
|
112
|
+
});
|
|
113
|
+
// Total fees
|
|
114
|
+
const totalHoldingFees = borrowingFeeV1 + borrowingFeeV2 + fundingFee;
|
|
115
|
+
const totalFees = totalHoldingFees + closingFee;
|
|
116
|
+
// Check liquidation (using raw PnL for liquidation check)
|
|
117
|
+
const liquidationThreshold = ((_a = context.tradeData) === null || _a === void 0 ? void 0 : _a.liquidationParams)
|
|
118
|
+
? (0, liquidation_1.getLiqPnlThresholdP)(context.tradeData.liquidationParams, trade.leverage) *
|
|
119
|
+
-100
|
|
120
|
+
: -90; // Default 90% loss
|
|
121
|
+
const isLiquidated = rawPnlPercent <= liquidationThreshold;
|
|
122
|
+
// If liquidated, set both PnL percentages to -100%
|
|
123
|
+
if (isLiquidated) {
|
|
124
|
+
rawPnlPercent = -100;
|
|
125
|
+
impactPnlPercent = -100;
|
|
126
|
+
}
|
|
127
|
+
// Get realized PnL components from TradeFeesData
|
|
128
|
+
const { totalRealizedPnlCollateral } = (0, exports.getTradeRealizedPnlCollateral)(context.tradeData.tradeFeesData);
|
|
129
|
+
// Calculate raw PnL in collateral (using market price)
|
|
130
|
+
const rawPnlCollateral = trade.collateralAmount * (rawPnlPercent / 100);
|
|
131
|
+
// Calculate impact-adjusted PnL in collateral (using execution price)
|
|
132
|
+
const impactPnlCollateral = trade.collateralAmount * (impactPnlPercent / 100);
|
|
133
|
+
// Calculate price impact
|
|
134
|
+
const priceImpactCollateral = impactPnlCollateral - rawPnlCollateral;
|
|
135
|
+
const priceImpactPercent = impactPnlPercent - rawPnlPercent;
|
|
136
|
+
// Calculate unrealized PnL (before closing fee, after holding fees, using market price)
|
|
137
|
+
// This is what the trader sees for open positions
|
|
138
|
+
const uPnlCollateral = rawPnlCollateral - totalHoldingFees + totalRealizedPnlCollateral;
|
|
139
|
+
const uPnlPercent = (uPnlCollateral / trade.collateralAmount) * 100;
|
|
140
|
+
// Calculate realized PnL (after all fees including closing, using execution price)
|
|
141
|
+
// This is what the trader would get if closing the position
|
|
142
|
+
const realizedPnlCollateral = impactPnlCollateral - totalFees + totalRealizedPnlCollateral;
|
|
143
|
+
const realizedPnlPercent = (realizedPnlCollateral / trade.collateralAmount) * 100;
|
|
144
|
+
// Calculate trade value using execution price (what trader would receive)
|
|
145
|
+
const tradeValue = (0, exports.getTradeValue)(trade.collateralAmount, impactPnlPercent, totalFees);
|
|
146
|
+
return {
|
|
147
|
+
// Raw PnL values (using market price, no price impact)
|
|
148
|
+
pnlPercent: rawPnlPercent,
|
|
149
|
+
pnlCollateral: rawPnlCollateral,
|
|
150
|
+
// Impact-adjusted PnL values (using execution price)
|
|
151
|
+
impactPnlPercent,
|
|
152
|
+
impactPnlCollateral,
|
|
153
|
+
// Price impact
|
|
154
|
+
priceImpact: {
|
|
155
|
+
percent: priceImpactPercent,
|
|
156
|
+
collateral: priceImpactCollateral,
|
|
157
|
+
},
|
|
158
|
+
// Trade value (what trader would receive if closing)
|
|
159
|
+
tradeValue,
|
|
160
|
+
// Unrealized PnL (after holding fees, before closing fee, using market price)
|
|
161
|
+
// Use for open position display
|
|
162
|
+
uPnlCollateral,
|
|
163
|
+
uPnlPercent,
|
|
164
|
+
// Realized PnL (after all fees, using execution price)
|
|
165
|
+
// Use for closing preview
|
|
166
|
+
realizedPnlCollateral,
|
|
167
|
+
realizedPnlPercent,
|
|
168
|
+
// Fee breakdown
|
|
169
|
+
fees: {
|
|
170
|
+
borrowingV1: borrowingFeeV1,
|
|
171
|
+
borrowingV2: borrowingFeeV2,
|
|
172
|
+
funding: fundingFee,
|
|
173
|
+
closing: closingFee,
|
|
174
|
+
total: totalFees,
|
|
175
|
+
},
|
|
176
|
+
// Status flags
|
|
177
|
+
isLiquidated,
|
|
178
|
+
isProfitable: rawPnlPercent > 0, // Based on raw PnL
|
|
179
|
+
};
|
|
180
|
+
};
|
|
181
|
+
exports.getComprehensivePnl = getComprehensivePnl;
|
|
182
|
+
/**
|
|
183
|
+
* @dev Legacy PnL calculation function
|
|
184
|
+
* @deprecated Use getComprehensivePnl for more comprehensive calculations
|
|
185
|
+
* @param price Current price
|
|
186
|
+
* @param trade Trade object
|
|
187
|
+
* @param tradeInfo Trade info (not used in legacy implementation)
|
|
188
|
+
* @param initialAccFees Initial accumulated fees
|
|
189
|
+
* @param liquidationParams Liquidation parameters
|
|
190
|
+
* @param useFees Whether to include fees
|
|
191
|
+
* @param context Context with fee calculation parameters
|
|
192
|
+
* @returns [pnlCollateral, pnlPercentage] or undefined if no price
|
|
193
|
+
*/
|
|
194
|
+
const getPnl = (price, trade, _tradeInfo, initialAccFees, liquidationParams, useFees, context) => {
|
|
195
|
+
var _a;
|
|
196
|
+
if (!price) {
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const posCollat = trade.collateralAmount;
|
|
200
|
+
const { openPrice, leverage } = trade;
|
|
201
|
+
let pnlCollat = trade.long
|
|
202
|
+
? ((price - openPrice) / openPrice) * leverage * posCollat
|
|
203
|
+
: ((openPrice - price) / openPrice) * leverage * posCollat;
|
|
204
|
+
if (useFees &&
|
|
205
|
+
context.pairs &&
|
|
206
|
+
context.groups &&
|
|
207
|
+
context.currentBlock !== undefined &&
|
|
208
|
+
context.collateralPriceUsd !== undefined) {
|
|
209
|
+
pnlCollat -= (0, borrowing_1.getBorrowingFee)(posCollat * trade.leverage, trade.pairIndex, trade.long, initialAccFees, price, {
|
|
210
|
+
currentBlock: context.currentBlock,
|
|
211
|
+
groups: context.groups,
|
|
212
|
+
pairs: context.pairs,
|
|
213
|
+
collateralPriceUsd: context.collateralPriceUsd,
|
|
214
|
+
pairOis: context.pairOis,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
let pnlPercentage = (pnlCollat / posCollat) * 100;
|
|
218
|
+
// Can be liquidated
|
|
219
|
+
if (pnlPercentage <=
|
|
220
|
+
(0, liquidation_1.getLiqPnlThresholdP)(liquidationParams, leverage) * -100) {
|
|
221
|
+
pnlPercentage = -100;
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
// Calculate closing fee using the same function as opening fees
|
|
225
|
+
const positionSizeCollateral = posCollat * trade.leverage;
|
|
226
|
+
const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(0, // collateralIndex not used
|
|
227
|
+
trade.user, trade.pairIndex, positionSizeCollateral, (_a = trade.isCounterTrade) !== null && _a !== void 0 ? _a : false, {
|
|
228
|
+
fee: context.fee,
|
|
229
|
+
globalTradeFeeParams: context.globalTradeFeeParams,
|
|
230
|
+
collateralPriceUsd: context.collateralPriceUsd || 1,
|
|
231
|
+
traderFeeMultiplier: context.traderFeeMultiplier,
|
|
232
|
+
});
|
|
233
|
+
pnlCollat -= closingFee;
|
|
234
|
+
pnlPercentage = (pnlCollat / posCollat) * 100;
|
|
235
|
+
}
|
|
236
|
+
pnlPercentage = pnlPercentage < -100 ? -100 : pnlPercentage;
|
|
237
|
+
pnlCollat = (posCollat * pnlPercentage) / 100;
|
|
238
|
+
return [pnlCollat, pnlPercentage];
|
|
239
|
+
};
|
|
240
|
+
exports.getPnl = getPnl;
|
|
241
|
+
/**
|
|
242
|
+
* @dev Calculates the price needed to achieve a target PnL percentage
|
|
243
|
+
* @param targetPnlPercent The target PnL percentage (e.g., 50 for 50% profit, -25 for 25% loss)
|
|
244
|
+
* @param trade The trade to calculate for
|
|
245
|
+
* @param tradeInfo Trade info with timestamps
|
|
246
|
+
* @param context Context with fee calculation parameters
|
|
247
|
+
* @param netPnl Whether to include closing fees in the calculation
|
|
248
|
+
* @returns The price that would result in the target PnL percentage
|
|
249
|
+
*/
|
|
250
|
+
const getPriceForTargetPnlPercentage = (targetPnlPercent, trade, tradeInfo, context, netPnl = false) => {
|
|
251
|
+
var _a, _b;
|
|
252
|
+
const { leverage, openPrice, long, collateralAmount } = trade;
|
|
253
|
+
const positionSizeCollateral = collateralAmount * leverage;
|
|
254
|
+
// Calculate holding fees - always use getTradePendingHoldingFeesCollateral
|
|
255
|
+
// This mirrors the contract's getTradeValueCollateral which always calls this function
|
|
256
|
+
const fees = (0, trading_1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, ((_a = context.tradeData) === null || _a === void 0 ? void 0 : _a.tradeFeesData) || {
|
|
257
|
+
realizedTradingFeesCollateral: 0,
|
|
258
|
+
realizedPnlCollateral: 0,
|
|
259
|
+
manuallyRealizedNegativePnlCollateral: 0,
|
|
260
|
+
alreadyTransferredNegativePnlCollateral: 0,
|
|
261
|
+
virtualAvailableCollateralInDiamond: 0,
|
|
262
|
+
initialAccFundingFeeP: 0,
|
|
263
|
+
initialAccBorrowingFeeP: 0,
|
|
264
|
+
}, openPrice, // Use open price as a baseline
|
|
265
|
+
{
|
|
266
|
+
contractsVersion: context.core.contractsVersion,
|
|
267
|
+
currentTimestamp: context.core.currentTimestamp,
|
|
268
|
+
collateralPriceUsd: context.core.collateralPriceUsd,
|
|
269
|
+
borrowingV1: context.borrowingV1,
|
|
270
|
+
borrowingV2: context.borrowingV2,
|
|
271
|
+
funding: context.funding,
|
|
272
|
+
initialAccFees: (_b = context.tradeData) === null || _b === void 0 ? void 0 : _b.initialAccFees,
|
|
273
|
+
});
|
|
274
|
+
const totalHoldingFees = fees.fundingFeeCollateral +
|
|
275
|
+
fees.borrowingFeeCollateral +
|
|
276
|
+
fees.borrowingFeeCollateral_old;
|
|
277
|
+
const targetPnlInCollateral = (collateralAmount * targetPnlPercent) / 100;
|
|
278
|
+
let targetPnlGross = targetPnlInCollateral + totalHoldingFees;
|
|
279
|
+
if (netPnl) {
|
|
280
|
+
// Include closing fees
|
|
281
|
+
const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(trade.collateralIndex, trade.user, trade.pairIndex, positionSizeCollateral, trade.isCounterTrade || false, {
|
|
282
|
+
fee: context.trading.fee,
|
|
283
|
+
globalTradeFeeParams: context.trading.globalTradeFeeParams,
|
|
284
|
+
collateralPriceUsd: context.core.collateralPriceUsd,
|
|
285
|
+
traderFeeMultiplier: context.trading.traderFeeMultiplier,
|
|
286
|
+
});
|
|
287
|
+
targetPnlGross += closingFee;
|
|
288
|
+
}
|
|
289
|
+
// Calculate the price
|
|
290
|
+
let price;
|
|
291
|
+
if (long) {
|
|
292
|
+
price = openPrice + (targetPnlGross * openPrice) / positionSizeCollateral;
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
price = openPrice - (targetPnlGross * openPrice) / positionSizeCollateral;
|
|
296
|
+
}
|
|
297
|
+
return price;
|
|
298
|
+
};
|
|
299
|
+
exports.getPriceForTargetPnlPercentage = getPriceForTargetPnlPercentage;
|
|
300
|
+
// Re-export types
|
|
301
|
+
__exportStar(require("./types"), exports);
|
|
302
|
+
__exportStar(require("./converter"), exports);
|
|
303
|
+
__exportStar(require("./builder"), exports);
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @dev Types for PnL calculations
|
|
3
|
+
*/
|
|
4
|
+
import { ContractsVersion } from "src/contracts/types";
|
|
5
|
+
import { BorrowingFee, GetBorrowingFeeContext, TradingFeesSubContext } from "../fees";
|
|
6
|
+
import { GetPairBorrowingFeeV2Context } from "../fees/borrowingV2";
|
|
7
|
+
import { GetPairFundingFeeContext } from "../fees/fundingFees";
|
|
8
|
+
import { TradeFeesData, LiquidationParams } from "../types";
|
|
9
|
+
/**
|
|
10
|
+
* @dev Result of trade value calculation
|
|
11
|
+
*/
|
|
12
|
+
export type TradeValueResult = {
|
|
13
|
+
tradeValue: number;
|
|
14
|
+
pnlPercent: number;
|
|
15
|
+
pnlCollateral: number;
|
|
16
|
+
totalFees: number;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* @dev Detailed fee breakdown
|
|
20
|
+
*/
|
|
21
|
+
export type FeeBreakdown = {
|
|
22
|
+
borrowingV1: number;
|
|
23
|
+
borrowingV2: number;
|
|
24
|
+
funding: number;
|
|
25
|
+
closing: number;
|
|
26
|
+
opening?: number;
|
|
27
|
+
total: number;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* @dev Price impact breakdown for v10
|
|
31
|
+
*/
|
|
32
|
+
export type PriceImpactBreakdown = {
|
|
33
|
+
fixedSpread: number;
|
|
34
|
+
skewImpact: number;
|
|
35
|
+
cumulVolImpact: number;
|
|
36
|
+
total: number;
|
|
37
|
+
priceAfterImpact: number;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* @dev Comprehensive PnL result with all details
|
|
41
|
+
*/
|
|
42
|
+
export type ComprehensivePnlResult = {
|
|
43
|
+
pnlPercent: number;
|
|
44
|
+
pnlCollateral: number;
|
|
45
|
+
impactPnlPercent: number;
|
|
46
|
+
impactPnlCollateral: number;
|
|
47
|
+
priceImpact: {
|
|
48
|
+
percent: number;
|
|
49
|
+
collateral: number;
|
|
50
|
+
};
|
|
51
|
+
tradeValue: number;
|
|
52
|
+
uPnlCollateral: number;
|
|
53
|
+
uPnlPercent: number;
|
|
54
|
+
realizedPnlCollateral: number;
|
|
55
|
+
realizedPnlPercent: number;
|
|
56
|
+
fees: FeeBreakdown;
|
|
57
|
+
isLiquidated: boolean;
|
|
58
|
+
isProfitable: boolean;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* @dev Context for comprehensive PnL calculations with nested sub-contexts
|
|
62
|
+
*/
|
|
63
|
+
export type GetComprehensivePnlContext = {
|
|
64
|
+
core: {
|
|
65
|
+
currentBlock: number;
|
|
66
|
+
currentTimestamp: number;
|
|
67
|
+
collateralPriceUsd: number;
|
|
68
|
+
contractsVersion: ContractsVersion;
|
|
69
|
+
};
|
|
70
|
+
borrowingV1?: GetBorrowingFeeContext;
|
|
71
|
+
borrowingV2?: GetPairBorrowingFeeV2Context;
|
|
72
|
+
funding?: GetPairFundingFeeContext;
|
|
73
|
+
trading: TradingFeesSubContext;
|
|
74
|
+
tradeData?: {
|
|
75
|
+
tradeFeesData: TradeFeesData;
|
|
76
|
+
liquidationParams: LiquidationParams;
|
|
77
|
+
initialAccFees?: BorrowingFee.InitialAccFees;
|
|
78
|
+
};
|
|
79
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { GlobalTradingVariablesType } from "../../../backend/tradingVariables/types";
|
|
2
|
+
import { TradeClosingPriceImpactContext } from "./types";
|
|
3
|
+
import { TradeInfo } from "../../types";
|
|
4
|
+
/**
|
|
5
|
+
* @dev Builds a complete context for trade closing price impact calculations
|
|
6
|
+
* @dev Uses sub-context builders to create properly scoped contexts
|
|
7
|
+
* @param globalTradingVariables The transformed global trading variables from backend
|
|
8
|
+
* @param collateralIndex The collateral index (1-based)
|
|
9
|
+
* @param pairIndex The pair index
|
|
10
|
+
* @param tradeInfo Trade information including createdBlock
|
|
11
|
+
* @param additionalParams Additional parameters not available in trading variables
|
|
12
|
+
* @returns Complete context ready for getTradeClosingPriceImpact
|
|
13
|
+
*/
|
|
14
|
+
export declare const buildTradeClosingPriceImpactContext: (globalTradingVariables: GlobalTradingVariablesType, collateralIndex: number, pairIndex: number, tradeInfo: TradeInfo, additionalParams: {
|
|
15
|
+
currentBlock: number;
|
|
16
|
+
contractsVersion?: number;
|
|
17
|
+
isPnlPositive?: boolean;
|
|
18
|
+
userPriceImpact?: {
|
|
19
|
+
cumulVolPriceImpactMultiplier: number;
|
|
20
|
+
fixedSpreadP: number;
|
|
21
|
+
};
|
|
22
|
+
protectionCloseFactorWhitelist?: boolean;
|
|
23
|
+
}) => TradeClosingPriceImpactContext | undefined;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildTradeClosingPriceImpactContext = void 0;
|
|
4
|
+
const builder_1 = require("../cumulVol/builder");
|
|
5
|
+
const builder_2 = require("../skew/builder");
|
|
6
|
+
/**
|
|
7
|
+
* @dev Builds a complete context for trade closing price impact calculations
|
|
8
|
+
* @dev Uses sub-context builders to create properly scoped contexts
|
|
9
|
+
* @param globalTradingVariables The transformed global trading variables from backend
|
|
10
|
+
* @param collateralIndex The collateral index (1-based)
|
|
11
|
+
* @param pairIndex The pair index
|
|
12
|
+
* @param tradeInfo Trade information including createdBlock
|
|
13
|
+
* @param additionalParams Additional parameters not available in trading variables
|
|
14
|
+
* @returns Complete context ready for getTradeClosingPriceImpact
|
|
15
|
+
*/
|
|
16
|
+
const buildTradeClosingPriceImpactContext = (globalTradingVariables, collateralIndex, pairIndex, tradeInfo, additionalParams) => {
|
|
17
|
+
var _a;
|
|
18
|
+
const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
|
|
19
|
+
if (!collateral) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
// Build cumulative volume subcontext for closing
|
|
23
|
+
const cumulVolContext = (0, builder_1.buildCumulVolContext)(globalTradingVariables, collateralIndex, pairIndex, {
|
|
24
|
+
currentBlock: additionalParams.currentBlock,
|
|
25
|
+
contractsVersion: additionalParams.contractsVersion || tradeInfo.contractsVersion,
|
|
26
|
+
isPnlPositive: additionalParams.isPnlPositive,
|
|
27
|
+
isOpen: false,
|
|
28
|
+
createdBlock: tradeInfo.createdBlock,
|
|
29
|
+
userPriceImpact: additionalParams.userPriceImpact,
|
|
30
|
+
protectionCloseFactorWhitelist: additionalParams.protectionCloseFactorWhitelist,
|
|
31
|
+
});
|
|
32
|
+
// Build skew price impact subcontext
|
|
33
|
+
const skewContext = (0, builder_2.buildSkewPriceImpactContext)(collateral, pairIndex);
|
|
34
|
+
if (!cumulVolContext || !skewContext) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
// Return structured context with proper subcontexts
|
|
38
|
+
return {
|
|
39
|
+
collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
|
|
40
|
+
cumulVolContext,
|
|
41
|
+
skewContext,
|
|
42
|
+
tradeInfo,
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
exports.buildTradeClosingPriceImpactContext = buildTradeClosingPriceImpactContext;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @dev Trade closing price impact calculations
|
|
3
|
+
* @dev Mirrors contract's TradingCommonUtils.getTradeClosingPriceImpact
|
|
4
|
+
*/
|
|
5
|
+
import { TradeClosingPriceImpactInput, TradeClosingPriceImpactContext, TradeClosingPriceImpactResult } from "./types";
|
|
6
|
+
export type { TradeClosingPriceImpactInput, TradeClosingPriceImpactContext, TradeClosingPriceImpactResult, };
|
|
7
|
+
export { buildTradeClosingPriceImpactContext } from "./builder";
|
|
8
|
+
/**
|
|
9
|
+
* @dev Calculates all price impacts for trade closing
|
|
10
|
+
* @dev Mirrors contract's getTradeClosingPriceImpact function
|
|
11
|
+
* @param input Trade parameters
|
|
12
|
+
* @param context Combined context for calculations
|
|
13
|
+
* @returns Price impact breakdown and trade value
|
|
14
|
+
*/
|
|
15
|
+
export declare const getTradeClosingPriceImpact: (input: TradeClosingPriceImpactInput, context: TradeClosingPriceImpactContext) => TradeClosingPriceImpactResult;
|
|
16
|
+
/**
|
|
17
|
+
* @dev Simplified version using oracle price as current price
|
|
18
|
+
* @param input Trade parameters (without currentPairPrice)
|
|
19
|
+
* @param context Combined context
|
|
20
|
+
* @returns Price impact breakdown and trade value
|
|
21
|
+
*/
|
|
22
|
+
export declare const getTradeClosingPriceImpactAtOracle: (input: Omit<TradeClosingPriceImpactInput, "currentPairPrice">, context: TradeClosingPriceImpactContext) => TradeClosingPriceImpactResult;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @dev Trade closing price impact calculations
|
|
4
|
+
* @dev Mirrors contract's TradingCommonUtils.getTradeClosingPriceImpact
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.getTradeClosingPriceImpactAtOracle = exports.getTradeClosingPriceImpact = exports.buildTradeClosingPriceImpactContext = void 0;
|
|
8
|
+
const cumulVol_1 = require("../cumulVol");
|
|
9
|
+
const skew_1 = require("../skew");
|
|
10
|
+
const types_1 = require("../../../contracts/types");
|
|
11
|
+
const pnl_1 = require("../../pnl");
|
|
12
|
+
const __1 = require("../");
|
|
13
|
+
// Export builder
|
|
14
|
+
var builder_1 = require("./builder");
|
|
15
|
+
Object.defineProperty(exports, "buildTradeClosingPriceImpactContext", { enumerable: true, get: function () { return builder_1.buildTradeClosingPriceImpactContext; } });
|
|
16
|
+
/**
|
|
17
|
+
* @dev Calculates position size in tokens for the portion being closed
|
|
18
|
+
* @param positionSizeCollateral Position size in collateral units being closed
|
|
19
|
+
* @param originalPositionSizeToken Original total position size in tokens
|
|
20
|
+
* @param originalCollateral Original collateral amount
|
|
21
|
+
* @param originalLeverage Original leverage
|
|
22
|
+
* @returns Position size in tokens for the closing portion
|
|
23
|
+
*/
|
|
24
|
+
const calculateClosingPositionSizeToken = (positionSizeCollateral, originalPositionSizeToken, originalCollateral, originalLeverage) => {
|
|
25
|
+
const totalPositionSizeCollateral = originalCollateral * originalLeverage;
|
|
26
|
+
if (totalPositionSizeCollateral === 0)
|
|
27
|
+
return 0;
|
|
28
|
+
// (positionSizeCollateral * originalPositionSizeToken) / totalPositionSizeCollateral
|
|
29
|
+
return ((positionSizeCollateral * originalPositionSizeToken) /
|
|
30
|
+
totalPositionSizeCollateral);
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* @dev Calculates all price impacts for trade closing
|
|
34
|
+
* @dev Mirrors contract's getTradeClosingPriceImpact function
|
|
35
|
+
* @param input Trade parameters
|
|
36
|
+
* @param context Combined context for calculations
|
|
37
|
+
* @returns Price impact breakdown and trade value
|
|
38
|
+
*/
|
|
39
|
+
const getTradeClosingPriceImpact = (input, context) => {
|
|
40
|
+
// For trades before V9.2, return oracle price without any impact
|
|
41
|
+
if (input.contractsVersion === types_1.ContractsVersion.BEFORE_V9_2) {
|
|
42
|
+
return {
|
|
43
|
+
positionSizeToken: 0,
|
|
44
|
+
fixedSpreadP: 0,
|
|
45
|
+
cumulVolPriceImpactP: 0,
|
|
46
|
+
baseSkewPriceImpactP: 0,
|
|
47
|
+
tradeSkewPriceImpactP: 0,
|
|
48
|
+
totalSkewPriceImpactP: 0,
|
|
49
|
+
totalPriceImpactP: 0,
|
|
50
|
+
totalPriceImpactPFromMarketPrice: 0,
|
|
51
|
+
priceAfterImpact: input.oraclePrice,
|
|
52
|
+
tradeValueCollateralNoFactor: 0,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
// Calculate position size in tokens (proportional to collateral being closed)
|
|
56
|
+
const positionSizeToken = input.trade.positionSizeToken
|
|
57
|
+
? calculateClosingPositionSizeToken(input.positionSizeCollateral, input.trade.positionSizeToken, input.trade.collateralAmount, input.trade.leverage)
|
|
58
|
+
: 0;
|
|
59
|
+
// Calculate fixed spread (reversed for closing)
|
|
60
|
+
const fixedSpreadP = (0, cumulVol_1.getFixedSpreadP)(input.pairSpreadP, input.trade.long, false // closing
|
|
61
|
+
);
|
|
62
|
+
let cumulVolPriceImpactP = 0;
|
|
63
|
+
let tradeValueCollateralNoFactor = 0;
|
|
64
|
+
if (input.useCumulativeVolPriceImpact) {
|
|
65
|
+
// First pass: Calculate with negative PnL assumption
|
|
66
|
+
const positionSizeUsd = input.positionSizeCollateral * context.collateralPriceUsd;
|
|
67
|
+
cumulVolPriceImpactP = (0, cumulVol_1.getTradeCumulVolPriceImpactP)(input.trade.user, input.pairIndex, input.trade.long, positionSizeUsd, false, // Assume negative PnL initially
|
|
68
|
+
false, // closing
|
|
69
|
+
context.tradeInfo.lastPosIncreaseBlock || context.tradeInfo.createdBlock, context.cumulVolContext);
|
|
70
|
+
// Calculate price with conservative impact
|
|
71
|
+
const priceWithImpact = (0, __1.getPriceAfterImpact)(input.currentPairPrice, fixedSpreadP + cumulVolPriceImpactP);
|
|
72
|
+
// Calculate PnL percentage using the proper function
|
|
73
|
+
const pnlPercent = (0, pnl_1.getPnlPercent)(input.trade.openPrice, priceWithImpact, input.trade.long, input.trade.leverage);
|
|
74
|
+
// Calculate trade value using getTradeValue function
|
|
75
|
+
// Note: We don't include fees here as this is the raw trade value
|
|
76
|
+
tradeValueCollateralNoFactor = (0, pnl_1.getTradeValue)(input.trade.collateralAmount, pnlPercent, 0 // No fees for raw trade value calculation
|
|
77
|
+
);
|
|
78
|
+
// Determine actual PnL from the calculated percentage
|
|
79
|
+
const isPnlPositive = pnlPercent > 0;
|
|
80
|
+
// Second pass: Recalculate with actual PnL if positive
|
|
81
|
+
if (isPnlPositive) {
|
|
82
|
+
cumulVolPriceImpactP = (0, cumulVol_1.getTradeCumulVolPriceImpactP)(input.trade.user, input.pairIndex, input.trade.long, positionSizeUsd, true, // Positive PnL
|
|
83
|
+
false, // closing
|
|
84
|
+
context.tradeInfo.lastPosIncreaseBlock ||
|
|
85
|
+
context.tradeInfo.createdBlock, context.cumulVolContext);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// Calculate skew price impact (v10+ only)
|
|
89
|
+
const skewPriceImpactObject = input.contractsVersion >= types_1.ContractsVersion.V10
|
|
90
|
+
? (0, skew_1.getTradeSkewPriceImpact)({
|
|
91
|
+
collateralIndex: input.collateralIndex,
|
|
92
|
+
pairIndex: input.pairIndex,
|
|
93
|
+
long: input.trade.long,
|
|
94
|
+
open: false,
|
|
95
|
+
positionSizeToken,
|
|
96
|
+
}, context.skewContext)
|
|
97
|
+
: {
|
|
98
|
+
basePriceImpactP: 0,
|
|
99
|
+
tradePriceImpactP: 0,
|
|
100
|
+
totalPriceImpactP: 0,
|
|
101
|
+
};
|
|
102
|
+
// Total price impact (all components)
|
|
103
|
+
const totalPriceImpactP = fixedSpreadP +
|
|
104
|
+
cumulVolPriceImpactP +
|
|
105
|
+
skewPriceImpactObject.totalPriceImpactP;
|
|
106
|
+
const totalPriceImpactPFromMarketPrice = fixedSpreadP +
|
|
107
|
+
cumulVolPriceImpactP +
|
|
108
|
+
skewPriceImpactObject.tradePriceImpactP;
|
|
109
|
+
// Calculate final price after all impacts
|
|
110
|
+
const priceAfterImpact = (0, __1.getPriceAfterImpact)(input.currentPairPrice, totalPriceImpactP);
|
|
111
|
+
return {
|
|
112
|
+
positionSizeToken,
|
|
113
|
+
fixedSpreadP,
|
|
114
|
+
cumulVolPriceImpactP,
|
|
115
|
+
baseSkewPriceImpactP: skewPriceImpactObject.basePriceImpactP,
|
|
116
|
+
tradeSkewPriceImpactP: skewPriceImpactObject.tradePriceImpactP,
|
|
117
|
+
totalSkewPriceImpactP: skewPriceImpactObject.totalPriceImpactP,
|
|
118
|
+
totalPriceImpactP,
|
|
119
|
+
totalPriceImpactPFromMarketPrice,
|
|
120
|
+
priceAfterImpact,
|
|
121
|
+
tradeValueCollateralNoFactor,
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
exports.getTradeClosingPriceImpact = getTradeClosingPriceImpact;
|
|
125
|
+
/**
|
|
126
|
+
* @dev Simplified version using oracle price as current price
|
|
127
|
+
* @param input Trade parameters (without currentPairPrice)
|
|
128
|
+
* @param context Combined context
|
|
129
|
+
* @returns Price impact breakdown and trade value
|
|
130
|
+
*/
|
|
131
|
+
const getTradeClosingPriceImpactAtOracle = (input, context) => {
|
|
132
|
+
return (0, exports.getTradeClosingPriceImpact)(Object.assign(Object.assign({}, input), { currentPairPrice: input.oraclePrice }), context);
|
|
133
|
+
};
|
|
134
|
+
exports.getTradeClosingPriceImpactAtOracle = getTradeClosingPriceImpactAtOracle;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @dev Types for trade closing price impact calculations
|
|
3
|
+
*/
|
|
4
|
+
import { CumulVolContext } from "../cumulVol";
|
|
5
|
+
import { SkewPriceImpactContext } from "../skew/types";
|
|
6
|
+
import { Trade, TradeInfo, PairIndex } from "../../types";
|
|
7
|
+
/**
|
|
8
|
+
* @dev Input parameters for trade closing price impact
|
|
9
|
+
* @dev Mirrors contract's TradePriceImpactInput struct
|
|
10
|
+
*/
|
|
11
|
+
export type TradeClosingPriceImpactInput = {
|
|
12
|
+
trade: Trade;
|
|
13
|
+
oraclePrice: number;
|
|
14
|
+
positionSizeCollateral: number;
|
|
15
|
+
currentPairPrice: number;
|
|
16
|
+
useCumulativeVolPriceImpact: boolean;
|
|
17
|
+
collateralIndex: number;
|
|
18
|
+
pairIndex: PairIndex;
|
|
19
|
+
pairSpreadP: number;
|
|
20
|
+
contractsVersion: number;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* @dev Context for trade closing price impact calculation
|
|
24
|
+
* Combines contexts from spread, cumul vol, and skew
|
|
25
|
+
*/
|
|
26
|
+
export type TradeClosingPriceImpactContext = {
|
|
27
|
+
collateralPriceUsd: number;
|
|
28
|
+
cumulVolContext: CumulVolContext;
|
|
29
|
+
skewContext: SkewPriceImpactContext;
|
|
30
|
+
tradeInfo: TradeInfo;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* @dev Result of trade closing price impact calculation
|
|
34
|
+
* @dev Mirrors contract's TradePriceImpact struct with additional return value
|
|
35
|
+
*/
|
|
36
|
+
export type TradeClosingPriceImpactResult = {
|
|
37
|
+
positionSizeToken: number;
|
|
38
|
+
fixedSpreadP: number;
|
|
39
|
+
cumulVolPriceImpactP: number;
|
|
40
|
+
baseSkewPriceImpactP: number;
|
|
41
|
+
tradeSkewPriceImpactP: number;
|
|
42
|
+
totalSkewPriceImpactP: number;
|
|
43
|
+
totalPriceImpactP: number;
|
|
44
|
+
totalPriceImpactPFromMarketPrice: number;
|
|
45
|
+
priceAfterImpact: number;
|
|
46
|
+
tradeValueCollateralNoFactor: number;
|
|
47
|
+
};
|