@reyaxyz/api-sdk 0.17.1 → 0.18.1

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 (38) hide show
  1. package/dist/clients/api-client.js +1 -1
  2. package/dist/clients/api-client.js.map +1 -1
  3. package/dist/clients/helpers/exposure.calculator.js +436 -0
  4. package/dist/clients/helpers/exposure.calculator.js.map +1 -0
  5. package/dist/clients/helpers/number.js +13 -0
  6. package/dist/clients/helpers/number.js.map +1 -0
  7. package/dist/clients/helpers/trade.simulation.types.js +3 -0
  8. package/dist/clients/helpers/trade.simulation.types.js.map +1 -0
  9. package/dist/clients/modules/account.js +11 -0
  10. package/dist/clients/modules/account.js.map +1 -1
  11. package/dist/clients/modules/trade.simulation.js +43 -41
  12. package/dist/clients/modules/trade.simulation.js.map +1 -1
  13. package/dist/clients/types.js.map +1 -1
  14. package/dist/index.js +2 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/types/clients/helpers/exposure.calculator.d.ts +58 -0
  17. package/dist/types/clients/helpers/exposure.calculator.d.ts.map +1 -0
  18. package/dist/types/clients/helpers/number.d.ts +3 -0
  19. package/dist/types/clients/helpers/number.d.ts.map +1 -0
  20. package/dist/types/clients/helpers/trade.simulation.types.d.ts +104 -0
  21. package/dist/types/clients/helpers/trade.simulation.types.d.ts.map +1 -0
  22. package/dist/types/clients/modules/account.d.ts +3 -1
  23. package/dist/types/clients/modules/account.d.ts.map +1 -1
  24. package/dist/types/clients/modules/trade.simulation.d.ts +4 -1
  25. package/dist/types/clients/modules/trade.simulation.d.ts.map +1 -1
  26. package/dist/types/clients/types.d.ts +6 -2
  27. package/dist/types/clients/types.d.ts.map +1 -1
  28. package/dist/types/index.d.ts +2 -0
  29. package/dist/types/index.d.ts.map +1 -1
  30. package/package.json +4 -3
  31. package/src/clients/api-client.ts +1 -1
  32. package/src/clients/helpers/exposure.calculator.ts +792 -0
  33. package/src/clients/helpers/number.ts +8 -0
  34. package/src/clients/helpers/trade.simulation.types.ts +115 -0
  35. package/src/clients/modules/account.ts +11 -0
  36. package/src/clients/modules/trade.simulation.ts +106 -47
  37. package/src/clients/types.ts +9 -2
  38. package/src/index.ts +2 -0
