@reyaxyz/api-sdk 0.114.2 → 0.115.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/clients/modules/conditional-orders/index.js +6 -2
- package/dist/clients/modules/conditional-orders/index.js.map +1 -1
- package/dist/clients/modules/trade.simulation/index.js +26 -0
- package/dist/clients/modules/trade.simulation/index.js.map +1 -1
- package/dist/clients/modules/trade.simulation/types.js.map +1 -1
- package/dist/types/clients/modules/conditional-orders/index.d.ts.map +1 -1
- package/dist/types/clients/modules/trade.simulation/index.d.ts +2 -1
- package/dist/types/clients/modules/trade.simulation/index.d.ts.map +1 -1
- package/dist/types/clients/modules/trade.simulation/types.d.ts +10 -0
- package/dist/types/clients/modules/trade.simulation/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/clients/modules/conditional-orders/index.ts +10 -2
- package/src/clients/modules/trade.simulation/index.ts +42 -0
- package/src/clients/modules/trade.simulation/types.ts +12 -0
package/README.md
CHANGED
|
@@ -6,5 +6,5 @@
|
|
|
6
6
|
|
|
7
7
|
| Statements | Branches | Functions | Lines |
|
|
8
8
|
| --------------------------- | ----------------------- | ------------------------- | ----------------- |
|
|
9
|
-
|  |  |  |  |
|
|
10
10
|
|
|
@@ -119,7 +119,9 @@ var ConditionalOrdersClient = /** @class */ (function (_super) {
|
|
|
119
119
|
case 0: return [4 /*yield*/, this.parseConditionalOrderInputs(params.signer, params.marginAccountId, params.marketId, params.orderType, params.triggerPrice, params.supportingParams.exchangeId, params.supportingParams.counterpartyAccountIds, params.amountInBase)];
|
|
120
120
|
case 1:
|
|
121
121
|
inputs = _d.sent();
|
|
122
|
-
uri =
|
|
122
|
+
uri = this.reyaChainId === common_1.ReyaChainId.reyaCronos
|
|
123
|
+
? "/api/conditional-orders/create-or-update-order"
|
|
124
|
+
: "/api/conditional-orders/create-order";
|
|
123
125
|
_a = this.post;
|
|
124
126
|
_b = [uri,
|
|
125
127
|
{}];
|
|
@@ -157,7 +159,9 @@ var ConditionalOrdersClient = /** @class */ (function (_super) {
|
|
|
157
159
|
case 0: return [4 /*yield*/, this.parseConditionalOrderInputs(params.signer, params.marginAccountId, params.marketId, params.orderType, params.triggerPrice, params.supportingParams.exchangeId, params.supportingParams.counterpartyAccountIds, params.amountInBase)];
|
|
158
160
|
case 1:
|
|
159
161
|
inputs = _d.sent();
|
|
160
|
-
uri =
|
|
162
|
+
uri = this.reyaChainId === common_1.ReyaChainId.reyaCronos
|
|
163
|
+
? "/api/conditional-orders/create-or-update-order"
|
|
164
|
+
: "/api/conditional-orders/update-order";
|
|
161
165
|
_a = this.post;
|
|
162
166
|
_b = [uri,
|
|
163
167
|
{}];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["clients/modules/conditional-orders/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAWyB;AACzB,iCAAkC;AAclC,iCAAsC;AAEtC;IAAqD,2CAAU;IAG7D,iCAAY,WAAwB,EAAE,IAAY;QAChD,YAAA,MAAK,YAAC,IAAI,CAAC,SAAC;QACZ,KAAI,CAAC,WAAW,GAAG,WAAW,CAAC;;IACjC,CAAC;IAED,yCAAyC;IACnC,6EAA2C,GAAjD,UACE,MAAyD;;;;gBAEnD,GAAG,GAAG,wDAAiD,MAAM,CAAC,eAAe,CAAE,CAAC;gBACtF,sBAAO,IAAI,CAAC,GAAG,CAAoD,GAAG,EAAE;wBACtE,KAAK,EAAE,MAAM,CAAC,KAAK;qBACpB,CAAC,EAAC;;;KACJ;IAEK,6DAA2B,GAAjC,UACE,MAAwC;;;;;;wBAElC,GAAG,GAAG,wDAAiD,MAAM,CAAC,SAAS,CAAE,CAAC;wBAC/D,qBAAM,IAAI,CAAC,GAAG,CAAU,GAAG,CAAC,EAAA;;wBAAvC,QAAQ,GAAG,SAA4B;wBAE7C,sBAAO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,EAAE,uCAA8B;gCACxC,mBAAmB,qBAAA;6BACpB,EAAC;;;;KACH;IACH,8BAAC;AAAD,CAAC,AA1ND,CAAqD,mBAAU,GA0N9D","sourcesContent":["import {\n calculateMaxPriceLimit,\n PositionEntity,\n RestClient,\n ReyaChainId,\n signConditionalOrder,\n signCancelConditionalOrder,\n ConditionalOrder,\n ConditionalOrderType,\n scale,\n CONDITIONAL_ORDER_SIG_DEADLINE,\n} from '@reyaxyz/common';\nimport { AbiCoder } from 'ethers';\nimport { Signer, JsonRpcSigner } from 'ethers';\nimport {\n AlreadyGaveTradePermissionParams,\n AlreadyGaveTradePermissionResult,\n CancelConditionalOrderParams,\n CancelConditionalOrderResult,\n GetConditionalOrdersHistoryForMarginAccountParams,\n GetConditionalOrdersHistoryForMarginAccountResult,\n RegisterConditionalOrderParams,\n RegisterConditionalOrderResult,\n UpdateConditionalOrderParams,\n UpdateConditionalOrderResult,\n} from './types';\nimport { createNonce } from './utils';\n\nexport default class ConditionalOrdersClient extends RestClient {\n private reyaChainId: ReyaChainId;\n\n constructor(reyaChainId: ReyaChainId, host: string) {\n super(host);\n this.reyaChainId = reyaChainId;\n }\n\n // ------ Conditional Orders History ---\n async getConditionalOrdersHistoryForMarginAccount(\n params: GetConditionalOrdersHistoryForMarginAccountParams,\n ): Promise<GetConditionalOrdersHistoryForMarginAccountResult> {\n const uri = `/api/conditional-orders/get-orders-by-account/${params.marginAccountId}`;\n return this.get<GetConditionalOrdersHistoryForMarginAccountResult>(uri, {\n limit: params.limit,\n });\n }\n\n async alreadyGaveTradePermissions(\n params: AlreadyGaveTradePermissionParams,\n ): Promise<AlreadyGaveTradePermissionResult> {\n const uri = `/api/conditional-orders/gave-trade-permission/${params.accountId}`;\n const response = await this.get<boolean>(uri);\n\n return {\n permissionGiven: response,\n };\n }\n\n async cancelConditionalOrder(\n params: CancelConditionalOrderParams,\n ): Promise<CancelConditionalOrderResult> {\n const signature = await signCancelConditionalOrder(\n params.signer,\n params.orderId,\n );\n\n const uri = `/api/conditional-orders/cancel-order`;\n const res = await this.put<ConditionalOrder>(\n uri,\n {},\n {\n orderId: params.orderId,\n userSignature: signature,\n },\n );\n return res;\n }\n\n async registerConditionalOrder(\n params: RegisterConditionalOrderParams,\n ): Promise<RegisterConditionalOrderResult> {\n const inputs = await this.parseConditionalOrderInputs(\n params.signer,\n params.marginAccountId,\n params.marketId,\n params.orderType,\n params.triggerPrice,\n params.supportingParams.exchangeId,\n params.supportingParams.counterpartyAccountIds,\n params.amountInBase,\n );\n\n // create new entry\n const uri = `/api/conditional-orders/create-or-update-order`;\n const result = await this.post<ConditionalOrder>(\n uri,\n {},\n {\n accountId: params.marginAccountId,\n poolId: params.supportingParams.counterpartyAccountIds[0],\n deadline: inputs.deadline,\n exchangeId: params.supportingParams.exchangeId,\n isLong: inputs.actualAmountInBase > 0,\n marketId: params.marketId,\n nonce: inputs.nonce.toString(),\n orderPriceLimit: inputs.orderPriceLimit.toString(),\n orderType: params.orderType,\n signature: inputs.signature,\n signerWallet: await params.signer.getAddress(),\n timestampMs: inputs.creationTimestampMs,\n triggerPrice: params.triggerPrice,\n orderBase: params.amountInBase,\n },\n );\n return result;\n }\n\n async updateConditionalOrder(\n params: UpdateConditionalOrderParams,\n ): Promise<UpdateConditionalOrderResult> {\n const inputs = await this.parseConditionalOrderInputs(\n params.signer,\n params.marginAccountId,\n params.marketId,\n params.orderType,\n params.triggerPrice,\n params.supportingParams.exchangeId,\n params.supportingParams.counterpartyAccountIds,\n params.amountInBase,\n );\n\n // create new entry\n const uri = `/api/conditional-orders/create-or-update-order`;\n const result = await this.post<ConditionalOrder>(\n uri,\n {},\n {\n accountId: params.marginAccountId,\n poolId: params.supportingParams.counterpartyAccountIds[0],\n deadline: inputs.deadline,\n exchangeId: params.supportingParams.exchangeId,\n isLong: inputs.actualAmountInBase > 0,\n marketId: params.marketId,\n nonce: inputs.nonce.toString(),\n orderPriceLimit: inputs.orderPriceLimit.toString(),\n orderType: params.orderType,\n signature: inputs.signature,\n signerWallet: await params.signer.getAddress(),\n timestampMs: inputs.creationTimestampMs,\n triggerPrice: params.triggerPrice,\n cancelOrderId: params.cancelOrderId,\n orderBase: params.amountInBase,\n },\n );\n return result;\n }\n\n private async getPosition(\n accountId: number,\n marketId: number,\n ): Promise<PositionEntity> {\n const uri = `/api/accounts/marginAccount/position/${accountId}/${marketId}`;\n return this.get<PositionEntity>(uri);\n }\n\n private async parseConditionalOrderInputs(\n signer: Signer | JsonRpcSigner,\n accountId: number,\n marketId: number,\n orderType: ConditionalOrderType,\n triggerPrice: number,\n exchangeId: number,\n counterpartyAccountIds: number[],\n amountInBase?: number,\n ): Promise<{\n signature: string;\n actualAmountInBase: number;\n orderPriceLimit: bigint;\n nonce: bigint;\n deadline: number;\n creationTimestampMs: number;\n }> {\n let inputs: string;\n let actualAmountInBase: number;\n let isLongOrder: boolean;\n let orderPriceLimit: bigint;\n\n if (orderType === ConditionalOrderType.LIMIT_ORDER) {\n if (amountInBase === undefined) {\n throw new Error('Order base is required for limit orders');\n }\n\n if (amountInBase === 0) {\n throw new Error('Cannot create an empty limit order');\n }\n\n actualAmountInBase = amountInBase;\n isLongOrder = actualAmountInBase > 0;\n orderPriceLimit = calculateMaxPriceLimit(isLongOrder);\n\n inputs = AbiCoder.defaultAbiCoder().encode(\n ['int256', 'uint256'],\n [scale(18)(amountInBase), scale(18)(triggerPrice)],\n );\n } else {\n const position = await this.getPosition(accountId, marketId);\n const positionBase = position.base;\n\n if (positionBase === 0) {\n throw new Error('Cannot create SL or TP order for closed positions');\n }\n\n actualAmountInBase = -positionBase;\n isLongOrder = actualAmountInBase > 0;\n orderPriceLimit = calculateMaxPriceLimit(isLongOrder);\n\n inputs = AbiCoder.defaultAbiCoder().encode(\n ['bool', 'uint256', 'uint256'],\n [isLongOrder, scale(18)(triggerPrice), orderPriceLimit],\n );\n }\n\n const creationTimestampMs = Date.now();\n const nonce = createNonce(accountId, marketId, creationTimestampMs);\n\n const signature = await signConditionalOrder(\n signer,\n this.reyaChainId,\n accountId,\n marketId,\n exchangeId,\n counterpartyAccountIds,\n orderType,\n inputs,\n nonce,\n CONDITIONAL_ORDER_SIG_DEADLINE,\n );\n\n return {\n signature,\n actualAmountInBase,\n orderPriceLimit,\n nonce,\n deadline: CONDITIONAL_ORDER_SIG_DEADLINE,\n creationTimestampMs,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"/","sources":["clients/modules/conditional-orders/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAWyB;AACzB,iCAAkC;AAclC,iCAAsC;AAEtC;IAAqD,2CAAU;IAG7D,iCAAY,WAAwB,EAAE,IAAY;QAChD,YAAA,MAAK,YAAC,IAAI,CAAC,SAAC;QACZ,KAAI,CAAC,WAAW,GAAG,WAAW,CAAC;;IACjC,CAAC;IAED,yCAAyC;IACnC,6EAA2C,GAAjD,UACE,MAAyD;;;;gBAEnD,GAAG,GAAG,wDAAiD,MAAM,CAAC,eAAe,CAAE,CAAC;gBACtF,sBAAO,IAAI,CAAC,GAAG,CAAoD,GAAG,EAAE;wBACtE,KAAK,EAAE,MAAM,CAAC,KAAK;qBACpB,CAAC,EAAC;;;KACJ;IAEK,6DAA2B,GAAjC,UACE,MAAwC;;;;;;wBAElC,GAAG,GAAG,wDAAiD,MAAM,CAAC,SAAS,CAAE,CAAC;wBAC/D,qBAAM,IAAI,CAAC,GAAG,CAAU,GAAG,CAAC,EAAA;;wBAAvC,QAAQ,GAAG,SAA4B;wBAE7C,sBAAO;gCACL,eAAe,EAAE,QAAQ;6BAC1B,EAAC;;;;KACH;IAEK,wDAAsB,GAA5B,UACE,MAAoC;;;;;4BAElB,qBAAM,IAAA,mCAA0B,EAChD,MAAM,CAAC,MAAM,EACb,MAAM,CAAC,OAAO,CACf,EAAA;;wBAHK,SAAS,GAAG,SAGjB;wBAEK,GAAG,GAAG,sCAAsC,CAAC;wBACv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H,8BAAC;AAAD,CAAC,AAlOD,CAAqD,mBAAU,GAkO9D","sourcesContent":["import {\n calculateMaxPriceLimit,\n PositionEntity,\n RestClient,\n ReyaChainId,\n signConditionalOrder,\n signCancelConditionalOrder,\n ConditionalOrder,\n ConditionalOrderType,\n scale,\n CONDITIONAL_ORDER_SIG_DEADLINE,\n} from '@reyaxyz/common';\nimport { AbiCoder } from 'ethers';\nimport { Signer, JsonRpcSigner } from 'ethers';\nimport {\n AlreadyGaveTradePermissionParams,\n AlreadyGaveTradePermissionResult,\n CancelConditionalOrderParams,\n CancelConditionalOrderResult,\n GetConditionalOrdersHistoryForMarginAccountParams,\n GetConditionalOrdersHistoryForMarginAccountResult,\n RegisterConditionalOrderParams,\n RegisterConditionalOrderResult,\n UpdateConditionalOrderParams,\n UpdateConditionalOrderResult,\n} from './types';\nimport { createNonce } from './utils';\n\nexport default class ConditionalOrdersClient extends RestClient {\n private reyaChainId: ReyaChainId;\n\n constructor(reyaChainId: ReyaChainId, host: string) {\n super(host);\n this.reyaChainId = reyaChainId;\n }\n\n // ------ Conditional Orders History ---\n async getConditionalOrdersHistoryForMarginAccount(\n params: GetConditionalOrdersHistoryForMarginAccountParams,\n ): Promise<GetConditionalOrdersHistoryForMarginAccountResult> {\n const uri = `/api/conditional-orders/get-orders-by-account/${params.marginAccountId}`;\n return this.get<GetConditionalOrdersHistoryForMarginAccountResult>(uri, {\n limit: params.limit,\n });\n }\n\n async alreadyGaveTradePermissions(\n params: AlreadyGaveTradePermissionParams,\n ): Promise<AlreadyGaveTradePermissionResult> {\n const uri = `/api/conditional-orders/gave-trade-permission/${params.accountId}`;\n const response = await this.get<boolean>(uri);\n\n return {\n permissionGiven: response,\n };\n }\n\n async cancelConditionalOrder(\n params: CancelConditionalOrderParams,\n ): Promise<CancelConditionalOrderResult> {\n const signature = await signCancelConditionalOrder(\n params.signer,\n params.orderId,\n );\n\n const uri = `/api/conditional-orders/cancel-order`;\n const res = await this.put<ConditionalOrder>(\n uri,\n {},\n {\n orderId: params.orderId,\n userSignature: signature,\n },\n );\n return res;\n }\n\n async registerConditionalOrder(\n params: RegisterConditionalOrderParams,\n ): Promise<RegisterConditionalOrderResult> {\n const inputs = await this.parseConditionalOrderInputs(\n params.signer,\n params.marginAccountId,\n params.marketId,\n params.orderType,\n params.triggerPrice,\n params.supportingParams.exchangeId,\n params.supportingParams.counterpartyAccountIds,\n params.amountInBase,\n );\n\n // create new entry\n const uri =\n this.reyaChainId === ReyaChainId.reyaCronos\n ? `/api/conditional-orders/create-or-update-order`\n : `/api/conditional-orders/create-order`;\n\n const result = await this.post<ConditionalOrder>(\n uri,\n {},\n {\n accountId: params.marginAccountId,\n poolId: params.supportingParams.counterpartyAccountIds[0],\n deadline: inputs.deadline,\n exchangeId: params.supportingParams.exchangeId,\n isLong: inputs.actualAmountInBase > 0,\n marketId: params.marketId,\n nonce: inputs.nonce.toString(),\n orderPriceLimit: inputs.orderPriceLimit.toString(),\n orderType: params.orderType,\n signature: inputs.signature,\n signerWallet: await params.signer.getAddress(),\n timestampMs: inputs.creationTimestampMs,\n triggerPrice: params.triggerPrice,\n orderBase: params.amountInBase,\n },\n );\n return result;\n }\n\n async updateConditionalOrder(\n params: UpdateConditionalOrderParams,\n ): Promise<UpdateConditionalOrderResult> {\n const inputs = await this.parseConditionalOrderInputs(\n params.signer,\n params.marginAccountId,\n params.marketId,\n params.orderType,\n params.triggerPrice,\n params.supportingParams.exchangeId,\n params.supportingParams.counterpartyAccountIds,\n params.amountInBase,\n );\n\n // create new entry\n const uri =\n this.reyaChainId === ReyaChainId.reyaCronos\n ? `/api/conditional-orders/create-or-update-order`\n : `/api/conditional-orders/update-order`;\n\n const result = await this.post<ConditionalOrder>(\n uri,\n {},\n {\n accountId: params.marginAccountId,\n poolId: params.supportingParams.counterpartyAccountIds[0],\n deadline: inputs.deadline,\n exchangeId: params.supportingParams.exchangeId,\n isLong: inputs.actualAmountInBase > 0,\n marketId: params.marketId,\n nonce: inputs.nonce.toString(),\n orderPriceLimit: inputs.orderPriceLimit.toString(),\n orderType: params.orderType,\n signature: inputs.signature,\n signerWallet: await params.signer.getAddress(),\n timestampMs: inputs.creationTimestampMs,\n triggerPrice: params.triggerPrice,\n cancelOrderId: params.cancelOrderId,\n orderBase: params.amountInBase,\n },\n );\n return result;\n }\n\n private async getPosition(\n accountId: number,\n marketId: number,\n ): Promise<PositionEntity> {\n const uri = `/api/accounts/marginAccount/position/${accountId}/${marketId}`;\n return this.get<PositionEntity>(uri);\n }\n\n private async parseConditionalOrderInputs(\n signer: Signer | JsonRpcSigner,\n accountId: number,\n marketId: number,\n orderType: ConditionalOrderType,\n triggerPrice: number,\n exchangeId: number,\n counterpartyAccountIds: number[],\n amountInBase?: number,\n ): Promise<{\n signature: string;\n actualAmountInBase: number;\n orderPriceLimit: bigint;\n nonce: bigint;\n deadline: number;\n creationTimestampMs: number;\n }> {\n let inputs: string;\n let actualAmountInBase: number;\n let isLongOrder: boolean;\n let orderPriceLimit: bigint;\n\n if (orderType === ConditionalOrderType.LIMIT_ORDER) {\n if (amountInBase === undefined) {\n throw new Error('Order base is required for limit orders');\n }\n\n if (amountInBase === 0) {\n throw new Error('Cannot create an empty limit order');\n }\n\n actualAmountInBase = amountInBase;\n isLongOrder = actualAmountInBase > 0;\n orderPriceLimit = calculateMaxPriceLimit(isLongOrder);\n\n inputs = AbiCoder.defaultAbiCoder().encode(\n ['int256', 'uint256'],\n [scale(18)(amountInBase), scale(18)(triggerPrice)],\n );\n } else {\n const position = await this.getPosition(accountId, marketId);\n const positionBase = position.base;\n\n if (positionBase === 0) {\n throw new Error('Cannot create SL or TP order for closed positions');\n }\n\n actualAmountInBase = -positionBase;\n isLongOrder = actualAmountInBase > 0;\n orderPriceLimit = calculateMaxPriceLimit(isLongOrder);\n\n inputs = AbiCoder.defaultAbiCoder().encode(\n ['bool', 'uint256', 'uint256'],\n [isLongOrder, scale(18)(triggerPrice), orderPriceLimit],\n );\n }\n\n const creationTimestampMs = Date.now();\n const nonce = createNonce(accountId, marketId, creationTimestampMs);\n\n const signature = await signConditionalOrder(\n signer,\n this.reyaChainId,\n accountId,\n marketId,\n exchangeId,\n counterpartyAccountIds,\n orderType,\n inputs,\n nonce,\n CONDITIONAL_ORDER_SIG_DEADLINE,\n );\n\n return {\n signature,\n actualAmountInBase,\n orderPriceLimit,\n nonce,\n deadline: CONDITIONAL_ORDER_SIG_DEADLINE,\n creationTimestampMs,\n };\n }\n}\n"]}
|
|
@@ -146,6 +146,32 @@ var TradeSimulationClient = /** @class */ (function () {
|
|
|
146
146
|
maxSlippage: 1,
|
|
147
147
|
};
|
|
148
148
|
};
|
|
149
|
+
// Synchronous method to simulate operations based on an amount
|
|
150
|
+
TradeSimulationClient.prototype.simulateLimit = function (params) {
|
|
151
|
+
if (!this.loadedData) {
|
|
152
|
+
throw new Error('Data not loaded. Call arm() first.');
|
|
153
|
+
}
|
|
154
|
+
var amount;
|
|
155
|
+
if (params.fromBase) {
|
|
156
|
+
amount = params.amount;
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
amount = (0, bignumber_js_1.default)(params.amount).div(params.triggerPrice).toNumber();
|
|
160
|
+
}
|
|
161
|
+
/*
|
|
162
|
+
max amount of margin in rUSD terms that can be transferred from the source account to the destination account
|
|
163
|
+
that performs the isolated position trade (PRE TRADE)
|
|
164
|
+
*/
|
|
165
|
+
var fees = common_1.ExposureCommand.calculateFee(params.triggerPrice, amount, this.loadedData.feeParameter);
|
|
166
|
+
var baseSpacing = (0, common_1.amountNormalizer)(this.loadedData.marketConfiguration.base_spacing).toNumber();
|
|
167
|
+
var snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);
|
|
168
|
+
var snappedAmount = snappedAmountInBase * params.triggerPrice;
|
|
169
|
+
return {
|
|
170
|
+
fees: fees,
|
|
171
|
+
snappedAmount: snappedAmount,
|
|
172
|
+
snappedAmountInBase: snappedAmountInBase,
|
|
173
|
+
};
|
|
174
|
+
};
|
|
149
175
|
TradeSimulationClient.prototype.convertValue = function (params) {
|
|
150
176
|
if (!this.loadedData) {
|
|
151
177
|
throw new Error('Data not loaded. Call arm() first.');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["clients/modules/trade.simulation/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,0CAKyB;AACzB,8DAAqC;AACrC,0CAA0D;AAE1D;IAKE,+BAAY,aAA4B;QAJhC,aAAQ,GAAkB,IAAI,CAAC;QAC/B,cAAS,GAAkB,IAAI,CAAC;QAChC,eAAU,GAAgC,IAAI,CAAC;QAGrD,oBAAoB;QACpB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;IAED,qEAAqE;IAC/D,mCAAG,GAAT,UAAU,MAAqC;;;;;;wBAC7C,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;wBAChC,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,eAAe,CAAC;wBAExC,KAAA,IAAI,CAAA;wBAAc,qBAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,EAAA;;wBAA3E,GAAK,UAAU,GAAG,SAAyD,CAAC;;;;;KAC7E;IAEa,+CAAe,GAA7B,UACE,QAAgB,EAChB,SAAiB;;;gBAEjB,sBAAO,IAAI,CAAC,aAAa,CAAC,mCAAmC,CAAC;wBAC5D,eAAe,EAAE,SAAS;wBAC1B,QAAQ,EAAE,QAAQ;qBACnB,CAAC,EAAC;;;KACJ;IAED,+DAA+D;IAC/D,wCAAQ,GAAR,UAAS,MAAqC;QAA9C,iBAiKC;QAhKC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACxD,CAAC;QAED,IAAI,MAAM,CAAC;QACX,IAAI,MAAM,CAAC,QAAQ,EAAE,C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4BAAC;AAAD,CAAC,AArVD,IAqVC","sourcesContent":["import {\n EstimatedPriceParams,\n EstimatedPriceResult,\n SimulateTradeEntity,\n TradeSimulationConvertValueEstimatedPriceParams,\n TradeSimulationConvertValueParams,\n TradeSimulationConvertValueResult,\n TradeSimulationLoadDataParams,\n TradeSimulationSimulateParams,\n} from './types';\nimport AccountClient from '../account';\nimport {\n amountNormalizer,\n ExposureCommand,\n MarginInfo,\n TradeSimulationState,\n} from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { INSTANT_TRADING_RATE_XP } from '@reyaxyz/common';\n\nexport default class TradeSimulationClient {\n private marketId: number | null = null;\n private accountId: number | null = null;\n private loadedData: TradeSimulationState | null = null;\n private accountClient: AccountClient;\n constructor(accountClient: AccountClient) {\n // Constructor added\n this.accountClient = accountClient;\n }\n\n // Method to asynchronously load data based on marketId and accountId\n async arm(params: TradeSimulationLoadDataParams): Promise<void> {\n this.marketId = params.marketId;\n this.accountId = params.marginAccountId;\n\n this.loadedData = await this.fetchMarketData(this.marketId, this.accountId);\n }\n\n private async fetchMarketData(\n marketId: number,\n accountId: number,\n ): Promise<TradeSimulationState> {\n return this.accountClient.getTransactionSimulationInitialData({\n marginAccountId: accountId,\n marketId: marketId,\n });\n }\n\n // Synchronous method to simulate operations based on an amount\n simulate(params: TradeSimulationSimulateParams): SimulateTradeEntity {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n let amount;\n if (params.fromBase) {\n amount = params.amount;\n } else {\n amount = BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n const userAccountExposure = new ExposureCommand(\n this.loadedData.exposureDataAccount.accountId,\n this.loadedData.exposureDataAccount.rootCollateralPoolId,\n this.loadedData.exposureDataAccount.oraclePricePerMarket,\n this.loadedData.exposureDataAccount.accountBalancePerAsset,\n this.loadedData.exposureDataAccount.groupedByCollateral,\n this.loadedData.exposureDataAccount.riskMultipliers,\n this.loadedData.exposureDataAccount.riskMatrices,\n this.loadedData.exposureDataAccount.exchangeInfoPerAsset,\n this.loadedData.exposureDataAccount.positionInfoMarketConfiguration,\n this.loadedData.exposureDataAccount.uniqueTokenAddresses,\n this.loadedData.exposureDataAccount.uniqueQuoteCollaterals,\n this.loadedData.exposureDataAccount.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataAccount.realizedPnLSum,\n this.loadedData.exposureDataAccount.unrealizedPnLSum,\n this.loadedData.exposureDataAccount.mtmRpnlSum,\n this.loadedData.exposureDataAccount.collateralAddressToExchangePrice,\n );\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n\n /*\n max amount of margin in rUSD terms that can be transferred from the source account to the destination account\n that performs the isolated position trade (PRE TRADE)\n */\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const marginBalance =\n userAccountExposure.getUsdNodeMarginInfo.marginBalance;\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amount).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n const fees = ExposureCommand.calculateFee(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n amount,\n this.loadedData.feeParameter,\n );\n\n const { usdNodeMarginInfo: newMarginInfo, tokenMarginInfoPerAsset } =\n userAccountExposure.getUsdNodeMarginInfoPostTrade(\n amount,\n this.loadedData.marketStorage.quote_collateral,\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage.risk_block_id,\n );\n\n const newQuoteTokenMarginInfo = tokenMarginInfoPerAsset.find(\n (marginInfo: MarginInfo) => {\n return (\n marginInfo.assetAddress ===\n this.loadedData?.marketStorage?.quote_collateral\n );\n },\n );\n\n if (!newQuoteTokenMarginInfo) {\n throw new Error('Error performing simulation');\n }\n\n /*\n * Note, required margin is the initial margin requirement in rUSD terms of the account after the trade.\n * margin balance rusd - initial delta rusd = margin balance rusd - (margin balance rusd - imr rusd) = imr rusd\n * */\n\n const requiredMargin =\n newQuoteTokenMarginInfo.marginBalance -\n newQuoteTokenMarginInfo.initialDelta;\n\n const liquidationPrice = ExposureCommand.calculateLiquidation(\n newMarginInfo.marginBalance,\n newQuoteTokenMarginInfo.liquidationMarginRequirement,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n amount,\n );\n\n const marginRatio = ExposureCommand.getMarginRatio(newMarginInfo);\n\n const marginRatioHealth = ExposureCommand.evaluateHealthStatus(\n marginRatio * 100,\n );\n\n const baseSpacing = amountNormalizer(\n this.loadedData.marketConfiguration.base_spacing,\n ).toNumber();\n\n const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);\n const snappedAmount = snappedAmountInBase * estimatedPrice;\n const xpEarnRangeMin = Math.round(\n Math.abs(snappedAmount) / INSTANT_TRADING_RATE_XP,\n );\n const xpEarnRangeMax = Math.round(\n (100 * Math.abs(snappedAmount)) / INSTANT_TRADING_RATE_XP,\n );\n\n return {\n estimatedPrice,\n estimatedSlippage: slippage * 100,\n fees,\n liquidationPrice: liquidationPrice.toNumber(),\n marginRatio: marginRatio * 100,\n marginRatioHealth,\n marginBalance,\n availableMargin,\n requiredMargin,\n snappedAmount,\n snappedAmountInBase,\n xpEarnRange: {\n min: xpEarnRangeMin,\n max: xpEarnRangeMax,\n },\n maxSlippage: 1,\n } as SimulateTradeEntity;\n }\n\n convertValue(\n params: TradeSimulationConvertValueParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n if (!params.fromBase)\n return BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n else\n return BigNumber(params.amount)\n .times(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n\n convertValueEstimatedPrice(\n params: TradeSimulationConvertValueEstimatedPriceParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n\n const amountForSlippage = params.fromBase\n ? params.amount\n : BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amountForSlippage).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n\n if (!params.fromBase)\n return BigNumber(params.amount).div(estimatedPrice).toNumber();\n else return BigNumber(params.amount).times(estimatedPrice).toNumber();\n }\n\n estimatedPrice(params: EstimatedPriceParams): EstimatedPriceResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(params.amount).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n\n const price =\n this.loadedData.exposureDataAccount.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ];\n\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n\n return {\n estimatedPrice,\n markPrice: price,\n };\n }\n\n roundToBaseSpacing(amount: number, baseSpacing: number): number {\n const snappedAmount = BigNumber(amount)\n .abs()\n .dividedBy(baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(baseSpacing)\n .toNumber();\n\n if (amount < 0) {\n return -snappedAmount;\n }\n return snappedAmount;\n }\n\n updatePrice(price: number): void {\n if (!this.loadedData || !this.marketId) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n // update price\n const marketId = this.marketId;\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[marketId] =\n price;\n this.loadedData.exposureDataAccount.oraclePricePerMarket[marketId] = price;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"/","sources":["clients/modules/trade.simulation/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,0CAKyB;AACzB,8DAAqC;AACrC,0CAA0D;AAE1D;IAKE,+BAAY,aAA4B;QAJhC,aAAQ,GAAkB,IAAI,CAAC;QAC/B,cAAS,GAAkB,IAAI,CAAC;QAChC,eAAU,GAAgC,IAAI,CAAC;QAGrD,oBAAoB;QACpB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,C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OAAO,aAAa,CAAC;IACvB,CAAC;IAED,2CAAW,GAAX,UAAY,KAAa;QACvB,IAAI,CAAC,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACxD,CAAC;QACD,eAAe;QACf,IAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,UAAU,CAAC,uBAAuB,CAAC,oBAAoB,CAAC,QAAQ,CAAC;YACpE,KAAK,CAAC;QACR,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,oBAAoB,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;IAC7E,CAAC;IACH,4BAAC;AAAD,CAAC,AA7XD,IA6XC","sourcesContent":["import {\n EstimatedPriceParams,\n EstimatedPriceResult,\n SimulateLimitTradeEntity,\n SimulateTradeEntity,\n TradeSimulationConvertValueEstimatedPriceParams,\n TradeSimulationConvertValueParams,\n TradeSimulationConvertValueResult,\n TradeSimulationLoadDataParams,\n TradeSimulationSimulateLimitParams,\n TradeSimulationSimulateParams,\n} from './types';\nimport AccountClient from '../account';\nimport {\n amountNormalizer,\n ExposureCommand,\n MarginInfo,\n TradeSimulationState,\n} from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { INSTANT_TRADING_RATE_XP } from '@reyaxyz/common';\n\nexport default class TradeSimulationClient {\n private marketId: number | null = null;\n private accountId: number | null = null;\n private loadedData: TradeSimulationState | null = null;\n private accountClient: AccountClient;\n constructor(accountClient: AccountClient) {\n // Constructor added\n this.accountClient = accountClient;\n }\n\n // Method to asynchronously load data based on marketId and accountId\n async arm(params: TradeSimulationLoadDataParams): Promise<void> {\n this.marketId = params.marketId;\n this.accountId = params.marginAccountId;\n\n this.loadedData = await this.fetchMarketData(this.marketId, this.accountId);\n }\n\n private async fetchMarketData(\n marketId: number,\n accountId: number,\n ): Promise<TradeSimulationState> {\n return this.accountClient.getTransactionSimulationInitialData({\n marginAccountId: accountId,\n marketId: marketId,\n });\n }\n\n // Synchronous method to simulate operations based on an amount\n simulate(params: TradeSimulationSimulateParams): SimulateTradeEntity {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n let amount;\n if (params.fromBase) {\n amount = params.amount;\n } else {\n amount = BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n const userAccountExposure = new ExposureCommand(\n this.loadedData.exposureDataAccount.accountId,\n this.loadedData.exposureDataAccount.rootCollateralPoolId,\n this.loadedData.exposureDataAccount.oraclePricePerMarket,\n this.loadedData.exposureDataAccount.accountBalancePerAsset,\n this.loadedData.exposureDataAccount.groupedByCollateral,\n this.loadedData.exposureDataAccount.riskMultipliers,\n this.loadedData.exposureDataAccount.riskMatrices,\n this.loadedData.exposureDataAccount.exchangeInfoPerAsset,\n this.loadedData.exposureDataAccount.positionInfoMarketConfiguration,\n this.loadedData.exposureDataAccount.uniqueTokenAddresses,\n this.loadedData.exposureDataAccount.uniqueQuoteCollaterals,\n this.loadedData.exposureDataAccount.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataAccount.realizedPnLSum,\n this.loadedData.exposureDataAccount.unrealizedPnLSum,\n this.loadedData.exposureDataAccount.mtmRpnlSum,\n this.loadedData.exposureDataAccount.collateralAddressToExchangePrice,\n );\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n\n /*\n max amount of margin in rUSD terms that can be transferred from the source account to the destination account\n that performs the isolated position trade (PRE TRADE)\n */\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const marginBalance =\n userAccountExposure.getUsdNodeMarginInfo.marginBalance;\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amount).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n const fees = ExposureCommand.calculateFee(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n amount,\n this.loadedData.feeParameter,\n );\n\n const { usdNodeMarginInfo: newMarginInfo, tokenMarginInfoPerAsset } =\n userAccountExposure.getUsdNodeMarginInfoPostTrade(\n amount,\n this.loadedData.marketStorage.quote_collateral,\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage.risk_block_id,\n );\n\n const newQuoteTokenMarginInfo = tokenMarginInfoPerAsset.find(\n (marginInfo: MarginInfo) => {\n return (\n marginInfo.assetAddress ===\n this.loadedData?.marketStorage?.quote_collateral\n );\n },\n );\n\n if (!newQuoteTokenMarginInfo) {\n throw new Error('Error performing simulation');\n }\n\n /*\n * Note, required margin is the initial margin requirement in rUSD terms of the account after the trade.\n * margin balance rusd - initial delta rusd = margin balance rusd - (margin balance rusd - imr rusd) = imr rusd\n * */\n\n const requiredMargin =\n newQuoteTokenMarginInfo.marginBalance -\n newQuoteTokenMarginInfo.initialDelta;\n\n const liquidationPrice = ExposureCommand.calculateLiquidation(\n newMarginInfo.marginBalance,\n newQuoteTokenMarginInfo.liquidationMarginRequirement,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n amount,\n );\n\n const marginRatio = ExposureCommand.getMarginRatio(newMarginInfo);\n\n const marginRatioHealth = ExposureCommand.evaluateHealthStatus(\n marginRatio * 100,\n );\n\n const baseSpacing = amountNormalizer(\n this.loadedData.marketConfiguration.base_spacing,\n ).toNumber();\n\n const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);\n const snappedAmount = snappedAmountInBase * estimatedPrice;\n const xpEarnRangeMin = Math.round(\n Math.abs(snappedAmount) / INSTANT_TRADING_RATE_XP,\n );\n const xpEarnRangeMax = Math.round(\n (100 * Math.abs(snappedAmount)) / INSTANT_TRADING_RATE_XP,\n );\n\n return {\n estimatedPrice,\n estimatedSlippage: slippage * 100,\n fees,\n liquidationPrice: liquidationPrice.toNumber(),\n marginRatio: marginRatio * 100,\n marginRatioHealth,\n marginBalance,\n availableMargin,\n requiredMargin,\n snappedAmount,\n snappedAmountInBase,\n xpEarnRange: {\n min: xpEarnRangeMin,\n max: xpEarnRangeMax,\n },\n maxSlippage: 1,\n } as SimulateTradeEntity;\n }\n\n // Synchronous method to simulate operations based on an amount\n simulateLimit(\n params: TradeSimulationSimulateLimitParams,\n ): SimulateLimitTradeEntity {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n let amount;\n if (params.fromBase) {\n amount = params.amount;\n } else {\n amount = BigNumber(params.amount).div(params.triggerPrice).toNumber();\n }\n\n /*\n max amount of margin in rUSD terms that can be transferred from the source account to the destination account\n that performs the isolated position trade (PRE TRADE)\n */\n\n const fees = ExposureCommand.calculateFee(\n params.triggerPrice,\n amount,\n this.loadedData.feeParameter,\n );\n\n const baseSpacing = amountNormalizer(\n this.loadedData.marketConfiguration.base_spacing,\n ).toNumber();\n\n const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);\n const snappedAmount = snappedAmountInBase * params.triggerPrice;\n\n return {\n fees,\n snappedAmount,\n snappedAmountInBase,\n };\n }\n\n convertValue(\n params: TradeSimulationConvertValueParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n if (!params.fromBase)\n return BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n else\n return BigNumber(params.amount)\n .times(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n\n convertValueEstimatedPrice(\n params: TradeSimulationConvertValueEstimatedPriceParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n\n const amountForSlippage = params.fromBase\n ? params.amount\n : BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amountForSlippage).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n\n if (!params.fromBase)\n return BigNumber(params.amount).div(estimatedPrice).toNumber();\n else return BigNumber(params.amount).times(estimatedPrice).toNumber();\n }\n\n estimatedPrice(params: EstimatedPriceParams): EstimatedPriceResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(params.amount).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n\n const price =\n this.loadedData.exposureDataAccount.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ];\n\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n\n return {\n estimatedPrice,\n markPrice: price,\n };\n }\n\n roundToBaseSpacing(amount: number, baseSpacing: number): number {\n const snappedAmount = BigNumber(amount)\n .abs()\n .dividedBy(baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(baseSpacing)\n .toNumber();\n\n if (amount < 0) {\n return -snappedAmount;\n }\n return snappedAmount;\n }\n\n updatePrice(price: number): void {\n if (!this.loadedData || !this.marketId) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n // update price\n const marketId = this.marketId;\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[marketId] =\n price;\n this.loadedData.exposureDataAccount.oraclePricePerMarket[marketId] = price;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"/","sources":["clients/modules/trade.simulation/types.ts"],"names":[],"mappings":"","sourcesContent":["import { MarginAccountEntity, MarketEntity } from '@reyaxyz/common';\n\nexport type TradeSimulationLoadDataParams = {\n marketId: MarketEntity['id'];\n marginAccountId: MarginAccountEntity['id'];\n};\n\nexport type TradeSimulationSimulateParams = {\n amount: number; // position size / base, + for long | - for short\n fromBase?: boolean;\n};\n\nexport type TradeSimulationConvertValueParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type EstimatedPriceParams = {\n amount: number; // amount in base\n};\n\nexport type EstimatedPriceResult = {\n estimatedPrice: number;\n markPrice: number;\n};\n\nexport type TradeSimulationConvertValueEstimatedPriceParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type TradeSimulationConvertValueEstimatedPriceResult = number;\n\nexport type SimulateTradeEntity = {\n liquidationPrice: number;\n fees: number;\n estimatedPrice: number;\n estimatedSlippage: number;\n marginRatio: MarginAccountEntity['marginRatioPercentage'];\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n availableMargin: number;\n marginBalance: number;\n requiredMargin: number;\n snappedAmount: number;\n snappedAmountInBase: number;\n xpEarnRange?: {\n min: number;\n max: number;\n };\n maxSlippage: number;\n};\n\nexport type TradeSimulationConvertValueResult = number;\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"/","sources":["clients/modules/trade.simulation/types.ts"],"names":[],"mappings":"","sourcesContent":["import { MarginAccountEntity, MarketEntity } from '@reyaxyz/common';\n\nexport type TradeSimulationLoadDataParams = {\n marketId: MarketEntity['id'];\n marginAccountId: MarginAccountEntity['id'];\n};\n\nexport type TradeSimulationSimulateParams = {\n amount: number; // position size / base, + for long | - for short\n fromBase?: boolean;\n};\n\nexport type TradeSimulationConvertValueParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type EstimatedPriceParams = {\n amount: number; // amount in base\n};\n\nexport type EstimatedPriceResult = {\n estimatedPrice: number;\n markPrice: number;\n};\n\nexport type TradeSimulationConvertValueEstimatedPriceParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type TradeSimulationConvertValueEstimatedPriceResult = number;\n\nexport type SimulateTradeEntity = {\n liquidationPrice: number;\n fees: number;\n estimatedPrice: number;\n estimatedSlippage: number;\n marginRatio: MarginAccountEntity['marginRatioPercentage'];\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n availableMargin: number;\n marginBalance: number;\n requiredMargin: number;\n snappedAmount: number;\n snappedAmountInBase: number;\n xpEarnRange?: {\n min: number;\n max: number;\n };\n maxSlippage: number;\n};\n\nexport type TradeSimulationSimulateLimitParams = {\n triggerPrice: number;\n amount: number; // position size / base, + for long | - for short\n fromBase?: boolean;\n};\n\nexport type SimulateLimitTradeEntity = {\n fees: number;\n snappedAmount: number;\n snappedAmountInBase: number;\n};\n\nexport type TradeSimulationConvertValueResult = number;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["clients/modules/conditional-orders/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,UAAU,EACV,WAAW,EAOZ,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,gCAAgC,EAChC,gCAAgC,EAChC,4BAA4B,EAC5B,4BAA4B,EAC5B,iDAAiD,EACjD,iDAAiD,EACjD,8BAA8B,EAC9B,8BAA8B,EAC9B,4BAA4B,EAC5B,4BAA4B,EAC7B,MAAM,SAAS,CAAC;AAGjB,MAAM,CAAC,OAAO,OAAO,uBAAwB,SAAQ,UAAU;IAC7D,OAAO,CAAC,WAAW,CAAc;gBAErB,WAAW,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM;IAM5C,2CAA2C,CAC/C,MAAM,EAAE,iDAAiD,GACxD,OAAO,CAAC,iDAAiD,CAAC;IAOvD,2BAA2B,CAC/B,MAAM,EAAE,gCAAgC,GACvC,OAAO,CAAC,gCAAgC,CAAC;IAStC,sBAAsB,CAC1B,MAAM,EAAE,4BAA4B,GACnC,OAAO,CAAC,4BAA4B,CAAC;IAkBlC,wBAAwB,CAC5B,MAAM,EAAE,8BAA8B,GACrC,OAAO,CAAC,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["clients/modules/conditional-orders/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,UAAU,EACV,WAAW,EAOZ,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,gCAAgC,EAChC,gCAAgC,EAChC,4BAA4B,EAC5B,4BAA4B,EAC5B,iDAAiD,EACjD,iDAAiD,EACjD,8BAA8B,EAC9B,8BAA8B,EAC9B,4BAA4B,EAC5B,4BAA4B,EAC7B,MAAM,SAAS,CAAC;AAGjB,MAAM,CAAC,OAAO,OAAO,uBAAwB,SAAQ,UAAU;IAC7D,OAAO,CAAC,WAAW,CAAc;gBAErB,WAAW,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM;IAM5C,2CAA2C,CAC/C,MAAM,EAAE,iDAAiD,GACxD,OAAO,CAAC,iDAAiD,CAAC;IAOvD,2BAA2B,CAC/B,MAAM,EAAE,gCAAgC,GACvC,OAAO,CAAC,gCAAgC,CAAC;IAStC,sBAAsB,CAC1B,MAAM,EAAE,4BAA4B,GACnC,OAAO,CAAC,4BAA4B,CAAC;IAkBlC,wBAAwB,CAC5B,MAAM,EAAE,8BAA8B,GACrC,OAAO,CAAC,8BAA8B,CAAC;IAyCpC,sBAAsB,CAC1B,MAAM,EAAE,4BAA4B,GACnC,OAAO,CAAC,4BAA4B,CAAC;YA0C1B,WAAW;YAQX,2BAA2B;CAkF1C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EstimatedPriceParams, EstimatedPriceResult, SimulateTradeEntity, TradeSimulationConvertValueEstimatedPriceParams, TradeSimulationConvertValueParams, TradeSimulationConvertValueResult, TradeSimulationLoadDataParams, TradeSimulationSimulateParams } from './types';
|
|
1
|
+
import { EstimatedPriceParams, EstimatedPriceResult, SimulateLimitTradeEntity, SimulateTradeEntity, TradeSimulationConvertValueEstimatedPriceParams, TradeSimulationConvertValueParams, TradeSimulationConvertValueResult, TradeSimulationLoadDataParams, TradeSimulationSimulateLimitParams, TradeSimulationSimulateParams } from './types';
|
|
2
2
|
import AccountClient from '../account';
|
|
3
3
|
export default class TradeSimulationClient {
|
|
4
4
|
private marketId;
|
|
@@ -9,6 +9,7 @@ export default class TradeSimulationClient {
|
|
|
9
9
|
arm(params: TradeSimulationLoadDataParams): Promise<void>;
|
|
10
10
|
private fetchMarketData;
|
|
11
11
|
simulate(params: TradeSimulationSimulateParams): SimulateTradeEntity;
|
|
12
|
+
simulateLimit(params: TradeSimulationSimulateLimitParams): SimulateLimitTradeEntity;
|
|
12
13
|
convertValue(params: TradeSimulationConvertValueParams): TradeSimulationConvertValueResult;
|
|
13
14
|
convertValueEstimatedPrice(params: TradeSimulationConvertValueEstimatedPriceParams): TradeSimulationConvertValueResult;
|
|
14
15
|
estimatedPrice(params: EstimatedPriceParams): EstimatedPriceResult;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["clients/modules/trade.simulation/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,+CAA+C,EAC/C,iCAAiC,EACjC,iCAAiC,EACjC,6BAA6B,EAC7B,6BAA6B,EAC9B,MAAM,SAAS,CAAC;AACjB,OAAO,aAAa,MAAM,YAAY,CAAC;AAUvC,MAAM,CAAC,OAAO,OAAO,qBAAqB;IACxC,OAAO,CAAC,QAAQ,CAAuB;IACvC,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,UAAU,CAAqC;IACvD,OAAO,CAAC,aAAa,CAAgB;gBACzB,aAAa,EAAE,aAAa;IAMlC,GAAG,CAAC,MAAM,EAAE,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC;YAOjD,eAAe;IAW7B,QAAQ,CAAC,MAAM,EAAE,6BAA6B,GAAG,mBAAmB;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["clients/modules/trade.simulation/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,wBAAwB,EACxB,mBAAmB,EACnB,+CAA+C,EAC/C,iCAAiC,EACjC,iCAAiC,EACjC,6BAA6B,EAC7B,kCAAkC,EAClC,6BAA6B,EAC9B,MAAM,SAAS,CAAC;AACjB,OAAO,aAAa,MAAM,YAAY,CAAC;AAUvC,MAAM,CAAC,OAAO,OAAO,qBAAqB;IACxC,OAAO,CAAC,QAAQ,CAAuB;IACvC,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,UAAU,CAAqC;IACvD,OAAO,CAAC,aAAa,CAAgB;gBACzB,aAAa,EAAE,aAAa;IAMlC,GAAG,CAAC,MAAM,EAAE,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC;YAOjD,eAAe;IAW7B,QAAQ,CAAC,MAAM,EAAE,6BAA6B,GAAG,mBAAmB;IAoKpE,aAAa,CACX,MAAM,EAAE,kCAAkC,GACzC,wBAAwB;IAqC3B,YAAY,CACV,MAAM,EAAE,iCAAiC,GACxC,iCAAiC;IAuBpC,0BAA0B,CACxB,MAAM,EAAE,+CAA+C,GACtD,iCAAiC;IAmDpC,cAAc,CAAC,MAAM,EAAE,oBAAoB,GAAG,oBAAoB;IA+ClE,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM;IAc/D,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;CAUjC"}
|
|
@@ -41,5 +41,15 @@ export type SimulateTradeEntity = {
|
|
|
41
41
|
};
|
|
42
42
|
maxSlippage: number;
|
|
43
43
|
};
|
|
44
|
+
export type TradeSimulationSimulateLimitParams = {
|
|
45
|
+
triggerPrice: number;
|
|
46
|
+
amount: number;
|
|
47
|
+
fromBase?: boolean;
|
|
48
|
+
};
|
|
49
|
+
export type SimulateLimitTradeEntity = {
|
|
50
|
+
fees: number;
|
|
51
|
+
snappedAmount: number;
|
|
52
|
+
snappedAmountInBase: number;
|
|
53
|
+
};
|
|
44
54
|
export type TradeSimulationConvertValueResult = number;
|
|
45
55
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"/","sources":["clients/modules/trade.simulation/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpE,MAAM,MAAM,6BAA6B,GAAG;IAC1C,QAAQ,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC;IAC7B,eAAe,EAAE,mBAAmB,CAAC,IAAI,CAAC,CAA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Z,GAAG,EAAE,MAAM,CAAC;QACZ,GAAG,EAAE,MAAM,CAAC;KACb,CAAC;IACF,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,kCAAkC,GAAG;IAC/C,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;IACtB,mBAAmB,EAAE,MAAM,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,iCAAiC,GAAG,MAAM,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reyaxyz/api-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.115.0",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"registry": "https://registry.npmjs.org"
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"ws": "^8.16.0"
|
|
41
41
|
},
|
|
42
42
|
"packageManager": "pnpm@8.3.1",
|
|
43
|
-
"gitHead": "
|
|
43
|
+
"gitHead": "d77cb9dec9d1753282c15f4784b24ecd23a05f41",
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@types/ws": "8.5.10"
|
|
46
46
|
}
|
|
@@ -90,7 +90,11 @@ export default class ConditionalOrdersClient extends RestClient {
|
|
|
90
90
|
);
|
|
91
91
|
|
|
92
92
|
// create new entry
|
|
93
|
-
const uri =
|
|
93
|
+
const uri =
|
|
94
|
+
this.reyaChainId === ReyaChainId.reyaCronos
|
|
95
|
+
? `/api/conditional-orders/create-or-update-order`
|
|
96
|
+
: `/api/conditional-orders/create-order`;
|
|
97
|
+
|
|
94
98
|
const result = await this.post<ConditionalOrder>(
|
|
95
99
|
uri,
|
|
96
100
|
{},
|
|
@@ -129,7 +133,11 @@ export default class ConditionalOrdersClient extends RestClient {
|
|
|
129
133
|
);
|
|
130
134
|
|
|
131
135
|
// create new entry
|
|
132
|
-
const uri =
|
|
136
|
+
const uri =
|
|
137
|
+
this.reyaChainId === ReyaChainId.reyaCronos
|
|
138
|
+
? `/api/conditional-orders/create-or-update-order`
|
|
139
|
+
: `/api/conditional-orders/update-order`;
|
|
140
|
+
|
|
133
141
|
const result = await this.post<ConditionalOrder>(
|
|
134
142
|
uri,
|
|
135
143
|
{},
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
EstimatedPriceParams,
|
|
3
3
|
EstimatedPriceResult,
|
|
4
|
+
SimulateLimitTradeEntity,
|
|
4
5
|
SimulateTradeEntity,
|
|
5
6
|
TradeSimulationConvertValueEstimatedPriceParams,
|
|
6
7
|
TradeSimulationConvertValueParams,
|
|
7
8
|
TradeSimulationConvertValueResult,
|
|
8
9
|
TradeSimulationLoadDataParams,
|
|
10
|
+
TradeSimulationSimulateLimitParams,
|
|
9
11
|
TradeSimulationSimulateParams,
|
|
10
12
|
} from './types';
|
|
11
13
|
import AccountClient from '../account';
|
|
@@ -210,6 +212,46 @@ export default class TradeSimulationClient {
|
|
|
210
212
|
} as SimulateTradeEntity;
|
|
211
213
|
}
|
|
212
214
|
|
|
215
|
+
// Synchronous method to simulate operations based on an amount
|
|
216
|
+
simulateLimit(
|
|
217
|
+
params: TradeSimulationSimulateLimitParams,
|
|
218
|
+
): SimulateLimitTradeEntity {
|
|
219
|
+
if (!this.loadedData) {
|
|
220
|
+
throw new Error('Data not loaded. Call arm() first.');
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let amount;
|
|
224
|
+
if (params.fromBase) {
|
|
225
|
+
amount = params.amount;
|
|
226
|
+
} else {
|
|
227
|
+
amount = BigNumber(params.amount).div(params.triggerPrice).toNumber();
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/*
|
|
231
|
+
max amount of margin in rUSD terms that can be transferred from the source account to the destination account
|
|
232
|
+
that performs the isolated position trade (PRE TRADE)
|
|
233
|
+
*/
|
|
234
|
+
|
|
235
|
+
const fees = ExposureCommand.calculateFee(
|
|
236
|
+
params.triggerPrice,
|
|
237
|
+
amount,
|
|
238
|
+
this.loadedData.feeParameter,
|
|
239
|
+
);
|
|
240
|
+
|
|
241
|
+
const baseSpacing = amountNormalizer(
|
|
242
|
+
this.loadedData.marketConfiguration.base_spacing,
|
|
243
|
+
).toNumber();
|
|
244
|
+
|
|
245
|
+
const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);
|
|
246
|
+
const snappedAmount = snappedAmountInBase * params.triggerPrice;
|
|
247
|
+
|
|
248
|
+
return {
|
|
249
|
+
fees,
|
|
250
|
+
snappedAmount,
|
|
251
|
+
snappedAmountInBase,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
213
255
|
convertValue(
|
|
214
256
|
params: TradeSimulationConvertValueParams,
|
|
215
257
|
): TradeSimulationConvertValueResult {
|
|
@@ -50,4 +50,16 @@ export type SimulateTradeEntity = {
|
|
|
50
50
|
maxSlippage: number;
|
|
51
51
|
};
|
|
52
52
|
|
|
53
|
+
export type TradeSimulationSimulateLimitParams = {
|
|
54
|
+
triggerPrice: number;
|
|
55
|
+
amount: number; // position size / base, + for long | - for short
|
|
56
|
+
fromBase?: boolean;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export type SimulateLimitTradeEntity = {
|
|
60
|
+
fees: number;
|
|
61
|
+
snappedAmount: number;
|
|
62
|
+
snappedAmountInBase: number;
|
|
63
|
+
};
|
|
64
|
+
|
|
53
65
|
export type TradeSimulationConvertValueResult = number;
|