@drift-labs/sdk 0.2.0-temp.1 → 2.0.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 +27 -29
- package/lib/accounts/bulkAccountLoader.d.ts +2 -0
- package/lib/accounts/bulkAccountLoader.js +36 -29
- package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
- package/lib/accounts/bulkUserStatsSubscription.js +21 -0
- package/lib/accounts/bulkUserSubscription.d.ts +2 -2
- package/lib/accounts/bulkUserSubscription.js +0 -1
- package/lib/accounts/fetch.d.ts +2 -1
- package/lib/accounts/fetch.js +9 -1
- package/lib/accounts/{pollingClearingHouseAccountSubscriber.d.ts → pollingDriftClientAccountSubscriber.d.ts} +20 -25
- package/lib/accounts/{pollingClearingHouseAccountSubscriber.js → pollingDriftClientAccountSubscriber.js} +45 -49
- package/lib/accounts/{pollingOracleSubscriber.d.ts → pollingOracleAccountSubscriber.d.ts} +2 -2
- package/lib/accounts/{pollingOracleSubscriber.js → pollingOracleAccountSubscriber.js} +3 -3
- package/lib/accounts/pollingUserAccountSubscriber.d.ts +1 -1
- package/lib/accounts/pollingUserAccountSubscriber.js +5 -11
- package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
- package/lib/accounts/pollingUserStatsAccountSubscriber.js +107 -0
- package/lib/accounts/types.d.ts +26 -15
- package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +49 -0
- package/lib/accounts/{webSocketClearingHouseAccountSubscriber.js → webSocketDriftClientAccountSubscriber.js} +47 -45
- package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
- package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
- package/lib/addresses/marketAddresses.d.ts +1 -3
- package/lib/addresses/marketAddresses.js +1 -1
- package/lib/addresses/pda.d.ts +15 -9
- package/lib/addresses/pda.js +73 -35
- package/lib/adminClient.d.ts +65 -0
- package/lib/adminClient.js +637 -0
- package/lib/config.d.ts +10 -10
- package/lib/config.js +26 -22
- package/lib/constants/numericConstants.d.ts +29 -12
- package/lib/constants/numericConstants.js +40 -21
- package/lib/constants/perpMarkets.d.ts +18 -0
- package/lib/constants/{markets.js → perpMarkets.js} +20 -9
- package/lib/constants/spotMarkets.d.ts +19 -0
- package/lib/constants/spotMarkets.js +63 -0
- package/lib/dlob/DLOB.d.ts +82 -0
- package/lib/dlob/DLOB.js +694 -0
- package/lib/dlob/DLOBNode.d.ts +54 -0
- package/lib/dlob/DLOBNode.js +77 -0
- package/lib/dlob/NodeList.d.ts +27 -0
- package/lib/dlob/NodeList.js +144 -0
- package/lib/driftClient.d.ts +234 -0
- package/lib/driftClient.js +2108 -0
- package/lib/{clearingHouseConfig.d.ts → driftClientConfig.d.ts} +9 -9
- package/lib/{clearingHouseConfig.js → driftClientConfig.js} +0 -0
- package/lib/events/eventList.js +3 -0
- package/lib/events/eventSubscriber.d.ts +5 -2
- package/lib/events/eventSubscriber.js +25 -11
- package/lib/events/fetchLogs.d.ts +13 -2
- package/lib/events/fetchLogs.js +45 -14
- package/lib/events/pollingLogProvider.d.ts +2 -1
- package/lib/events/pollingLogProvider.js +7 -3
- package/lib/events/sort.js +8 -11
- package/lib/events/types.d.ts +11 -3
- package/lib/events/types.js +8 -0
- package/lib/events/webSocketLogProvider.js +1 -1
- package/lib/examples/makeTradeExample.js +30 -18
- package/lib/factory/bigNum.d.ts +8 -4
- package/lib/factory/bigNum.js +109 -19
- package/lib/idl/drift.json +8392 -0
- package/lib/index.d.ts +29 -12
- package/lib/index.js +29 -12
- package/lib/math/amm.d.ts +9 -6
- package/lib/math/amm.js +91 -38
- package/lib/math/conversion.js +1 -1
- package/lib/math/exchangeStatus.d.ts +4 -0
- package/lib/math/exchangeStatus.js +18 -0
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +23 -21
- package/lib/math/insurance.d.ts +4 -0
- package/lib/math/insurance.js +27 -0
- package/lib/math/margin.d.ts +11 -0
- package/lib/math/margin.js +82 -0
- package/lib/math/market.d.ts +14 -9
- package/lib/math/market.js +70 -10
- package/lib/math/oracles.d.ts +4 -0
- package/lib/math/oracles.js +36 -8
- package/lib/math/orders.d.ts +16 -6
- package/lib/math/orders.js +97 -17
- package/lib/math/position.d.ts +27 -13
- package/lib/math/position.js +91 -37
- package/lib/math/repeg.js +17 -8
- package/lib/math/spotBalance.d.ts +22 -0
- package/lib/math/spotBalance.js +192 -0
- package/lib/math/spotMarket.d.ts +4 -0
- package/lib/math/spotMarket.js +8 -0
- package/lib/math/spotPosition.d.ts +6 -0
- package/lib/math/spotPosition.js +23 -0
- package/lib/math/trade.d.ts +10 -10
- package/lib/math/trade.js +27 -31
- package/lib/oracles/pythClient.js +1 -1
- package/lib/oracles/quoteAssetOracleClient.js +1 -1
- package/lib/oracles/switchboardClient.js +1 -1
- package/lib/orderParams.d.ts +4 -4
- package/lib/orderParams.js +12 -4
- package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
- package/lib/serum/serumFulfillmentConfigMap.js +17 -0
- package/lib/serum/serumSubscriber.d.ts +27 -0
- package/lib/serum/serumSubscriber.js +56 -0
- package/lib/serum/types.d.ts +11 -0
- package/{src/oracles → lib/serum}/types.js +0 -0
- package/lib/tokenFaucet.d.ts +1 -0
- package/lib/tokenFaucet.js +23 -12
- package/lib/tx/retryTxSender.d.ts +1 -1
- package/lib/tx/retryTxSender.js +13 -4
- package/lib/tx/types.d.ts +1 -1
- package/lib/types.d.ts +631 -222
- package/lib/types.js +137 -24
- package/lib/user.d.ts +228 -0
- package/lib/user.js +959 -0
- package/lib/userConfig.d.ts +14 -0
- package/lib/{clearingHouseUserConfig.js → userConfig.js} +0 -0
- package/lib/userMap/userMap.d.ts +41 -0
- package/lib/userMap/userMap.js +85 -0
- package/lib/userMap/userStatsMap.d.ts +19 -0
- package/lib/userMap/userStatsMap.js +68 -0
- package/lib/userName.d.ts +1 -0
- package/lib/userName.js +3 -2
- package/lib/userStats.d.ts +18 -0
- package/lib/userStats.js +49 -0
- package/lib/userStatsConfig.d.ts +14 -0
- package/{src/clearingHouseConfig.js → lib/userStatsConfig.js} +0 -0
- package/lib/util/getTokenAddress.d.ts +2 -0
- package/lib/util/getTokenAddress.js +9 -0
- package/package.json +12 -5
- package/src/accounts/bulkAccountLoader.ts +44 -34
- package/src/accounts/bulkUserStatsSubscription.ts +33 -0
- package/src/accounts/bulkUserSubscription.ts +2 -3
- package/src/accounts/fetch.ts +27 -2
- package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
- package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
- package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
- package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
- package/src/accounts/types.ts +35 -15
- package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
- package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
- package/src/addresses/marketAddresses.ts +3 -4
- package/src/addresses/pda.ts +105 -33
- package/src/adminClient.ts +1207 -0
- package/src/config.ts +41 -34
- package/src/constants/numericConstants.ts +59 -26
- package/src/constants/{markets.ts → perpMarkets.ts} +22 -11
- package/src/constants/spotMarkets.ts +83 -0
- package/src/dlob/DLOB.ts +1120 -0
- package/src/dlob/DLOBNode.ts +155 -0
- package/src/dlob/NodeList.ts +195 -0
- package/src/driftClient.ts +3594 -0
- package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
- package/src/events/eventList.ts +3 -0
- package/src/events/eventSubscriber.ts +36 -14
- package/src/events/fetchLogs.ts +60 -15
- package/src/events/pollingLogProvider.ts +11 -3
- package/src/events/sort.ts +11 -15
- package/src/events/types.ts +27 -2
- package/src/events/webSocketLogProvider.ts +1 -1
- package/src/examples/makeTradeExample.js +152 -75
- package/src/examples/makeTradeExample.ts +44 -28
- package/src/factory/bigNum.ts +150 -22
- package/src/idl/drift.json +8392 -0
- package/src/idl/pyth.json +98 -2
- package/src/index.ts +29 -12
- package/src/math/amm.ts +161 -48
- package/src/math/conversion.ts +2 -2
- package/src/math/exchangeStatus.ts +31 -0
- package/src/math/funding.ts +41 -31
- package/src/math/insurance.ts +35 -0
- package/src/math/margin.ts +133 -0
- package/src/math/market.ts +143 -14
- package/src/math/oracles.ts +63 -9
- package/src/math/orders.ts +168 -26
- package/src/math/position.ts +133 -59
- package/src/math/repeg.ts +19 -9
- package/src/math/spotBalance.ts +319 -0
- package/src/math/spotMarket.ts +9 -0
- package/src/math/spotPosition.ts +47 -0
- package/src/math/trade.ts +33 -37
- package/src/oracles/pythClient.ts +2 -2
- package/src/oracles/quoteAssetOracleClient.ts +2 -2
- package/src/oracles/switchboardClient.ts +2 -2
- package/src/orderParams.ts +16 -8
- package/src/serum/serumFulfillmentConfigMap.ts +26 -0
- package/src/serum/serumSubscriber.ts +99 -0
- package/src/serum/types.ts +13 -0
- package/src/tokenFaucet.ts +38 -15
- package/src/tx/retryTxSender.ts +16 -5
- package/src/tx/types.ts +2 -1
- package/src/types.ts +594 -195
- package/src/user.ts +1599 -0
- package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
- package/src/userMap/userMap.ts +124 -0
- package/src/userMap/userStatsMap.ts +108 -0
- package/src/userName.ts +2 -1
- package/src/userStats.ts +75 -0
- package/src/userStatsConfig.ts +18 -0
- package/src/util/getTokenAddress.ts +18 -0
- package/tests/bn/test.ts +46 -11
- package/tests/dlob/helpers.ts +619 -0
- package/tests/dlob/test.ts +4586 -0
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
- package/lib/admin.d.ts +0 -44
- package/lib/admin.js +0 -438
- package/lib/clearingHouse.d.ts +0 -146
- package/lib/clearingHouse.js +0 -1154
- package/lib/clearingHouseUser.d.ts +0 -187
- package/lib/clearingHouseUser.js +0 -634
- package/lib/clearingHouseUserConfig.d.ts +0 -14
- package/lib/constants/banks.d.ts +0 -16
- package/lib/constants/banks.js +0 -41
- package/lib/constants/markets.d.ts +0 -19
- package/lib/idl/clearing_house.json +0 -4464
- package/lib/math/bankBalance.d.ts +0 -9
- package/lib/math/bankBalance.js +0 -75
- package/lib/math/state.d.ts +0 -8
- package/lib/math/state.js +0 -15
- package/lib/orders.d.ts +0 -8
- package/lib/orders.js +0 -134
- package/src/accounts/bulkAccountLoader.js +0 -197
- package/src/accounts/bulkUserSubscription.js +0 -33
- package/src/accounts/pollingClearingHouseAccountSubscriber.js +0 -311
- package/src/accounts/pollingOracleSubscriber.js +0 -93
- package/src/accounts/pollingTokenAccountSubscriber.js +0 -90
- package/src/accounts/pollingUserAccountSubscriber.js +0 -132
- package/src/accounts/types.js +0 -10
- package/src/accounts/utils.js +0 -7
- package/src/accounts/webSocketAccountSubscriber.js +0 -93
- package/src/accounts/webSocketClearingHouseAccountSubscriber.js +0 -233
- package/src/accounts/webSocketUserAccountSubscriber.js +0 -62
- package/src/addresses/marketAddresses.js +0 -26
- package/src/admin.js +0 -517
- package/src/admin.ts +0 -730
- package/src/clearingHouse.ts +0 -1828
- package/src/clearingHouseUser.ts +0 -978
- package/src/clearingHouseUserConfig.js +0 -2
- package/src/config.js +0 -67
- package/src/constants/banks.js +0 -42
- package/src/constants/banks.ts +0 -50
- package/src/constants/markets.js +0 -42
- package/src/constants/numericConstants.js +0 -41
- package/src/events/eventSubscriber.js +0 -139
- package/src/events/fetchLogs.js +0 -50
- package/src/events/pollingLogProvider.js +0 -64
- package/src/events/sort.js +0 -44
- package/src/events/txEventCache.js +0 -71
- package/src/events/types.js +0 -20
- package/src/events/webSocketLogProvider.js +0 -41
- package/src/factory/bigNum.js +0 -390
- package/src/factory/oracleClient.js +0 -20
- package/src/idl/clearing_house.json +0 -4464
- package/src/index.js +0 -69
- package/src/math/amm.js +0 -369
- package/src/math/auction.js +0 -42
- package/src/math/bankBalance.ts +0 -112
- package/src/math/conversion.js +0 -11
- package/src/math/funding.js +0 -248
- package/src/math/oracles.js +0 -26
- package/src/math/repeg.js +0 -128
- package/src/math/state.js +0 -15
- package/src/math/state.ts +0 -14
- package/src/math/trade.js +0 -253
- package/src/math/utils.js +0 -26
- package/src/math/utils.js.map +0 -1
- package/src/mockUSDCFaucet.js +0 -280
- package/src/oracles/oracleClientCache.js +0 -19
- package/src/oracles/pythClient.js +0 -46
- package/src/oracles/quoteAssetOracleClient.js +0 -32
- package/src/oracles/switchboardClient.js +0 -69
- package/src/orderParams.js +0 -20
- package/src/orders.ts +0 -245
- package/src/slot/SlotSubscriber.js +0 -39
- package/src/tokenFaucet.js +0 -189
- package/src/types.js +0 -125
- package/src/userName.js +0 -20
- package/src/wallet.js +0 -35
package/src/math/funding.js
DELETED
|
@@ -1,248 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.calculateFundingPool = exports.calculateLongShortFundingRateAndLiveTwaps = exports.calculateLongShortFundingRate = exports.calculateEstimatedFundingRate = exports.calculateAllEstimatedFundingRate = void 0;
|
|
13
|
-
const anchor_1 = require("@project-serum/anchor");
|
|
14
|
-
const numericConstants_1 = require("../constants/numericConstants");
|
|
15
|
-
const market_1 = require("./market");
|
|
16
|
-
/**
|
|
17
|
-
*
|
|
18
|
-
* @param market
|
|
19
|
-
* @param oraclePriceData
|
|
20
|
-
* @param periodAdjustment
|
|
21
|
-
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
22
|
-
*/
|
|
23
|
-
function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
|
|
24
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
25
|
-
// periodAdjustment
|
|
26
|
-
// 1: hourly
|
|
27
|
-
// 24: daily
|
|
28
|
-
// 24 * 365.25: annualized
|
|
29
|
-
const secondsInHour = new anchor_1.BN(3600);
|
|
30
|
-
const hoursInDay = new anchor_1.BN(24);
|
|
31
|
-
const ONE = new anchor_1.BN(1);
|
|
32
|
-
if (!market.initialized) {
|
|
33
|
-
return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
34
|
-
}
|
|
35
|
-
const payFreq = new anchor_1.BN(market.amm.fundingPeriod);
|
|
36
|
-
// todo: sufficiently differs from blockchain timestamp?
|
|
37
|
-
const now = new anchor_1.BN((Date.now() / 1000).toFixed(0));
|
|
38
|
-
const timeSinceLastUpdate = now.sub(market.amm.lastFundingRateTs);
|
|
39
|
-
// calculate real-time mark twap
|
|
40
|
-
const lastMarkTwapWithMantissa = market.amm.lastMarkPriceTwap;
|
|
41
|
-
const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
|
|
42
|
-
const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
|
|
43
|
-
const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, anchor_1.BN.max(numericConstants_1.ZERO, secondsInHour.sub(timeSinceLastMarkChange)));
|
|
44
|
-
const baseAssetPriceWithMantissa = market_1.calculateMarkPrice(market, oraclePriceData);
|
|
45
|
-
const markTwapWithMantissa = markTwapTimeSinceLastUpdate
|
|
46
|
-
.mul(lastMarkTwapWithMantissa)
|
|
47
|
-
.add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
|
|
48
|
-
.div(timeSinceLastMarkChange.add(markTwapTimeSinceLastUpdate));
|
|
49
|
-
// calculate real-time (predicted) oracle twap
|
|
50
|
-
// note: oracle twap depends on `when the chord is struck` (market is trade)
|
|
51
|
-
const lastOracleTwapWithMantissa = market.amm.lastOraclePriceTwap;
|
|
52
|
-
const lastOraclePriceTwapTs = market.amm.lastOraclePriceTwapTs;
|
|
53
|
-
const oracleInvalidDuration = anchor_1.BN.max(numericConstants_1.ZERO, lastMarkPriceTwapTs.sub(lastOraclePriceTwapTs));
|
|
54
|
-
const timeSinceLastOracleTwapUpdate = now.sub(lastOraclePriceTwapTs);
|
|
55
|
-
const oracleTwapTimeSinceLastUpdate = anchor_1.BN.max(ONE, anchor_1.BN.min(secondsInHour, anchor_1.BN.max(ONE, secondsInHour.sub(timeSinceLastOracleTwapUpdate))));
|
|
56
|
-
let oracleTwapWithMantissa = lastOracleTwapWithMantissa;
|
|
57
|
-
// if passing live oracle data, improve predicted calc estimate
|
|
58
|
-
if (oraclePriceData) {
|
|
59
|
-
const oraclePrice = oraclePriceData.price;
|
|
60
|
-
const oracleLiveVsTwap = oraclePrice
|
|
61
|
-
.sub(lastOracleTwapWithMantissa)
|
|
62
|
-
.abs()
|
|
63
|
-
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
64
|
-
.mul(new anchor_1.BN(100))
|
|
65
|
-
.div(lastOracleTwapWithMantissa);
|
|
66
|
-
// verify pyth live input is within 10% of last twap for live update
|
|
67
|
-
if (oracleLiveVsTwap.lte(numericConstants_1.MARK_PRICE_PRECISION.mul(new anchor_1.BN(10)))) {
|
|
68
|
-
oracleTwapWithMantissa = oracleTwapTimeSinceLastUpdate
|
|
69
|
-
.mul(lastOracleTwapWithMantissa)
|
|
70
|
-
.add(timeSinceLastMarkChange.mul(oraclePrice))
|
|
71
|
-
.div(timeSinceLastMarkChange.add(oracleTwapTimeSinceLastUpdate));
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
const shrunkLastOracleTwapwithMantissa = oracleTwapTimeSinceLastUpdate
|
|
75
|
-
.mul(lastOracleTwapWithMantissa)
|
|
76
|
-
.add(oracleInvalidDuration.mul(lastMarkTwapWithMantissa))
|
|
77
|
-
.div(oracleTwapTimeSinceLastUpdate.add(oracleInvalidDuration));
|
|
78
|
-
const twapSpread = lastMarkTwapWithMantissa.sub(shrunkLastOracleTwapwithMantissa);
|
|
79
|
-
const twapSpreadPct = twapSpread
|
|
80
|
-
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
81
|
-
.mul(new anchor_1.BN(100))
|
|
82
|
-
.div(shrunkLastOracleTwapwithMantissa);
|
|
83
|
-
const lowerboundEst = twapSpreadPct
|
|
84
|
-
.mul(payFreq)
|
|
85
|
-
.mul(anchor_1.BN.min(secondsInHour, timeSinceLastUpdate))
|
|
86
|
-
.mul(periodAdjustment)
|
|
87
|
-
.div(secondsInHour)
|
|
88
|
-
.div(secondsInHour)
|
|
89
|
-
.div(hoursInDay);
|
|
90
|
-
const interpEst = twapSpreadPct.mul(periodAdjustment).div(hoursInDay);
|
|
91
|
-
const interpRateQuote = twapSpreadPct
|
|
92
|
-
.mul(periodAdjustment)
|
|
93
|
-
.div(hoursInDay)
|
|
94
|
-
.div(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION));
|
|
95
|
-
let feePoolSize = calculateFundingPool(market);
|
|
96
|
-
if (interpRateQuote.lt(new anchor_1.BN(0))) {
|
|
97
|
-
feePoolSize = feePoolSize.mul(new anchor_1.BN(-1));
|
|
98
|
-
}
|
|
99
|
-
let cappedAltEst;
|
|
100
|
-
let largerSide;
|
|
101
|
-
let smallerSide;
|
|
102
|
-
if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
|
|
103
|
-
largerSide = market.baseAssetAmountLong.abs();
|
|
104
|
-
smallerSide = market.baseAssetAmountShort.abs();
|
|
105
|
-
if (twapSpread.gt(new anchor_1.BN(0))) {
|
|
106
|
-
return [
|
|
107
|
-
markTwapWithMantissa,
|
|
108
|
-
oracleTwapWithMantissa,
|
|
109
|
-
lowerboundEst,
|
|
110
|
-
interpEst,
|
|
111
|
-
interpEst,
|
|
112
|
-
];
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
|
|
116
|
-
largerSide = market.baseAssetAmountShort.abs();
|
|
117
|
-
smallerSide = market.baseAssetAmountLong.abs();
|
|
118
|
-
if (twapSpread.lt(new anchor_1.BN(0))) {
|
|
119
|
-
return [
|
|
120
|
-
markTwapWithMantissa,
|
|
121
|
-
oracleTwapWithMantissa,
|
|
122
|
-
lowerboundEst,
|
|
123
|
-
interpEst,
|
|
124
|
-
interpEst,
|
|
125
|
-
];
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
else {
|
|
129
|
-
return [
|
|
130
|
-
markTwapWithMantissa,
|
|
131
|
-
oracleTwapWithMantissa,
|
|
132
|
-
lowerboundEst,
|
|
133
|
-
interpEst,
|
|
134
|
-
interpEst,
|
|
135
|
-
];
|
|
136
|
-
}
|
|
137
|
-
if (largerSide.gt(numericConstants_1.ZERO)) {
|
|
138
|
-
// funding smaller flow
|
|
139
|
-
cappedAltEst = smallerSide.mul(twapSpread).div(hoursInDay);
|
|
140
|
-
const feePoolTopOff = feePoolSize
|
|
141
|
-
.mul(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION))
|
|
142
|
-
.mul(numericConstants_1.AMM_RESERVE_PRECISION);
|
|
143
|
-
cappedAltEst = cappedAltEst.add(feePoolTopOff).div(largerSide);
|
|
144
|
-
cappedAltEst = cappedAltEst
|
|
145
|
-
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
146
|
-
.mul(new anchor_1.BN(100))
|
|
147
|
-
.div(oracleTwapWithMantissa)
|
|
148
|
-
.mul(periodAdjustment);
|
|
149
|
-
if (cappedAltEst.abs().gte(interpEst.abs())) {
|
|
150
|
-
cappedAltEst = interpEst;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
else {
|
|
154
|
-
cappedAltEst = interpEst;
|
|
155
|
-
}
|
|
156
|
-
return [
|
|
157
|
-
markTwapWithMantissa,
|
|
158
|
-
oracleTwapWithMantissa,
|
|
159
|
-
lowerboundEst,
|
|
160
|
-
cappedAltEst,
|
|
161
|
-
interpEst,
|
|
162
|
-
];
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
exports.calculateAllEstimatedFundingRate = calculateAllEstimatedFundingRate;
|
|
166
|
-
/**
|
|
167
|
-
*
|
|
168
|
-
* @param market
|
|
169
|
-
* @param oraclePriceData
|
|
170
|
-
* @param periodAdjustment
|
|
171
|
-
* @param estimationMethod
|
|
172
|
-
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
173
|
-
*/
|
|
174
|
-
function calculateEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1), estimationMethod) {
|
|
175
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
176
|
-
const [_1, _2, lowerboundEst, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
|
|
177
|
-
if (estimationMethod == 'lowerbound') {
|
|
178
|
-
//assuming remaining funding period has no gap
|
|
179
|
-
return lowerboundEst;
|
|
180
|
-
}
|
|
181
|
-
else if (estimationMethod == 'capped') {
|
|
182
|
-
return cappedAltEst;
|
|
183
|
-
}
|
|
184
|
-
else {
|
|
185
|
-
return interpEst;
|
|
186
|
-
}
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
exports.calculateEstimatedFundingRate = calculateEstimatedFundingRate;
|
|
190
|
-
/**
|
|
191
|
-
*
|
|
192
|
-
* @param market
|
|
193
|
-
* @param oraclePriceData
|
|
194
|
-
* @param periodAdjustment
|
|
195
|
-
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
196
|
-
*/
|
|
197
|
-
function calculateLongShortFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
|
|
198
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
199
|
-
const [_1, _2, _, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
|
|
200
|
-
if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort)) {
|
|
201
|
-
return [cappedAltEst, interpEst];
|
|
202
|
-
}
|
|
203
|
-
else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort)) {
|
|
204
|
-
return [interpEst, cappedAltEst];
|
|
205
|
-
}
|
|
206
|
-
else {
|
|
207
|
-
return [interpEst, interpEst];
|
|
208
|
-
}
|
|
209
|
-
});
|
|
210
|
-
}
|
|
211
|
-
exports.calculateLongShortFundingRate = calculateLongShortFundingRate;
|
|
212
|
-
/**
|
|
213
|
-
*
|
|
214
|
-
* @param market
|
|
215
|
-
* @param oraclePriceData
|
|
216
|
-
* @param periodAdjustment
|
|
217
|
-
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
218
|
-
*/
|
|
219
|
-
function calculateLongShortFundingRateAndLiveTwaps(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
|
|
220
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
221
|
-
const [markTwapLive, oracleTwapLive, _2, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
|
|
222
|
-
if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
|
|
223
|
-
return [markTwapLive, oracleTwapLive, cappedAltEst, interpEst];
|
|
224
|
-
}
|
|
225
|
-
else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
|
|
226
|
-
return [markTwapLive, oracleTwapLive, interpEst, cappedAltEst];
|
|
227
|
-
}
|
|
228
|
-
else {
|
|
229
|
-
return [markTwapLive, oracleTwapLive, interpEst, interpEst];
|
|
230
|
-
}
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
exports.calculateLongShortFundingRateAndLiveTwaps = calculateLongShortFundingRateAndLiveTwaps;
|
|
234
|
-
/**
|
|
235
|
-
*
|
|
236
|
-
* @param market
|
|
237
|
-
* @returns Estimated fee pool size
|
|
238
|
-
*/
|
|
239
|
-
function calculateFundingPool(market) {
|
|
240
|
-
// todo
|
|
241
|
-
const totalFeeLB = market.amm.totalExchangeFee.div(new anchor_1.BN(2));
|
|
242
|
-
const feePool = anchor_1.BN.max(numericConstants_1.ZERO, market.amm.totalFeeMinusDistributions
|
|
243
|
-
.sub(totalFeeLB)
|
|
244
|
-
.mul(new anchor_1.BN(1))
|
|
245
|
-
.div(new anchor_1.BN(3)));
|
|
246
|
-
return feePool;
|
|
247
|
-
}
|
|
248
|
-
exports.calculateFundingPool = calculateFundingPool;
|
package/src/math/oracles.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isOracleValid = void 0;
|
|
4
|
-
const numericConstants_1 = require("../constants/numericConstants");
|
|
5
|
-
const index_1 = require("../index");
|
|
6
|
-
function isOracleValid(amm, oraclePriceData, oracleGuardRails, slot) {
|
|
7
|
-
const isOraclePriceNonPositive = oraclePriceData.price.lt(numericConstants_1.ZERO);
|
|
8
|
-
const isOraclePriceTooVolatile = oraclePriceData.price
|
|
9
|
-
.div(index_1.BN.max(numericConstants_1.ONE, amm.lastOraclePriceTwap))
|
|
10
|
-
.gt(oracleGuardRails.validity.tooVolatileRatio) ||
|
|
11
|
-
amm.lastOraclePriceTwap
|
|
12
|
-
.div(index_1.BN.max(numericConstants_1.ONE, oraclePriceData.price))
|
|
13
|
-
.gt(oracleGuardRails.validity.tooVolatileRatio);
|
|
14
|
-
const isConfidenceTooLarge = oraclePriceData.price
|
|
15
|
-
.div(index_1.BN.max(numericConstants_1.ONE, oraclePriceData.confidence))
|
|
16
|
-
.lt(oracleGuardRails.validity.confidenceIntervalMaxSize);
|
|
17
|
-
const oracleIsStale = oraclePriceData.slot
|
|
18
|
-
.sub(new index_1.BN(slot))
|
|
19
|
-
.gt(oracleGuardRails.validity.slotsBeforeStale);
|
|
20
|
-
return !(!oraclePriceData.hasSufficientNumberOfDataPoints ||
|
|
21
|
-
oracleIsStale ||
|
|
22
|
-
isOraclePriceNonPositive ||
|
|
23
|
-
isOraclePriceTooVolatile ||
|
|
24
|
-
isConfidenceTooLarge);
|
|
25
|
-
}
|
|
26
|
-
exports.isOracleValid = isOracleValid;
|
package/src/math/repeg.js
DELETED
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.calculateBudgetedPeg = exports.calculateBudgetedK = exports.calculateBudgetedKBN = exports.calculateRepegCost = exports.calculateAdjustKCost = void 0;
|
|
4
|
-
const anchor_1 = require("@project-serum/anchor");
|
|
5
|
-
const assert_1 = require("../assert/assert");
|
|
6
|
-
const numericConstants_1 = require("../constants/numericConstants");
|
|
7
|
-
/**
|
|
8
|
-
* Helper function calculating adjust k cost
|
|
9
|
-
* @param amm
|
|
10
|
-
* @param numerator
|
|
11
|
-
* @param denomenator
|
|
12
|
-
* @returns cost : Precision QUOTE_ASSET_PRECISION
|
|
13
|
-
*/
|
|
14
|
-
function calculateAdjustKCost(amm, numerator, denomenator) {
|
|
15
|
-
// const k = market.amm.sqrtK.mul(market.amm.sqrtK);
|
|
16
|
-
const x = amm.baseAssetReserve;
|
|
17
|
-
const y = amm.quoteAssetReserve;
|
|
18
|
-
const d = amm.netBaseAssetAmount;
|
|
19
|
-
const Q = amm.pegMultiplier;
|
|
20
|
-
const quoteScale = y.mul(d).mul(Q); //.div(AMM_RESERVE_PRECISION);
|
|
21
|
-
const p = numerator.mul(numericConstants_1.MARK_PRICE_PRECISION).div(denomenator);
|
|
22
|
-
const cost = quoteScale
|
|
23
|
-
.div(x.add(d))
|
|
24
|
-
.sub(quoteScale
|
|
25
|
-
.mul(p)
|
|
26
|
-
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
27
|
-
.div(x.mul(p).div(numericConstants_1.MARK_PRICE_PRECISION).add(d)))
|
|
28
|
-
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
29
|
-
.div(numericConstants_1.PEG_PRECISION);
|
|
30
|
-
return cost.mul(new anchor_1.BN(-1));
|
|
31
|
-
}
|
|
32
|
-
exports.calculateAdjustKCost = calculateAdjustKCost;
|
|
33
|
-
/**
|
|
34
|
-
* Helper function calculating adjust pegMultiplier (repeg) cost
|
|
35
|
-
*
|
|
36
|
-
* @param amm
|
|
37
|
-
* @param newPeg
|
|
38
|
-
* @returns cost : Precision QUOTE_ASSET_PRECISION
|
|
39
|
-
*/
|
|
40
|
-
function calculateRepegCost(amm, newPeg) {
|
|
41
|
-
const dqar = amm.quoteAssetReserve.sub(amm.terminalQuoteAssetReserve);
|
|
42
|
-
const cost = dqar
|
|
43
|
-
.mul(newPeg.sub(amm.pegMultiplier))
|
|
44
|
-
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
45
|
-
.div(numericConstants_1.PEG_PRECISION);
|
|
46
|
-
return cost;
|
|
47
|
-
}
|
|
48
|
-
exports.calculateRepegCost = calculateRepegCost;
|
|
49
|
-
function calculateBudgetedKBN(x, y, budget, Q, d) {
|
|
50
|
-
assert_1.assert(Q.gt(new anchor_1.BN(0)));
|
|
51
|
-
const C = budget.mul(new anchor_1.BN(-1));
|
|
52
|
-
let dSign = new anchor_1.BN(1);
|
|
53
|
-
if (d.lt(new anchor_1.BN(0))) {
|
|
54
|
-
dSign = new anchor_1.BN(-1);
|
|
55
|
-
}
|
|
56
|
-
const pegged_y_d_d = y
|
|
57
|
-
.mul(d)
|
|
58
|
-
.mul(d)
|
|
59
|
-
.mul(Q)
|
|
60
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
61
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
62
|
-
.div(numericConstants_1.PEG_PRECISION);
|
|
63
|
-
const numer1 = pegged_y_d_d;
|
|
64
|
-
const numer2 = C.mul(d)
|
|
65
|
-
.div(numericConstants_1.QUOTE_PRECISION)
|
|
66
|
-
.mul(x.add(d))
|
|
67
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
68
|
-
.mul(dSign);
|
|
69
|
-
const denom1 = C.mul(x)
|
|
70
|
-
.mul(x.add(d))
|
|
71
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
72
|
-
.div(numericConstants_1.QUOTE_PRECISION);
|
|
73
|
-
const denom2 = pegged_y_d_d;
|
|
74
|
-
const numerator = numer1.sub(numer2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
75
|
-
const denominator = denom1.add(denom2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
76
|
-
return [numerator, denominator];
|
|
77
|
-
}
|
|
78
|
-
exports.calculateBudgetedKBN = calculateBudgetedKBN;
|
|
79
|
-
function calculateBudgetedK(amm, cost) {
|
|
80
|
-
// wolframalpha.com
|
|
81
|
-
// (1/(x+d) - p/(x*p+d))*y*d*Q = C solve for p
|
|
82
|
-
// p = (d(y*d*Q - C(x+d))) / (C*x(x+d) + y*d*d*Q)
|
|
83
|
-
// numer
|
|
84
|
-
// = y*d*d*Q - Cxd - Cdd
|
|
85
|
-
// = y/x*Q*d*d - Cd - Cd/x
|
|
86
|
-
// = mark - C/d - C/(x)
|
|
87
|
-
// = mark/C - 1/d - 1/x
|
|
88
|
-
// denom
|
|
89
|
-
// = C*x*x + C*x*d + y*d*d*Q
|
|
90
|
-
// = x/d**2 + 1 / d + mark/C
|
|
91
|
-
// todo: assumes k = x * y
|
|
92
|
-
// otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
|
|
93
|
-
const x = amm.baseAssetReserve;
|
|
94
|
-
const y = amm.quoteAssetReserve;
|
|
95
|
-
const d = amm.netBaseAssetAmount;
|
|
96
|
-
const Q = amm.pegMultiplier;
|
|
97
|
-
const [numerator, denominator] = calculateBudgetedKBN(x, y, cost, Q, d);
|
|
98
|
-
return [numerator, denominator];
|
|
99
|
-
}
|
|
100
|
-
exports.calculateBudgetedK = calculateBudgetedK;
|
|
101
|
-
function calculateBudgetedPeg(amm, cost, targetPrice) {
|
|
102
|
-
// wolframalpha.com
|
|
103
|
-
// (1/(x+d) - p/(x*p+d))*y*d*Q = C solve for p
|
|
104
|
-
// p = (d(y*d*Q - C(x+d))) / (C*x(x+d) + y*y*d*Q)
|
|
105
|
-
// todo: assumes k = x * y
|
|
106
|
-
// otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
|
|
107
|
-
const targetPeg = targetPrice
|
|
108
|
-
.mul(amm.baseAssetReserve)
|
|
109
|
-
.div(amm.quoteAssetReserve)
|
|
110
|
-
.div(numericConstants_1.PRICE_DIV_PEG);
|
|
111
|
-
const k = amm.sqrtK.mul(amm.sqrtK);
|
|
112
|
-
const x = amm.baseAssetReserve;
|
|
113
|
-
const y = amm.quoteAssetReserve;
|
|
114
|
-
const d = amm.netBaseAssetAmount;
|
|
115
|
-
const Q = amm.pegMultiplier;
|
|
116
|
-
const C = cost.mul(new anchor_1.BN(-1));
|
|
117
|
-
const deltaQuoteAssetReserves = y.sub(k.div(x.add(d)));
|
|
118
|
-
const pegChangeDirection = targetPeg.sub(Q);
|
|
119
|
-
const useTargetPeg = (deltaQuoteAssetReserves.lt(numericConstants_1.ZERO) && pegChangeDirection.gt(numericConstants_1.ZERO)) ||
|
|
120
|
-
(deltaQuoteAssetReserves.gt(numericConstants_1.ZERO) && pegChangeDirection.lt(numericConstants_1.ZERO));
|
|
121
|
-
if (deltaQuoteAssetReserves.eq(numericConstants_1.ZERO) || useTargetPeg) {
|
|
122
|
-
return targetPeg;
|
|
123
|
-
}
|
|
124
|
-
const deltaPegMultiplier = C.mul(numericConstants_1.MARK_PRICE_PRECISION).div(deltaQuoteAssetReserves.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO));
|
|
125
|
-
const newPeg = Q.sub(deltaPegMultiplier.mul(numericConstants_1.PEG_PRECISION).div(numericConstants_1.MARK_PRICE_PRECISION));
|
|
126
|
-
return newPeg;
|
|
127
|
-
}
|
|
128
|
-
exports.calculateBudgetedPeg = calculateBudgetedPeg;
|
package/src/math/state.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getExchangeFee = void 0;
|
|
4
|
-
/**
|
|
5
|
-
* Get the clearing house percent fee charged on notional of taking trades
|
|
6
|
-
*
|
|
7
|
-
* @param state
|
|
8
|
-
* @returns Precision : basis points (bps)
|
|
9
|
-
*/
|
|
10
|
-
function getExchangeFee(state) {
|
|
11
|
-
const exchangeFee = state.feeStructure.feeNumerator.toNumber() /
|
|
12
|
-
state.feeStructure.feeDenominator.toNumber();
|
|
13
|
-
return exchangeFee;
|
|
14
|
-
}
|
|
15
|
-
exports.getExchangeFee = getExchangeFee;
|
package/src/math/state.ts
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { StateAccount } from '../types';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Get the clearing house percent fee charged on notional of taking trades
|
|
5
|
-
*
|
|
6
|
-
* @param state
|
|
7
|
-
* @returns Precision : basis points (bps)
|
|
8
|
-
*/
|
|
9
|
-
export function getExchangeFee(state: StateAccount): number {
|
|
10
|
-
const exchangeFee =
|
|
11
|
-
state.feeStructure.feeNumerator.toNumber() /
|
|
12
|
-
state.feeStructure.feeDenominator.toNumber();
|
|
13
|
-
return exchangeFee;
|
|
14
|
-
}
|
package/src/math/trade.js
DELETED
|
@@ -1,253 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.calculateTargetPriceTrade = exports.calculateTradeAcquiredAmounts = exports.calculateTradeSlippage = void 0;
|
|
4
|
-
const types_1 = require("../types");
|
|
5
|
-
const anchor_1 = require("@project-serum/anchor");
|
|
6
|
-
const assert_1 = require("../assert/assert");
|
|
7
|
-
const numericConstants_1 = require("../constants/numericConstants");
|
|
8
|
-
const market_1 = require("./market");
|
|
9
|
-
const amm_1 = require("./amm");
|
|
10
|
-
const utils_1 = require("./utils");
|
|
11
|
-
const types_2 = require("../types");
|
|
12
|
-
const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
|
|
13
|
-
/**
|
|
14
|
-
* Calculates avg/max slippage (price impact) for candidate trade
|
|
15
|
-
* @param direction
|
|
16
|
-
* @param amount
|
|
17
|
-
* @param market
|
|
18
|
-
* @param inputAssetType which asset is being traded
|
|
19
|
-
* @param useSpread whether to consider spread with calculating slippage
|
|
20
|
-
* @return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice]
|
|
21
|
-
*
|
|
22
|
-
* 'pctAvgSlippage' => the percentage change to entryPrice (average est slippage in execution) : Precision MARK_PRICE_PRECISION
|
|
23
|
-
*
|
|
24
|
-
* 'pctMaxSlippage' => the percentage change to maxPrice (highest est slippage in execution) : Precision MARK_PRICE_PRECISION
|
|
25
|
-
*
|
|
26
|
-
* 'entryPrice' => the average price of the trade : Precision MARK_PRICE_PRECISION
|
|
27
|
-
*
|
|
28
|
-
* 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
|
|
29
|
-
*/
|
|
30
|
-
function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
|
|
31
|
-
let oldPrice;
|
|
32
|
-
if (useSpread && market.amm.baseSpread > 0) {
|
|
33
|
-
if (types_2.isVariant(direction, 'long')) {
|
|
34
|
-
oldPrice = market_1.calculateAskPrice(market, oraclePriceData);
|
|
35
|
-
}
|
|
36
|
-
else {
|
|
37
|
-
oldPrice = market_1.calculateBidPrice(market, oraclePriceData);
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
else {
|
|
41
|
-
oldPrice = market_1.calculateMarkPrice(market, oraclePriceData);
|
|
42
|
-
}
|
|
43
|
-
if (amount.eq(numericConstants_1.ZERO)) {
|
|
44
|
-
return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
|
|
45
|
-
}
|
|
46
|
-
const [acquiredBaseReserve, acquiredQuoteReserve, acquiredQuoteAssetAmount] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread);
|
|
47
|
-
const entryPrice = acquiredQuoteAssetAmount
|
|
48
|
-
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
49
|
-
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
50
|
-
.div(acquiredBaseReserve.abs());
|
|
51
|
-
let amm;
|
|
52
|
-
if (useSpread && market.amm.baseSpread > 0) {
|
|
53
|
-
const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
|
|
54
|
-
amm = {
|
|
55
|
-
baseAssetReserve,
|
|
56
|
-
quoteAssetReserve,
|
|
57
|
-
sqrtK: sqrtK,
|
|
58
|
-
pegMultiplier: newPeg,
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
else {
|
|
62
|
-
amm = market.amm;
|
|
63
|
-
}
|
|
64
|
-
const newPrice = amm_1.calculatePrice(amm.baseAssetReserve.sub(acquiredBaseReserve), amm.quoteAssetReserve.sub(acquiredQuoteReserve), amm.pegMultiplier);
|
|
65
|
-
if (direction == types_1.PositionDirection.SHORT) {
|
|
66
|
-
assert_1.assert(newPrice.lte(oldPrice));
|
|
67
|
-
}
|
|
68
|
-
else {
|
|
69
|
-
assert_1.assert(oldPrice.lte(newPrice));
|
|
70
|
-
}
|
|
71
|
-
const pctMaxSlippage = newPrice
|
|
72
|
-
.sub(oldPrice)
|
|
73
|
-
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
74
|
-
.div(oldPrice)
|
|
75
|
-
.abs();
|
|
76
|
-
const pctAvgSlippage = entryPrice
|
|
77
|
-
.sub(oldPrice)
|
|
78
|
-
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
79
|
-
.div(oldPrice)
|
|
80
|
-
.abs();
|
|
81
|
-
return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice];
|
|
82
|
-
}
|
|
83
|
-
exports.calculateTradeSlippage = calculateTradeSlippage;
|
|
84
|
-
/**
|
|
85
|
-
* Calculates acquired amounts for trade executed
|
|
86
|
-
* @param direction
|
|
87
|
-
* @param amount
|
|
88
|
-
* @param market
|
|
89
|
-
* @param inputAssetType
|
|
90
|
-
* @param useSpread
|
|
91
|
-
* @return
|
|
92
|
-
* | 'acquiredBase' => positive/negative change in user's base : BN AMM_RESERVE_PRECISION
|
|
93
|
-
* | 'acquiredQuote' => positive/negative change in user's quote : BN TODO-PRECISION
|
|
94
|
-
*/
|
|
95
|
-
function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
|
|
96
|
-
if (amount.eq(numericConstants_1.ZERO)) {
|
|
97
|
-
return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
98
|
-
}
|
|
99
|
-
const swapDirection = amm_1.getSwapDirection(inputAssetType, direction);
|
|
100
|
-
let amm;
|
|
101
|
-
if (useSpread && market.amm.baseSpread > 0) {
|
|
102
|
-
const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
|
|
103
|
-
amm = {
|
|
104
|
-
baseAssetReserve,
|
|
105
|
-
quoteAssetReserve,
|
|
106
|
-
sqrtK: sqrtK,
|
|
107
|
-
pegMultiplier: newPeg,
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
else {
|
|
111
|
-
amm = market.amm;
|
|
112
|
-
}
|
|
113
|
-
const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(amm, inputAssetType, amount, swapDirection);
|
|
114
|
-
const acquiredBase = amm.baseAssetReserve.sub(newBaseAssetReserve);
|
|
115
|
-
const acquiredQuote = amm.quoteAssetReserve.sub(newQuoteAssetReserve);
|
|
116
|
-
const acquiredQuoteAssetamount = amm_1.calculateQuoteAssetAmountSwapped(acquiredQuote.abs(), amm.pegMultiplier, swapDirection);
|
|
117
|
-
return [acquiredBase, acquiredQuote, acquiredQuoteAssetamount];
|
|
118
|
-
}
|
|
119
|
-
exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
|
|
120
|
-
/**
|
|
121
|
-
* calculateTargetPriceTrade
|
|
122
|
-
* simple function for finding arbitraging trades
|
|
123
|
-
* @param market
|
|
124
|
-
* @param targetPrice
|
|
125
|
-
* @param pct optional default is 100% gap filling, can set smaller.
|
|
126
|
-
* @param outputAssetType which asset to trade.
|
|
127
|
-
* @param useSpread whether or not to consider the spread when calculating the trade size
|
|
128
|
-
* @returns trade direction/size in order to push price to a targetPrice,
|
|
129
|
-
*
|
|
130
|
-
* [
|
|
131
|
-
* direction => direction of trade required, PositionDirection
|
|
132
|
-
* tradeSize => size of trade required, TODO-PRECISION
|
|
133
|
-
* entryPrice => the entry price for the trade, MARK_PRICE_PRECISION
|
|
134
|
-
* targetPrice => the target price MARK_PRICE_PRECISION
|
|
135
|
-
* ]
|
|
136
|
-
*/
|
|
137
|
-
function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote', oraclePriceData, useSpread = true) {
|
|
138
|
-
assert_1.assert(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
|
|
139
|
-
assert_1.assert(targetPrice.gt(numericConstants_1.ZERO));
|
|
140
|
-
assert_1.assert(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
|
|
141
|
-
const markPriceBefore = market_1.calculateMarkPrice(market, oraclePriceData);
|
|
142
|
-
const bidPriceBefore = market_1.calculateBidPrice(market, oraclePriceData);
|
|
143
|
-
const askPriceBefore = market_1.calculateAskPrice(market, oraclePriceData);
|
|
144
|
-
let direction;
|
|
145
|
-
if (targetPrice.gt(markPriceBefore)) {
|
|
146
|
-
const priceGap = targetPrice.sub(markPriceBefore);
|
|
147
|
-
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
|
|
148
|
-
targetPrice = markPriceBefore.add(priceGapScaled);
|
|
149
|
-
direction = types_1.PositionDirection.LONG;
|
|
150
|
-
}
|
|
151
|
-
else {
|
|
152
|
-
const priceGap = markPriceBefore.sub(targetPrice);
|
|
153
|
-
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
|
|
154
|
-
targetPrice = markPriceBefore.sub(priceGapScaled);
|
|
155
|
-
direction = types_1.PositionDirection.SHORT;
|
|
156
|
-
}
|
|
157
|
-
let tradeSize;
|
|
158
|
-
let baseSize;
|
|
159
|
-
let baseAssetReserveBefore;
|
|
160
|
-
let quoteAssetReserveBefore;
|
|
161
|
-
let peg = market.amm.pegMultiplier;
|
|
162
|
-
if (useSpread && market.amm.baseSpread > 0) {
|
|
163
|
-
const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
|
|
164
|
-
baseAssetReserveBefore = baseAssetReserve;
|
|
165
|
-
quoteAssetReserveBefore = quoteAssetReserve;
|
|
166
|
-
peg = newPeg;
|
|
167
|
-
}
|
|
168
|
-
else {
|
|
169
|
-
baseAssetReserveBefore = market.amm.baseAssetReserve;
|
|
170
|
-
quoteAssetReserveBefore = market.amm.quoteAssetReserve;
|
|
171
|
-
}
|
|
172
|
-
const invariant = market.amm.sqrtK.mul(market.amm.sqrtK);
|
|
173
|
-
const k = invariant.mul(numericConstants_1.MARK_PRICE_PRECISION);
|
|
174
|
-
let baseAssetReserveAfter;
|
|
175
|
-
let quoteAssetReserveAfter;
|
|
176
|
-
const biasModifier = new anchor_1.BN(1);
|
|
177
|
-
let markPriceAfter;
|
|
178
|
-
if (useSpread &&
|
|
179
|
-
targetPrice.lt(askPriceBefore) &&
|
|
180
|
-
targetPrice.gt(bidPriceBefore)) {
|
|
181
|
-
// no trade, market is at target
|
|
182
|
-
if (markPriceBefore.gt(targetPrice)) {
|
|
183
|
-
direction = types_1.PositionDirection.SHORT;
|
|
184
|
-
}
|
|
185
|
-
else {
|
|
186
|
-
direction = types_1.PositionDirection.LONG;
|
|
187
|
-
}
|
|
188
|
-
tradeSize = numericConstants_1.ZERO;
|
|
189
|
-
return [direction, tradeSize, targetPrice, targetPrice];
|
|
190
|
-
}
|
|
191
|
-
else if (markPriceBefore.gt(targetPrice)) {
|
|
192
|
-
// overestimate y2
|
|
193
|
-
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
|
|
194
|
-
quoteAssetReserveAfter = k
|
|
195
|
-
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
196
|
-
.div(baseAssetReserveAfter);
|
|
197
|
-
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
198
|
-
direction = types_1.PositionDirection.SHORT;
|
|
199
|
-
tradeSize = quoteAssetReserveBefore
|
|
200
|
-
.sub(quoteAssetReserveAfter)
|
|
201
|
-
.mul(peg)
|
|
202
|
-
.div(numericConstants_1.PEG_PRECISION)
|
|
203
|
-
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
204
|
-
baseSize = baseAssetReserveAfter.sub(baseAssetReserveBefore);
|
|
205
|
-
}
|
|
206
|
-
else if (markPriceBefore.lt(targetPrice)) {
|
|
207
|
-
// underestimate y2
|
|
208
|
-
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
|
|
209
|
-
quoteAssetReserveAfter = k
|
|
210
|
-
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
211
|
-
.div(baseAssetReserveAfter);
|
|
212
|
-
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
213
|
-
direction = types_1.PositionDirection.LONG;
|
|
214
|
-
tradeSize = quoteAssetReserveAfter
|
|
215
|
-
.sub(quoteAssetReserveBefore)
|
|
216
|
-
.mul(peg)
|
|
217
|
-
.div(numericConstants_1.PEG_PRECISION)
|
|
218
|
-
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
219
|
-
baseSize = baseAssetReserveBefore.sub(baseAssetReserveAfter);
|
|
220
|
-
}
|
|
221
|
-
else {
|
|
222
|
-
// no trade, market is at target
|
|
223
|
-
direction = types_1.PositionDirection.LONG;
|
|
224
|
-
tradeSize = numericConstants_1.ZERO;
|
|
225
|
-
return [direction, tradeSize, targetPrice, targetPrice];
|
|
226
|
-
}
|
|
227
|
-
let tp1 = targetPrice;
|
|
228
|
-
let tp2 = markPriceAfter;
|
|
229
|
-
let originalDiff = targetPrice.sub(markPriceBefore);
|
|
230
|
-
if (direction == types_1.PositionDirection.SHORT) {
|
|
231
|
-
tp1 = markPriceAfter;
|
|
232
|
-
tp2 = targetPrice;
|
|
233
|
-
originalDiff = markPriceBefore.sub(targetPrice);
|
|
234
|
-
}
|
|
235
|
-
const entryPrice = tradeSize
|
|
236
|
-
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
237
|
-
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
238
|
-
.div(baseSize.abs());
|
|
239
|
-
assert_1.assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
|
|
240
|
-
assert_1.assert(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
|
|
241
|
-
tp2.toString() +
|
|
242
|
-
'>=' +
|
|
243
|
-
tp1.toString() +
|
|
244
|
-
'err: ' +
|
|
245
|
-
tp2.sub(tp1).abs().toString());
|
|
246
|
-
if (outputAssetType == 'quote') {
|
|
247
|
-
return [direction, tradeSize, entryPrice, targetPrice];
|
|
248
|
-
}
|
|
249
|
-
else {
|
|
250
|
-
return [direction, baseSize, entryPrice, targetPrice];
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
exports.calculateTargetPriceTrade = calculateTargetPriceTrade;
|