@drift-labs/sdk 0.1.18-master.0 → 0.1.18-orders.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts +7 -4
- package/lib/accounts/defaultClearingHouseAccountSubscriber.js +27 -2
- package/lib/accounts/defaultHistoryAccountSubscriber.d.ts +28 -0
- package/lib/accounts/defaultHistoryAccountSubscriber.js +110 -0
- package/lib/accounts/defaultUserAccountSubscriber.d.ts +3 -2
- package/lib/accounts/defaultUserAccountSubscriber.js +12 -1
- package/lib/accounts/types.d.ts +31 -5
- package/lib/accounts/webSocketAccountSubscriber.d.ts +0 -1
- package/lib/addresses.d.ts +4 -1
- package/lib/addresses.js +28 -1
- package/lib/admin.d.ts +10 -5
- package/lib/admin.js +53 -30
- package/lib/assert/assert.d.ts +0 -1
- package/lib/clearingHouse.d.ts +22 -3
- package/lib/clearingHouse.js +246 -15
- package/lib/clearingHouseUser.d.ts +10 -17
- package/lib/clearingHouseUser.js +111 -97
- package/lib/config.d.ts +0 -1
- package/lib/config.js +1 -1
- package/lib/constants/markets.d.ts +0 -1
- package/lib/constants/numericConstants.d.ts +0 -1
- package/lib/examples/makeTradeExample.d.ts +0 -1
- package/lib/examples/makeTradeExample.js +6 -6
- package/lib/idl/clearing_house.json +895 -132
- package/lib/index.d.ts +4 -1
- package/lib/index.js +4 -0
- package/lib/math/amm.d.ts +1 -1
- package/lib/math/amm.js +38 -15
- package/lib/math/conversion.d.ts +0 -1
- package/lib/math/conversion.js +1 -1
- package/lib/math/funding.d.ts +0 -1
- package/lib/math/funding.js +1 -1
- package/lib/math/insuranceFund.d.ts +0 -1
- package/lib/math/market.d.ts +2 -2
- package/lib/math/market.js +12 -2
- package/lib/math/orders.d.ts +3 -0
- package/lib/math/orders.js +30 -0
- package/lib/math/position.d.ts +4 -2
- package/lib/math/position.js +19 -5
- package/lib/math/trade.d.ts +0 -1
- package/lib/math/trade.js +16 -16
- package/lib/math/utils.d.ts +0 -1
- package/lib/mockUSDCFaucet.d.ts +0 -1
- package/lib/orderParams.d.ts +7 -0
- package/lib/orderParams.js +88 -0
- package/lib/orders.d.ts +5 -0
- package/lib/orders.js +136 -0
- package/lib/pythClient.d.ts +0 -1
- package/lib/pythClient.js +1 -1
- package/lib/tx/defaultTxSender.d.ts +0 -1
- package/lib/tx/types.d.ts +0 -1
- package/lib/tx/utils.d.ts +0 -1
- package/lib/types.d.ts +140 -7
- package/lib/types.js +36 -1
- package/lib/util/computeUnits.d.ts +0 -1
- package/lib/util/tps.d.ts +0 -1
- package/lib/wallet.d.ts +0 -1
- package/package.json +1 -1
- package/src/accounts/defaultClearingHouseAccountSubscriber.ts +52 -5
- package/src/accounts/defaultHistoryAccountSubscriber.ts +176 -0
- package/src/accounts/defaultUserAccountSubscriber.ts +29 -2
- package/src/accounts/types.ts +41 -4
- package/src/addresses.ts +35 -0
- package/src/admin.ts +86 -33
- package/src/clearingHouse.ts +340 -7
- package/src/clearingHouseUser.ts +154 -102
- package/src/config.ts +1 -1
- package/src/idl/clearing_house.json +895 -132
- package/src/index.ts +4 -0
- package/src/math/amm.ts +47 -14
- package/src/math/market.ts +28 -2
- package/src/math/orders.ts +39 -0
- package/src/math/position.ts +23 -3
- package/src/orderParams.ts +128 -0
- package/src/orders.ts +230 -0
- package/src/types.ts +124 -6
- package/tsconfig.json +0 -1
- package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +0 -1
- package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +0 -1
- package/lib/accounts/types.d.ts.map +0 -1
- package/lib/accounts/webSocketAccountSubscriber.d.ts.map +0 -1
- package/lib/addresses.d.ts.map +0 -1
- package/lib/admin.d.ts.map +0 -1
- package/lib/assert/assert.d.ts.map +0 -1
- package/lib/clearingHouse.d.ts.map +0 -1
- package/lib/clearingHouseUser.d.ts.map +0 -1
- package/lib/config.d.ts.map +0 -1
- package/lib/constants/markets.d.ts.map +0 -1
- package/lib/constants/numericConstants.d.ts.map +0 -1
- package/lib/examples/makeTradeExample.d.ts.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/math/amm.d.ts.map +0 -1
- package/lib/math/conversion.d.ts.map +0 -1
- package/lib/math/funding.d.ts.map +0 -1
- package/lib/math/insuranceFund.d.ts.map +0 -1
- package/lib/math/market.d.ts.map +0 -1
- package/lib/math/position.d.ts.map +0 -1
- package/lib/math/trade.d.ts.map +0 -1
- package/lib/math/utils.d.ts.map +0 -1
- package/lib/mockUSDCFaucet.d.ts.map +0 -1
- package/lib/pythClient.d.ts.map +0 -1
- package/lib/tx/defaultTxSender.d.ts.map +0 -1
- package/lib/tx/types.d.ts.map +0 -1
- package/lib/tx/utils.d.ts.map +0 -1
- package/lib/types.d.ts.map +0 -1
- package/lib/util/computeUnits.d.ts.map +0 -1
- package/lib/util/tps.d.ts.map +0 -1
- package/lib/wallet.d.ts.map +0 -1
package/lib/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ export * from './mockUSDCFaucet';
|
|
|
3
3
|
export * from './pythClient';
|
|
4
4
|
export * from './types';
|
|
5
5
|
export * from './constants/markets';
|
|
6
|
+
export * from './accounts/defaultHistoryAccountSubscriber';
|
|
6
7
|
export * from './accounts/defaultClearingHouseAccountSubscriber';
|
|
7
8
|
export * from './accounts/types';
|
|
8
9
|
export * from './addresses';
|
|
@@ -16,6 +17,9 @@ export * from './math/market';
|
|
|
16
17
|
export * from './math/position';
|
|
17
18
|
export * from './math/amm';
|
|
18
19
|
export * from './math/trade';
|
|
20
|
+
export * from './math/orders';
|
|
21
|
+
export * from './orders';
|
|
22
|
+
export * from './orderParams';
|
|
19
23
|
export * from './wallet';
|
|
20
24
|
export * from './types';
|
|
21
25
|
export * from './math/utils';
|
|
@@ -24,4 +28,3 @@ export * from './constants/numericConstants';
|
|
|
24
28
|
export * from './util/computeUnits';
|
|
25
29
|
export * from './util/tps';
|
|
26
30
|
export { BN };
|
|
27
|
-
//# sourceMappingURL=index.d.ts.map
|
package/lib/index.js
CHANGED
|
@@ -17,6 +17,7 @@ __exportStar(require("./mockUSDCFaucet"), exports);
|
|
|
17
17
|
__exportStar(require("./pythClient"), exports);
|
|
18
18
|
__exportStar(require("./types"), exports);
|
|
19
19
|
__exportStar(require("./constants/markets"), exports);
|
|
20
|
+
__exportStar(require("./accounts/defaultHistoryAccountSubscriber"), exports);
|
|
20
21
|
__exportStar(require("./accounts/defaultClearingHouseAccountSubscriber"), exports);
|
|
21
22
|
__exportStar(require("./accounts/types"), exports);
|
|
22
23
|
__exportStar(require("./addresses"), exports);
|
|
@@ -30,6 +31,9 @@ __exportStar(require("./math/market"), exports);
|
|
|
30
31
|
__exportStar(require("./math/position"), exports);
|
|
31
32
|
__exportStar(require("./math/amm"), exports);
|
|
32
33
|
__exportStar(require("./math/trade"), exports);
|
|
34
|
+
__exportStar(require("./math/orders"), exports);
|
|
35
|
+
__exportStar(require("./orders"), exports);
|
|
36
|
+
__exportStar(require("./orderParams"), exports);
|
|
33
37
|
__exportStar(require("./wallet"), exports);
|
|
34
38
|
__exportStar(require("./types"), exports);
|
|
35
39
|
__exportStar(require("./math/utils"), exports);
|
package/lib/math/amm.d.ts
CHANGED
|
@@ -63,4 +63,4 @@ export declare function calculateRepegCost(market: Market, marketIndex: BN, newP
|
|
|
63
63
|
* @returns cost : Precision MARK_PRICE_PRECISION
|
|
64
64
|
*/
|
|
65
65
|
export declare function calculateTerminalPrice(market: Market): BN;
|
|
66
|
-
|
|
66
|
+
export declare function calculateMaxBaseAssetAmountToTrade(amm: AMM, limit_price: BN): [BN, PositionDirection];
|
package/lib/math/amm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.calculateTerminalPrice = exports.calculateRepegCost = exports.calculateAdjustKCost = exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateAmmReservesAfterSwap = exports.calculatePrice = void 0;
|
|
3
|
+
exports.calculateMaxBaseAssetAmountToTrade = exports.calculateTerminalPrice = exports.calculateRepegCost = exports.calculateAdjustKCost = exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateAmmReservesAfterSwap = exports.calculatePrice = void 0;
|
|
4
4
|
const anchor_1 = require("@project-serum/anchor");
|
|
5
5
|
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
6
|
const position_1 = require("./position");
|
|
@@ -36,7 +36,7 @@ exports.calculatePrice = calculatePrice;
|
|
|
36
36
|
* @returns quoteAssetReserve and baseAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
|
|
37
37
|
*/
|
|
38
38
|
function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDirection) {
|
|
39
|
-
|
|
39
|
+
assert_1.assert(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
|
|
40
40
|
let newQuoteAssetReserve;
|
|
41
41
|
let newBaseAssetReserve;
|
|
42
42
|
if (inputAssetType === 'quote') {
|
|
@@ -79,12 +79,10 @@ exports.calculateSwapOutput = calculateSwapOutput;
|
|
|
79
79
|
* @param positionDirection
|
|
80
80
|
*/
|
|
81
81
|
function getSwapDirection(inputAssetType, positionDirection) {
|
|
82
|
-
if (positionDirection ===
|
|
83
|
-
inputAssetType === 'base') {
|
|
82
|
+
if (types_1.isVariant(positionDirection, 'long') && inputAssetType === 'base') {
|
|
84
83
|
return types_1.SwapDirection.REMOVE;
|
|
85
84
|
}
|
|
86
|
-
if (positionDirection ===
|
|
87
|
-
inputAssetType === 'quote') {
|
|
85
|
+
if (types_1.isVariant(positionDirection, 'short') && inputAssetType === 'quote') {
|
|
88
86
|
return types_1.SwapDirection.REMOVE;
|
|
89
87
|
}
|
|
90
88
|
return types_1.SwapDirection.ADD;
|
|
@@ -104,8 +102,9 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
|
|
|
104
102
|
lastCumulativeFundingRate: market.amm.cumulativeFundingRate,
|
|
105
103
|
marketIndex: new anchor_1.BN(marketIndex),
|
|
106
104
|
quoteAssetAmount: new anchor_1.BN(0),
|
|
105
|
+
openOrders: new anchor_1.BN(0),
|
|
107
106
|
};
|
|
108
|
-
const currentValue =
|
|
107
|
+
const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
|
|
109
108
|
const marketNewK = Object.assign({}, market);
|
|
110
109
|
marketNewK.amm = Object.assign({}, market.amm);
|
|
111
110
|
marketNewK.amm.baseAssetReserve = market.amm.baseAssetReserve
|
|
@@ -116,7 +115,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
|
|
|
116
115
|
.div(denomenator);
|
|
117
116
|
marketNewK.amm.sqrtK = market.amm.sqrtK.mul(numerator).div(denomenator);
|
|
118
117
|
netUserPosition.quoteAssetAmount = currentValue;
|
|
119
|
-
const cost =
|
|
118
|
+
const cost = __1.calculatePositionPNL(marketNewK, netUserPosition);
|
|
120
119
|
return cost;
|
|
121
120
|
}
|
|
122
121
|
exports.calculateAdjustKCost = calculateAdjustKCost;
|
|
@@ -134,16 +133,17 @@ function calculateRepegCost(market, marketIndex, newPeg) {
|
|
|
134
133
|
lastCumulativeFundingRate: market.amm.cumulativeFundingRate,
|
|
135
134
|
marketIndex: new anchor_1.BN(marketIndex),
|
|
136
135
|
quoteAssetAmount: new anchor_1.BN(0),
|
|
136
|
+
openOrders: new anchor_1.BN(0),
|
|
137
137
|
};
|
|
138
|
-
const currentValue =
|
|
138
|
+
const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
|
|
139
139
|
netUserPosition.quoteAssetAmount = currentValue;
|
|
140
|
-
const prevMarketPrice =
|
|
140
|
+
const prevMarketPrice = __1.calculateMarkPrice(market);
|
|
141
141
|
const marketNewPeg = Object.assign({}, market);
|
|
142
142
|
marketNewPeg.amm = Object.assign({}, market.amm);
|
|
143
143
|
// const marketNewPeg = JSON.parse(JSON.stringify(market));
|
|
144
144
|
marketNewPeg.amm.pegMultiplier = newPeg;
|
|
145
|
-
console.log('Price moves from',
|
|
146
|
-
const cost =
|
|
145
|
+
console.log('Price moves from', __1.convertToNumber(prevMarketPrice), 'to', __1.convertToNumber(__1.calculateMarkPrice(marketNewPeg)));
|
|
146
|
+
const cost = __1.calculatePositionPNL(marketNewPeg, netUserPosition);
|
|
147
147
|
return cost;
|
|
148
148
|
}
|
|
149
149
|
exports.calculateRepegCost = calculateRepegCost;
|
|
@@ -154,9 +154,6 @@ exports.calculateRepegCost = calculateRepegCost;
|
|
|
154
154
|
* @returns cost : Precision MARK_PRICE_PRECISION
|
|
155
155
|
*/
|
|
156
156
|
function calculateTerminalPrice(market) {
|
|
157
|
-
if (!market.initialized) {
|
|
158
|
-
return new anchor_1.BN(0);
|
|
159
|
-
}
|
|
160
157
|
const directionToClose = market.baseAssetAmount.gt(numericConstants_1.ZERO)
|
|
161
158
|
? types_1.PositionDirection.SHORT
|
|
162
159
|
: types_1.PositionDirection.LONG;
|
|
@@ -169,3 +166,29 @@ function calculateTerminalPrice(market) {
|
|
|
169
166
|
return terminalPrice;
|
|
170
167
|
}
|
|
171
168
|
exports.calculateTerminalPrice = calculateTerminalPrice;
|
|
169
|
+
function calculateMaxBaseAssetAmountToTrade(amm, limit_price) {
|
|
170
|
+
const invariant = amm.sqrtK.mul(amm.sqrtK);
|
|
171
|
+
const newBaseAssetReserveSquared = invariant
|
|
172
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
173
|
+
.mul(amm.pegMultiplier)
|
|
174
|
+
.div(limit_price)
|
|
175
|
+
.div(numericConstants_1.PEG_PRECISION);
|
|
176
|
+
const newBaseAssetReserve = __1.squareRootBN(newBaseAssetReserveSquared);
|
|
177
|
+
if (newBaseAssetReserve.gt(amm.baseAssetReserve)) {
|
|
178
|
+
return [
|
|
179
|
+
newBaseAssetReserve.sub(amm.baseAssetReserve),
|
|
180
|
+
types_1.PositionDirection.SHORT,
|
|
181
|
+
];
|
|
182
|
+
}
|
|
183
|
+
else if (newBaseAssetReserve.lt(amm.baseAssetReserve)) {
|
|
184
|
+
return [
|
|
185
|
+
amm.baseAssetReserve.sub(newBaseAssetReserve),
|
|
186
|
+
types_1.PositionDirection.LONG,
|
|
187
|
+
];
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
console.log('tradeSize Too Small');
|
|
191
|
+
return [new anchor_1.BN(0), types_1.PositionDirection.LONG];
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
exports.calculateMaxBaseAssetAmountToTrade = calculateMaxBaseAssetAmountToTrade;
|
package/lib/math/conversion.d.ts
CHANGED
package/lib/math/conversion.js
CHANGED
|
@@ -10,6 +10,6 @@ const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PR
|
|
|
10
10
|
};
|
|
11
11
|
exports.convertToNumber = convertToNumber;
|
|
12
12
|
const convertBaseAssetAmountToNumber = (baseAssetAmount) => {
|
|
13
|
-
return
|
|
13
|
+
return exports.convertToNumber(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
|
|
14
14
|
};
|
|
15
15
|
exports.convertBaseAssetAmountToNumber = convertBaseAssetAmountToNumber;
|
package/lib/math/funding.d.ts
CHANGED
package/lib/math/funding.js
CHANGED
|
@@ -40,7 +40,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
|
|
|
40
40
|
const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
|
|
41
41
|
const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
|
|
42
42
|
const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, secondsInHour.sub(timeSinceLastMarkChange));
|
|
43
|
-
const baseAssetPriceWithMantissa =
|
|
43
|
+
const baseAssetPriceWithMantissa = market_1.calculateMarkPrice(market);
|
|
44
44
|
const markTwapWithMantissa = markTwapTimeSinceLastUpdate
|
|
45
45
|
.mul(lastMarkTwapWithMantissa)
|
|
46
46
|
.add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
|
|
@@ -12,4 +12,3 @@ import { Connection } from '@solana/web3.js';
|
|
|
12
12
|
* @returns Precision : QUOTE_ASSET_PRECISION
|
|
13
13
|
*/
|
|
14
14
|
export declare function calculateInsuranceFundSize(connection: Connection, state: StateAccount, marketsAccount: MarketsAccount): Promise<BN>;
|
|
15
|
-
//# sourceMappingURL=insuranceFund.d.ts.map
|
package/lib/math/market.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/// <reference types="bn.js" />
|
|
2
2
|
import { BN } from '@project-serum/anchor';
|
|
3
|
-
import { Market } from '../types';
|
|
3
|
+
import { Market, PositionDirection } from '../types';
|
|
4
4
|
/**
|
|
5
5
|
* Calculates market mark price
|
|
6
6
|
*
|
|
@@ -8,4 +8,4 @@ import { Market } from '../types';
|
|
|
8
8
|
* @return markPrice : Precision MARK_PRICE_PRECISION
|
|
9
9
|
*/
|
|
10
10
|
export declare function calculateMarkPrice(market: Market): BN;
|
|
11
|
-
|
|
11
|
+
export declare function calculateNewMarketAfterTrade(baseAssetAmount: BN, direction: PositionDirection, market: Market): Market;
|
package/lib/math/market.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.calculateMarkPrice = void 0;
|
|
3
|
+
exports.calculateNewMarketAfterTrade = exports.calculateMarkPrice = void 0;
|
|
4
4
|
const amm_1 = require("./amm");
|
|
5
5
|
/**
|
|
6
6
|
* Calculates market mark price
|
|
@@ -9,6 +9,16 @@ const amm_1 = require("./amm");
|
|
|
9
9
|
* @return markPrice : Precision MARK_PRICE_PRECISION
|
|
10
10
|
*/
|
|
11
11
|
function calculateMarkPrice(market) {
|
|
12
|
-
return
|
|
12
|
+
return amm_1.calculatePrice(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
|
|
13
13
|
}
|
|
14
14
|
exports.calculateMarkPrice = calculateMarkPrice;
|
|
15
|
+
function calculateNewMarketAfterTrade(baseAssetAmount, direction, market) {
|
|
16
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', baseAssetAmount.abs(), 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;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isOrderRiskIncreasing = void 0;
|
|
4
|
+
const types_1 = require("../types");
|
|
5
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
|
+
function isOrderRiskIncreasing(user, order) {
|
|
7
|
+
if (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) && 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
|
+
types_1.isVariant(order.direction, 'short')) {
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
// if order will flip position
|
|
26
|
+
if (position.baseAssetAmount.abs().gt(order.baseAssetAmountFilled)) {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.isOrderRiskIncreasing = isOrderRiskIncreasing;
|
package/lib/math/position.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import BN from 'bn.js';
|
|
2
|
-
import { Market, UserPosition } from '../types';
|
|
2
|
+
import { Market, PositionDirection, UserPosition } from '../types';
|
|
3
3
|
/**
|
|
4
4
|
* calculateBaseAssetValue
|
|
5
5
|
* = market value of closing entire position
|
|
@@ -30,4 +30,6 @@ export declare function calculatePositionFundingPNL(market: Market, marketPositi
|
|
|
30
30
|
* @returns Precision: MARK_PRICE_PRECISION (10^10)
|
|
31
31
|
*/
|
|
32
32
|
export declare function calculateEntryPrice(userPosition: UserPosition): BN;
|
|
33
|
-
|
|
33
|
+
export declare function findDirectionToClose(userPosition: UserPosition): PositionDirection;
|
|
34
|
+
export declare function positionCurrentDirection(userPosition: UserPosition): PositionDirection;
|
|
35
|
+
export declare function isEmptyPosition(userPosition: UserPosition): boolean;
|
package/lib/math/position.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.calculateEntryPrice = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
|
|
6
|
+
exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateEntryPrice = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
|
|
7
7
|
const bn_js_1 = __importDefault(require("bn.js"));
|
|
8
8
|
const numericConstants_1 = require("../constants/numericConstants");
|
|
9
9
|
const types_1 = require("../types");
|
|
@@ -19,10 +19,8 @@ function calculateBaseAssetValue(market, userPosition) {
|
|
|
19
19
|
if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
20
20
|
return numericConstants_1.ZERO;
|
|
21
21
|
}
|
|
22
|
-
const directionToClose = userPosition
|
|
23
|
-
|
|
24
|
-
: types_1.PositionDirection.LONG;
|
|
25
|
-
const [newQuoteAssetReserve, _] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', userPosition.baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', directionToClose));
|
|
22
|
+
const directionToClose = findDirectionToClose(userPosition);
|
|
23
|
+
const [newQuoteAssetReserve, _] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
|
|
26
24
|
switch (directionToClose) {
|
|
27
25
|
case types_1.PositionDirection.SHORT:
|
|
28
26
|
return market.amm.quoteAssetReserve
|
|
@@ -106,3 +104,19 @@ function calculateEntryPrice(userPosition) {
|
|
|
106
104
|
.abs();
|
|
107
105
|
}
|
|
108
106
|
exports.calculateEntryPrice = calculateEntryPrice;
|
|
107
|
+
function findDirectionToClose(userPosition) {
|
|
108
|
+
return userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
|
|
109
|
+
? types_1.PositionDirection.SHORT
|
|
110
|
+
: types_1.PositionDirection.LONG;
|
|
111
|
+
}
|
|
112
|
+
exports.findDirectionToClose = findDirectionToClose;
|
|
113
|
+
function positionCurrentDirection(userPosition) {
|
|
114
|
+
return userPosition.baseAssetAmount.gte(numericConstants_1.ZERO)
|
|
115
|
+
? types_1.PositionDirection.LONG
|
|
116
|
+
: types_1.PositionDirection.SHORT;
|
|
117
|
+
}
|
|
118
|
+
exports.positionCurrentDirection = positionCurrentDirection;
|
|
119
|
+
function isEmptyPosition(userPosition) {
|
|
120
|
+
return (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && userPosition.openOrders.eq(numericConstants_1.ZERO));
|
|
121
|
+
}
|
|
122
|
+
exports.isEmptyPosition = isEmptyPosition;
|
package/lib/math/trade.d.ts
CHANGED
|
@@ -45,4 +45,3 @@ export declare function calculateTradeAcquiredAmounts(direction: PositionDirecti
|
|
|
45
45
|
* ]
|
|
46
46
|
*/
|
|
47
47
|
export declare function calculateTargetPriceTrade(market: Market, targetPrice: BN, pct?: BN, outputAssetType?: AssetType): [PositionDirection, BN, BN, BN];
|
|
48
|
-
//# sourceMappingURL=trade.d.ts.map
|
package/lib/math/trade.js
CHANGED
|
@@ -25,18 +25,18 @@ const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
|
|
|
25
25
|
* 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
|
|
26
26
|
*/
|
|
27
27
|
function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote') {
|
|
28
|
-
const oldPrice =
|
|
28
|
+
const oldPrice = market_1.calculateMarkPrice(market);
|
|
29
29
|
if (amount.eq(numericConstants_1.ZERO)) {
|
|
30
30
|
return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
|
|
31
31
|
}
|
|
32
32
|
const [acquiredBase, acquiredQuote] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType);
|
|
33
|
-
const entryPrice =
|
|
34
|
-
const newPrice =
|
|
33
|
+
const entryPrice = amm_1.calculatePrice(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
|
|
34
|
+
const newPrice = amm_1.calculatePrice(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
|
|
35
35
|
if (direction == types_1.PositionDirection.SHORT) {
|
|
36
|
-
|
|
36
|
+
assert_1.assert(newPrice.lt(oldPrice));
|
|
37
37
|
}
|
|
38
38
|
else {
|
|
39
|
-
|
|
39
|
+
assert_1.assert(oldPrice.lt(newPrice));
|
|
40
40
|
}
|
|
41
41
|
const pctMaxSlippage = newPrice
|
|
42
42
|
.sub(oldPrice)
|
|
@@ -64,7 +64,7 @@ function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType
|
|
|
64
64
|
if (amount.eq(numericConstants_1.ZERO)) {
|
|
65
65
|
return [numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
66
66
|
}
|
|
67
|
-
const [newQuoteAssetReserve, newBaseAssetReserve] =
|
|
67
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, inputAssetType, amount, amm_1.getSwapDirection(inputAssetType, direction));
|
|
68
68
|
const acquiredBase = market.amm.baseAssetReserve.sub(newBaseAssetReserve);
|
|
69
69
|
const acquiredQuote = market.amm.quoteAssetReserve.sub(newQuoteAssetReserve);
|
|
70
70
|
return [acquiredBase, acquiredQuote];
|
|
@@ -86,10 +86,10 @@ exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
|
|
|
86
86
|
* ]
|
|
87
87
|
*/
|
|
88
88
|
function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote') {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
const markPriceBefore =
|
|
89
|
+
assert_1.assert(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
|
|
90
|
+
assert_1.assert(targetPrice.gt(numericConstants_1.ZERO));
|
|
91
|
+
assert_1.assert(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
|
|
92
|
+
const markPriceBefore = market_1.calculateMarkPrice(market);
|
|
93
93
|
if (targetPrice.gt(markPriceBefore)) {
|
|
94
94
|
const priceGap = targetPrice.sub(markPriceBefore);
|
|
95
95
|
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
|
|
@@ -114,11 +114,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
|
|
|
114
114
|
let markPriceAfter;
|
|
115
115
|
if (markPriceBefore.gt(targetPrice)) {
|
|
116
116
|
// overestimate y2
|
|
117
|
-
baseAssetReserveAfter =
|
|
117
|
+
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
|
|
118
118
|
quoteAssetReserveAfter = k
|
|
119
119
|
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
120
120
|
.div(baseAssetReserveAfter);
|
|
121
|
-
markPriceAfter =
|
|
121
|
+
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
122
122
|
direction = types_1.PositionDirection.SHORT;
|
|
123
123
|
tradeSize = quoteAssetReserveBefore
|
|
124
124
|
.sub(quoteAssetReserveAfter)
|
|
@@ -129,11 +129,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
|
|
|
129
129
|
}
|
|
130
130
|
else if (markPriceBefore.lt(targetPrice)) {
|
|
131
131
|
// underestimate y2
|
|
132
|
-
baseAssetReserveAfter =
|
|
132
|
+
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
|
|
133
133
|
quoteAssetReserveAfter = k
|
|
134
134
|
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
135
135
|
.div(baseAssetReserveAfter);
|
|
136
|
-
markPriceAfter =
|
|
136
|
+
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
137
137
|
direction = types_1.PositionDirection.LONG;
|
|
138
138
|
tradeSize = quoteAssetReserveAfter
|
|
139
139
|
.sub(quoteAssetReserveBefore)
|
|
@@ -160,8 +160,8 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
|
|
|
160
160
|
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
161
161
|
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
162
162
|
.div(baseSize.abs());
|
|
163
|
-
|
|
164
|
-
|
|
163
|
+
assert_1.assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
|
|
164
|
+
assert_1.assert(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
|
|
165
165
|
tp2.toString() +
|
|
166
166
|
'>=' +
|
|
167
167
|
tp1.toString() +
|
package/lib/math/utils.d.ts
CHANGED
package/lib/mockUSDCFaucet.d.ts
CHANGED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
2
|
+
import { OrderParams, OrderTriggerCondition, PositionDirection } from './types';
|
|
3
|
+
import { BN } from '@project-serum/anchor';
|
|
4
|
+
export declare function getLimitOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, price: BN, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean): OrderParams;
|
|
5
|
+
export declare function getStopOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, triggerPrice: BN, triggerCondition: OrderTriggerCondition, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean): OrderParams;
|
|
6
|
+
export declare function getStopLimitOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, price: BN, triggerPrice: BN, triggerCondition: OrderTriggerCondition, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean): OrderParams;
|
|
7
|
+
export declare function getMarketOrderParams(marketIndex: BN, direction: PositionDirection, quoteAssetAmount: BN, baseAssetAmount: BN, reduceOnly: boolean, price?: BN, discountToken?: boolean, referrer?: boolean): OrderParams;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getMarketOrderParams = exports.getStopLimitOrderParams = exports.getStopOrderParams = exports.getLimitOrderParams = void 0;
|
|
4
|
+
const types_1 = require("./types");
|
|
5
|
+
const numericConstants_1 = require("./constants/numericConstants");
|
|
6
|
+
function getLimitOrderParams(marketIndex, direction, baseAssetAmount, price, reduceOnly, discountToken = false, referrer = false) {
|
|
7
|
+
return {
|
|
8
|
+
orderType: types_1.OrderType.LIMIT,
|
|
9
|
+
marketIndex,
|
|
10
|
+
direction,
|
|
11
|
+
quoteAssetAmount: numericConstants_1.ZERO,
|
|
12
|
+
baseAssetAmount,
|
|
13
|
+
price,
|
|
14
|
+
reduceOnly,
|
|
15
|
+
postOnly: false,
|
|
16
|
+
immediateOrCancel: false,
|
|
17
|
+
optionalAccounts: {
|
|
18
|
+
discountToken,
|
|
19
|
+
referrer,
|
|
20
|
+
},
|
|
21
|
+
triggerCondition: types_1.OrderTriggerCondition.ABOVE,
|
|
22
|
+
triggerPrice: numericConstants_1.ZERO,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
exports.getLimitOrderParams = getLimitOrderParams;
|
|
26
|
+
function getStopOrderParams(marketIndex, direction, baseAssetAmount, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false) {
|
|
27
|
+
return {
|
|
28
|
+
orderType: types_1.OrderType.STOP,
|
|
29
|
+
marketIndex,
|
|
30
|
+
direction,
|
|
31
|
+
quoteAssetAmount: numericConstants_1.ZERO,
|
|
32
|
+
baseAssetAmount,
|
|
33
|
+
price: numericConstants_1.ZERO,
|
|
34
|
+
reduceOnly,
|
|
35
|
+
postOnly: false,
|
|
36
|
+
immediateOrCancel: false,
|
|
37
|
+
optionalAccounts: {
|
|
38
|
+
discountToken,
|
|
39
|
+
referrer,
|
|
40
|
+
},
|
|
41
|
+
triggerCondition,
|
|
42
|
+
triggerPrice,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
exports.getStopOrderParams = getStopOrderParams;
|
|
46
|
+
function getStopLimitOrderParams(marketIndex, direction, baseAssetAmount, price, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false) {
|
|
47
|
+
return {
|
|
48
|
+
orderType: types_1.OrderType.STOP_LIMIT,
|
|
49
|
+
marketIndex,
|
|
50
|
+
direction,
|
|
51
|
+
quoteAssetAmount: numericConstants_1.ZERO,
|
|
52
|
+
baseAssetAmount,
|
|
53
|
+
price,
|
|
54
|
+
reduceOnly,
|
|
55
|
+
postOnly: false,
|
|
56
|
+
immediateOrCancel: false,
|
|
57
|
+
optionalAccounts: {
|
|
58
|
+
discountToken,
|
|
59
|
+
referrer,
|
|
60
|
+
},
|
|
61
|
+
triggerCondition,
|
|
62
|
+
triggerPrice,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
exports.getStopLimitOrderParams = getStopLimitOrderParams;
|
|
66
|
+
function getMarketOrderParams(marketIndex, direction, quoteAssetAmount, baseAssetAmount, reduceOnly, price = numericConstants_1.ZERO, discountToken = false, referrer = false) {
|
|
67
|
+
if (baseAssetAmount.eq(numericConstants_1.ZERO) && quoteAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
68
|
+
throw Error('baseAssetAmount or quoteAssetAmount must be zero');
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
orderType: types_1.OrderType.MARKET,
|
|
72
|
+
marketIndex,
|
|
73
|
+
direction,
|
|
74
|
+
quoteAssetAmount,
|
|
75
|
+
baseAssetAmount,
|
|
76
|
+
price,
|
|
77
|
+
reduceOnly,
|
|
78
|
+
postOnly: false,
|
|
79
|
+
immediateOrCancel: false,
|
|
80
|
+
optionalAccounts: {
|
|
81
|
+
discountToken,
|
|
82
|
+
referrer,
|
|
83
|
+
},
|
|
84
|
+
triggerCondition: types_1.OrderTriggerCondition.ABOVE,
|
|
85
|
+
triggerPrice: numericConstants_1.ZERO,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
exports.getMarketOrderParams = getMarketOrderParams;
|
package/lib/orders.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { Market, Order, UserAccount, UserPosition } from './types';
|
|
2
|
+
import BN from 'bn.js';
|
|
3
|
+
export declare function calculateNewStateAfterOrder(userAccount: UserAccount, userPosition: UserPosition, market: Market, order: Order): [UserAccount, UserPosition, Market] | null;
|
|
4
|
+
export declare function calculateAmountToTradeForLimit(market: Market, order: Order): BN;
|
|
5
|
+
export declare function calculateAmountToTradeForStopLimit(market: Market, order: Order): BN;
|