@gainsnetwork/sdk 0.2.71-rc4 → 1.0.0-rc2

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.
Files changed (247) hide show
  1. package/README.md +2 -2
  2. package/lib/backend/globalTrades/index.d.ts +11 -0
  3. package/lib/backend/globalTrades/index.js +69 -0
  4. package/lib/backend/index.d.ts +3 -0
  5. package/lib/backend/index.js +28 -0
  6. package/lib/backend/tradingVariables/backend.types.d.ts +318 -0
  7. package/lib/backend/tradingVariables/backend.types.js +2 -0
  8. package/lib/backend/tradingVariables/converter.d.ts +34 -0
  9. package/lib/backend/tradingVariables/converter.js +338 -0
  10. package/lib/backend/tradingVariables/index.d.ts +5 -0
  11. package/lib/backend/tradingVariables/index.js +96 -0
  12. package/lib/backend/tradingVariables/types.d.ts +113 -0
  13. package/lib/backend/tradingVariables/types.js +14 -0
  14. package/lib/constants.d.ts +0 -3
  15. package/lib/constants.js +7 -9
  16. package/lib/contracts/types/generated/GFarmTradingStorageV5.d.ts +1911 -0
  17. package/lib/contracts/types/generated/GFarmTradingStorageV5.js +2 -0
  18. package/lib/contracts/types/generated/GNSBorrowingFees.d.ts +1067 -0
  19. package/lib/contracts/types/generated/GNSBorrowingFees.js +2 -0
  20. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.d.ts +979 -0
  21. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.js +2 -0
  22. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.d.ts +1058 -0
  23. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.js +2 -0
  24. package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +2134 -293
  25. package/lib/contracts/types/generated/GNSNftRewardsV6.d.ts +533 -0
  26. package/lib/contracts/types/generated/GNSNftRewardsV6.js +2 -0
  27. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.d.ts +613 -0
  28. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.js +2 -0
  29. package/lib/contracts/types/generated/GNSPairInfosV6_1.d.ts +911 -0
  30. package/lib/contracts/types/generated/GNSPairInfosV6_1.js +2 -0
  31. package/lib/contracts/types/generated/GNSPairsStorageV6.d.ts +660 -0
  32. package/lib/contracts/types/generated/GNSPairsStorageV6.js +2 -0
  33. package/lib/contracts/types/generated/GNSTrading.d.ts +758 -0
  34. package/lib/contracts/types/generated/GNSTrading.js +2 -0
  35. package/lib/contracts/types/generated/GNSTradingCallbacks.d.ts +875 -0
  36. package/lib/contracts/types/generated/GNSTradingCallbacks.js +2 -0
  37. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.d.ts +806 -0
  38. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.js +2 -0
  39. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.d.ts +821 -0
  40. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.js +2 -0
  41. package/lib/contracts/types/generated/GNSTradingStorage.d.ts +1387 -0
  42. package/lib/contracts/types/generated/GNSTradingStorage.js +2 -0
  43. package/lib/contracts/types/generated/GToken.d.ts +78 -107
  44. package/lib/contracts/types/generated/GTokenV6_3_2.d.ts +1838 -0
  45. package/lib/contracts/types/generated/GTokenV6_3_2.js +2 -0
  46. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.d.ts +83 -0
  47. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.js +2691 -0
  48. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.d.ts +88 -0
  49. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.js +1654 -0
  50. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.d.ts +113 -0
  51. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.js +1742 -0
  52. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.d.ts +124 -0
  53. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.js +1784 -0
  54. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.d.ts +90 -53
  55. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +4496 -430
  56. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.d.ts +100 -0
  57. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.js +1116 -0
  58. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.d.ts +100 -0
  59. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.js +1003 -0
  60. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.d.ts +98 -0
  61. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.js +1485 -0
  62. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.d.ts +117 -0
  63. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.js +1265 -0
  64. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.d.ts +82 -0
  65. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.js +1273 -0
  66. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.d.ts +82 -0
  67. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.js +1326 -0
  68. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.d.ts +113 -0
  69. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.js +1428 -0
  70. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.d.ts +96 -0
  71. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.js +2241 -0
  72. package/lib/contracts/types/generated/factories/GNSTrading__factory.d.ts +95 -0
  73. package/lib/contracts/types/generated/factories/GNSTrading__factory.js +1071 -0
  74. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.d.ts +110 -0
  75. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.js +2682 -0
  76. package/lib/contracts/types/generated/factories/GToken__factory.d.ts +7 -0
  77. package/lib/contracts/types/generated/factories/GToken__factory.js +69 -142
  78. package/lib/contracts/types/index.d.ts +2 -1
  79. package/lib/contracts/types/index.js +1 -0
  80. package/lib/contracts/utils/openTrades.d.ts +1 -0
  81. package/lib/contracts/utils/openTrades.js +94 -56
  82. package/lib/contracts/utils/pairs.js +0 -3
  83. package/lib/index.d.ts +2 -0
  84. package/lib/index.js +5 -0
  85. package/lib/markets/collateral/converter.d.ts +5 -0
  86. package/lib/markets/collateral/converter.js +11 -0
  87. package/lib/markets/collateral/index.d.ts +1 -0
  88. package/lib/markets/collateral/index.js +17 -0
  89. package/lib/markets/collateral/types.d.ts +7 -0
  90. package/lib/markets/collateral/types.js +2 -0
  91. package/lib/markets/holdingFees/index.d.ts +46 -0
  92. package/lib/markets/holdingFees/index.js +105 -0
  93. package/lib/markets/holdingFees/types.d.ts +23 -0
  94. package/lib/markets/holdingFees/types.js +5 -0
  95. package/lib/markets/index.d.ts +5 -0
  96. package/lib/markets/index.js +5 -0
  97. package/lib/markets/leverage/builder.d.ts +12 -0
  98. package/lib/markets/leverage/builder.js +25 -0
  99. package/lib/markets/leverage/getMarketLeverageRestrictions.d.ts +7 -0
  100. package/lib/markets/leverage/getMarketLeverageRestrictions.js +38 -0
  101. package/lib/markets/leverage/index.d.ts +3 -0
  102. package/lib/markets/leverage/index.js +19 -0
  103. package/lib/markets/leverage/types.d.ts +15 -0
  104. package/lib/markets/leverage/types.js +2 -0
  105. package/lib/markets/oi/converter.d.ts +62 -0
  106. package/lib/markets/oi/converter.js +102 -0
  107. package/lib/markets/oi/fetcher.d.ts +58 -0
  108. package/lib/markets/oi/fetcher.js +181 -0
  109. package/lib/markets/oi/index.d.ts +49 -0
  110. package/lib/markets/oi/index.js +77 -0
  111. package/lib/markets/oi/types.d.ts +73 -0
  112. package/lib/markets/oi/types.js +6 -0
  113. package/lib/markets/oi/validation.d.ts +80 -0
  114. package/lib/markets/oi/validation.js +172 -0
  115. package/lib/markets/price/builder.d.ts +25 -0
  116. package/lib/markets/price/builder.js +69 -0
  117. package/lib/markets/price/index.d.ts +6 -0
  118. package/lib/markets/price/index.js +22 -0
  119. package/lib/markets/price/marketPrice.d.ts +13 -0
  120. package/lib/markets/price/marketPrice.js +35 -0
  121. package/lib/markets/price/types.d.ts +23 -0
  122. package/lib/markets/price/types.js +5 -0
  123. package/lib/trade/counterTrade/index.d.ts +2 -0
  124. package/lib/trade/counterTrade/index.js +18 -0
  125. package/lib/trade/counterTrade/types.d.ts +7 -0
  126. package/lib/trade/counterTrade/types.js +2 -0
  127. package/lib/trade/counterTrade/validateCounterTrade.d.ts +10 -0
  128. package/lib/trade/counterTrade/validateCounterTrade.js +29 -0
  129. package/lib/trade/effectiveLeverage/builder.d.ts +23 -0
  130. package/lib/trade/effectiveLeverage/builder.js +30 -0
  131. package/lib/trade/effectiveLeverage/getTradeNewEffectiveLeverage.d.ts +23 -0
  132. package/lib/trade/effectiveLeverage/getTradeNewEffectiveLeverage.js +64 -0
  133. package/lib/trade/effectiveLeverage/index.d.ts +3 -0
  134. package/lib/trade/effectiveLeverage/index.js +22 -0
  135. package/lib/trade/effectiveLeverage/types.d.ts +33 -0
  136. package/lib/trade/effectiveLeverage/types.js +2 -0
  137. package/lib/trade/fees/borrowing/builder.d.ts +14 -0
  138. package/lib/trade/fees/borrowing/builder.js +33 -0
  139. package/lib/trade/fees/borrowing/index.d.ts +23 -2
  140. package/lib/trade/fees/borrowing/index.js +50 -16
  141. package/lib/trade/fees/borrowingV2/builder.d.ts +6 -0
  142. package/lib/trade/fees/borrowingV2/builder.js +24 -0
  143. package/lib/trade/fees/borrowingV2/converter.d.ts +75 -0
  144. package/lib/trade/fees/borrowingV2/converter.js +132 -0
  145. package/lib/trade/fees/borrowingV2/fetcher.d.ts +75 -0
  146. package/lib/trade/fees/borrowingV2/fetcher.js +185 -0
  147. package/lib/trade/fees/borrowingV2/index.d.ts +48 -0
  148. package/lib/trade/fees/borrowingV2/index.js +112 -0
  149. package/lib/trade/fees/borrowingV2/types.d.ts +95 -0
  150. package/lib/trade/fees/borrowingV2/types.js +5 -0
  151. package/lib/trade/fees/converter.d.ts +48 -0
  152. package/lib/trade/fees/converter.js +114 -0
  153. package/lib/trade/fees/fundingFees/builder.d.ts +9 -0
  154. package/lib/trade/fees/fundingFees/builder.js +35 -0
  155. package/lib/trade/fees/fundingFees/converter.d.ts +102 -0
  156. package/lib/trade/fees/fundingFees/converter.js +196 -0
  157. package/lib/trade/fees/fundingFees/fetcher.d.ts +66 -0
  158. package/lib/trade/fees/fundingFees/fetcher.js +150 -0
  159. package/lib/trade/fees/fundingFees/index.d.ts +124 -0
  160. package/lib/trade/fees/fundingFees/index.js +309 -0
  161. package/lib/trade/fees/fundingFees/pairContext.d.ts +33 -0
  162. package/lib/trade/fees/fundingFees/pairContext.js +17 -0
  163. package/lib/trade/fees/fundingFees/types.d.ts +77 -0
  164. package/lib/trade/fees/fundingFees/types.js +5 -0
  165. package/lib/trade/fees/holdingFees/index.d.ts +46 -0
  166. package/lib/trade/fees/holdingFees/index.js +105 -0
  167. package/lib/trade/fees/holdingFees/types.d.ts +23 -0
  168. package/lib/trade/fees/holdingFees/types.js +5 -0
  169. package/lib/trade/fees/index.d.ts +8 -2
  170. package/lib/trade/fees/index.js +67 -16
  171. package/lib/trade/fees/tiers/converter.d.ts +54 -0
  172. package/lib/trade/fees/tiers/converter.js +81 -0
  173. package/lib/trade/fees/tiers/index.d.ts +18 -0
  174. package/lib/trade/fees/tiers/index.js +45 -1
  175. package/lib/trade/fees/trading/builder.d.ts +18 -0
  176. package/lib/trade/fees/trading/builder.js +20 -0
  177. package/lib/trade/fees/trading/converter.d.ts +32 -0
  178. package/lib/trade/fees/trading/converter.js +47 -0
  179. package/lib/trade/fees/trading/holdingFees.d.ts +28 -0
  180. package/lib/trade/fees/trading/holdingFees.js +66 -0
  181. package/lib/trade/fees/trading/holdingFeesStructured.d.ts +28 -0
  182. package/lib/trade/fees/trading/holdingFeesStructured.js +66 -0
  183. package/lib/trade/fees/trading/index.d.ts +62 -0
  184. package/lib/trade/fees/trading/index.js +155 -0
  185. package/lib/trade/fees/trading/types.d.ts +48 -0
  186. package/lib/trade/fees/trading/types.js +5 -0
  187. package/lib/trade/index.d.ts +5 -2
  188. package/lib/trade/index.js +5 -2
  189. package/lib/trade/liquidation/builder.d.ts +25 -0
  190. package/lib/trade/liquidation/builder.js +59 -0
  191. package/lib/trade/liquidation/converter.d.ts +23 -0
  192. package/lib/trade/liquidation/converter.js +46 -0
  193. package/lib/trade/liquidation/index.d.ts +29 -0
  194. package/lib/trade/liquidation/index.js +218 -0
  195. package/lib/trade/liquidation/types.d.ts +43 -0
  196. package/lib/trade/liquidation/types.js +2 -0
  197. package/lib/trade/pnl/builder.d.ts +16 -0
  198. package/lib/trade/pnl/builder.js +44 -0
  199. package/lib/trade/pnl/converter.d.ts +47 -0
  200. package/lib/trade/pnl/converter.js +72 -0
  201. package/lib/trade/pnl/index.d.ts +89 -0
  202. package/lib/trade/pnl/index.js +302 -0
  203. package/lib/trade/pnl/types.d.ts +79 -0
  204. package/lib/trade/pnl/types.js +5 -0
  205. package/lib/trade/priceImpact/close/builder.d.ts +23 -0
  206. package/lib/trade/priceImpact/close/builder.js +45 -0
  207. package/lib/trade/priceImpact/close/index.d.ts +22 -0
  208. package/lib/trade/priceImpact/close/index.js +134 -0
  209. package/lib/trade/priceImpact/close/types.d.ts +47 -0
  210. package/lib/trade/priceImpact/close/types.js +5 -0
  211. package/lib/trade/priceImpact/cumulVol/builder.d.ts +22 -0
  212. package/lib/trade/priceImpact/cumulVol/builder.js +43 -0
  213. package/lib/trade/priceImpact/cumulVol/converter.d.ts +31 -0
  214. package/lib/trade/priceImpact/cumulVol/converter.js +59 -0
  215. package/lib/trade/priceImpact/cumulVol/index.d.ts +108 -0
  216. package/lib/trade/priceImpact/cumulVol/index.js +235 -0
  217. package/lib/trade/priceImpact/index.d.ts +21 -0
  218. package/lib/trade/priceImpact/index.js +79 -0
  219. package/lib/trade/priceImpact/open/builder.d.ts +21 -0
  220. package/lib/trade/priceImpact/open/builder.js +43 -0
  221. package/lib/trade/priceImpact/open/index.d.ts +23 -0
  222. package/lib/trade/priceImpact/open/index.js +78 -0
  223. package/lib/trade/priceImpact/open/types.d.ts +44 -0
  224. package/lib/trade/priceImpact/open/types.js +5 -0
  225. package/lib/trade/priceImpact/skew/builder.d.ts +12 -0
  226. package/lib/trade/priceImpact/skew/builder.js +28 -0
  227. package/lib/trade/priceImpact/skew/converter.d.ts +46 -0
  228. package/lib/trade/priceImpact/skew/converter.js +81 -0
  229. package/lib/trade/priceImpact/skew/fetcher.d.ts +60 -0
  230. package/lib/trade/priceImpact/skew/fetcher.js +169 -0
  231. package/lib/trade/priceImpact/skew/index.d.ts +53 -0
  232. package/lib/trade/priceImpact/skew/index.js +148 -0
  233. package/lib/trade/priceImpact/skew/types.d.ts +44 -0
  234. package/lib/trade/priceImpact/skew/types.js +5 -0
  235. package/lib/trade/spread.d.ts +5 -18
  236. package/lib/trade/spread.js +17 -106
  237. package/lib/trade/types.d.ts +109 -12
  238. package/lib/trade/types.js +0 -3
  239. package/lib/trade/utils.d.ts +18 -0
  240. package/lib/trade/utils.js +30 -0
  241. package/lib/vault/index.d.ts +3 -1
  242. package/lib/vault/index.js +2 -2
  243. package/package.json +2 -1
  244. package/lib/trade/liquidation.d.ts +0 -12
  245. package/lib/trade/liquidation.js +0 -55
  246. package/lib/trade/pnl.d.ts +0 -10
  247. package/lib/trade/pnl.js +0 -33
