@d8x/perpetuals-sdk 2.6.22 → 2.7.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.
Files changed (58) hide show
  1. package/dist/cjs/config/defaultConfig.json +2 -2
  2. package/dist/cjs/constants.js.map +1 -1
  3. package/dist/cjs/d8XMath.d.ts +42 -25
  4. package/dist/cjs/d8XMath.js +188 -151
  5. package/dist/cjs/d8XMath.js.map +1 -1
  6. package/dist/cjs/liquidatorTool.d.ts +1 -1
  7. package/dist/cjs/liquidatorTool.js +9 -9
  8. package/dist/cjs/liquidatorTool.js.map +1 -1
  9. package/dist/cjs/marketData.d.ts +3 -3
  10. package/dist/cjs/marketData.js +9 -8
  11. package/dist/cjs/marketData.js.map +1 -1
  12. package/dist/cjs/perpetualDataHandler.d.ts +3 -3
  13. package/dist/cjs/perpetualDataHandler.js +7 -5
  14. package/dist/cjs/perpetualDataHandler.js.map +1 -1
  15. package/dist/cjs/polyMktsPxFeed.js +2 -2
  16. package/dist/cjs/polyMktsPxFeed.js.map +1 -1
  17. package/dist/cjs/priceFeeds.d.ts +1 -0
  18. package/dist/cjs/priceFeeds.js +18 -2
  19. package/dist/cjs/priceFeeds.js.map +1 -1
  20. package/dist/cjs/utils.d.ts +3 -3
  21. package/dist/cjs/utils.js.map +1 -1
  22. package/dist/cjs/version.d.ts +1 -1
  23. package/dist/cjs/version.js +1 -1
  24. package/dist/esm/config/defaultConfig.json +2 -2
  25. package/dist/esm/constants.js.map +1 -1
  26. package/dist/esm/d8XMath.d.ts +42 -25
  27. package/dist/esm/d8XMath.js +187 -150
  28. package/dist/esm/d8XMath.js.map +1 -1
  29. package/dist/esm/liquidatorTool.d.ts +1 -1
  30. package/dist/esm/liquidatorTool.js +10 -10
  31. package/dist/esm/liquidatorTool.js.map +1 -1
  32. package/dist/esm/marketData.d.ts +3 -3
  33. package/dist/esm/marketData.js +9 -8
  34. package/dist/esm/marketData.js.map +1 -1
  35. package/dist/esm/perpetualDataHandler.d.ts +3 -3
  36. package/dist/esm/perpetualDataHandler.js +7 -5
  37. package/dist/esm/perpetualDataHandler.js.map +1 -1
  38. package/dist/esm/polyMktsPxFeed.js +2 -2
  39. package/dist/esm/polyMktsPxFeed.js.map +1 -1
  40. package/dist/esm/priceFeeds.d.ts +1 -0
  41. package/dist/esm/priceFeeds.js +18 -2
  42. package/dist/esm/priceFeeds.js.map +1 -1
  43. package/dist/esm/utils.d.ts +3 -3
  44. package/dist/esm/utils.js.map +1 -1
  45. package/dist/esm/version.d.ts +1 -1
  46. package/dist/esm/version.js +1 -1
  47. package/doc/d8x-perpetuals-sdk.md +116 -64
  48. package/package.json +1 -1
  49. package/src/config/defaultConfig.json +2 -2
  50. package/src/constants.ts +0 -1
  51. package/src/d8XMath.ts +210 -167
  52. package/src/liquidatorTool.ts +16 -10
  53. package/src/marketData.ts +38 -25
  54. package/src/perpetualDataHandler.ts +13 -9
  55. package/src/polyMktsPxFeed.ts +6 -7
  56. package/src/priceFeeds.ts +19 -3
  57. package/src/utils.ts +3 -3
  58. package/src/version.ts +1 -1
@@ -40,21 +40,21 @@ export declare function fromBytes4HexString(s: string): string;
40
40
  * @param {Object} mapping List of symbol and clean symbol pairs, e.g. [{symbol: "MATIC", cleanSymbol: "MATC"}, ...]
41
41
  * @returns {string} User friendly currency symbol, e.g. "MATIC"
42
42
  */
43
- export declare function contractSymbolToSymbol(s: string, mapping: Map<string, string>): string;
43
+ export declare function contractSymbolToSymbol(s: string, mapping: ReadonlyMap<string, string>): string;
44
44
  /**
45
45
  *
46
46
  * @param {string} s User friendly currency symbol, e.g. "MATIC"
47
47
  * @param {Object} mapping List of symbol and clean symbol pairs, e.g. [{symbol: "MATIC", cleanSymbol: "MATC"}, ...]
48
48
  * @returns {Buffer} Buffer that can be used with smart contract to identify tokens
49
49
  */
50
- export declare function symbolToContractSymbol(s: string, mapping: Map<string, string>): Buffer;
50
+ export declare function symbolToContractSymbol(s: string, mapping: ReadonlyMap<string, string>): Buffer;
51
51
  /**
52
52
  * Converts symbol or symbol combination into long format
53
53
  * @param {string} s symbol, e.g., USDC-MATC-USDC, MATC, USDC, ...
54
54
  * @param {Object} mapping list of symbol and clean symbol pairs, e.g. [{symbol: "MATIC", cleanSymbol: "MATC"}, ...]
55
55
  * @returns {string} long format e.g. MATIC. if not found the element is ""
56
56
  */