@@ -30,7 +30,7 @@ var ApiClient = /** @class */ (function () {
30
30
  this._markets = new markets_1.default(this.apiEndpoint);
31
31
  this._account = new account_1.default(this.apiEndpoint);
32
32
  this._lp = new lp_1.default(this.apiEndpoint);
33
- this._trade_simulation = new trade_simulation_1.default();
33
+ this._trade_simulation = new trade_simulation_1.default(this._account);
34
34
  }
35
35
  ApiClient.configure = function (config) {
36
36
  ApiClient.config = config;
@@ -1 +1 @@
1
- {"version":3,"file":"api-client.js","sourceRoot":"/","sources":["clients/api-client.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,iDAK6B;AAC7B,8DAA8C;AAC9C,8DAA8C;AAC9C,gFAA+D;AAC/D,oDAAoC;AAEpC;;GAEG;AACH;IAYE,mBAAoB,MAAqB;QACvC,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,0BAAc,CAAC,CAAC,CAAC,uBAAW,CAAC;QACpE,SAAS,CAAC,MAAM,yBAAQ,SAAS,CAAC,MAAM,GAAK,MAAM,CAAE,CAAC;QACtD,IAAI,CAAC,QAAQ,GAAG,IAAI,iBAAa,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACpD,IAAI,CAAC,QAAQ,GAAG,IAAI,iBAAa,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACpD,IAAI,CAAC,GAAG,GAAG,IAAI,YAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC1C,IAAI,CAAC,iBAAiB,GAAG,IAAI,0BAAqB,EAAE,CAAC;IACvD,CAAC;IAEa,mBAAS,GAAvB,UAAwB,MAAqB;QAC3C,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC;QAC1B,SAAS,CAAC,QAAQ,GAAG,IAAI,SAAS,CAAC,MAAM,CAAC,CAAC;IAC7C,CAAC;IAEc,qBAAW,GAA1B;QACE,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;QACJ,CAAC;QACD,OAAO,SAAS,CAAC,QAAQ,CAAC;IAC5B,CAAC;IASD,sBAAkB,oBAAO;QAPzB;;;;;;WAMG;aACH;YACE,OAAO,SAAS,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC;QAC1C,CAAC;;;OAAA;IASD,sBAAkB,oBAAO;QAPzB;;;;;;WAMG;aACH;YACE,OAAO,SAAS,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC;QAC1C,CAAC;;;OAAA;IAgBD,sBAAkB,4BAAe;QAdjC;;;;;;;;;;;;WAYG;aAEH;YACE,OAAO,SAAS,CAAC,WAAW,EAAE,CAAC,iBAAiB,CAAC;QACnD,CAAC;;;OAAA;IAYD,sBAAkB,eAAE;QAVpB;;;;;;;;;WASG;aACH;YACE,OAAO,SAAS,CAAC,WAAW,EAAE,CAAC,GAAG,CAAC;QACrC,CAAC;;;OAAA;IArFc,gBAAM,GAAkB;QACrC,UAAU,EAAE,IAAI,EAAE,gBAAgB;QAClC,OAAO,EAAE,uBAAW,EAAE,yCAAyC;KAChE,CAAC;IAmFJ,gBAAC;CAAA,AAxFD,IAwFC;AAxFY,8BAAS","sourcesContent":["import {\n ServiceConfig,\n API_TIMEOUT,\n API_TESTNET,\n API_PRODUCTION,\n} from './helpers/constants';\nimport MarketsClient from './modules/markets';\nimport AccountClient from './modules/account';\nimport TradeSimulationClient from './modules/trade.simulation';\nimport LpClient from './modules/lp';\n\n/**\n * @description Client for API\n */\nexport class ApiClient {\n private static instance: ApiClient;\n private static config: ServiceConfig = {\n production: true, // default value\n timeout: API_TIMEOUT, // default value, e.g., 5000 milliseconds\n };\n private readonly apiEndpoint: string;\n private readonly _markets: MarketsClient;\n private readonly _account: AccountClient;\n private readonly _lp: LpClient;\n private readonly _trade_simulation: TradeSimulationClient;\n\n private constructor(config: ServiceConfig) {\n this.apiEndpoint = config.production ? API_PRODUCTION : API_TESTNET;\n ApiClient.config = { ...ApiClient.config, ...config };\n this._markets = new MarketsClient(this.apiEndpoint);\n this._account = new AccountClient(this.apiEndpoint);\n this._lp = new LpClient(this.apiEndpoint);\n this._trade_simulation = new TradeSimulationClient();\n }\n\n public static configure(config: ServiceConfig): void {\n ApiClient.config = config;\n ApiClient.instance = new ApiClient(config);\n }\n\n private static getInstance(): ApiClient {\n if (!ApiClient.instance) {\n throw new Error(\n 'ApiClient is not configured. Please configure it before using.',\n );\n }\n return ApiClient.instance;\n }\n\n /**\n * Provides access to the MarketsClient instance.\n * This getter allows for interacting with market-related API functionalities.\n *\n * @returns {MarketsClient} An instance of MarketsClient for market-related operations.\n * @memberof ApiClient\n */\n public static get markets(): MarketsClient {\n return ApiClient.getInstance()._markets;\n }\n\n /**\n * Provides access to the AccountClient instance.\n * This getter allows for interacting with account-related API functionalities.\n *\n * @returns {AccountClient} An instance of AccountClient for account-related operations.\n * @memberof ApiClient\n */\n public static get account(): AccountClient {\n return ApiClient.getInstance()._account;\n }\n\n /**\n * Provides access to the TradeSimulationClient instance.\n * This getter allows for interacting with trade simulation functionalities.\n * It ensures a singleton pattern by fetching the instance from the ApiClient's\n * private `_trade_simulation` property, ensuring that trade simulation operations\n * use a consistent client configuration and state.\n *\n * @returns {TradeSimulationClient} An instance of TradeSimulationClient for trade simulation operations.\n * @memberof ApiClient\n * @example\n * // Access the trade simulation client from the ApiClient\n * const tradeSimulationClient = ApiClient.tradeSimulation;\n */\n\n public static get tradeSimulation(): TradeSimulationClient {\n return ApiClient.getInstance()._trade_simulation;\n }\n\n /**\n * Gets the current instance of the LpClient from the ApiClient.\n *\n * This static getter allows access to the LpClient instance managed within the ApiClient's singleton instance. It is a convenience method for retrieving the LpClient directly, bypassing the need to manually access the internal `_lp` property of the ApiClient instance.\n *\n * @returns {LpClient} The LpClient instance currently held by the ApiClient.\n * @example\n * // Assuming ApiClient and LpClient are properly set up\n * const lpClient = ApiClient.lp;\n */\n public static get lp(): LpClient {\n return ApiClient.getInstance()._lp;\n }\n}\n"]}
1
+ {"version":3,"file":"api-client.js","sourceRoot":"/","sources":["clients/api-client.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,iDAK6B;AAC7B,8DAA8C;AAC9C,8DAA8C;AAC9C,gFAA+D;AAC/D,oDAAoC;AAEpC;;GAEG;AACH;IAYE,mBAAoB,MAAqB;QACvC,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,0BAAc,CAAC,CAAC,CAAC,uBAAW,CAAC;QACpE,SAAS,CAAC,MAAM,yBAAQ,SAAS,CAAC,MAAM,GAAK,MAAM,CAAE,CAAC;QACtD,IAAI,CAAC,QAAQ,GAAG,IAAI,iBAAa,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACpD,IAAI,CAAC,QAAQ,GAAG,IAAI,iBAAa,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACpD,IAAI,CAAC,GAAG,GAAG,IAAI,YAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC1C,IAAI,CAAC,iBAAiB,GAAG,IAAI,0BAAqB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACpE,CAAC;IAEa,mBAAS,GAAvB,UAAwB,MAAqB;QAC3C,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC;QAC1B,SAAS,CAAC,QAAQ,GAAG,IAAI,SAAS,CAAC,MAAM,CAAC,CAAC;IAC7C,CAAC;IAEc,qBAAW,GAA1B;QACE,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;QACJ,CAAC;QACD,OAAO,SAAS,CAAC,QAAQ,CAAC;IAC5B,CAAC;IASD,sBAAkB,oBAAO;QAPzB;;;;;;WAMG;aACH;YACE,OAAO,SAAS,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC;QAC1C,CAAC;;;OAAA;IASD,sBAAkB,oBAAO;QAPzB;;;;;;WAMG;aACH;YACE,OAAO,SAAS,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC;QAC1C,CAAC;;;OAAA;IAgBD,sBAAkB,4BAAe;QAdjC;;;;;;;;;;;;WAYG;aAEH;YACE,OAAO,SAAS,CAAC,WAAW,EAAE,CAAC,iBAAiB,CAAC;QACnD,CAAC;;;OAAA;IAYD,sBAAkB,eAAE;QAVpB;;;;;;;;;WASG;aACH;YACE,OAAO,SAAS,CAAC,WAAW,EAAE,CAAC,GAAG,CAAC;QACrC,CAAC;;;OAAA;IArFc,gBAAM,GAAkB;QACrC,UAAU,EAAE,IAAI,EAAE,gBAAgB;QAClC,OAAO,EAAE,uBAAW,EAAE,yCAAyC;KAChE,CAAC;IAmFJ,gBAAC;CAAA,AAxFD,IAwFC;AAxFY,8BAAS","sourcesContent":["import {\n ServiceConfig,\n API_TIMEOUT,\n API_TESTNET,\n API_PRODUCTION,\n} from './helpers/constants';\nimport MarketsClient from './modules/markets';\nimport AccountClient from './modules/account';\nimport TradeSimulationClient from './modules/trade.simulation';\nimport LpClient from './modules/lp';\n\n/**\n * @description Client for API\n */\nexport class ApiClient {\n private static instance: ApiClient;\n private static config: ServiceConfig = {\n production: true, // default value\n timeout: API_TIMEOUT, // default value, e.g., 5000 milliseconds\n };\n private readonly apiEndpoint: string;\n private readonly _markets: MarketsClient;\n private readonly _account: AccountClient;\n private readonly _lp: LpClient;\n private readonly _trade_simulation: TradeSimulationClient;\n\n private constructor(config: ServiceConfig) {\n this.apiEndpoint = config.production ? API_PRODUCTION : API_TESTNET;\n ApiClient.config = { ...ApiClient.config, ...config };\n this._markets = new MarketsClient(this.apiEndpoint);\n this._account = new AccountClient(this.apiEndpoint);\n this._lp = new LpClient(this.apiEndpoint);\n this._trade_simulation = new TradeSimulationClient(this._account);\n }\n\n public static configure(config: ServiceConfig): void {\n ApiClient.config = config;\n ApiClient.instance = new ApiClient(config);\n }\n\n private static getInstance(): ApiClient {\n if (!ApiClient.instance) {\n throw new Error(\n 'ApiClient is not configured. Please configure it before using.',\n );\n }\n return ApiClient.instance;\n }\n\n /**\n * Provides access to the MarketsClient instance.\n * This getter allows for interacting with market-related API functionalities.\n *\n * @returns {MarketsClient} An instance of MarketsClient for market-related operations.\n * @memberof ApiClient\n */\n public static get markets(): MarketsClient {\n return ApiClient.getInstance()._markets;\n }\n\n /**\n * Provides access to the AccountClient instance.\n * This getter allows for interacting with account-related API functionalities.\n *\n * @returns {AccountClient} An instance of AccountClient for account-related operations.\n * @memberof ApiClient\n */\n public static get account(): AccountClient {\n return ApiClient.getInstance()._account;\n }\n\n /**\n * Provides access to the TradeSimulationClient instance.\n * This getter allows for interacting with trade simulation functionalities.\n * It ensures a singleton pattern by fetching the instance from the ApiClient's\n * private `_trade_simulation` property, ensuring that trade simulation operations\n * use a consistent client configuration and state.\n *\n * @returns {TradeSimulationClient} An instance of TradeSimulationClient for trade simulation operations.\n * @memberof ApiClient\n * @example\n * // Access the trade simulation client from the ApiClient\n * const tradeSimulationClient = ApiClient.tradeSimulation;\n */\n\n public static get tradeSimulation(): TradeSimulationClient {\n return ApiClient.getInstance()._trade_simulation;\n }\n\n /**\n * Gets the current instance of the LpClient from the ApiClient.\n *\n * This static getter allows access to the LpClient instance managed within the ApiClient's singleton instance. It is a convenience method for retrieving the LpClient directly, bypassing the need to manually access the internal `_lp` property of the ApiClient instance.\n *\n * @returns {LpClient} The LpClient instance currently held by the ApiClient.\n * @example\n * // Assuming ApiClient and LpClient are properly set up\n * const lpClient = ApiClient.lp;\n */\n public static get lp(): LpClient {\n return ApiClient.getInstance()._lp;\n }\n}\n"]}
@@ -0,0 +1,436 @@
1
+ "use strict";
2
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
3
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
4
+ if (ar || !(i in from)) {
5
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
6
+ ar[i] = from[i];
7
+ }
8
+ }
9
+ return to.concat(ar || Array.prototype.slice.call(from));
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ExposureCommand = void 0;
16
+ var bignumber_js_1 = __importDefault(require("bignumber.js"));
17
+ var number_1 = require("./number");
18
+ var ExposureCommand = /** @class */ (function () {
19
+ function ExposureCommand(rootCollateralPoolId, oraclePrice, rate, accountBalancePerAsset, groupedByCollateral, riskMultipliers, riskMatrices, exchangeInfoPerAsset, positionInfoMarketConfiguration, uniqueTokenAddresses, uniqueQuoteCollaterals, tokenMarginInfoPerAsset, realizedPnLSum, unrealizedPnLSum) {
20
+ this.rootCollateralPoolId = rootCollateralPoolId;
21
+ this.oraclePrice = oraclePrice;
22
+ this.rate = rate;
23
+ this.accountBalancePerAsset = accountBalancePerAsset;
24
+ this.groupedByCollateral = groupedByCollateral;
25
+ this.riskMultipliers = riskMultipliers;
26
+ this.riskMatrices = riskMatrices;
27
+ this.exchangeInfoPerAsset = exchangeInfoPerAsset;
28
+ this.positionInfoMarketConfiguration = positionInfoMarketConfiguration;
29
+ this.uniqueTokenAddresses = uniqueTokenAddresses;
30
+ this.uniqueQuoteCollaterals = uniqueQuoteCollaterals;
31
+ this.tokenMarginInfoPerAsset = tokenMarginInfoPerAsset;
32
+ this.realizedPnLSum = realizedPnLSum;
33
+ this.unrealizedPnLSum = unrealizedPnLSum;
34
+ }
35
+ ExposureCommand.prototype.getState = function () {
36
+ return {
37
+ rootCollateralPoolId: this.rootCollateralPoolId,
38
+ oraclePrice: this.oraclePrice,
39
+ rate: this.rate,
40
+ accountBalancePerAsset: this.accountBalancePerAsset,
41
+ groupedByCollateral: this.groupedByCollateral,
42
+ riskMultipliers: this.riskMultipliers,
43
+ riskMatrices: this.riskMatrices,
44
+ exchangeInfoPerAsset: this.exchangeInfoPerAsset,
45
+ positionInfoMarketConfiguration: this.positionInfoMarketConfiguration,
46
+ uniqueTokenAddresses: this.uniqueTokenAddresses,
47
+ uniqueQuoteCollaterals: this.uniqueQuoteCollaterals,
48
+ tokenMarginInfoPerAsset: this.tokenMarginInfoPerAsset,
49
+ realizedPnLSum: this.realizedPnLSum,
50
+ unrealizedPnLSum: this.unrealizedPnLSum,
51
+ };
52
+ };
53
+ Object.defineProperty(ExposureCommand.prototype, "getUsdNodeMarginInfo", {
54
+ get: function () {
55
+ return ExposureCommand.getUsdNodeMarginInfo(this.rootCollateralPoolId, this.uniqueTokenAddresses, this.exchangeInfoPerAsset, this.tokenMarginInfoPerAsset);
56
+ },
57
+ enumerable: false,
58
+ configurable: true
59
+ });
60
+ Object.defineProperty(ExposureCommand.prototype, "balancePerAsset", {
61
+ get: function () {
62
+ return this.tokenMarginInfoPerAsset;
63
+ },
64
+ enumerable: false,
65
+ configurable: true
66
+ });
67
+ ExposureCommand.prototype.getUsdNodeMarginInfoPostTrade = function (positionAmount, collateralAddress, marketConfiguration) {
68
+ var positionInfoMarketConfiguration = __spreadArray([], this.positionInfoMarketConfiguration, true);
69
+ // Check if the market_id already exists in the array
70
+ var existingConfigIndex = positionInfoMarketConfiguration.findIndex(function (config) {
71
+ return config.market_id ===
72
+ (0, bignumber_js_1.default)(String(marketConfiguration.market_id)).toNumber();
73
+ });
74
+ if (existingConfigIndex !== -1) {
75
+ // If it exists, update the amount
76
+ positionInfoMarketConfiguration[existingConfigIndex].base = (0, bignumber_js_1.default)(positionInfoMarketConfiguration[existingConfigIndex].base).plus(positionAmount);
77
+ }
78
+ else {
79
+ // If it doesn't exist, add a new element
80
+ positionInfoMarketConfiguration.push({
81
+ base: (0, bignumber_js_1.default)(positionAmount),
82
+ realized_pnl: (0, bignumber_js_1.default)(0),
83
+ last_price: (0, bignumber_js_1.default)(0),
84
+ last_timestamp: (0, bignumber_js_1.default)(0),
85
+ funding_value: (0, bignumber_js_1.default)(0),
86
+ base_multiplier: (0, bignumber_js_1.default)(0),
87
+ adl_unwind_price: (0, bignumber_js_1.default)(0),
88
+ market_id: (0, bignumber_js_1.default)(String(marketConfiguration.market_id)).toNumber(),
89
+ market_configuration: marketConfiguration,
90
+ });
91
+ }
92
+ var uniqueQuoteCollaterals = new Set(this.uniqueQuoteCollaterals);
93
+ uniqueQuoteCollaterals.add(collateralAddress);
94
+ var tokenMarginInfoPerAsset = ExposureCommand.calculateTokenMarginInfoPerAsset(this.groupedByCollateral, this.rootCollateralPoolId, this.riskMatrices, this.riskMultipliers, uniqueQuoteCollaterals, this.realizedPnLSum, this.unrealizedPnLSum, positionInfoMarketConfiguration, this.oraclePrice);
95
+ var uniqueTokenAddresses = __spreadArray([], this.uniqueTokenAddresses, true);
96
+ if (!this.uniqueTokenAddresses.includes(collateralAddress)) {
97
+ uniqueTokenAddresses.push(collateralAddress);
98
+ }
99
+ return ExposureCommand.getUsdNodeMarginInfo(this.rootCollateralPoolId, uniqueTokenAddresses, this.exchangeInfoPerAsset, tokenMarginInfoPerAsset);
100
+ };
101
+ ExposureCommand.calculateTokenMarginInfoPerAsset = function (groupedByCollateral, rootCollateralPoolId, riskMatrices, riskMultipliers, uniqueQuoteCollaterals, realizedPnLSum, unrealizedPnLSum, positionInfoMarketConfiguration, oraclePrice) {
102
+ var _a;
103
+ var tokenMarginInfoPerAsset = [];
104
+ var uniqueQuoteTokens = Array.from(uniqueQuoteCollaterals);
105
+ var tokenUnion = new Set(__spreadArray(__spreadArray([], Object.keys(groupedByCollateral), true), uniqueQuoteTokens, true)); // get unique union of those arrays
106
+ var uniqueTokenAddresses = Array.from(tokenUnion);
107
+ for (var _i = 0, uniqueTokenAddresses_1 = uniqueTokenAddresses; _i < uniqueTokenAddresses_1.length; _i++) {
108
+ var token = uniqueTokenAddresses_1[_i];
109
+ tokenMarginInfoPerAsset.push(ExposureCommand.getTokenMarginInfo(rootCollateralPoolId, riskMatrices, riskMultipliers, ExposureCommand.getCollateralInfo(token, uniqueQuoteCollaterals.has(token) ? realizedPnLSum : (0, bignumber_js_1.default)(0), uniqueQuoteCollaterals.has(token) ? unrealizedPnLSum : (0, bignumber_js_1.default)(0), ((_a = groupedByCollateral[token]) === null || _a === void 0 ? void 0 : _a.amount) || 0), token, positionInfoMarketConfiguration, oraclePrice));
110
+ }
111
+ return tokenMarginInfoPerAsset;
112
+ };
113
+ ExposureCommand.calculateLiquidation = function (globalMarginInfo, oraclePrice, positionBase) {
114
+ var liquidationPrice = (0, bignumber_js_1.default)(oraclePrice).minus((0, bignumber_js_1.default)(globalMarginInfo.marginBalance)
115
+ .minus(globalMarginInfo.liquidationMarginRequirement)
116
+ .div(positionBase));
117
+ return bignumber_js_1.default.max(0, liquidationPrice);
118
+ };
119
+ ExposureCommand.calculateImpliedLeverage = function (notionalExposure, oldIMR, newIMR) {
120
+ var changeInImr = (0, bignumber_js_1.default)(newIMR).minus(oldIMR);
121
+ if (changeInImr.eq(0)) {
122
+ return 0;
123
+ }
124
+ return (0, bignumber_js_1.default)(notionalExposure).div(changeInImr).toNumber();
125
+ };
126
+ ExposureCommand.combineMarginInfo = function (parentMarginInfo, sonMarginInfo, sonParentExchangeInfo) {
127
+ return {
128
+ assetAddress: parentMarginInfo.assetAddress,
129
+ marginBalance: (0, bignumber_js_1.default)(parentMarginInfo.marginBalance)
130
+ .plus(ExposureCommand.exchangeWithPriceHaircut(sonMarginInfo.marginBalance, sonParentExchangeInfo.price, sonParentExchangeInfo.priceHaircut))
131
+ .toNumber(),
132
+ realBalance: (0, bignumber_js_1.default)(parentMarginInfo.realBalance)
133
+ .plus(ExposureCommand.exchangeWithPriceHaircut(sonMarginInfo.realBalance, sonParentExchangeInfo.price, sonParentExchangeInfo.priceHaircut))
134
+ .toNumber(),
135
+ initialDelta: (0, bignumber_js_1.default)(parentMarginInfo.initialDelta)
136
+ .plus(ExposureCommand.exchangeWithPriceHaircut(bignumber_js_1.default.min(sonMarginInfo.realBalance, sonMarginInfo.initialDelta).toNumber(), sonParentExchangeInfo.price, sonParentExchangeInfo.priceHaircut))
137
+ .toNumber(),
138
+ maintenanceDelta: (0, bignumber_js_1.default)(parentMarginInfo.maintenanceDelta)
139
+ .plus(ExposureCommand.exchangeWithPriceHaircut(bignumber_js_1.default.min(sonMarginInfo.maintenanceDelta, sonMarginInfo.realBalance).toNumber(), sonParentExchangeInfo.price, sonParentExchangeInfo.priceHaircut))
140
+ .toNumber(),
141
+ liquidationDelta: (0, bignumber_js_1.default)(parentMarginInfo.liquidationDelta)
142
+ .plus(ExposureCommand.exchangeWithPriceHaircut(bignumber_js_1.default.min(sonMarginInfo.liquidationDelta, sonMarginInfo.realBalance).toNumber(), sonParentExchangeInfo.price, sonParentExchangeInfo.priceHaircut))
143
+ .toNumber(),
144
+ dutchDelta: (0, bignumber_js_1.default)(parentMarginInfo.dutchDelta)
145
+ .plus(ExposureCommand.exchangeWithPriceHaircut(bignumber_js_1.default.min(sonMarginInfo.dutchDelta, sonMarginInfo.realBalance).toNumber(), sonParentExchangeInfo.price, sonParentExchangeInfo.priceHaircut))
146
+ .toNumber(),
147
+ adlDelta: (0, bignumber_js_1.default)(parentMarginInfo.adlDelta)
148
+ .plus(ExposureCommand.exchangeWithPriceHaircut(bignumber_js_1.default.min(sonMarginInfo.adlDelta, sonMarginInfo.realBalance).toNumber(), sonParentExchangeInfo.price, sonParentExchangeInfo.priceHaircut))
149
+ .toNumber(),
150
+ initialBufferDelta: (0, bignumber_js_1.default)(parentMarginInfo.initialBufferDelta)
151
+ .plus(ExposureCommand.exchangeWithPriceHaircut(bignumber_js_1.default.min(sonMarginInfo.initialBufferDelta, sonMarginInfo.realBalance).toNumber(), sonParentExchangeInfo.price, sonParentExchangeInfo.priceHaircut))
152
+ .toNumber(),
153
+ liquidationMarginRequirement: (0, bignumber_js_1.default)(parentMarginInfo.liquidationMarginRequirement)
154
+ .plus(ExposureCommand.exchangeWithPriceHaircut(sonMarginInfo.liquidationMarginRequirement, sonParentExchangeInfo.price, sonParentExchangeInfo.priceHaircut))
155
+ .toNumber(),
156
+ };
157
+ };
158
+ ExposureCommand.getUsdNodeMarginInfo = function (accountCollateralPoolId, quoteTokens, exchangeInfoPerAsset, marginInfoPerToken) {
159
+ var usdNodeMarginInfo = {
160
+ assetAddress: '',
161
+ marginBalance: 0,
162
+ realBalance: 0,
163
+ initialDelta: 0,
164
+ maintenanceDelta: 0,
165
+ liquidationDelta: 0,
166
+ dutchDelta: 0,
167
+ adlDelta: 0,
168
+ initialBufferDelta: 0,
169
+ liquidationMarginRequirement: 0,
170
+ };
171
+ var _loop_1 = function (quoteToken) {
172
+ var exchangeInfo = exchangeInfoPerAsset.find(function (exchangeInfo) {
173
+ return quoteToken === exchangeInfo.tokenAddress;
174
+ });
175
+ var marginInfo = marginInfoPerToken.find(function (marginInfo) {
176
+ return quoteToken === marginInfo.assetAddress;
177
+ });
178
+ if (!exchangeInfo || !marginInfo) {
179
+ throw Error('Missing exchangeInfo/marginInfo');
180
+ }
181
+ usdNodeMarginInfo = ExposureCommand.combineMarginInfo(usdNodeMarginInfo, marginInfo, exchangeInfo);
182
+ };
183
+ for (var _i = 0, quoteTokens_1 = quoteTokens; _i < quoteTokens_1.length; _i++) {
184
+ var quoteToken = quoteTokens_1[_i];
185
+ _loop_1(quoteToken);
186
+ }
187
+ return usdNodeMarginInfo;
188
+ };
189
+ ExposureCommand.getCollateralInfo = function (collateralAddress, realisedPnl, unrealizedPnL, netDeposits) {
190
+ return {
191
+ netDeposits: netDeposits,
192
+ marginBalance: (0, bignumber_js_1.default)(netDeposits)
193
+ .plus(realisedPnl)
194
+ .plus(unrealizedPnL)
195
+ .toNumber(),
196
+ realBalance: (0, bignumber_js_1.default)(netDeposits).plus(realisedPnl).toNumber(),
197
+ };
198
+ };
199
+ ExposureCommand.getTokenMarginInfo = function (rootCollateralPoolId, riskMatrices, riskMultipliers, collateralInfo, collateralAddress, positions, oraclePrice) {
200
+ var marginRequirements = {
201
+ liquidationMarginRequirement: 0,
202
+ initialMarginRequirement: 0,
203
+ maintenanceMarginRequirement: 0,
204
+ dutchMarginRequirement: 0,
205
+ adlMarginRequirement: 0,
206
+ initialBufferMarginRequirement: 0,
207
+ };
208
+ for (var _i = 0, riskMatrices_1 = riskMatrices; _i < riskMatrices_1.length; _i++) {
209
+ var riskMatrix = riskMatrices_1[_i];
210
+ var filledExposures = ExposureCommand.getBlockExposures(positions, oraclePrice);
211
+ marginRequirements.liquidationMarginRequirement = (0, bignumber_js_1.default)(marginRequirements.liquidationMarginRequirement)
212
+ .plus(ExposureCommand.computeLiquidationMarginRequirement(riskMatrix.matrix, filledExposures))
213
+ .toNumber();
214
+ }
215
+ // Get the initial margin requirement
216
+ marginRequirements.initialMarginRequirement = (0, number_1.amountNormalizer)(String(riskMultipliers.im_multiplier))
217
+ .multipliedBy(marginRequirements.liquidationMarginRequirement)
218
+ .toNumber();
219
+ // Get the maintenance margin requirement
220
+ marginRequirements.maintenanceMarginRequirement = (0, number_1.amountNormalizer)(String(riskMultipliers.mmr_multiplier))
221
+ .multipliedBy(marginRequirements.liquidationMarginRequirement)
222
+ .toNumber();
223
+ // Get the dutch margin requirement
224
+ marginRequirements.dutchMarginRequirement = (0, number_1.amountNormalizer)(String(riskMultipliers.dutch_multiplier))
225
+ .multipliedBy(marginRequirements.liquidationMarginRequirement)
226
+ .toNumber();
227
+ // Get the adl margin requirement
228
+ marginRequirements.adlMarginRequirement = (0, number_1.amountNormalizer)(String(riskMultipliers.adl_multiplier))
229
+ .multipliedBy(marginRequirements.liquidationMarginRequirement)
230
+ .toNumber();
231
+ // Get the initial buffer margin requirement
232
+ marginRequirements.initialBufferMarginRequirement = (0, number_1.amountNormalizer)(String(riskMultipliers.im_buffer_multiplier))
233
+ .multipliedBy(marginRequirements.liquidationMarginRequirement)
234
+ .toNumber();
235
+ return {
236
+ assetAddress: collateralAddress,
237
+ marginBalance: collateralInfo.marginBalance,
238
+ realBalance: collateralInfo.realBalance,
239
+ initialDelta: (0, bignumber_js_1.default)(collateralInfo.marginBalance)
240
+ .minus(marginRequirements.initialMarginRequirement)
241
+ .toNumber(),
242
+ maintenanceDelta: (0, bignumber_js_1.default)(collateralInfo.marginBalance)
243
+ .minus(marginRequirements.maintenanceMarginRequirement)
244
+ .toNumber(),
245
+ liquidationDelta: (0, bignumber_js_1.default)(collateralInfo.marginBalance)
246
+ .minus(marginRequirements.liquidationMarginRequirement)
247
+ .toNumber(),
248
+ dutchDelta: (0, bignumber_js_1.default)(collateralInfo.marginBalance)
249
+ .minus(marginRequirements.dutchMarginRequirement)
250
+ .toNumber(),
251
+ adlDelta: (0, bignumber_js_1.default)(collateralInfo.marginBalance)
252
+ .minus(marginRequirements.adlMarginRequirement)
253
+ .toNumber(),
254
+ initialBufferDelta: (0, bignumber_js_1.default)(collateralInfo.marginBalance)
255
+ .minus(marginRequirements.initialBufferMarginRequirement)
256
+ .toNumber(),
257
+ liquidationMarginRequirement: marginRequirements.liquidationMarginRequirement,
258
+ };
259
+ };
260
+ ExposureCommand.computeLiquidationMarginRequirement = function (matrix, filledExposures) {
261
+ var lmrFilledSquared = 0;
262
+ for (var i = 0; i < filledExposures.length; i++) {
263
+ if ((0, bignumber_js_1.default)(filledExposures[i]).eq(0)) {
264
+ continue;
265
+ }
266
+ for (var j = 0; j < filledExposures.length; j++) {
267
+ var riskParam = matrix[i][j];
268
+ if ((0, bignumber_js_1.default)(filledExposures[j]).eq(0) || (0, bignumber_js_1.default)(riskParam).eq(0)) {
269
+ continue;
270
+ }
271
+ lmrFilledSquared = (0, bignumber_js_1.default)(lmrFilledSquared)
272
+ .plus((0, bignumber_js_1.default)(filledExposures[i])
273
+ .multipliedBy(filledExposures[j])
274
+ .multipliedBy(riskParam))
275
+ .toNumber();
276
+ }
277
+ }
278
+ return (0, bignumber_js_1.default)(lmrFilledSquared).sqrt().toNumber();
279
+ };
280
+ ExposureCommand.getBlockExposures = function (positions, oraclePrice) {
281
+ var filledExposures = [];
282
+ for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
283
+ var position = positions_1[_i];
284
+ var marketFilledExposure = ExposureCommand.getAccountFilledExposures(position, position.market_configuration, oraclePrice);
285
+ filledExposures[marketFilledExposure.riskMatrixIndex] = (0, bignumber_js_1.default)(filledExposures[marketFilledExposure.riskMatrixIndex] || 0)
286
+ .plus(marketFilledExposure.exposure)
287
+ .toNumber();
288
+ }
289
+ return filledExposures.map(function (num) { return (0, bignumber_js_1.default)(num); });
290
+ };
291
+ ExposureCommand.getAccountFilledExposures = function (position, marketConfiguration, oraclePrice) {
292
+ var base = position.base;
293
+ return {
294
+ exposure: (0, bignumber_js_1.default)(oraclePrice).multipliedBy(base),
295
+ riskMatrixIndex: (0, bignumber_js_1.default)(String(marketConfiguration.risk_matrix_index)).toNumber(),
296
+ };
297
+ };
298
+ ExposureCommand.computePricePnL = function (openBase, openPrice, exitPrice) {
299
+ return (0, bignumber_js_1.default)((0, bignumber_js_1.default)(exitPrice).minus(openPrice).multipliedBy(openBase));
300
+ };
301
+ ExposureCommand.getMarginRatio = function (marginInfo) {
302
+ if (marginInfo.liquidationMarginRequirement === 0) {
303
+ return 0;
304
+ }
305
+ if (marginInfo.marginBalance <= 0) {
306
+ return 1;
307
+ }
308
+ var health = (0, bignumber_js_1.default)(marginInfo.liquidationMarginRequirement).div(marginInfo.marginBalance);
309
+ if (health.gt(1)) {
310
+ return 1;
311
+ }
312
+ return health.toNumber();
313
+ };
314
+ ExposureCommand.exchangeWithPriceHaircut = function (quantity, price, haircut) {
315
+ // For positive quantities, the haircut is `quantity * (1 - haircut)`
316
+ // For negative values, the haircut is `quantity / (1 - haircut)` because a negative value means the haircut should be applied from B to A.
317
+ var calHelper = (0, bignumber_js_1.default)(quantity).gt(0)
318
+ ? (0, bignumber_js_1.default)(1).minus(haircut)
319
+ : (0, bignumber_js_1.default)(1).div((0, bignumber_js_1.default)(1).minus(haircut));
320
+ var haircutPrice = (0, bignumber_js_1.default)(price).multipliedBy(calHelper);
321
+ return haircutPrice.multipliedBy(quantity).toNumber();
322
+ };
323
+ ExposureCommand.prototype.getSlippage = function (deltaBase, marketConfiguration, marketStorage) {
324
+ var deltaExposure = (0, bignumber_js_1.default)(this.oraclePrice)
325
+ .times(deltaBase)
326
+ .toNumber();
327
+ var riskMatrixIndex = (0, bignumber_js_1.default)(String(marketConfiguration.risk_matrix_index)).toNumber();
328
+ var _a = this.getMaxExposure(marketConfiguration, marketStorage), maxExposureShort = _a.maxExposureShort, maxExposureLong = _a.maxExposureLong, exposures = _a.exposures;
329
+ var netExposure = exposures[riskMatrixIndex].plus(deltaExposure);
330
+ var maxExposure = netExposure.lt(0) ? maxExposureShort : maxExposureLong;
331
+ return (0, bignumber_js_1.default)(netExposure)
332
+ .negated()
333
+ .div((0, bignumber_js_1.default)(maxExposure).plus(netExposure))
334
+ .toNumber();
335
+ };
336
+ ExposureCommand.prototype.getMaxExposure = function (marketConfiguration, marketStorage) {
337
+ var riskMatrix = this.riskMatrices.find(function (riskMatrix) {
338
+ return (riskMatrix.risk_block_id ===
339
+ (0, bignumber_js_1.default)(String(marketStorage.risk_block_id)).toNumber());
340
+ });
341
+ if (!riskMatrix) {
342
+ throw new Error("RiskMatrix Doesn't exist");
343
+ }
344
+ var riskMatrixIndex = (0, bignumber_js_1.default)(String(marketConfiguration.risk_matrix_index)).toNumber();
345
+ var imrMultiplier = (0, number_1.amountNormalizer)(String(this.riskMultipliers.im_multiplier)).toNumber();
346
+ var marginInfo = this.tokenMarginInfoPerAsset.find(function (marginInfo) {
347
+ return marginInfo.assetAddress === marketStorage.quote_collateral;
348
+ });
349
+ if (!marginInfo) {
350
+ throw new Error("marginInfo doesn't exist");
351
+ }
352
+ var exposures = ExposureCommand.getBlockExposures(this.positionInfoMarketConfiguration, this.oraclePrice);
353
+ var _a = ExposureCommand.computeMaxExposures(riskMatrix.matrix, exposures, marginInfo.liquidationMarginRequirement, marginInfo.marginBalance < 0 ? 0 : marginInfo.marginBalance, imrMultiplier, riskMatrixIndex), maxExposureShort = _a.maxExposureShort, maxExposureLong = _a.maxExposureLong;
354
+ return {
355
+ maxExposureShort: maxExposureShort,
356
+ maxExposureLong: maxExposureLong,
357
+ exposures: exposures,
358
+ };
359
+ };
360
+ ExposureCommand.computeMaxExposures = function (riskMatrix, exposures, lmr, balance, imrMultiplier, exposureIndex) {
361
+ var b = (0, bignumber_js_1.default)(0);
362
+ for (var i = 0; i < exposures.length; i++) {
363
+ b = (0, bignumber_js_1.default)(b).plus((0, bignumber_js_1.default)(exposures[i]).multipliedBy((0, bignumber_js_1.default)(riskMatrix[exposureIndex][i]).plus(riskMatrix[i][exposureIndex])));
364
+ }
365
+ var _a = this.solveQuadraticEquation((0, bignumber_js_1.default)(riskMatrix[exposureIndex][exposureIndex]).toNumber(), // changes here
366
+ b.toNumber(), this.computeC(lmr, balance, imrMultiplier)), x1 = _a.x1, x2 = _a.x2;
367
+ var maxShortExposure = (0, bignumber_js_1.default)(x1).plus(exposures[exposureIndex]);
368
+ var maxLongExposure = (0, bignumber_js_1.default)(x2).plus(exposures[exposureIndex]);
369
+ var availableShortExposure = maxShortExposure.lt(0)
370
+ ? maxShortExposure.negated().toNumber()
371
+ : 0;
372
+ var availableLongExposure = maxLongExposure.gt(0)
373
+ ? maxLongExposure.toNumber()
374
+ : 0;
375
+ return {
376
+ maxExposureShort: availableShortExposure,
377
+ maxExposureLong: availableLongExposure,
378
+ };
379
+ };
380
+ ExposureCommand.solveQuadraticEquation = function (a, b, c) {
381
+ if ((0, bignumber_js_1.default)(a).eq(0)) {
382
+ throw new Error('ZeroQuadraticCoefficient');
383
+ }
384
+ var delta = (0, bignumber_js_1.default)(b)
385
+ .multipliedBy(b)
386
+ .minus((0, bignumber_js_1.default)(4).multipliedBy(a).multipliedBy(c));
387
+ if (delta.lt(0)) {
388
+ throw new Error('ComplexQuadraticRoots(a, b, c)');
389
+ }
390
+ var rootDelta = delta.sqrt();
391
+ var x1 = (0, bignumber_js_1.default)(b)
392
+ .multipliedBy(-1)
393
+ .minus(rootDelta)
394
+ .div((0, bignumber_js_1.default)(2).multipliedBy(a));
395
+ var x2 = (0, bignumber_js_1.default)(b)
396
+ .multipliedBy(-1)
397
+ .plus(rootDelta)
398
+ .div((0, bignumber_js_1.default)(2).multipliedBy(a));
399
+ return {
400
+ x1: x1,
401
+ x2: x2,
402
+ };
403
+ };
404
+ ExposureCommand.computeC = function (lmr, balance, imrMultiplier) {
405
+ var lmrSD = (0, bignumber_js_1.default)(lmr);
406
+ var lmrSquared = lmrSD.multipliedBy(lmrSD);
407
+ var balanceSD = (0, bignumber_js_1.default)(balance);
408
+ var balanceSquared = balanceSD.multipliedBy(balanceSD);
409
+ var imrMultiplierSD = (0, bignumber_js_1.default)(imrMultiplier);
410
+ var imrMultiplierSquared = imrMultiplierSD.multipliedBy(imrMultiplierSD);
411
+ return lmrSquared
412
+ .minus(balanceSquared.div(imrMultiplierSquared))
413
+ .toNumber();
414
+ };
415
+ ExposureCommand.calculateFee = function (price, amount, feeParameter) {
416
+ return (0, bignumber_js_1.default)(price).times(amount).times(feeParameter).abs().toNumber(); // @todo abs value
417
+ };
418
+ ExposureCommand.calculateEstimatedPrice = function (price, slippage) {
419
+ return (0, bignumber_js_1.default)(price).times((0, bignumber_js_1.default)(1).plus(slippage)).toNumber();
420
+ };
421
+ ExposureCommand.evaluateHealthStatus = function (number) {
422
+ // todo update logic
423
+ if (number >= 67) {
424
+ return 'danger';
425
+ }
426
+ else if (number >= 34) {
427
+ return 'warning';
428
+ }
429
+ else {
430
+ return 'healthy';
431
+ }
432
+ };
433
+ return ExposureCommand;
434
+ }());
435
+ exports.ExposureCommand = ExposureCommand;
436
+ //# sourceMappingURL=exposure.calculator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exposure.calculator.js","sourceRoot":"/","sources":["clients/helpers/exposure.calculator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,8DAAqC;AAcrC,mCAA4C;AAE5C;IAeE,yBACE,oBAA4B,EAC5B,W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AoB,GAA3B,UAA4B,MAAc;QACxC,oBAAoB;QACpB,IAAI,MAAM,IAAI,EAAE,EAAE,CAAC;YACjB,OAAO,QAAQ,CAAC;QAClB,CAAC;aAAM,IAAI,MAAM,IAAI,EAAE,EAAE,CAAC;YACxB,OAAO,SAAS,CAAC;QACnB,CAAC;aAAM,CAAC;YACN,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;IACH,sBAAC;AAAD,CAAC,AAvwBD,IAuwBC;AAvwBY,0CAAe","sourcesContent":["import BigNumber from 'bignumber.js';\nimport {\n AccountAssetBalance,\n CollateralInfo,\n ExchangeInfo,\n ExposureCommandState,\n MarginInfo,\n MarketConfiguration,\n MarketStorage,\n PositionInfo,\n PositionInfoMarketConfiguration,\n RiskMatrix,\n RiskMultipliersConfiguration,\n} from './trade.simulation.types';\nimport { amountNormalizer } from './number';\n\nexport class ExposureCommand {\n rootCollateralPoolId: number;\n oraclePrice: number;\n rate: number;\n accountBalancePerAsset: AccountAssetBalance[];\n groupedByCollateral: Record<string, AccountAssetBalance>;\n riskMultipliers: RiskMultipliersConfiguration;\n riskMatrices: RiskMatrix[];\n exchangeInfoPerAsset: ExchangeInfo[];\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[];\n uniqueTokenAddresses: string[];\n uniqueQuoteCollaterals: string[];\n tokenMarginInfoPerAsset: MarginInfo[];\n realizedPnLSum: BigNumber;\n unrealizedPnLSum: BigNumber;\n constructor(\n rootCollateralPoolId: number,\n oraclePrice: number,\n rate: number,\n accountBalancePerAsset: AccountAssetBalance[],\n groupedByCollateral: Record<string, AccountAssetBalance>,\n riskMultipliers: RiskMultipliersConfiguration,\n riskMatrices: RiskMatrix[],\n exchangeInfoPerAsset: ExchangeInfo[],\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[],\n uniqueTokenAddresses: string[],\n uniqueQuoteCollaterals: string[],\n tokenMarginInfoPerAsset: MarginInfo[],\n realizedPnLSum: BigNumber,\n unrealizedPnLSum: BigNumber,\n ) {\n this.rootCollateralPoolId = rootCollateralPoolId;\n this.oraclePrice = oraclePrice;\n this.rate = rate;\n this.accountBalancePerAsset = accountBalancePerAsset;\n this.groupedByCollateral = groupedByCollateral;\n this.riskMultipliers = riskMultipliers;\n this.riskMatrices = riskMatrices;\n this.exchangeInfoPerAsset = exchangeInfoPerAsset;\n this.positionInfoMarketConfiguration = positionInfoMarketConfiguration;\n this.uniqueTokenAddresses = uniqueTokenAddresses;\n this.uniqueQuoteCollaterals = uniqueQuoteCollaterals;\n this.tokenMarginInfoPerAsset = tokenMarginInfoPerAsset;\n this.realizedPnLSum = realizedPnLSum;\n this.unrealizedPnLSum = unrealizedPnLSum;\n }\n\n getState(): ExposureCommandState {\n return {\n rootCollateralPoolId: this.rootCollateralPoolId,\n oraclePrice: this.oraclePrice,\n rate: this.rate,\n accountBalancePerAsset: this.accountBalancePerAsset,\n groupedByCollateral: this.groupedByCollateral,\n riskMultipliers: this.riskMultipliers,\n riskMatrices: this.riskMatrices,\n exchangeInfoPerAsset: this.exchangeInfoPerAsset,\n positionInfoMarketConfiguration: this.positionInfoMarketConfiguration,\n uniqueTokenAddresses: this.uniqueTokenAddresses,\n uniqueQuoteCollaterals: this.uniqueQuoteCollaterals,\n tokenMarginInfoPerAsset: this.tokenMarginInfoPerAsset,\n realizedPnLSum: this.realizedPnLSum,\n unrealizedPnLSum: this.unrealizedPnLSum,\n };\n }\n\n get getUsdNodeMarginInfo() {\n return ExposureCommand.getUsdNodeMarginInfo(\n this.rootCollateralPoolId,\n this.uniqueTokenAddresses,\n this.exchangeInfoPerAsset,\n this.tokenMarginInfoPerAsset,\n );\n }\n\n get balancePerAsset() {\n return this.tokenMarginInfoPerAsset;\n }\n\n getUsdNodeMarginInfoPostTrade(\n positionAmount: number,\n collateralAddress: string,\n marketConfiguration: MarketConfiguration,\n ) {\n const positionInfoMarketConfiguration = [\n ...this.positionInfoMarketConfiguration,\n ];\n\n // Check if the market_id already exists in the array\n const existingConfigIndex = positionInfoMarketConfiguration.findIndex(\n (config) =>\n config.market_id ===\n BigNumber(String(marketConfiguration.market_id)).toNumber(),\n );\n\n if (existingConfigIndex !== -1) {\n // If it exists, update the amount\n positionInfoMarketConfiguration[existingConfigIndex].base = BigNumber(\n positionInfoMarketConfiguration[existingConfigIndex].base,\n ).plus(positionAmount);\n } else {\n // If it doesn't exist, add a new element\n positionInfoMarketConfiguration.push({\n base: BigNumber(positionAmount),\n realized_pnl: BigNumber(0),\n last_price: BigNumber(0),\n last_timestamp: BigNumber(0),\n funding_value: BigNumber(0),\n base_multiplier: BigNumber(0),\n adl_unwind_price: BigNumber(0),\n market_id: BigNumber(String(marketConfiguration.market_id)).toNumber(),\n market_configuration: marketConfiguration,\n });\n }\n\n const uniqueQuoteCollaterals = new Set(this.uniqueQuoteCollaterals);\n uniqueQuoteCollaterals.add(collateralAddress);\n\n const tokenMarginInfoPerAsset =\n ExposureCommand.calculateTokenMarginInfoPerAsset(\n this.groupedByCollateral,\n this.rootCollateralPoolId,\n this.riskMatrices,\n this.riskMultipliers,\n uniqueQuoteCollaterals,\n this.realizedPnLSum,\n this.unrealizedPnLSum,\n positionInfoMarketConfiguration,\n this.oraclePrice,\n );\n\n const uniqueTokenAddresses = [...this.uniqueTokenAddresses];\n if (!this.uniqueTokenAddresses.includes(collateralAddress)) {\n uniqueTokenAddresses.push(collateralAddress);\n }\n\n return ExposureCommand.getUsdNodeMarginInfo(\n this.rootCollateralPoolId,\n uniqueTokenAddresses,\n this.exchangeInfoPerAsset,\n tokenMarginInfoPerAsset,\n );\n }\n\n static calculateTokenMarginInfoPerAsset(\n groupedByCollateral: Record<string, AccountAssetBalance>,\n rootCollateralPoolId: number,\n riskMatrices: RiskMatrix[],\n riskMultipliers: RiskMultipliersConfiguration,\n uniqueQuoteCollaterals: Set<string>,\n realizedPnLSum: BigNumber,\n unrealizedPnLSum: BigNumber,\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[],\n oraclePrice: number,\n ) {\n const tokenMarginInfoPerAsset: MarginInfo[] = [];\n\n const uniqueQuoteTokens: string[] = Array.from(uniqueQuoteCollaterals);\n\n const tokenUnion = new Set([\n ...Object.keys(groupedByCollateral),\n ...uniqueQuoteTokens,\n ]); // get unique union of those arrays\n const uniqueTokenAddresses: string[] = Array.from(tokenUnion);\n\n for (const token of uniqueTokenAddresses) {\n tokenMarginInfoPerAsset.push(\n ExposureCommand.getTokenMarginInfo(\n rootCollateralPoolId,\n riskMatrices,\n riskMultipliers,\n ExposureCommand.getCollateralInfo(\n token,\n uniqueQuoteCollaterals.has(token) ? realizedPnLSum : BigNumber(0),\n uniqueQuoteCollaterals.has(token) ? unrealizedPnLSum : BigNumber(0),\n groupedByCollateral[token]?.amount || 0,\n ),\n token,\n positionInfoMarketConfiguration,\n oraclePrice,\n ),\n );\n }\n\n return tokenMarginInfoPerAsset;\n }\n static calculateLiquidation(\n globalMarginInfo: MarginInfo,\n oraclePrice: number,\n positionBase: number,\n ): BigNumber {\n const liquidationPrice = BigNumber(oraclePrice).minus(\n BigNumber(globalMarginInfo.marginBalance)\n .minus(globalMarginInfo.liquidationMarginRequirement)\n .div(positionBase),\n );\n\n return BigNumber.max(0, liquidationPrice);\n }\n\n static calculateImpliedLeverage(\n notionalExposure: number,\n oldIMR: number,\n newIMR: number,\n ): number {\n const changeInImr = BigNumber(newIMR).minus(oldIMR);\n\n if (changeInImr.eq(0)) {\n return 0;\n }\n return BigNumber(notionalExposure).div(changeInImr).toNumber();\n }\n\n static combineMarginInfo(\n parentMarginInfo: MarginInfo,\n sonMarginInfo: MarginInfo,\n sonParentExchangeInfo: ExchangeInfo,\n ): MarginInfo {\n return {\n assetAddress: parentMarginInfo.assetAddress,\n marginBalance: BigNumber(parentMarginInfo.marginBalance)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n sonMarginInfo.marginBalance,\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n realBalance: BigNumber(parentMarginInfo.realBalance)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n sonMarginInfo.realBalance,\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n initialDelta: BigNumber(parentMarginInfo.initialDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.realBalance,\n sonMarginInfo.initialDelta,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n maintenanceDelta: BigNumber(parentMarginInfo.maintenanceDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.maintenanceDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n liquidationDelta: BigNumber(parentMarginInfo.liquidationDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.liquidationDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n dutchDelta: BigNumber(parentMarginInfo.dutchDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.dutchDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n adlDelta: BigNumber(parentMarginInfo.adlDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.adlDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n\n initialBufferDelta: BigNumber(parentMarginInfo.initialBufferDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.initialBufferDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n liquidationMarginRequirement: BigNumber(\n parentMarginInfo.liquidationMarginRequirement,\n )\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n sonMarginInfo.liquidationMarginRequirement,\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n };\n }\n\n static getUsdNodeMarginInfo(\n accountCollateralPoolId: number,\n quoteTokens: string[],\n exchangeInfoPerAsset: ExchangeInfo[],\n marginInfoPerToken: MarginInfo[],\n ) {\n let usdNodeMarginInfo: MarginInfo = {\n assetAddress: '',\n marginBalance: 0,\n realBalance: 0,\n initialDelta: 0,\n maintenanceDelta: 0,\n liquidationDelta: 0,\n dutchDelta: 0,\n adlDelta: 0,\n initialBufferDelta: 0,\n liquidationMarginRequirement: 0,\n };\n for (const quoteToken of quoteTokens) {\n const exchangeInfo = exchangeInfoPerAsset.find((exchangeInfo) => {\n return quoteToken === exchangeInfo.tokenAddress;\n });\n\n const marginInfo = marginInfoPerToken.find((marginInfo) => {\n return quoteToken === marginInfo.assetAddress;\n });\n\n if (!exchangeInfo || !marginInfo) {\n throw Error('Missing exchangeInfo/marginInfo');\n }\n\n usdNodeMarginInfo = ExposureCommand.combineMarginInfo(\n usdNodeMarginInfo,\n marginInfo,\n exchangeInfo,\n );\n }\n\n return usdNodeMarginInfo;\n }\n static getCollateralInfo(\n collateralAddress: string,\n realisedPnl: BigNumber,\n unrealizedPnL: BigNumber,\n netDeposits: number,\n ): CollateralInfo {\n return {\n netDeposits: netDeposits,\n marginBalance: BigNumber(netDeposits)\n .plus(realisedPnl)\n .plus(unrealizedPnL)\n .toNumber(),\n realBalance: BigNumber(netDeposits).plus(realisedPnl).toNumber(),\n };\n }\n\n static getTokenMarginInfo(\n rootCollateralPoolId: number,\n riskMatrices: RiskMatrix[],\n riskMultipliers: RiskMultipliersConfiguration,\n collateralInfo: CollateralInfo,\n collateralAddress: string,\n positions: PositionInfoMarketConfiguration[],\n oraclePrice: number,\n ): MarginInfo {\n const marginRequirements = {\n liquidationMarginRequirement: 0,\n initialMarginRequirement: 0,\n maintenanceMarginRequirement: 0,\n dutchMarginRequirement: 0,\n adlMarginRequirement: 0,\n initialBufferMarginRequirement: 0,\n };\n\n for (const riskMatrix of riskMatrices) {\n const filledExposures = ExposureCommand.getBlockExposures(\n positions,\n oraclePrice,\n );\n\n marginRequirements.liquidationMarginRequirement = BigNumber(\n marginRequirements.liquidationMarginRequirement,\n )\n .plus(\n ExposureCommand.computeLiquidationMarginRequirement(\n riskMatrix.matrix,\n filledExposures,\n ),\n )\n .toNumber();\n }\n\n // Get the initial margin requirement\n marginRequirements.initialMarginRequirement = amountNormalizer(\n String(riskMultipliers.im_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n // Get the maintenance margin requirement\n marginRequirements.maintenanceMarginRequirement = amountNormalizer(\n String(riskMultipliers.mmr_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n // Get the dutch margin requirement\n marginRequirements.dutchMarginRequirement = amountNormalizer(\n String(riskMultipliers.dutch_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n\n // Get the adl margin requirement\n marginRequirements.adlMarginRequirement = amountNormalizer(\n String(riskMultipliers.adl_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n\n // Get the initial buffer margin requirement\n marginRequirements.initialBufferMarginRequirement = amountNormalizer(\n String(riskMultipliers.im_buffer_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n\n return {\n assetAddress: collateralAddress,\n marginBalance: collateralInfo.marginBalance,\n realBalance: collateralInfo.realBalance,\n initialDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.initialMarginRequirement)\n .toNumber(),\n maintenanceDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.maintenanceMarginRequirement)\n .toNumber(),\n liquidationDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.liquidationMarginRequirement)\n .toNumber(),\n dutchDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.dutchMarginRequirement)\n .toNumber(),\n adlDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.adlMarginRequirement)\n .toNumber(),\n initialBufferDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.initialBufferMarginRequirement)\n .toNumber(),\n liquidationMarginRequirement:\n marginRequirements.liquidationMarginRequirement,\n };\n }\n\n static computeLiquidationMarginRequirement(\n matrix: BigNumber[][],\n filledExposures: BigNumber[],\n ): number {\n let lmrFilledSquared = 0;\n\n for (let i = 0; i < filledExposures.length; i++) {\n if (BigNumber(filledExposures[i]).eq(0)) {\n continue;\n }\n for (let j = 0; j < filledExposures.length; j++) {\n const riskParam = matrix[i][j];\n\n if (BigNumber(filledExposures[j]).eq(0) || BigNumber(riskParam).eq(0)) {\n continue;\n }\n\n lmrFilledSquared = BigNumber(lmrFilledSquared)\n .plus(\n BigNumber(filledExposures[i])\n .multipliedBy(filledExposures[j])\n .multipliedBy(riskParam),\n )\n .toNumber();\n }\n }\n return BigNumber(lmrFilledSquared).sqrt().toNumber();\n }\n\n static getBlockExposures(\n positions: PositionInfoMarketConfiguration[],\n oraclePrice: number,\n ): BigNumber[] {\n const filledExposures: number[] = [];\n\n for (const position of positions) {\n const marketFilledExposure = ExposureCommand.getAccountFilledExposures(\n position,\n position.market_configuration,\n oraclePrice,\n );\n filledExposures[marketFilledExposure.riskMatrixIndex] = BigNumber(\n filledExposures[marketFilledExposure.riskMatrixIndex] || 0,\n )\n .plus(marketFilledExposure.exposure)\n .toNumber();\n }\n\n return filledExposures.map((num) => BigNumber(num));\n }\n\n static getAccountFilledExposures(\n position: PositionInfo,\n marketConfiguration: MarketConfiguration,\n oraclePrice: number,\n ) {\n const base = position.base;\n\n return {\n exposure: BigNumber(oraclePrice).multipliedBy(base),\n riskMatrixIndex: BigNumber(\n String(marketConfiguration.risk_matrix_index),\n ).toNumber(),\n };\n }\n\n static computePricePnL(\n openBase: BigNumber,\n openPrice: BigNumber,\n exitPrice: BigNumber,\n ) {\n return BigNumber(\n BigNumber(exitPrice).minus(openPrice).multipliedBy(openBase),\n );\n }\n\n static getMarginRatio(marginInfo: MarginInfo) {\n if (marginInfo.liquidationMarginRequirement === 0) {\n return 0;\n }\n\n if (marginInfo.marginBalance <= 0) {\n return 1;\n }\n\n const health = BigNumber(marginInfo.liquidationMarginRequirement).div(\n marginInfo.marginBalance,\n );\n\n if (health.gt(1)) {\n return 1;\n }\n return health.toNumber();\n }\n\n static exchangeWithPriceHaircut(\n quantity: number,\n price: number,\n haircut: number,\n ) {\n // For positive quantities, the haircut is `quantity * (1 - haircut)`\n // For negative values, the haircut is `quantity / (1 - haircut)` because a negative value means the haircut should be applied from B to A.\n const calHelper = BigNumber(quantity).gt(0)\n ? BigNumber(1).minus(haircut)\n : BigNumber(1).div(BigNumber(1).minus(haircut));\n const haircutPrice = BigNumber(price).multipliedBy(calHelper);\n\n return haircutPrice.multipliedBy(quantity).toNumber();\n }\n\n getSlippage(\n deltaBase: number,\n marketConfiguration: MarketConfiguration,\n marketStorage: MarketStorage,\n ): number {\n const deltaExposure = BigNumber(this.oraclePrice)\n .times(deltaBase)\n .toNumber();\n\n const riskMatrixIndex = BigNumber(\n String(marketConfiguration.risk_matrix_index),\n ).toNumber();\n\n const { maxExposureShort, maxExposureLong, exposures } =\n this.getMaxExposure(marketConfiguration, marketStorage);\n\n const netExposure = exposures[riskMatrixIndex].plus(deltaExposure);\n const maxExposure = netExposure.lt(0) ? maxExposureShort : maxExposureLong;\n\n return BigNumber(netExposure)\n .negated()\n .div(BigNumber(maxExposure).plus(netExposure))\n .toNumber();\n }\n\n getMaxExposure(\n marketConfiguration: MarketConfiguration,\n marketStorage: MarketStorage,\n ) {\n const riskMatrix = this.riskMatrices.find((riskMatrix) => {\n return (\n riskMatrix.risk_block_id ===\n BigNumber(String(marketStorage.risk_block_id)).toNumber()\n );\n });\n\n if (!riskMatrix) {\n throw new Error(\"RiskMatrix Doesn't exist\");\n }\n\n const riskMatrixIndex = BigNumber(\n String(marketConfiguration.risk_matrix_index),\n ).toNumber();\n\n const imrMultiplier = amountNormalizer(\n String(this.riskMultipliers.im_multiplier),\n ).toNumber();\n\n const marginInfo = this.tokenMarginInfoPerAsset.find((marginInfo) => {\n return marginInfo.assetAddress === marketStorage.quote_collateral;\n });\n\n if (!marginInfo) {\n throw new Error(\"marginInfo doesn't exist\");\n }\n\n const exposures = ExposureCommand.getBlockExposures(\n this.positionInfoMarketConfiguration,\n this.oraclePrice,\n );\n\n const { maxExposureShort, maxExposureLong } =\n ExposureCommand.computeMaxExposures(\n riskMatrix.matrix,\n exposures,\n marginInfo.liquidationMarginRequirement,\n marginInfo.marginBalance < 0 ? 0 : marginInfo.marginBalance,\n imrMultiplier,\n riskMatrixIndex,\n );\n\n return {\n maxExposureShort,\n maxExposureLong,\n exposures,\n };\n }\n\n static computeMaxExposures(\n riskMatrix: BigNumber[][],\n exposures: BigNumber[],\n lmr: number,\n balance: number,\n imrMultiplier: number,\n exposureIndex: number,\n ) {\n let b = BigNumber(0);\n\n for (let i = 0; i < exposures.length; i++) {\n b = BigNumber(b).plus(\n BigNumber(exposures[i]).multipliedBy(\n BigNumber(riskMatrix[exposureIndex][i]).plus(\n riskMatrix[i][exposureIndex],\n ),\n ),\n );\n }\n const { x1, x2 } = this.solveQuadraticEquation(\n BigNumber(riskMatrix[exposureIndex][exposureIndex]).toNumber(), // changes here\n b.toNumber(),\n this.computeC(lmr, balance, imrMultiplier),\n );\n\n const maxShortExposure = BigNumber(x1).plus(exposures[exposureIndex]);\n const maxLongExposure = BigNumber(x2).plus(exposures[exposureIndex]);\n\n const availableShortExposure = maxShortExposure.lt(0)\n ? maxShortExposure.negated().toNumber()\n : 0;\n\n const availableLongExposure = maxLongExposure.gt(0)\n ? maxLongExposure.toNumber()\n : 0;\n\n return {\n maxExposureShort: availableShortExposure,\n maxExposureLong: availableLongExposure,\n };\n }\n\n static solveQuadraticEquation(a: number, b: number, c: number) {\n if (BigNumber(a).eq(0)) {\n throw new Error('ZeroQuadraticCoefficient');\n }\n\n const delta = BigNumber(b)\n .multipliedBy(b)\n .minus(BigNumber(4).multipliedBy(a).multipliedBy(c));\n\n if (delta.lt(0)) {\n throw new Error('ComplexQuadraticRoots(a, b, c)');\n }\n\n const rootDelta = delta.sqrt();\n\n const x1 = BigNumber(b)\n .multipliedBy(-1)\n .minus(rootDelta)\n .div(BigNumber(2).multipliedBy(a));\n\n const x2 = BigNumber(b)\n .multipliedBy(-1)\n .plus(rootDelta)\n .div(BigNumber(2).multipliedBy(a));\n\n return {\n x1,\n x2,\n };\n }\n\n static computeC(lmr: number, balance: number, imrMultiplier: number): number {\n const lmrSD = BigNumber(lmr);\n const lmrSquared = lmrSD.multipliedBy(lmrSD);\n\n const balanceSD = BigNumber(balance);\n const balanceSquared = balanceSD.multipliedBy(balanceSD);\n\n const imrMultiplierSD = BigNumber(imrMultiplier);\n const imrMultiplierSquared = imrMultiplierSD.multipliedBy(imrMultiplierSD);\n\n return lmrSquared\n .minus(balanceSquared.div(imrMultiplierSquared))\n .toNumber();\n }\n\n static calculateFee(\n price: number,\n amount: number,\n feeParameter: BigNumber,\n ): number {\n return BigNumber(price).times(amount).times(feeParameter).abs().toNumber(); // @todo abs value\n }\n\n static calculateEstimatedPrice(price: number, slippage: number): number {\n return BigNumber(price).times(BigNumber(1).plus(slippage)).toNumber();\n }\n\n static evaluateHealthStatus(number: number) {\n // todo update logic\n if (number >= 67) {\n return 'danger';\n } else if (number >= 34) {\n return 'warning';\n } else {\n return 'healthy';\n }\n }\n}\n"]}
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.amountNormalizer = void 0;
7
+ var bignumber_js_1 = __importDefault(require("bignumber.js"));
8
+ function amountNormalizer(value, decimals) {
9
+ if (decimals === void 0) { decimals = 18; }
10
+ return (0, bignumber_js_1.default)(value).div((0, bignumber_js_1.default)(10).pow(decimals));
11
+ }
12
+ exports.amountNormalizer = amountNormalizer;
13
+ //# sourceMappingURL=number.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"number.js","sourceRoot":"/","sources":["clients/helpers/number.ts"],"names":[],"mappings":";;;;;;AAAA,8DAAqC;AAErC,SAAgB,gBAAgB,CAC9B,KAAkC,EAClC,QAAqB;IAArB,yBAAA,EAAA,aAAqB;IAErB,OAAO,IAAA,sBAAS,EAAC,KAAK,CAAC,CAAC,GAAG,CAAC,IAAA,sBAAS,EAAC,EAAE,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;AAC3D,CAAC;AALD,4CAKC","sourcesContent":["import BigNumber from 'bignumber.js';\n\nexport function amountNormalizer(\n value: BigNumber | number | string,\n decimals: number = 18,\n): BigNumber {\n return BigNumber(value).div(BigNumber(10).pow(decimals));\n}\n"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=trade.simulation.types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trade.simulation.types.js","sourceRoot":"/","sources":["clients/helpers/trade.simulation.types.ts"],"names":[],"mappings":"","sourcesContent":["import BigNumber from 'bignumber.js';\n\nexport interface MarketStorage {\n market_id: number;\n quote_collateral: string;\n instrument_address: string;\n name: string;\n risk_block_id: number;\n collateral_pool_id: number;\n block_timestamp: number;\n block_number: number;\n}\n\nexport interface MarketConfiguration {\n market_id: number;\n risk_matrix_index: number;\n max_open_interest: number;\n oracle_node_id: string;\n mtm_window: number;\n dutch_config_lambda: number;\n dutch_config_min_base: number;\n slippage_params_phi: number;\n slippage_params_beta: number;\n block_timestamp: number;\n block_number: number;\n}\n\nexport type AccountAssetBalance = {\n accountId: number;\n collateral: string;\n amount: number;\n};\n\nexport interface RiskMultipliersConfiguration {\n collateral_pool_id: number;\n im_multiplier: number;\n mmr_multiplier: number;\n dutch_multiplier: number;\n adl_multiplier: number;\n im_buffer_multiplier: number;\n block_timestamp: number;\n block_number: number;\n}\n\nexport interface RiskMatrix {\n collateral_pool_id: number;\n risk_block_id: number;\n matrix: BigNumber[][];\n}\n\nexport interface ExchangeInfo {\n price: number;\n priceHaircut: number;\n autoExchangeDiscount: number;\n tokenAddress: string;\n}\n\nexport interface PositionInfo {\n base: BigNumber;\n realized_pnl: BigNumber;\n last_price: BigNumber;\n last_timestamp: BigNumber;\n funding_value: BigNumber;\n base_multiplier: BigNumber;\n adl_unwind_price: BigNumber;\n market_id: number;\n}\n\nexport type PositionInfoMarketConfiguration = PositionInfo & {\n market_configuration: MarketConfiguration;\n};\n\nexport interface MarginInfo {\n assetAddress: string;\n marginBalance: number;\n realBalance: number;\n initialDelta: number;\n maintenanceDelta: number;\n liquidationDelta: number;\n dutchDelta: number;\n adlDelta: number;\n initialBufferDelta: number;\n liquidationMarginRequirement: number;\n}\n\nexport interface CollateralInfo {\n netDeposits: number;\n marginBalance: number;\n realBalance: number;\n}\n\nexport type ExposureCommandState = {\n rootCollateralPoolId: number;\n oraclePrice: number;\n rate: number;\n accountBalancePerAsset: AccountAssetBalance[];\n groupedByCollateral: Record<string, AccountAssetBalance>;\n riskMultipliers: RiskMultipliersConfiguration;\n riskMatrices: RiskMatrix[];\n exchangeInfoPerAsset: ExchangeInfo[];\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[];\n uniqueTokenAddresses: string[];\n uniqueQuoteCollaterals: string[];\n tokenMarginInfoPerAsset: MarginInfo[];\n realizedPnLSum: BigNumber;\n unrealizedPnLSum: BigNumber;\n};\n\nexport type TradeSimulationState = {\n feeParameter: BigNumber;\n marketStorage: MarketStorage;\n marketConfiguration: MarketConfiguration;\n exposureDataAccount: ExposureCommandState;\n exposureDataPassivePool: ExposureCommandState;\n};\n"]}
@@ -131,6 +131,17 @@ var AccountClient = /** @class */ (function (_super) {
131
131
  });
132
132
  });
133
133
  };
134
+ AccountClient.prototype.getTransactionSimulationInitialData = function (params) {
135
+ return __awaiter(this, void 0, void 0, function () {
136
+ var uri;
137
+ return __generator(this, function (_a) {
138
+ uri = "/api/accounts/".concat(params.marginAccountId, "/trade-simulation-data");
139
+ return [2 /*return*/, this.get(uri, {
140
+ marketId: params.marketId,
141
+ })];
142
+ });
143
+ });
144
+ };
134
145
  return AccountClient;
135
146
  }(rest_1.default));
136
147
  exports.default = AccountClient;