@drift-labs/sdk 0.1.24 → 0.1.27
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/lib/accounts/bulkAccountLoader.d.ts +1 -0
- package/lib/accounts/bulkAccountLoader.js +16 -2
- package/lib/accounts/pollingClearingHouseAccountSubscriber.js +3 -3
- package/lib/accounts/pollingOracleSubscriber.d.ts +26 -0
- package/lib/accounts/pollingOracleSubscriber.js +79 -0
- package/lib/accounts/pollingTokenAccountSubscriber.js +2 -2
- package/lib/accounts/pollingUserAccountSubscriber.js +4 -4
- package/lib/accounts/types.d.ts +14 -1
- package/lib/accounts/webSocketAccountSubscriber.js +2 -2
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +1 -1
- package/lib/accounts/webSocketUserAccountSubscriber.js +2 -2
- package/lib/addresses.js +5 -1
- package/lib/admin.d.ts +1 -1
- package/lib/admin.js +15 -10
- package/lib/clearingHouse.d.ts +4 -4
- package/lib/clearingHouse.js +56 -25
- package/lib/clearingHouseUser.js +18 -18
- package/lib/constants/markets.d.ts +8 -6
- package/lib/constants/markets.js +85 -26
- package/lib/constants/numericConstants.d.ts +1 -0
- package/lib/constants/numericConstants.js +2 -1
- package/lib/examples/makeTradeExample.js +6 -6
- package/lib/factory/oracleClient.d.ts +5 -0
- package/lib/factory/oracleClient.js +16 -0
- package/lib/idl/clearing_house.json +22 -2
- package/lib/idl/switchboard_v2.json +4663 -0
- package/lib/index.d.ts +5 -1
- package/lib/index.js +10 -2
- package/lib/math/amm.js +12 -12
- package/lib/math/conversion.js +1 -1
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +5 -17
- package/lib/math/market.d.ts +2 -0
- package/lib/math/market.js +8 -3
- package/lib/math/orders.js +9 -9
- package/lib/math/position.js +1 -1
- package/lib/math/trade.js +18 -18
- package/lib/mockUSDCFaucet.js +5 -1
- package/lib/oracles/pythClient.d.ts +14 -0
- package/lib/oracles/pythClient.js +53 -0
- package/lib/oracles/switchboardClient.d.ts +13 -0
- package/lib/oracles/switchboardClient.js +76 -0
- package/lib/oracles/types.d.ts +15 -0
- package/lib/oracles/types.js +2 -0
- package/lib/orderParams.d.ts +1 -1
- package/lib/orderParams.js +3 -3
- package/lib/orders.d.ts +3 -2
- package/lib/orders.js +29 -22
- package/lib/tx/retryTxSender.js +1 -1
- package/lib/types.d.ts +1 -0
- package/package.json +2 -1
- package/src/accounts/bulkAccountLoader.js +180 -0
- package/src/accounts/bulkAccountLoader.js.map +1 -0
- package/src/accounts/bulkAccountLoader.ts +19 -0
- package/src/accounts/bulkUserSubscription.js +56 -0
- package/src/accounts/bulkUserSubscription.js.map +1 -0
- package/src/accounts/pollingClearingHouseAccountSubscriber.js +210 -0
- package/src/accounts/pollingClearingHouseAccountSubscriber.js.map +1 -0
- package/src/accounts/pollingOracleSubscriber.js +65 -0
- package/src/accounts/pollingOracleSubscriber.js.map +1 -0
- package/src/accounts/pollingOracleSubscriber.ts +103 -0
- package/src/accounts/pollingTokenAccountSubscriber.js +65 -0
- package/src/accounts/pollingTokenAccountSubscriber.js.map +1 -0
- package/src/accounts/pollingUserAccountSubscriber.js +139 -0
- package/src/accounts/pollingUserAccountSubscriber.js.map +1 -0
- package/src/accounts/types.js +1 -0
- package/src/accounts/types.js.map +1 -0
- package/src/accounts/types.ts +22 -1
- package/src/accounts/utils.js +1 -0
- package/src/accounts/utils.js.map +1 -0
- package/src/accounts/webSocketAccountSubscriber.js +15 -27
- package/src/accounts/webSocketAccountSubscriber.js.map +1 -0
- package/src/accounts/webSocketClearingHouseAccountSubscriber.js +212 -0
- package/src/accounts/webSocketClearingHouseAccountSubscriber.js.map +1 -0
- package/src/accounts/webSocketUserAccountSubscriber.js +78 -0
- package/src/accounts/webSocketUserAccountSubscriber.js.map +1 -0
- package/src/addresses.js +20 -44
- package/src/addresses.js.map +1 -0
- package/src/admin.js +443 -0
- package/src/admin.js.map +1 -0
- package/src/admin.ts +2 -0
- package/src/assert/assert.js +10 -0
- package/src/assert/assert.js.map +1 -0
- package/src/clearingHouse.js +769 -0
- package/src/clearingHouse.js.map +1 -0
- package/src/clearingHouse.ts +47 -7
- package/src/clearingHouseUser.js +581 -0
- package/src/clearingHouseUser.js.map +1 -0
- package/src/config.js +37 -0
- package/src/config.js.map +1 -0
- package/src/constants/markets.js +167 -0
- package/src/constants/markets.js.map +1 -0
- package/src/constants/markets.ts +93 -31
- package/src/constants/numericConstants.js +22 -0
- package/src/constants/numericConstants.js.map +1 -0
- package/src/constants/numericConstants.ts +1 -0
- package/src/factory/clearingHouse.js +65 -0
- package/src/factory/clearingHouse.js.map +1 -0
- package/src/factory/clearingHouseUser.js +35 -0
- package/src/factory/clearingHouseUser.js.map +1 -0
- package/src/factory/oracleClient.js +17 -0
- package/src/factory/oracleClient.js.map +1 -0
- package/src/factory/oracleClient.ts +22 -0
- package/src/idl/clearing_house.json +22 -2
- package/src/idl/switchboard_v2.json +4663 -0
- package/src/index.js +56 -0
- package/src/index.js.map +1 -0
- package/src/index.ts +5 -1
- package/src/math/amm.js +285 -0
- package/src/math/amm.js.map +1 -0
- package/src/math/conversion.js +16 -0
- package/src/math/conversion.js.map +1 -0
- package/src/math/funding.js +223 -0
- package/src/math/funding.js.map +1 -0
- package/src/math/funding.ts +9 -25
- package/src/math/insuranceFund.js +23 -0
- package/src/math/insuranceFund.js.map +1 -0
- package/src/math/market.js +30 -0
- package/src/math/market.js.map +1 -0
- package/src/math/market.ts +9 -0
- package/src/math/orders.js +73 -0
- package/src/math/orders.js.map +1 -0
- package/src/math/position.js +121 -0
- package/src/math/position.js.map +1 -0
- package/src/math/trade.js +182 -0
- package/src/math/trade.js.map +1 -0
- package/src/math/utils.js +27 -0
- package/src/math/utils.js.map +1 -0
- package/src/mockUSDCFaucet.js +88 -116
- package/src/mockUSDCFaucet.js.map +1 -0
- package/src/oracles/pythClient.js +39 -0
- package/src/oracles/pythClient.js.map +1 -0
- package/src/oracles/pythClient.ts +49 -0
- package/src/oracles/switchboardClient.js +60 -0
- package/src/oracles/switchboardClient.js.map +1 -0
- package/src/oracles/switchboardClient.ts +87 -0
- package/src/oracles/types.js +3 -0
- package/src/oracles/types.js.map +1 -0
- package/src/oracles/types.ts +15 -0
- package/src/orderParams.js +109 -0
- package/src/orderParams.js.map +1 -0
- package/src/orderParams.ts +5 -3
- package/src/orders.js +172 -0
- package/src/orders.js.map +1 -0
- package/src/orders.ts +17 -4
- package/src/token/index.js +39 -0
- package/src/token/index.js.map +1 -0
- package/src/tx/defaultTxSender.js +13 -0
- package/src/tx/defaultTxSender.js.map +1 -0
- package/src/tx/retryTxSender.js +137 -0
- package/src/tx/retryTxSender.js.map +1 -0
- package/src/tx/types.js +3 -0
- package/src/tx/types.js.map +1 -0
- package/src/tx/utils.js +9 -0
- package/src/tx/utils.js.map +1 -0
- package/src/types.js +1 -0
- package/src/types.js.map +1 -0
- package/src/types.ts +1 -0
- package/src/util/computeUnits.js +17 -0
- package/src/util/computeUnits.js.map +1 -0
- package/src/util/tps.js +17 -0
- package/src/util/tps.js.map +1 -0
- package/src/wallet.js +23 -0
- package/src/wallet.js.map +1 -0
- package/lib/pythClient.d.ts +0 -7
- package/lib/pythClient.js +0 -25
- package/src/pythClient.ts +0 -15
package/src/math/funding.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { BN } from '@project-serum/anchor';
|
|
2
|
-
import { PriceData } from '@pythnetwork/client';
|
|
3
2
|
import {
|
|
4
3
|
AMM_RESERVE_PRECISION,
|
|
5
4
|
MARK_PRICE_PRECISION,
|
|
@@ -8,17 +7,18 @@ import {
|
|
|
8
7
|
} from '../constants/numericConstants';
|
|
9
8
|
import { Market } from '../types';
|
|
10
9
|
import { calculateMarkPrice } from './market';
|
|
10
|
+
import { OraclePriceData } from '../oracles/types';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
*
|
|
14
14
|
* @param market
|
|
15
|
-
* @param
|
|
15
|
+
* @param oraclePriceData
|
|
16
16
|
* @param periodAdjustment
|
|
17
17
|
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
18
18
|
*/
|
|
19
19
|
export async function calculateAllEstimatedFundingRate(
|
|
20
20
|
market: Market,
|
|
21
|
-
oraclePriceData:
|
|
21
|
+
oraclePriceData: OraclePriceData,
|
|
22
22
|
periodAdjustment: BN = new BN(1)
|
|
23
23
|
): Promise<[BN, BN, BN, BN, BN]> {
|
|
24
24
|
// periodAdjustment
|
|
@@ -65,26 +65,10 @@ export async function calculateAllEstimatedFundingRate(
|
|
|
65
65
|
secondsInHour.sub(timeSinceLastOracleTwapUpdate)
|
|
66
66
|
);
|
|
67
67
|
|
|
68
|
-
|
|
69
|
-
let oracleStablePriceNum = 0;
|
|
70
|
-
let oracleInputCount = 0;
|
|
71
|
-
if (oraclePriceData.price >= 0) {
|
|
72
|
-
oracleStablePriceNum += oraclePriceData.price;
|
|
73
|
-
oracleInputCount += 1;
|
|
74
|
-
}
|
|
75
|
-
if (oraclePriceData.previousPrice >= 0) {
|
|
76
|
-
oracleStablePriceNum += oraclePriceData.previousPrice;
|
|
77
|
-
oracleInputCount += 1;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
oracleStablePriceNum = oracleStablePriceNum / oracleInputCount;
|
|
81
|
-
const oraclePriceStableWithMantissa = new BN(
|
|
82
|
-
oracleStablePriceNum * MARK_PRICE_PRECISION.toNumber()
|
|
83
|
-
);
|
|
84
|
-
|
|
68
|
+
const oraclePrice = oraclePriceData.price;
|
|
85
69
|
let oracleTwapWithMantissa = lastOracleTwapWithMantissa;
|
|
86
70
|
|
|
87
|
-
const oracleLiveVsTwap =
|
|
71
|
+
const oracleLiveVsTwap = oraclePrice
|
|
88
72
|
.sub(lastOracleTwapWithMantissa)
|
|
89
73
|
.abs()
|
|
90
74
|
.mul(MARK_PRICE_PRECISION)
|
|
@@ -95,7 +79,7 @@ export async function calculateAllEstimatedFundingRate(
|
|
|
95
79
|
if (oracleLiveVsTwap.lte(MARK_PRICE_PRECISION.mul(new BN(10)))) {
|
|
96
80
|
oracleTwapWithMantissa = oracleTwapTimeSinceLastUpdate
|
|
97
81
|
.mul(lastOracleTwapWithMantissa)
|
|
98
|
-
.add(timeSinceLastMarkChange.mul(
|
|
82
|
+
.add(timeSinceLastMarkChange.mul(oraclePrice))
|
|
99
83
|
.div(timeSinceLastOracleTwapUpdate.add(oracleTwapTimeSinceLastUpdate));
|
|
100
84
|
}
|
|
101
85
|
|
|
@@ -203,7 +187,7 @@ export async function calculateAllEstimatedFundingRate(
|
|
|
203
187
|
*/
|
|
204
188
|
export async function calculateEstimatedFundingRate(
|
|
205
189
|
market: Market,
|
|
206
|
-
oraclePriceData:
|
|
190
|
+
oraclePriceData: OraclePriceData,
|
|
207
191
|
periodAdjustment: BN = new BN(1),
|
|
208
192
|
estimationMethod: 'interpolated' | 'lowerbound' | 'capped'
|
|
209
193
|
): Promise<BN> {
|
|
@@ -233,7 +217,7 @@ export async function calculateEstimatedFundingRate(
|
|
|
233
217
|
*/
|
|
234
218
|
export async function calculateLongShortFundingRate(
|
|
235
219
|
market: Market,
|
|
236
|
-
oraclePriceData:
|
|
220
|
+
oraclePriceData: OraclePriceData,
|
|
237
221
|
periodAdjustment: BN = new BN(1)
|
|
238
222
|
): Promise<[BN, BN]> {
|
|
239
223
|
const [_1, _2, _, cappedAltEst, interpEst] =
|
|
@@ -261,7 +245,7 @@ export async function calculateLongShortFundingRate(
|
|
|
261
245
|
*/
|
|
262
246
|
export async function calculateLongShortFundingRateAndLiveTwaps(
|
|
263
247
|
market: Market,
|
|
264
|
-
oraclePriceData:
|
|
248
|
+
oraclePriceData: OraclePriceData,
|
|
265
249
|
periodAdjustment: BN = new BN(1)
|
|
266
250
|
): Promise<[BN, BN, BN, BN]> {
|
|
267
251
|
const [markTwapLive, oracleTwapLive, _2, cappedAltEst, interpEst] =
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.calculateInsuranceFundSize = void 0;
|
|
4
|
+
const __1 = require("../");
|
|
5
|
+
/**
|
|
6
|
+
* In the case of a levered loss, the exchange first pays out undistributed fees and then the insurance fund.
|
|
7
|
+
* Thus the de facto size of the insurance fund is the amount in the insurance vault plus the sum of each markets
|
|
8
|
+
* undistributed fees.
|
|
9
|
+
*
|
|
10
|
+
* @param connection
|
|
11
|
+
* @param state
|
|
12
|
+
* @param marketsAccount
|
|
13
|
+
* @returns Precision : QUOTE_ASSET_PRECISION
|
|
14
|
+
*/
|
|
15
|
+
async function calculateInsuranceFundSize(connection, state, marketsAccount) {
|
|
16
|
+
const insuranceVaultPublicKey = state.insuranceVault;
|
|
17
|
+
const insuranceVaultAmount = new __1.BN((await connection.getTokenAccountBalance(insuranceVaultPublicKey)).value.amount);
|
|
18
|
+
return marketsAccount.markets.reduce((insuranceVaultAmount, market) => {
|
|
19
|
+
return insuranceVaultAmount.add(market.amm.totalFee.div(new __1.BN(2)));
|
|
20
|
+
}, insuranceVaultAmount);
|
|
21
|
+
}
|
|
22
|
+
exports.calculateInsuranceFundSize = calculateInsuranceFundSize;
|
|
23
|
+
//# sourceMappingURL=insuranceFund.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"insuranceFund.js","sourceRoot":"","sources":["insuranceFund.ts"],"names":[],"mappings":";;;AACA,2BAAyB;AAGzB;;;;;;;;;GASG;AACI,KAAK,UAAU,0BAA0B,CAC/C,UAAsB,EACtB,KAAmB,EACnB,cAA8B;IAE9B,MAAM,uBAAuB,GAAG,KAAK,CAAC,cAAc,CAAC;IACrD,MAAM,oBAAoB,GAAG,IAAI,MAAE,CAClC,CACC,MAAM,UAAU,CAAC,sBAAsB,CAAC,uBAAuB,CAAC,CAChE,CAAC,KAAK,CAAC,MAAM,CACd,CAAC;IACF,OAAO,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,oBAAoB,EAAE,MAAM,EAAE,EAAE;QACrE,OAAO,oBAAoB,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,MAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrE,CAAC,EAAE,oBAAoB,CAAC,CAAC;AAC1B,CAAC;AAdD,gEAcC"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.calculateOracleMarkSpread = exports.calculateNewMarketAfterTrade = exports.calculateMarkPrice = void 0;
|
|
4
|
+
const amm_1 = require("./amm");
|
|
5
|
+
/**
|
|
6
|
+
* Calculates market mark price
|
|
7
|
+
*
|
|
8
|
+
* @param market
|
|
9
|
+
* @return markPrice : Precision MARK_PRICE_PRECISION
|
|
10
|
+
*/
|
|
11
|
+
function calculateMarkPrice(market) {
|
|
12
|
+
return (0, amm_1.calculatePrice)(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
|
|
13
|
+
}
|
|
14
|
+
exports.calculateMarkPrice = calculateMarkPrice;
|
|
15
|
+
function calculateNewMarketAfterTrade(baseAssetAmount, direction, market) {
|
|
16
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', direction));
|
|
17
|
+
const newAmm = Object.assign({}, market.amm);
|
|
18
|
+
const newMarket = Object.assign({}, market);
|
|
19
|
+
newMarket.amm = newAmm;
|
|
20
|
+
newMarket.amm.quoteAssetReserve = newQuoteAssetReserve;
|
|
21
|
+
newMarket.amm.baseAssetReserve = newBaseAssetReserve;
|
|
22
|
+
return newMarket;
|
|
23
|
+
}
|
|
24
|
+
exports.calculateNewMarketAfterTrade = calculateNewMarketAfterTrade;
|
|
25
|
+
function calculateOracleMarkSpread(market, oraclePriceData) {
|
|
26
|
+
const markPrice = calculateMarkPrice(market);
|
|
27
|
+
return oraclePriceData.price.sub(markPrice);
|
|
28
|
+
}
|
|
29
|
+
exports.calculateOracleMarkSpread = calculateOracleMarkSpread;
|
|
30
|
+
//# sourceMappingURL=market.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"market.js","sourceRoot":"","sources":["market.ts"],"names":[],"mappings":";;;AAEA,+BAIe;AAGf;;;;;GAKG;AACH,SAAgB,kBAAkB,CAAC,MAAc;IAChD,OAAO,IAAA,oBAAc,EACpB,MAAM,CAAC,GAAG,CAAC,gBAAgB,EAC3B,MAAM,CAAC,GAAG,CAAC,iBAAiB,EAC5B,MAAM,CAAC,GAAG,CAAC,aAAa,CACxB,CAAC;AACH,CAAC;AAND,gDAMC;AAED,SAAgB,4BAA4B,CAC3C,eAAmB,EACnB,SAA4B,EAC5B,MAAc;IAEd,MAAM,CAAC,oBAAoB,EAAE,mBAAmB,CAAC,GAChD,IAAA,mCAA6B,EAC5B,MAAM,CAAC,GAAG,EACV,MAAM,EACN,eAAe,CAAC,GAAG,EAAE,EACrB,IAAA,sBAAgB,EAAC,MAAM,EAAE,SAAS,CAAC,CACnC,CAAC;IAEH,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAC7C,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;IAC5C,SAAS,CAAC,GAAG,GAAG,MAAM,CAAC;IACvB,SAAS,CAAC,GAAG,CAAC,iBAAiB,GAAG,oBAAoB,CAAC;IACvD,SAAS,CAAC,GAAG,CAAC,gBAAgB,GAAG,mBAAmB,CAAC;IAErD,OAAO,SAAS,CAAC;AAClB,CAAC;AApBD,oEAoBC;AAED,SAAgB,yBAAyB,CACxC,MAAc,EACd,eAAgC;IAEhC,MAAM,SAAS,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAC7C,OAAO,eAAe,CAAC,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC;AAND,8DAMC"}
|
package/src/math/market.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
calculatePrice,
|
|
6
6
|
getSwapDirection,
|
|
7
7
|
} from './amm';
|
|
8
|
+
import { OraclePriceData } from '../oracles/types';
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* Calculates market mark price
|
|
@@ -41,3 +42,11 @@ export function calculateNewMarketAfterTrade(
|
|
|
41
42
|
|
|
42
43
|
return newMarket;
|
|
43
44
|
}
|
|
45
|
+
|
|
46
|
+
export function calculateMarkOracleSpread(
|
|
47
|
+
market: Market,
|
|
48
|
+
oraclePriceData: OraclePriceData
|
|
49
|
+
): BN {
|
|
50
|
+
const markPrice = calculateMarkPrice(market);
|
|
51
|
+
return markPrice.sub(oraclePriceData.price);
|
|
52
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isOrderReduceOnly = exports.isOrderRiskIncreasingInSameDirection = exports.isOrderRiskIncreasing = void 0;
|
|
4
|
+
const types_1 = require("../types");
|
|
5
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
|
+
function isOrderRiskIncreasing(user, order) {
|
|
7
|
+
if ((0, types_1.isVariant)(order.status, 'init')) {
|
|
8
|
+
return false;
|
|
9
|
+
}
|
|
10
|
+
const position = user.getUserPosition(order.marketIndex) ||
|
|
11
|
+
user.getEmptyPosition(order.marketIndex);
|
|
12
|
+
// if no position exists, it's risk increasing
|
|
13
|
+
if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
// if position is long and order is long
|
|
17
|
+
if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && (0, types_1.isVariant)(order.direction, 'long')) {
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
// if position is short and order is short
|
|
21
|
+
if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
|
|
22
|
+
(0, types_1.isVariant)(order.direction, 'short')) {
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
const baseAssetAmountToFill = order.baseAssetAmount.sub(order.baseAssetAmountFilled);
|
|
26
|
+
// if order will flip position
|
|
27
|
+
if (baseAssetAmountToFill.gt(position.baseAssetAmount.abs().mul(numericConstants_1.TWO))) {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
exports.isOrderRiskIncreasing = isOrderRiskIncreasing;
|
|
33
|
+
function isOrderRiskIncreasingInSameDirection(user, order) {
|
|
34
|
+
if ((0, types_1.isVariant)(order.status, 'init')) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
const position = user.getUserPosition(order.marketIndex) ||
|
|
38
|
+
user.getEmptyPosition(order.marketIndex);
|
|
39
|
+
// if no position exists, it's risk increasing
|
|
40
|
+
if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
// if position is long and order is long
|
|
44
|
+
if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && (0, types_1.isVariant)(order.direction, 'long')) {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
// if position is short and order is short
|
|
48
|
+
if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
|
|
49
|
+
(0, types_1.isVariant)(order.direction, 'short')) {
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
exports.isOrderRiskIncreasingInSameDirection = isOrderRiskIncreasingInSameDirection;
|
|
55
|
+
function isOrderReduceOnly(user, order) {
|
|
56
|
+
if ((0, types_1.isVariant)(order.status, 'init')) {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
const position = user.getUserPosition(order.marketIndex) ||
|
|
60
|
+
user.getEmptyPosition(order.marketIndex);
|
|
61
|
+
// if position is long and order is long
|
|
62
|
+
if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && (0, types_1.isVariant)(order.direction, 'long')) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
// if position is short and order is short
|
|
66
|
+
if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
|
|
67
|
+
(0, types_1.isVariant)(order.direction, 'short')) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
return order.baseAssetAmount.abs().lte(position.baseAssetAmount.abs());
|
|
71
|
+
}
|
|
72
|
+
exports.isOrderReduceOnly = isOrderReduceOnly;
|
|
73
|
+
//# sourceMappingURL=orders.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orders.js","sourceRoot":"","sources":["orders.ts"],"names":[],"mappings":";;;AACA,oCAA4C;AAC5C,oEAA0D;AAE1D,SAAgB,qBAAqB,CACpC,IAAuB,EACvB,KAAY;IAEZ,IAAI,IAAA,iBAAS,EAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE;QACpC,OAAO,KAAK,CAAC;KACb;IAED,MAAM,QAAQ,GACb,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAE1C,8CAA8C;IAC9C,IAAI,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC,EAAE;QACtC,OAAO,IAAI,CAAC;KACZ;IAED,wCAAwC;IACxC,IAAI,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC,IAAI,IAAA,iBAAS,EAAC,KAAK,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE;QAC5E,OAAO,IAAI,CAAC;KACZ;IAED,0CAA0C;IAC1C,IACC,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC;QACjC,I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AAY;IAEZ,IAAI,IAAA,iBAAS,EAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE;QACpC,OAAO,KAAK,CAAC;KACb;IAED,MAAM,QAAQ,GACb,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAE1C,wCAAwC;IACxC,IAAI,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC,IAAI,IAAA,iBAAS,EAAC,KAAK,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE;QAC5E,OAAO,KAAK,CAAC;KACb;IAED,0CAA0C;IAC1C,IACC,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC;QACjC,IAAA,iBAAS,EAAC,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,EAClC;QACD,OAAO,KAAK,CAAC;KACb;IAED,OAAO,KAAK,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC;AACxE,CAAC;AA1BD,8CA0BC"}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateEntryPrice = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
|
|
4
|
+
const __1 = require("../");
|
|
5
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
|
+
const types_1 = require("../types");
|
|
7
|
+
const amm_1 = require("./amm");
|
|
8
|
+
/**
|
|
9
|
+
* calculateBaseAssetValue
|
|
10
|
+
* = market value of closing entire position
|
|
11
|
+
* @param market
|
|
12
|
+
* @param userPosition
|
|
13
|
+
* @returns Base Asset Value. : Precision QUOTE_PRECISION
|
|
14
|
+
*/
|
|
15
|
+
function calculateBaseAssetValue(market, userPosition) {
|
|
16
|
+
if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
17
|
+
return numericConstants_1.ZERO;
|
|
18
|
+
}
|
|
19
|
+
const directionToClose = findDirectionToClose(userPosition);
|
|
20
|
+
const [newQuoteAssetReserve, _] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', userPosition.baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', directionToClose));
|
|
21
|
+
switch (directionToClose) {
|
|
22
|
+
case types_1.PositionDirection.SHORT:
|
|
23
|
+
return market.amm.quoteAssetReserve
|
|
24
|
+
.sub(newQuoteAssetReserve)
|
|
25
|
+
.mul(market.amm.pegMultiplier)
|
|
26
|
+
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
27
|
+
case types_1.PositionDirection.LONG:
|
|
28
|
+
return newQuoteAssetReserve
|
|
29
|
+
.sub(market.amm.quoteAssetReserve)
|
|
30
|
+
.mul(market.amm.pegMultiplier)
|
|
31
|
+
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
|
|
32
|
+
.add(numericConstants_1.ONE);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
exports.calculateBaseAssetValue = calculateBaseAssetValue;
|
|
36
|
+
/**
|
|
37
|
+
* calculatePositionPNL
|
|
38
|
+
* = BaseAssetAmount * (Avg Exit Price - Avg Entry Price)
|
|
39
|
+
* @param market
|
|
40
|
+
* @param marketPosition
|
|
41
|
+
* @param withFunding (adds unrealized funding payment pnl to result)
|
|
42
|
+
* @returns BaseAssetAmount : Precision QUOTE_PRECISION
|
|
43
|
+
*/
|
|
44
|
+
function calculatePositionPNL(market, marketPosition, withFunding = false) {
|
|
45
|
+
if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
46
|
+
return numericConstants_1.ZERO;
|
|
47
|
+
}
|
|
48
|
+
const baseAssetValue = calculateBaseAssetValue(market, marketPosition);
|
|
49
|
+
let pnl;
|
|
50
|
+
if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
51
|
+
pnl = baseAssetValue.sub(marketPosition.quoteAssetAmount);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
pnl = marketPosition.quoteAssetAmount.sub(baseAssetValue);
|
|
55
|
+
}
|
|
56
|
+
if (withFunding) {
|
|
57
|
+
const fundingRatePnL = calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
|
|
58
|
+
pnl = pnl.add(fundingRatePnL);
|
|
59
|
+
}
|
|
60
|
+
return pnl;
|
|
61
|
+
}
|
|
62
|
+
exports.calculatePositionPNL = calculatePositionPNL;
|
|
63
|
+
/**
|
|
64
|
+
*
|
|
65
|
+
* @param market
|
|
66
|
+
* @param marketPosition
|
|
67
|
+
* @returns // TODO-PRECISION
|
|
68
|
+
*/
|
|
69
|
+
function calculatePositionFundingPNL(market, marketPosition) {
|
|
70
|
+
if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
71
|
+
return numericConstants_1.ZERO;
|
|
72
|
+
}
|
|
73
|
+
let ammCumulativeFundingRate;
|
|
74
|
+
if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
75
|
+
ammCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
ammCumulativeFundingRate = market.amm.cumulativeFundingRateShort;
|
|
79
|
+
}
|
|
80
|
+
const perPositionFundingRate = ammCumulativeFundingRate
|
|
81
|
+
.sub(marketPosition.lastCumulativeFundingRate)
|
|
82
|
+
.mul(marketPosition.baseAssetAmount)
|
|
83
|
+
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
84
|
+
.div(numericConstants_1.FUNDING_PAYMENT_PRECISION)
|
|
85
|
+
.mul(new __1.BN(-1));
|
|
86
|
+
return perPositionFundingRate;
|
|
87
|
+
}
|
|
88
|
+
exports.calculatePositionFundingPNL = calculatePositionFundingPNL;
|
|
89
|
+
/**
|
|
90
|
+
*
|
|
91
|
+
* @param userPosition
|
|
92
|
+
* @returns Precision: MARK_PRICE_PRECISION (10^10)
|
|
93
|
+
*/
|
|
94
|
+
function calculateEntryPrice(userPosition) {
|
|
95
|
+
if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
96
|
+
return numericConstants_1.ZERO;
|
|
97
|
+
}
|
|
98
|
+
return userPosition.quoteAssetAmount
|
|
99
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
100
|
+
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
101
|
+
.div(userPosition.baseAssetAmount)
|
|
102
|
+
.abs();
|
|
103
|
+
}
|
|
104
|
+
exports.calculateEntryPrice = calculateEntryPrice;
|
|
105
|
+
function findDirectionToClose(userPosition) {
|
|
106
|
+
return userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
|
|
107
|
+
? types_1.PositionDirection.SHORT
|
|
108
|
+
: types_1.PositionDirection.LONG;
|
|
109
|
+
}
|
|
110
|
+
exports.findDirectionToClose = findDirectionToClose;
|
|
111
|
+
function positionCurrentDirection(userPosition) {
|
|
112
|
+
return userPosition.baseAssetAmount.gte(numericConstants_1.ZERO)
|
|
113
|
+
? types_1.PositionDirection.LONG
|
|
114
|
+
: types_1.PositionDirection.SHORT;
|
|
115
|
+
}
|
|
116
|
+
exports.positionCurrentDirection = positionCurrentDirection;
|
|
117
|
+
function isEmptyPosition(userPosition) {
|
|
118
|
+
return (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && userPosition.openOrders.eq(numericConstants_1.ZERO));
|
|
119
|
+
}
|
|
120
|
+
exports.isEmptyPosition = isEmptyPosition;
|
|
121
|
+
//# sourceMappingURL=position.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"position.js","sourceRoot":"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,CAAC;AAvBD,kEAuBC;AAED;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,YAA0B;IAC7D,IAAI,YAAY,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC,EAAE;QAC1C,OAAO,uBAAI,CAAC;KACZ;IAED,OAAO,YAAY,CAAC,gBAAgB;SAClC,GAAG,CAAC,uCAAoB,CAAC;SACzB,GAAG,CAAC,+CAA4B,CAAC;SACjC,GAAG,CAAC,YAAY,CAAC,eAAe,CAAC;SACjC,GAAG,EAAE,CAAC;AACT,CAAC;AAVD,kDAUC;AAED,SAAgB,oBAAoB,CACnC,YAA0B;IAE1B,OAAO,YAAY,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC;QAC3C,CAAC,CAAC,yBAAiB,CAAC,KAAK;QACzB,CAAC,CAAC,yBAAiB,CAAC,IAAI,CAAC;AAC3B,CAAC;AAND,oDAMC;AAED,SAAgB,wBAAwB,CACvC,YAA0B;IAE1B,OAAO,YAAY,CAAC,eAAe,CAAC,GAAG,CAAC,uBAAI,CAAC;QAC5C,CAAC,CAAC,yBAAiB,CAAC,IAAI;QACxB,CAAC,CAAC,yBAAiB,CAAC,KAAK,CAAC;AAC5B,CAAC;AAND,4DAMC;AAED,SAAgB,eAAe,CAAC,YAA0B;IACzD,OAAO,CACN,YAAY,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC,IAAI,YAAY,CAAC,UAAU,CAAC,EAAE,CAAC,uBAAI,CAAC,CACzE,CAAC;AACH,CAAC;AAJD,0CAIC"}
|
|
@@ -0,0 +1,182 @@
|
|
|
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 MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
|
|
12
|
+
/**
|
|
13
|
+
* Calculates avg/max slippage (price impact) for candidate trade
|
|
14
|
+
* @param direction
|
|
15
|
+
* @param amount
|
|
16
|
+
* @param market
|
|
17
|
+
* @return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice]
|
|
18
|
+
*
|
|
19
|
+
* 'pctAvgSlippage' => the percentage change to entryPrice (average est slippage in execution) : Precision MARK_PRICE_PRECISION
|
|
20
|
+
*
|
|
21
|
+
* 'pctMaxSlippage' => the percentage change to maxPrice (highest est slippage in execution) : Precision MARK_PRICE_PRECISION
|
|
22
|
+
*
|
|
23
|
+
* 'entryPrice' => the average price of the trade : Precision MARK_PRICE_PRECISION
|
|
24
|
+
*
|
|
25
|
+
* 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
|
|
26
|
+
*/
|
|
27
|
+
function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote') {
|
|
28
|
+
const oldPrice = (0, market_1.calculateMarkPrice)(market);
|
|
29
|
+
if (amount.eq(numericConstants_1.ZERO)) {
|
|
30
|
+
return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
|
|
31
|
+
}
|
|
32
|
+
const [acquiredBase, acquiredQuote] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType);
|
|
33
|
+
const entryPrice = (0, amm_1.calculatePrice)(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
|
|
34
|
+
const newPrice = (0, amm_1.calculatePrice)(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
|
|
35
|
+
if (direction == types_1.PositionDirection.SHORT) {
|
|
36
|
+
(0, assert_1.assert)(newPrice.lt(oldPrice));
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
(0, assert_1.assert)(oldPrice.lt(newPrice));
|
|
40
|
+
}
|
|
41
|
+
const pctMaxSlippage = newPrice
|
|
42
|
+
.sub(oldPrice)
|
|
43
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
44
|
+
.div(oldPrice)
|
|
45
|
+
.abs();
|
|
46
|
+
const pctAvgSlippage = entryPrice
|
|
47
|
+
.sub(oldPrice)
|
|
48
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
49
|
+
.div(oldPrice)
|
|
50
|
+
.abs();
|
|
51
|
+
return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice];
|
|
52
|
+
}
|
|
53
|
+
exports.calculateTradeSlippage = calculateTradeSlippage;
|
|
54
|
+
/**
|
|
55
|
+
* Calculates acquired amounts for trade executed
|
|
56
|
+
* @param direction
|
|
57
|
+
* @param amount
|
|
58
|
+
* @param market
|
|
59
|
+
* @return
|
|
60
|
+
* | 'acquiredBase' => positive/negative change in user's base : BN TODO-PRECISION
|
|
61
|
+
* | 'acquiredQuote' => positive/negative change in user's quote : BN TODO-PRECISION
|
|
62
|
+
*/
|
|
63
|
+
function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType = 'quote') {
|
|
64
|
+
if (amount.eq(numericConstants_1.ZERO)) {
|
|
65
|
+
return [numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
66
|
+
}
|
|
67
|
+
const swapDirection = (0, amm_1.getSwapDirection)(inputAssetType, direction);
|
|
68
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, inputAssetType, amount, swapDirection);
|
|
69
|
+
const acquiredBase = market.amm.baseAssetReserve.sub(newBaseAssetReserve);
|
|
70
|
+
let acquiredQuote = market.amm.quoteAssetReserve.sub(newQuoteAssetReserve);
|
|
71
|
+
if (inputAssetType === 'base' && (0, types_1.isVariant)(swapDirection, 'remove')) {
|
|
72
|
+
acquiredQuote = acquiredQuote.sub(numericConstants_1.ONE);
|
|
73
|
+
}
|
|
74
|
+
return [acquiredBase, acquiredQuote];
|
|
75
|
+
}
|
|
76
|
+
exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
|
|
77
|
+
/**
|
|
78
|
+
* calculateTargetPriceTrade
|
|
79
|
+
* simple function for finding arbitraging trades
|
|
80
|
+
* @param market
|
|
81
|
+
* @param targetPrice
|
|
82
|
+
* @param pct optional default is 100% gap filling, can set smaller.
|
|
83
|
+
* @returns trade direction/size in order to push price to a targetPrice,
|
|
84
|
+
*
|
|
85
|
+
* [
|
|
86
|
+
* direction => direction of trade required, TODO-PRECISION
|
|
87
|
+
* tradeSize => size of trade required, TODO-PRECISION
|
|
88
|
+
* entryPrice => the entry price for the trade, TODO-PRECISION
|
|
89
|
+
* targetPrice => the target price TODO-PRECISION
|
|
90
|
+
* ]
|
|
91
|
+
*/
|
|
92
|
+
function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote') {
|
|
93
|
+
(0, assert_1.assert)(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
|
|
94
|
+
(0, assert_1.assert)(targetPrice.gt(numericConstants_1.ZERO));
|
|
95
|
+
(0, assert_1.assert)(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
|
|
96
|
+
const markPriceBefore = (0, market_1.calculateMarkPrice)(market);
|
|
97
|
+
if (targetPrice.gt(markPriceBefore)) {
|
|
98
|
+
const priceGap = targetPrice.sub(markPriceBefore);
|
|
99
|
+
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
|
|
100
|
+
targetPrice = markPriceBefore.add(priceGapScaled);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
const priceGap = markPriceBefore.sub(targetPrice);
|
|
104
|
+
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
|
|
105
|
+
targetPrice = markPriceBefore.sub(priceGapScaled);
|
|
106
|
+
}
|
|
107
|
+
let direction;
|
|
108
|
+
let tradeSize;
|
|
109
|
+
let baseSize;
|
|
110
|
+
const baseAssetReserveBefore = market.amm.baseAssetReserve;
|
|
111
|
+
const quoteAssetReserveBefore = market.amm.quoteAssetReserve;
|
|
112
|
+
const peg = market.amm.pegMultiplier;
|
|
113
|
+
const invariant = market.amm.sqrtK.mul(market.amm.sqrtK);
|
|
114
|
+
const k = invariant.mul(numericConstants_1.MARK_PRICE_PRECISION);
|
|
115
|
+
let baseAssetReserveAfter;
|
|
116
|
+
let quoteAssetReserveAfter;
|
|
117
|
+
const biasModifier = new anchor_1.BN(1);
|
|
118
|
+
let markPriceAfter;
|
|
119
|
+
if (markPriceBefore.gt(targetPrice)) {
|
|
120
|
+
// overestimate y2
|
|
121
|
+
baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
|
|
122
|
+
quoteAssetReserveAfter = k
|
|
123
|
+
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
124
|
+
.div(baseAssetReserveAfter);
|
|
125
|
+
markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
126
|
+
direction = types_1.PositionDirection.SHORT;
|
|
127
|
+
tradeSize = quoteAssetReserveBefore
|
|
128
|
+
.sub(quoteAssetReserveAfter)
|
|
129
|
+
.mul(peg)
|
|
130
|
+
.div(numericConstants_1.PEG_PRECISION)
|
|
131
|
+
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
132
|
+
baseSize = baseAssetReserveAfter.sub(baseAssetReserveBefore);
|
|
133
|
+
}
|
|
134
|
+
else if (markPriceBefore.lt(targetPrice)) {
|
|
135
|
+
// underestimate y2
|
|
136
|
+
baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
|
|
137
|
+
quoteAssetReserveAfter = k
|
|
138
|
+
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
139
|
+
.div(baseAssetReserveAfter);
|
|
140
|
+
markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
141
|
+
direction = types_1.PositionDirection.LONG;
|
|
142
|
+
tradeSize = quoteAssetReserveAfter
|
|
143
|
+
.sub(quoteAssetReserveBefore)
|
|
144
|
+
.mul(peg)
|
|
145
|
+
.div(numericConstants_1.PEG_PRECISION)
|
|
146
|
+
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
147
|
+
baseSize = baseAssetReserveBefore.sub(baseAssetReserveAfter);
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
// no trade, market is at target
|
|
151
|
+
direction = types_1.PositionDirection.LONG;
|
|
152
|
+
tradeSize = numericConstants_1.ZERO;
|
|
153
|
+
return [direction, tradeSize, targetPrice, targetPrice];
|
|
154
|
+
}
|
|
155
|
+
let tp1 = targetPrice;
|
|
156
|
+
let tp2 = markPriceAfter;
|
|
157
|
+
let originalDiff = targetPrice.sub(markPriceBefore);
|
|
158
|
+
if (direction == types_1.PositionDirection.SHORT) {
|
|
159
|
+
tp1 = markPriceAfter;
|
|
160
|
+
tp2 = targetPrice;
|
|
161
|
+
originalDiff = markPriceBefore.sub(targetPrice);
|
|
162
|
+
}
|
|
163
|
+
const entryPrice = tradeSize
|
|
164
|
+
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
165
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
166
|
+
.div(baseSize.abs());
|
|
167
|
+
(0, assert_1.assert)(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
|
|
168
|
+
(0, assert_1.assert)(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
|
|
169
|
+
tp2.toString() +
|
|
170
|
+
'>=' +
|
|
171
|
+
tp1.toString() +
|
|
172
|
+
'err: ' +
|
|
173
|
+
tp2.sub(tp1).abs().toString());
|
|
174
|
+
if (outputAssetType == 'quote') {
|
|
175
|
+
return [direction, tradeSize, entryPrice, targetPrice];
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
return [direction, baseSize, entryPrice, targetPrice];
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
exports.calculateTargetPriceTrade = calculateTargetPriceTrade;
|
|
182
|
+
//# sourceMappingURL=trade.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trade.js","sourceRoot":"","sources":["trade.ts"],"names":[],"mappings":";;;AAAA,oCAAgE;AAChE,kDAA2C;AAC3C,6CAA0C;AAC1C,oEAMuC;AACvC,qCAA8C;AAC9C,+BAKe;AACf,mCAAuC;AAEvC,MAAM,MAAM,GAAG,IAAI,WAAE,CAAC,IAAI,CAAC,CAAC,CAAC,wCAAwC;AAerE;;;;;;;;;;;;;;GAcG;AACH,SAAgB,sBAAsB,CACrC,SAA4B,EAC5B,MAAU,EACV,MAAc,EACd,iBAA4B,OAAO;IAEnC,MAAM,QAAQ,GAAG,IAAA,2BAAkB,EAAC,MAAM,CAAC,CAAC;IAC5C,IAAI,MAAM,CAAC,EAAE,CAAC,uBAAI,CAAC,EAAE;QACpB,OAAO,CAAC,uBAAI,EAAE,uBAAI,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;KACxC;IACD,MAAM,CAAC,YAAY,EAAE,aAAa,CAAC,GAAG,6BAA6B,CAClE,SAAS,EACT,MAAM,EACN,MAAM,EACN,cAAc,CACd,CAAC;IAEF,MAAM,UAAU,GAAG,IAAA,oBAAc,EAChC,YAAY,EACZ,aAAa,EACb,MAAM,CAAC,GAAG,CAAC,aAAa,CACxB,CAAC,GAAG,CAAC,IAAI,WAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IA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ule", { value: true });
|
|
3
|
+
exports.squareRootBN = void 0;
|
|
4
|
+
const __1 = require("../");
|
|
5
|
+
const squareRootBN = (n, closeness = new __1.BN(1)) => {
|
|
6
|
+
// Assuming the sqrt of n as n only
|
|
7
|
+
let x = n;
|
|
8
|
+
// The closed guess will be stored in the root
|
|
9
|
+
let root;
|
|
10
|
+
// To count the number of iterations
|
|
11
|
+
let count = 0;
|
|
12
|
+
const TWO = new __1.BN(2);
|
|
13
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
14
|
+
while (count < Number.MAX_SAFE_INTEGER) {
|
|
15
|
+
count++;
|
|
16
|
+
// Calculate more closed x
|
|
17
|
+
root = x.add(n.div(x)).div(TWO);
|
|
18
|
+
// Check for closeness
|
|
19
|
+
if (x.sub(root).abs().lte(closeness))
|
|
20
|
+
break;
|
|
21
|
+
// Update root
|
|
22
|
+
x = root;
|
|
23
|
+
}
|
|
24
|
+
return root;
|
|
25
|
+
};
|
|
26
|
+
exports.squareRootBN = squareRootBN;
|
|
27
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["utils.ts"],"names":[],"mappings":";;;AAAA,2BAAyB;AAElB,MAAM,YAAY,GAAG,CAAC,CAAC,EAAE,SAAS,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,EAAE,EAAE;IACxD,mCAAmC;IACnC,IAAI,CAAC,GAAG,CAAC,CAAC;IAEV,8CAA8C;IAC9C,IAAI,IAAI,CAAC;IAET,oCAAoC;IACpC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,MAAM,GAAG,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,CAAC;IAEtB,6DAA6D;IAC7D,OAAO,KAAK,GAAG,MAAM,CAAC,gBAAgB,EAAE;QACvC,KAAK,EAAE,CAAC;QAER,0BAA0B;QAC1B,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEhC,sBAAsB;QACtB,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC;YAAE,MAAM;QAE5C,cAAc;QACd,CAAC,GAAG,IAAI,CAAC;KACT;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AA1BW,QAAA,YAAY,gBA0BvB"}
|