57
- export declare function symbol4BToLongSymbol(s: string, mapping: Map<string, string>): string;
57
+ export declare function symbol4BToLongSymbol(s: string, mapping: ReadonlyMap<string, string>): string;
58
58
  export declare function combineFlags(f1: bigint, f2: bigint): bigint;
59
59
  export declare function containsFlag(f1: bigint, f2: bigint): boolean;
60
60
  export declare function loadConfigAbis(config: NodeSDKConfig): void;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAAA,mCAAgC;AAGhC;;GAEG;AAEH,SAAS,QAAQ,CAAC,IAAY;IAC5B,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;IAC1B,OAAO,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,CAAC;AACjF,CAAC;AAED;;;;GAIG;AACH,SAAgB,QAAQ,CAAC,CAAS;IAChC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;QACnB,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;KACd;IACD,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IACrB,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QAC7B,yCAAyC;QACzC,qBAAqB;QACrB,IAAI,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;YACzB,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC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AAC,OAAe;IAC/C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAK,CAAC,CAAC,CAAC;AACxE,CAAC;AAFD,kCAEC"}
@@ -1 +1 @@
1
- export declare const D8X_SDK_VERSION = "2.6.22";
1
+ export declare const D8X_SDK_VERSION = "2.7.00";
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.D8X_SDK_VERSION = void 0;
4
- exports.D8X_SDK_VERSION = "2.6.22";
4
+ exports.D8X_SDK_VERSION = "2.7.00";
5
5
  //# sourceMappingURL=version.js.map
@@ -28,8 +28,8 @@
28
28
  {
29
29
  "name": "base_sepolia",
30
30
  "chainId": 84532,
31
- "version": 1,
32
- "proxyAddr": "0xa7868558E094E58251c6D12f407294c11522E88D",
31
+ "version": 3,
32
+ "proxyAddr": "0xfaC638d51B769D060aFC5953C41bF35595620b1c",
33
33
  "nodeURL": "https://sepolia.base.org",
34
34
  "priceFeedConfigNetwork": "mainnet",
35
35
  "shareTokenABILocation": "./abi/ShareToken.json",
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAG/C,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;AACrD,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;AACvE,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC,8BAA8B,CAAC,CAAC;AACjE,+EAA+E;AAC/E,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC,kCAAkC,CAAC,CAAC;AAC3E,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;AAC5D,M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AAG,aAAa,CAAC;AACpD,MAAM,CAAC,MAAM,qBAAqB,GAAG,YAAY,CAAC;AAClD,MAAM,CAAC,MAAM,QAAQ,GAAG,KAAK,CAAC;AAC9B,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC;AAChC,MAAM,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC;AAEpC,MAAM,CAAN,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,iDAAS,CAAA;IACT,+CAAI,CAAA;IACJ,mDAAM,CAAA;AACR,CAAC,EAJW,YAAY,KAAZ,YAAY,QAIvB;AAED,MAAM,CAAN,IAAY,WAKX;AALD,WAAY,WAAW;IACrB,qDAAY,CAAA;IACZ,qDAAQ,CAAA;IACR,6CAAI,CAAA;IACJ,mDAAO,CAAA;AACT,CAAC,EALW,WAAW,KAAX,WAAW,QAKtB;AAED,MAAM,CAAC,MAAM,2BAA2B,GAAG,SAAS,CAAC;AACrD,MAAM,CAAC,MAAM,2BAA2B,GAAG,SAAS,CAAC;AAErD,IAAI,cAAc,GAAG,OAAO,CAAC,6BAA6B,CAAoB,CAAC;AAC/E,cAAc,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;IAC5B,gGAAgG;IAChG,MAAM,CAAC,QAAQ,GAAG,SAAS,CAAC;IAC5B,MAAM,CAAC,MAAM,GAAG,OAAO,CAAC;IACxB,MAAM,CAAC,aAAa,GAAG,eAAe,CAAC;IACvC,MAAM,CAAC,aAAa,GAAG,eAAe,CAAC;AACzC,CAAC,CAAC,CAAC;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,cAAc,CAAC"}
@@ -160,10 +160,27 @@ export declare function getNewPositionLeverage(tradeAmount: number, marginCollat
160
160
  * @param {number} price - price to trade amount 'tradeAmnt'
161
161
  * @param {number} S3 - collateral to quote conversion (=S2 if base-collateral, =1 if quote collateral, = index S3 if quanto)
162
162
  * @param {number} S2Mark - mark price
163
- * @param {boolean} isPredMkt - true if prediction market
163
+ * @param {number} cmin - Absolute minimum margin per contract, only for pred markets
164
164
  * @returns {number} Amount to be deposited to have the given leverage when trading into position pos before fees
165
165
  */
166
- export declare function getDepositAmountForLvgTrade(pos0: number, b0: number, tradeAmnt: number, targetLvg: number, price: number, S3: number, S2Mark: number, isPredMkt: boolean): number;
166
+ export declare function getDepositAmountForLvgTrade(pos0: number, b0: number, tradeAmnt: number, targetLvg: number, price: number, S3: number, S2Mark: number, cmin: number | undefined): number;
167
+ /**
168
+ * Determine amount to be deposited into margin account so that the given leverage
169
+ * is obtained when opening a prediction market position
170
+ * Does NOT include fees, but accounts for a possible non-zero current position
171
+ * Smart contract equivalent: getDepositAmountForPredMktLvgPosition
172
+ * @param {number} pos0 - current position
173
+ * @param {number} b0 - current balance
174
+ * @param {number} c0 - current available cash
175
+ * @param {number} tradeAmnt - amount to trade
176
+ * @param {number} targetLvg - target leverage
177
+ * @param {number} prob - prob to trade amount 'tradeAmnt'
178
+ * @param {number} S3 - collateral to quote conversion (=S2 if base-collateral, =1 if quote collateral, = index S3 if quanto)
179
+ * @param {number} markProb - mark prob
180
+ * @param {number} imr - minimum absolute margin per contract (fInitialMarginRate)
181
+ * @returns {number} Amount to be deposited to have the given leverage when trading into position pos before fees
182
+ */
183
+ export declare function getDepositAmountForPredMktLvgTrade(pos0: number, b0: number, c0: number, tradeAmnt: number, targetLvg: number, prob: number, S3: number, markProb: number, imr: number): number;
167
184
  /**
168
185
  * Convert a perpetual price to probability (predtictive markets)
169
186
  * @param px Perpetual price
@@ -179,32 +196,22 @@ export declare function probToPrice(prob: number): number;
179
196
  export declare function entropy(prob: number): number;
180
197
  /**
181
198
  * Maintenance margin rate for prediction markets.
182
- * @param posSign sign of position in base currency (can be signed position or -1, 1)
199
+ * @param position signed position in base currency
200
+ * @param lockedInQC locked in value, p or 1-p times number of contracts
183
201
  * @param sm mark-price (=1+p)
184
- * @param m max margin rate from fInitialMarginRate
185
- * @returns margin rate to be applied (Math.abs(pos) * p * tau) / s3;
202
+ * @param m absolute maintenance buffer per contract (mu_m, fMaintenanceMarginRate)
203
+ * @returns {number} The margin rate to be applied: (Math.abs(pos) * p * tau) / s3
186
204
  */
187
- export declare function pmMaintenanceMarginRate(posSign: number, sm: number, m?: number | undefined): number;
205
+ export declare function pmMaintenanceMarginRate(position: number, lockedInQC: number, sm: number, m: number): number;
188
206
  /**
189
- * Maintenance margin rate for prediction markets.
207
+ * Initial margin rate for prediction markets.
190
208
  * @param posSign sign of position in base currency (can be signed position or -1, 1)
209
+ * @param s0 trade price
191
210
  * @param sm mark-price (=1+p)
192
- * @param m max margin rate from fMaintenanceMarginRate
193
- * @returns margin rate to be applied (Math.abs(pos) * p * tau) / s3;
194
- */
195
- export declare function pmInitialMarginRate(posSign: number, sm: number, m?: number | undefined): number;
196
- /**
197
- * Calculate the expected loss for a prediction market trade used for
198
- * prediction market fees
199
- * @param p probability derived from mark price (long)
200
- * @param m maximal maintenance rate from which we defer the actual maintenance margin rate
201
- * @param totLong total long in base currency
202
- * @param totShort total short
203
- * @param tradeAmt signed trade amount, can be zero
204
- * @param tradeMgnRate margin rate of the trader
205
- * @returns expected loss in dollars
211
+ * @param cmin Absolute min margin saved as `fInitialMarginRate`
212
+ * @returns {number} The margin rate to be applied: `(Math.abs(pos) * p * tau) / s3`
206
213
  */
207
- export declare function expectedLoss(p: number, m: number, totLong: number, totShort: number, tradeAmt: number, tradeMgnRate: number): number;
214
+ export declare function pmInitialMarginRate(posSign: number, s0: number, sm: number, cmin: number): number;
208
215
  /**
209
216
  * Exchange fee as a rate for prediction markets
210
217
  * For opening trades only
@@ -225,8 +232,18 @@ export declare function pmExchangeFee(prob: number, m: number, tradeAmt: number,
225
232
  * @returns current margin balance
226
233
  */
227
234
  export declare function pmMarginBalance(pos: number, s2: number, s3: number, ell: number, mc: number): number;
228
- export declare function pmExcessBalance(pos: number, s2: number, s3: number, ell: number, mc: number, m: number | undefined): number;
229
- export declare function pmFindLiquidationPrice(pos: number, s3: number, ell: number, mc: number, baseMarginRate: number | undefined, s2Start?: number | undefined): number;
235
+ export declare function pmExcessBalance(pos: number, s2: number, s3: number, ell: number, mc: number, m: number): number;
236
+ /**
237
+ *
238
+ * @param pos Signed position size
239
+ * @param s3 Collateral to quote conversion at spot
240
+ * @param ell Locked-in value
241
+ * @param mc Margin collateral
242
+ * @param baseMarginRate Maintenance margin per contract (mu_m)
243
+ * @param sm Mark price at entry
244
+ * @returns {number} Liquidation price as a probability in the range [0, 1]
245
+ */
246
+ export declare function pmFindLiquidationPrice(pos: number, s3: number, ell: number, mc: number, baseMarginRate: number): number;
230
247
  /**
231
248
  * Find maximal *affordable* trade size (short dir=-1 or long dir=1) for prediction
232
249
  * markets at provided leverage and incorporating the current position
@@ -254,6 +271,6 @@ export declare function pmFindMaxPersonalTradeSizeAtLeverage(dir: number, lvg: n
254
271
  * @param short Short open OI
255
272
  * @param sm Mark price (>1)
256
273
  * @param isBuy True if trade is long
257
- * @param mr Maintenance margin rate
274
+ * @param mr Margin threshold per contract for liquidation (mu_m)
258
275
  */
259
276
  export declare function pmMaxSignedOpenTradeSize(long: number, short: number, sm: number, isBuy: boolean, mr: number, ammFundsQC: number): number;
@@ -331,30 +331,100 @@ export function getNewPositionLeverage(tradeAmount, marginCollateral, currentPos
331
331
  * @param {number} price - price to trade amount 'tradeAmnt'
332
332
  * @param {number} S3 - collateral to quote conversion (=S2 if base-collateral, =1 if quote collateral, = index S3 if quanto)
333
333
  * @param {number} S2Mark - mark price
334
- * @param {boolean} isPredMkt - true if prediction market
334
+ * @param {number} cmin - Absolute minimum margin per contract, only for pred markets
335
335
  * @returns {number} Amount to be deposited to have the given leverage when trading into position pos before fees
336
336
  */
337
- export function getDepositAmountForLvgTrade(pos0, b0, tradeAmnt, targetLvg, price, S3, S2Mark, isPredMkt) {
338
- let pnl = (tradeAmnt * (S2Mark - price)) / S3;
339
- let S2MarkBefore = S2Mark;
340
- if (isPredMkt) {
341
- // adjust mark price to 'probability'
342
- S2Mark = S2Mark - 1;
343
- S2MarkBefore = S2Mark;
344
- if (pos0 < 0) {
345
- S2MarkBefore = 1 - S2Mark;
346
- }
347
- if (pos0 + tradeAmnt < 0) {
348
- S2Mark = 1 - S2Mark;
337
+ export function getDepositAmountForLvgTrade(pos0, b0, tradeAmnt, targetLvg, price, S3, S2Mark, cmin) {
338
+ if (cmin && cmin > 0) {
339
+ // TODO: c0?
340
+ if (b0 != 0) {
341
+ console.log("b0 != 0");
349
342
  }
343
+ return getDepositAmountForPredMktLvgTrade(pos0, b0, 0, tradeAmnt, targetLvg, price - 1, S3, S2Mark - 1, cmin);
350
344
  }
345
+ let pnl = (tradeAmnt * (S2Mark - price)) / S3;
351
346
  if (targetLvg == 0) {
352
347
  // use current leverage
353
- targetLvg = (Math.abs(pos0) * S2MarkBefore) / S3 / b0;
348
+ targetLvg = (Math.abs(pos0) * S2Mark) / S3 / b0;
354
349
  }
355
350
  let b = (Math.abs(pos0 + tradeAmnt) * S2Mark) / S3 / targetLvg;
356
351
  return -(b0 + pnl - b);
357
352
  }
353
+ /**
354
+ * Determine amount to be deposited into margin account so that the given leverage
355
+ * is obtained when opening a prediction market position
356
+ * Does NOT include fees, but accounts for a possible non-zero current position
357
+ * Smart contract equivalent: getDepositAmountForPredMktLvgPosition
358
+ * @param {number} pos0 - current position
359
+ * @param {number} b0 - current balance
360
+ * @param {number} c0 - current available cash
361
+ * @param {number} tradeAmnt - amount to trade
362
+ * @param {number} targetLvg - target leverage
363
+ * @param {number} prob - prob to trade amount 'tradeAmnt'
364
+ * @param {number} S3 - collateral to quote conversion (=S2 if base-collateral, =1 if quote collateral, = index S3 if quanto)
365
+ * @param {number} markProb - mark prob
366
+ * @param {number} imr - minimum absolute margin per contract (fInitialMarginRate)
367
+ * @returns {number} Amount to be deposited to have the given leverage when trading into position pos before fees
368
+ */
369
+ export function getDepositAmountForPredMktLvgTrade(pos0, b0, c0, tradeAmnt, targetLvg, prob, S3, markProb, imr) {
370
+ /**
371
+ * Smart contract implementation:
372
+ // find smallest x such that:
373
+ // bal * s3 >= pos value / lvg
374
+ // where:
375
+ // pos value / lvg = |pos| * R(pm, sign(pos)) * margin rate
376
+ // pos = pos0 + k
377
+ // cash = cash0 + x
378
+ // ell = ell0 + px * k
379
+ // bal * s3 = cash * s3 + pos * sm - ell
380
+ // = bal0 * s3 + x * s3 + k * (sm - px)
381
+
382
+ // subject to:
383
+ // x >= 0
384
+ // cash * s3 >= |pos| * min(cmin, prob(sign(pos)))
385
+ // k * (sm - px) <= 0 a.s.
386
+ // (positive pnl does not contribute, i.e. ignore px better than mark)
387
+
388
+ // solution:
389
+ // bal0 * s3 + x * s3 >= pos value / lvg + (k * (px - sm))_+ = v * s3
390
+ // -->
391
+ // x >= v + (cash0 - bal0)_+ - cash0 = v - min(bal0, cash0)
392
+ // = pos value / lvg/ s3 + (k * (px - sm))_+ / s3 - min (bal0, cash0)
393
+ // = A + B - C
394
+ // x >= |pos| * min(cmin, prob(sign(pos))) / s3 - cash0
395
+ // x >= 0
396
+
397
+ // init x = A = pos value / lvg / s3
398
+ int128 fNewPos = _fPosition0.add(_fTradeAmount);
399
+ int128 v = (
400
+ fNewPos > 0 ? fNewPos.mul(_fMarkProb) : fNewPos.neg().mul(ONE_64x64.sub(_fMarkProb))
401
+ ).mul(_fMarginRate).div(_fS3);
402
+ // + B = max(0,k * (px - sm)) / s3
403
+ {
404
+ int128 fPnL = _fTradeAmount.mul(_fMarkProb.sub(_fTradeProb));
405
+ if (fPnL < 0) {
406
+ v = v.sub(fPnL.div(_fS3)); // pnl < 0 -> increase v
407
+ }
408
+ }
409
+ // - C = - min(bal0, cash0) = - Equity
410
+ {
411
+ int128 equity = _fCash0CC < _fBalance0 ? _fCash0CC : _fBalance0;
412
+ v = v.sub(equity); // equity can be used / must be covered if negative
413
+ }
414
+ return v > 0 ? v : int128(0);
415
+ */
416
+ const newPos = pos0 + tradeAmnt;
417
+ const posProb = newPos > 0 ? markProb : 1 - markProb; // R(pm, sign(new pos))
418
+ const maxLvg = pmMaxLeverage(newPos, markProb, imr);
419
+ targetLvg = targetLvg > maxLvg ? maxLvg : targetLvg;
420
+ const posValue = (Math.abs(newPos) * posProb) / S3;
421
+ const tradeLoss = Math.max(0, tradeAmnt * (prob - markProb)) / S3;
422
+ const curEquity = Math.min(c0, b0);
423
+ return Math.max(posValue / targetLvg + tradeLoss - curEquity, 0);
424
+ }
425
+ function pmMaxLeverage(posSign, markProb, minMarginPerCtrct) {
426
+ return Math.round(100 * (posSign > 0 ? markProb / minMarginPerCtrct : (1 - markProb) / minMarginPerCtrct)) / 100;
427
+ }
358
428
  /**
359
429
  * Convert a perpetual price to probability (predtictive markets)
360
430
  * @param px Perpetual price
@@ -369,7 +439,7 @@ export function priceToProb(px) {
369
439
  * @returns Perpetual price
370
440
  */
371
441
  export function probToPrice(prob) {
372
- return 1 + prob;
442
+ return Math.max(1, Math.min(2, 1 + prob));
373
443
  }
374
444
  // shannon entropy
375
445
  export function entropy(prob) {
@@ -381,109 +451,56 @@ export function entropy(prob) {
381
451
  /**
382
452
  * Maintenance margin requirement for prediction markets
383
453
  * @param pos signed position
454
+ * @param lockedInQC locked in value
384
455
  * @param s2 mark price
385
456
  * @param s3 collateral to quote conversion
386
457
  * @param m base margin rate
387
458
  * @returns required margin balance
388
459
  */
389
- function pmMarginThresh(pos, s2, s3, m = 0.18) {
390
- let p = s2 - 1;
391
- if (pos < 0) {
392
- p = 1 - p;
393
- }
394
- const h = entropy(p);
395
- const tau = m + (0.4 - m) * h;
396
- return (Math.abs(pos) * p * tau) / s3;
460
+ function pmMarginThresh(pos, lockedInQC, s2, s3, m) {
461
+ return (pmMaintenanceMarginRate(pos, lockedInQC, s2, m) * Math.abs(pos)) / s3;
397
462
  }
398
463
  /**
399
464
  * Maintenance margin rate for prediction markets.
400
- * @param posSign sign of position in base currency (can be signed position or -1, 1)
465
+ * @param position signed position in base currency
466
+ * @param lockedInQC locked in value, p or 1-p times number of contracts
401
467
  * @param sm mark-price (=1+p)
402
- * @param m max margin rate from fInitialMarginRate
403
- * @returns margin rate to be applied (Math.abs(pos) * p * tau) / s3;
404
- */
405
- export function pmMaintenanceMarginRate(posSign, sm, m = 0.18) {
406
- let p = sm - 1;
407
- if (posSign < 0) {
408
- p = 1 - p;
468
+ * @param m absolute maintenance buffer per contract (mu_m, fMaintenanceMarginRate)
469
+ * @returns {number} The margin rate to be applied: (Math.abs(pos) * p * tau) / s3
470
+ */
471
+ export function pmMaintenanceMarginRate(position, lockedInQC, sm, m) {
472
+ let pm = sm - 1;
473
+ let entryP = position == 0 ? pm : Math.abs(lockedInQC / position) - 1;
474
+ if (position < 0) {
475
+ pm = 1 - pm;
476
+ entryP = 1 - entryP;
409
477
  }
410
- const h = entropy(p);
411
- return m + (0.4 - m) * h;
478
+ const L = Math.max(entryP - pm, 0);
479
+ const balAtLiq = Math.min(m + L, entryP) * Math.abs(position) + position * sm - lockedInQC;
480
+ return balAtLiq / (Math.abs(position) * pm);
412
481
  }
413
482
  /**
414
- * Maintenance margin rate for prediction markets.
483
+ * Initial margin rate for prediction markets.
415
484
  * @param posSign sign of position in base currency (can be signed position or -1, 1)
485
+ * @param s0 trade price
416
486
  * @param sm mark-price (=1+p)
417
- * @param m max margin rate from fMaintenanceMarginRate
418
- * @returns margin rate to be applied (Math.abs(pos) * p * tau) / s3;
487
+ * @param cmin Absolute min margin saved as `fInitialMarginRate`
488
+ * @returns {number} The margin rate to be applied: `(Math.abs(pos) * p * tau) / s3`
419
489
  */
420
- export function pmInitialMarginRate(posSign, sm, m = 0.2) {
421
- let p = sm - 1;
490
+ export function pmInitialMarginRate(posSign, s0, sm, cmin) {
491
+ let pm = sm - 1;
492
+ let p0 = s0 - 1;
422
493
  if (posSign < 0) {
423
- p = 1 - p;
494
+ pm = 1 - pm; // R(p_mark, sign(pos))
495
+ p0 = 1 - p0; // R(p_entry, sign(pos))
424
496
  }
425
- const h = entropy(p);
426
- return m + (0.5 - m) * h;
427
- }
428
- /**
429
- * Calculate the expected loss for a prediction market trade used for
430
- * prediction market fees
431
- * @param p probability derived from mark price (long)
432
- * @param m maximal maintenance rate from which we defer the actual maintenance margin rate
433
- * @param totLong total long in base currency
434
- * @param totShort total short
435
- * @param tradeAmt signed trade amount, can be zero
436
- * @param tradeMgnRate margin rate of the trader
437
- * @returns expected loss in dollars
438
- */
439
- export function expectedLoss(p, m, totLong, totShort, tradeAmt, tradeMgnRate) {
440
- // maintenance margin rate
441
- m = (0.4 - m) * entropy(p) + m;
442
- let dlm = 0;
443
- let dl = 0;
444
- let dsm = 0;
445
- let ds = 0;
446
- if (tradeAmt > 0) {
447
- dlm = p * tradeAmt * tradeMgnRate;
448
- dl = tradeAmt;
449
- }
450
- else if (tradeAmt < 0) {
451
- dsm = (1 - p) * Math.abs(tradeAmt) * tradeMgnRate;
452
- ds = Math.abs(tradeAmt);
453
- }
454
- const a = dl + totLong - m * totShort - dsm;
455
- const b = ds + totShort - m * totLong - dlm;
456
- return p * (1 - p) * Math.max(0, a + b);
457
- }
458
- /**
459
- * Equivalent to
460
- * const el0 = expectedLoss(prob, m, totLong, totShort, 0, 0);
461
- * const el1 = expectedLoss(prob, m, totLong, totShort, tradeAmt, tradeMgnRate)
462
- * const fee = (el1 - el0) / Math.abs(tradeAmt);
463
- * @param p prob long probability
464
- * @param m max maintenance margin rate (0.18)
465
- * @param tradeAmt trade amount in base currency
466
- * @param tradeMgnRate margin rate for this trade
467
- * @returns dollar fee
468
- */
469
- function expectedLossImpact(p, m, tradeAmt, tradeMgnRate) {
470
- m = (0.4 - m) * entropy(p) + m;
471
- let dlm = 0;
472
- let dl = 0;
473
- let dsm = 0;
474
- let ds = 0;
475
- if (tradeAmt > 0) {
476
- dlm = p * tradeAmt * tradeMgnRate;
477
- dl = tradeAmt;
478
- }
479
- else if (tradeAmt < 0) {
480
- dsm = (1 - p) * Math.abs(tradeAmt) * tradeMgnRate;
481
- ds = Math.abs(tradeAmt);
482
- }
483
- //long: p * (1 - p) max(0, dl-dlm) = p * (1 - p) max(0, tradeAmt - p * tradeAmt * tradeMgnRate)
484
- const a = dl - dsm;
485
- const b = ds - dlm;
486
- return p * (1 - p) * Math.max(0, a + b);
497
+ // mu0 = max(Rm/lvg, min(Rm, cmin))
498
+ // balance = (mu0 * |k| + k *(sm - s0)) / s3
499
+ // pos value = |k| * Rm / s3
500
+ // at max init lvg: Rm/lvg = min(cmin, Rm)
501
+ // --> margin rate = (mu0 + Rm - R0) / Rm
502
+ const mu0 = Math.min(pm, cmin) + Math.max(0, p0 - pm);
503
+ return (mu0 + pm - p0) / pm;
487
504
  }
488
505
  /**
489
506
  * Exchange fee as a rate for prediction markets
@@ -495,13 +512,12 @@ function expectedLossImpact(p, m, tradeAmt, tradeMgnRate) {
495
512
  * @returns dollar fee relative to tradeAmt
496
513
  */
497
514
  export function pmExchangeFee(prob, m, tradeAmt, tradeMgnRate) {
498
- /*
499
- equivalent:
500
- const el0 = expectedLoss(prob, m, totLong, totShort, 0, 0);
501
- const el1 = expectedLoss(prob, m, totLong, totShort, tradeAmt, tradeMgnRate);
502
- const fee = (el1 - el0) / Math.abs(tradeAmt);
503
- */
504
- let fee = expectedLossImpact(prob, m, tradeAmt, tradeMgnRate) / Math.abs(tradeAmt);
515
+ // TODO: port contract logic here
516
+ const [kappa, es] = [0, 0];
517
+ prob = tradeAmt > 0 ? prob : 1 - prob;
518
+ let fee = prob * (1 - kappa);
519
+ const scaledLvg = prob * tradeMgnRate * (1 - fee);
520
+ fee = fee * (1 - prob) - scaledLvg + es;
505
521
  return Math.max(fee, 0.001);
506
522
  }
507
523
  /**
@@ -517,27 +533,39 @@ export function pmMarginBalance(pos, s2, s3, ell, mc) {
517
533
  return (pos * s2) / s3 - ell / s3 + mc;
518
534
  }
519
535
  export function pmExcessBalance(pos, s2, s3, ell, mc, m) {
520
- return pmMarginBalance(pos, s2, s3, ell, mc) - pmMarginThresh(pos, s2, s3, m);
521
- }
522
- // finds the liquidation price for prediction markets
523
- // using Newton's algorithm
524
- export function pmFindLiquidationPrice(pos, s3, ell, mc, baseMarginRate, s2Start = 0.5) {
525
- const delta_s = 0.01;
526
- let s = 100;
527
- let s_new = s2Start;
528
- while (Math.abs(s_new - s) > 0.01) {
529
- s = s_new;
530
- const f = Math.pow(pmExcessBalance(pos, s, s3, ell, mc, baseMarginRate), 2);
531
- const ds = (Math.pow(pmExcessBalance(pos, s + delta_s, s3, ell, mc, baseMarginRate), 2) - f) / delta_s;
532
- s_new = s - f / ds;
533
- if (s_new < 1) {
534
- return 1;
535
- }
536
- if (s_new > 2) {
537
- return 2;
538
- }
536
+ return pmMarginBalance(pos, s2, s3, ell, mc) - pmMarginThresh(pos, ell, s2, s3, m);
537
+ }
538
+ /**
539
+ *
540
+ * @param pos Signed position size
541
+ * @param s3 Collateral to quote conversion at spot
542
+ * @param ell Locked-in value
543
+ * @param mc Margin collateral
544
+ * @param baseMarginRate Maintenance margin per contract (mu_m)
545
+ * @param sm Mark price at entry
546
+ * @returns {number} Liquidation price as a probability in the range [0, 1]
547
+ */
548
+ export function pmFindLiquidationPrice(pos, s3, ell, mc, baseMarginRate) {
549
+ // liq <--> (A) c / |k| < R0 && (B) E < |k| * mu_m
550
+ // if not (A), return 0 (long) or 1 (short) [no liq]
551
+ // else, solve for pm:
552
+ // E = c - |k| max(0, s * (p0 - pm)) = |k| * mu_m
553
+ // if c/|k| < mu_m:
554
+ // any number would do --> return 1 (long) or 0 (short)
555
+ // else:
556
+ // pm = p0 - s * (c/|k| - mu_m)
557
+ const p0 = Math.abs(ell / pos) - 1;
558
+ const R0 = pos > 0 ? p0 : 1 - p0;
559
+ const excessPerCtrct = (mc * s3) / Math.abs(pos) - baseMarginRate; // c/|k| - mu_m, mu_m < CMINUS
560
+ if (mc * s3 > R0 * Math.abs(pos)) {
561
+ // c > |k| R(p0, s) --> no liquidation
562
+ return probToPrice(pos > 0 ? 0.0001 : 0.9999);
563
+ }
564
+ if (excessPerCtrct < 0) {
565
+ // already underwater
566
+ return probToPrice(pos > 0 ? 0.9999 : 0.0001);
539
567
  }
540
- return s;
568
+ return probToPrice(pos > 0 ? p0 - excessPerCtrct : p0 + excessPerCtrct);
541
569
  }
542
570
  /**
543
571
  * Calculate the excess margin defined as
@@ -581,19 +609,22 @@ function excessMargin(tradeAmt, currentCashCC, currentPos, currentLockedInQC, li
581
609
  * @returns deposit amount
582
610
  */
583
611
  function pmGetDepositAmtForLvgTrade(tradeAmt, targetLvg, price, S3, S2Mark) {
584
- const pnl = (tradeAmt * (S2Mark - price)) / S3;
585
- let p = S2Mark - 1;
586
- if (tradeAmt < 0) {
587
- p = 1 - p;
588
- }
589
- const b = (Math.abs(tradeAmt) * p) / S3 / targetLvg;
590
- const amt = -(pnl - b);
591
- // check:
592
- //bal = amt+pnl
593
- //pos_val = (np.abs(trade_amt) * p) / S3
594
- //lvg = pos_val/bal
595
- //assert(np.abs(lvg-targetLvg)<0.1)
596
- return amt;
612
+ const cmin = 0.05;
613
+ // refer to main contract function for this:
614
+ return getDepositAmountForPredMktLvgTrade(0, 0, 0, tradeAmt, targetLvg, price - 1, S3, S2Mark - 1, cmin);
615
+ // const pnl = (tradeAmt * (S2Mark - price)) / S3;
616
+ // let p = S2Mark - 1;
617
+ // if (tradeAmt < 0) {
618
+ // p = 1 - p;
619
+ // }
620
+ // const b = (Math.abs(tradeAmt) * p) / S3 / targetLvg;
621
+ // const amt = -(pnl - b);
622
+ // // check:
623
+ // //bal = amt+pnl
624
+ // //pos_val = (np.abs(trade_amt) * p) / S3
625
+ // //lvg = pos_val/bal
626
+ // //assert(np.abs(lvg-targetLvg)<0.1)
627
+ // return amt;
597
628
  }
598
629
  /**
599
630
  * Internal function to calculate cash over initial margin rate
@@ -613,16 +644,19 @@ function pmGetDepositAmtForLvgTrade(tradeAmt, targetLvg, price, S3, S2Mark) {
613
644
  * @returns excess cash
614
645
  */
615
646
  function pmExcessCashAtLvg(tradeAmt, lvg, walletBalCC, currentCashCC, currentPosition, currentLockedInValue, slippage, S2, Sm, S3) {
647
+ const cmin = 0.05;
648
+ const mu_m = 0.01;
649
+ const maxLvg = pmMaxLeverage(currentPosition + tradeAmt, Sm - 1, cmin);
650
+ lvg = lvg < maxLvg ? lvg : maxLvg;
616
651
  //determine deposit amount for given leverage
617
652
  const limitPrice = S2 * (1 + Math.sign(tradeAmt) * slippage);
618
653
  const depositFromWallet = pmGetDepositAmtForLvgTrade(tradeAmt, lvg, limitPrice, S3, Sm);
619
- const m0 = 0.18;
620
654
  //leverage fee
621
655
  let p0 = Sm - 1;
622
656
  if (tradeAmt < 0) {
623
657
  p0 = 2 - Sm; //=1-(Sm-1)
624
658
  }
625
- const feeCc = (Math.abs(tradeAmt) * pmExchangeFee(p0, m0, tradeAmt, 1 / lvg)) / S3;
659
+ const feeCc = (Math.abs(tradeAmt) * pmExchangeFee(p0, mu_m, tradeAmt, 1 / lvg)) / S3;
626
660
  //excess cash
627
661
  let exc = walletBalCC - depositFromWallet - feeCc;
628
662
  if (exc < 0) {
@@ -631,12 +665,13 @@ function pmExcessCashAtLvg(tradeAmt, lvg, walletBalCC, currentCashCC, currentPos
631
665
  // margin balance
632
666
  let pos = currentPosition + tradeAmt;
633
667
  let p = Sm - 1;
668
+ let entryP = limitPrice - 1;
634
669
  if (pos < 0) {
635
- p = 2 - Sm;
670
+ p = 1 - Sm;
671
+ entryP = 1 - entryP;
636
672
  }
637
- const h = entropy(p);
638
- const tau = m0 + (0.5 - m0) * h;
639
- const thresh = Math.abs(pos) * p * tau;
673
+ const mu0 = p / lvg + Math.max(0, entryP - p);
674
+ const thresh = Math.abs(pos) * mu0;
640
675
  const b0 = depositFromWallet +
641
676
  currentCashCC +
642
677
  Math.abs(currentPosition) * Sm -
@@ -748,13 +783,15 @@ export function pmFindMaxPersonalTradeSizeAtLeverage(dir, lvg, walletBalCC, slip
748
783
  * @param short Short open OI
749
784
  * @param sm Mark price (>1)
750
785
  * @param isBuy True if trade is long
751
- * @param mr Maintenance margin rate
786
+ * @param mr Margin threshold per contract for liquidation (mu_m)
752
787
  */
753
788
  export function pmMaxSignedOpenTradeSize(long, short, sm, isBuy, mr, ammFundsQC) {
754
- if (sm < 1) {
789
+ if (sm <= 1 || sm >= 2) {
790
+ // closed
755
791
  return 0;
756
792
  }
757
- const m = pmMaintenanceMarginRate(isBuy ? 1 : -1, sm, mr);
793
+ const counterPos = isBuy ? -short : long;
794
+ const m = pmMaintenanceMarginRate(counterPos, counterPos * sm, sm, mr);
758
795
  let p = !isBuy ? sm - 1 : 2 - sm;
759
796
  p = p < 0.01 ? 0.01 : p > 0.99 ? 0.99 : p; // same cap as contract
760
797
  return isBuy ? (ammFundsQC + m * p * short) / p - long : -(ammFundsQC + m * p * long) / p + short;