@@ -0,0 +1,302 @@
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, executionPrice, {
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, {
210
+ currentBlock: context.currentBlock,
211
+ groups: context.groups,
212
+ pairs: context.pairs,
213
+ collateralPriceUsd: context.collateralPriceUsd,
214
+ });
215
+ }
216
+ let pnlPercentage = (pnlCollat / posCollat) * 100;
217
+ // Can be liquidated
218
+ if (pnlPercentage <=
219
+ (0, liquidation_1.getLiqPnlThresholdP)(liquidationParams, leverage) * -100) {
220
+ pnlPercentage = -100;
221
+ }
222
+ else {
223
+ // Calculate closing fee using the same function as opening fees
224
+ const positionSizeCollateral = posCollat * trade.leverage;
225
+ const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(0, // collateralIndex not used
226
+ trade.user, trade.pairIndex, positionSizeCollateral, (_a = trade.isCounterTrade) !== null && _a !== void 0 ? _a : false, {
227
+ fee: context.fee,
228
+ globalTradeFeeParams: context.globalTradeFeeParams,
229
+ collateralPriceUsd: context.collateralPriceUsd || 1,
230
+ traderFeeMultiplier: context.traderFeeMultiplier,
231
+ });
232
+ pnlCollat -= closingFee;
233
+ pnlPercentage = (pnlCollat / posCollat) * 100;
234
+ }
235
+ pnlPercentage = pnlPercentage < -100 ? -100 : pnlPercentage;
236
+ pnlCollat = (posCollat * pnlPercentage) / 100;
237
+ return [pnlCollat, pnlPercentage];
238
+ };
239
+ exports.getPnl = getPnl;
240
+ /**
241
+ * @dev Calculates the price needed to achieve a target PnL percentage
242
+ * @param targetPnlPercent The target PnL percentage (e.g., 50 for 50% profit, -25 for 25% loss)
243
+ * @param trade The trade to calculate for
244
+ * @param tradeInfo Trade info with timestamps
245
+ * @param context Context with fee calculation parameters
246
+ * @param netPnl Whether to include closing fees in the calculation
247
+ * @returns The price that would result in the target PnL percentage
248
+ */
249
+ const getPriceForTargetPnlPercentage = (targetPnlPercent, trade, tradeInfo, context, netPnl = false) => {
250
+ var _a, _b;
251
+ const { leverage, openPrice, long, collateralAmount } = trade;
252
+ const positionSizeCollateral = collateralAmount * leverage;
253
+ // Calculate holding fees - always use getTradePendingHoldingFeesCollateral
254
+ // This mirrors the contract's getTradeValueCollateral which always calls this function
255
+ const fees = (0, trading_1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, ((_a = context.tradeData) === null || _a === void 0 ? void 0 : _a.tradeFeesData) || {
256
+ realizedTradingFeesCollateral: 0,
257
+ realizedPnlCollateral: 0,
258
+ manuallyRealizedNegativePnlCollateral: 0,
259
+ alreadyTransferredNegativePnlCollateral: 0,
260
+ virtualAvailableCollateralInDiamond: 0,
261
+ initialAccFundingFeeP: 0,
262
+ initialAccBorrowingFeeP: 0,
263
+ }, openPrice, // Use open price as a baseline
264
+ {
265
+ contractsVersion: context.core.contractsVersion,
266
+ currentTimestamp: context.core.currentTimestamp,
267
+ collateralPriceUsd: context.core.collateralPriceUsd,
268
+ borrowingV1: context.borrowingV1,
269
+ borrowingV2: context.borrowingV2,
270
+ funding: context.funding,
271
+ initialAccFees: (_b = context.tradeData) === null || _b === void 0 ? void 0 : _b.initialAccFees,
272
+ });
273
+ const totalHoldingFees = fees.fundingFeeCollateral +
274
+ fees.borrowingFeeCollateral +
275
+ fees.borrowingFeeCollateral_old;
276
+ const targetPnlInCollateral = (collateralAmount * targetPnlPercent) / 100;
277
+ let targetPnlGross = targetPnlInCollateral + totalHoldingFees;
278
+ if (netPnl) {
279
+ // Include closing fees
280
+ const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(trade.collateralIndex, trade.user, trade.pairIndex, positionSizeCollateral, trade.isCounterTrade || false, {
281
+ fee: context.trading.fee,
282
+ globalTradeFeeParams: context.trading.globalTradeFeeParams,
283
+ collateralPriceUsd: context.core.collateralPriceUsd,
284
+ traderFeeMultiplier: context.trading.traderFeeMultiplier,
285
+ });
286
+ targetPnlGross += closingFee;
287
+ }
288
+ // Calculate the price
289
+ let price;
290
+ if (long) {
291
+ price = openPrice + (targetPnlGross * openPrice) / positionSizeCollateral;
292
+ }
293
+ else {
294
+ price = openPrice - (targetPnlGross * openPrice) / positionSizeCollateral;
295
+ }
296
+ return price;
297
+ };
298
+ exports.getPriceForTargetPnlPercentage = getPriceForTargetPnlPercentage;
299
+ // Re-export types
300
+ __exportStar(require("./types"), exports);
301
+ __exportStar(require("./converter"), exports);
302
+ __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,5 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Types for PnL calculations
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -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
+ };
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Types for trade closing price impact calculations
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });