@yuants/vendor-hyperliquid 0.6.0 → 0.6.2
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/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/services/account-actions-with-credential.js +7 -93
- package/dist/services/account-actions-with-credential.js.map +1 -1
- package/dist/services/accounts/perp.js +44 -47
- package/dist/services/accounts/perp.js.map +1 -1
- package/dist/services/accounts/spot.js +36 -0
- package/dist/services/accounts/spot.js.map +1 -0
- package/dist/services/legacy.js +63 -0
- package/dist/services/legacy.js.map +1 -0
- package/dist/services/orders/submitOrder.js +1 -1
- package/dist/services/orders/submitOrder.js.map +1 -1
- package/dist/utils.js +17 -26
- package/dist/utils.js.map +1 -1
- package/lib/index.d.ts +5 -2
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +5 -3
- package/lib/index.js.map +1 -1
- package/lib/services/account-actions-with-credential.js +8 -94
- package/lib/services/account-actions-with-credential.js.map +1 -1
- package/lib/services/accounts/perp.d.ts +23 -1
- package/lib/services/accounts/perp.d.ts.map +1 -1
- package/lib/services/accounts/perp.js +44 -46
- package/lib/services/accounts/perp.js.map +1 -1
- package/lib/services/accounts/spot.d.ts +15 -0
- package/lib/services/accounts/spot.d.ts.map +1 -0
- package/lib/services/accounts/spot.js +40 -0
- package/lib/services/accounts/spot.js.map +1 -0
- package/lib/services/legacy.d.ts +2 -0
- package/lib/services/legacy.d.ts.map +1 -0
- package/lib/services/legacy.js +65 -0
- package/lib/services/legacy.js.map +1 -0
- package/lib/services/orders/submitOrder.d.ts.map +1 -1
- package/lib/services/orders/submitOrder.js +1 -1
- package/lib/services/orders/submitOrder.js.map +1 -1
- package/lib/utils.d.ts.map +1 -1
- package/lib/utils.js +17 -26
- package/lib/utils.js.map +1 -1
- package/package.json +11 -19
- package/temp/package-deps.json +22 -20
package/dist/index.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// Import services from new structure
|
|
2
2
|
import './services/account-actions-with-credential';
|
|
3
|
-
import './services/
|
|
4
|
-
import './services/order-actions-with-credential';
|
|
5
|
-
// Import market data services
|
|
3
|
+
import './services/legacy';
|
|
6
4
|
import './services/markets/interest-rate';
|
|
7
5
|
import './services/markets/ohlc';
|
|
8
6
|
import './services/markets/product';
|
|
9
7
|
import './services/markets/quote';
|
|
8
|
+
import './services/order-actions-with-credential';
|
|
9
|
+
import './services/orders/cancelOrder';
|
|
10
|
+
import './services/orders/modifyOrder';
|
|
11
|
+
import './services/orders/submitOrder';
|
|
10
12
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,qCAAqC;AACrC,OAAO,4CAA4C,CAAC;AACpD,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,qCAAqC;AACrC,OAAO,4CAA4C,CAAC;AACpD,OAAO,mBAAmB,CAAC;AAC3B,OAAO,kCAAkC,CAAC;AAC1C,OAAO,yBAAyB,CAAC;AACjC,OAAO,4BAA4B,CAAC;AACpC,OAAO,0BAA0B,CAAC;AAClC,OAAO,0CAA0C,CAAC;AAClD,OAAO,+BAA+B,CAAC;AACvC,OAAO,+BAA+B,CAAC;AACvC,OAAO,+BAA+B,CAAC","sourcesContent":["// Import services from new structure\nimport './services/account-actions-with-credential';\nimport './services/legacy';\nimport './services/markets/interest-rate';\nimport './services/markets/ohlc';\nimport './services/markets/product';\nimport './services/markets/quote';\nimport './services/order-actions-with-credential';\nimport './services/orders/cancelOrder';\nimport './services/orders/modifyOrder';\nimport './services/orders/submitOrder';\n"]}
|
|
@@ -1,95 +1,9 @@
|
|
|
1
1
|
import { provideAccountActionsWithCredential } from '@yuants/data-account';
|
|
2
2
|
import { Terminal } from '@yuants/protocol';
|
|
3
|
-
import {
|
|
4
|
-
import { getUserOpenOrders, getUserPerpetualsAccountSummary, getUserTokenBalances } from '../api/public-api';
|
|
3
|
+
import { formatTime } from '@yuants/utils';
|
|
5
4
|
import { getAddressFromCredential } from '../api/types';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
*/
|
|
9
|
-
const getPerpAccountInfo = async (credential, account_id) => {
|
|
10
|
-
console.info(`[${formatTime(Date.now())}] Getting perp account info for ${account_id}`);
|
|
11
|
-
const summary = await getUserPerpetualsAccountSummary({ user: getAddressFromCredential(credential) });
|
|
12
|
-
const orders = await getUserOpenOrders({ user: getAddressFromCredential(credential) });
|
|
13
|
-
// Map positions
|
|
14
|
-
const positions = summary.assetPositions.map((position) => ({
|
|
15
|
-
position_id: `${position.position.coin}-USD`,
|
|
16
|
-
datasource_id: 'HYPERLIQUID',
|
|
17
|
-
product_id: encodePath('PERPETUAL', `${position.position.coin}-USD`),
|
|
18
|
-
direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',
|
|
19
|
-
volume: Math.abs(+position.position.szi),
|
|
20
|
-
free_volume: Math.abs(+position.position.szi),
|
|
21
|
-
position_price: +position.position.entryPx,
|
|
22
|
-
closable_price: Math.abs(+position.position.positionValue / +position.position.szi || 0),
|
|
23
|
-
floating_profit: +position.position.unrealizedPnl,
|
|
24
|
-
valuation: +position.position.positionValue,
|
|
25
|
-
margin: +position.position.marginUsed,
|
|
26
|
-
}));
|
|
27
|
-
// Map orders
|
|
28
|
-
const mapOrderDirection = (side) => {
|
|
29
|
-
const normalized = side.toUpperCase();
|
|
30
|
-
if (normalized === 'BID' || normalized === 'BUY') {
|
|
31
|
-
return 'OPEN_LONG';
|
|
32
|
-
}
|
|
33
|
-
if (normalized === 'ASK' || normalized === 'SELL') {
|
|
34
|
-
return 'OPEN_SHORT';
|
|
35
|
-
}
|
|
36
|
-
return 'OPEN_LONG';
|
|
37
|
-
};
|
|
38
|
-
const pending_orders = orders.map((order) => {
|
|
39
|
-
var _a, _b;
|
|
40
|
-
return ({
|
|
41
|
-
order_id: `${order.oid}`,
|
|
42
|
-
account_id,
|
|
43
|
-
product_id: encodePath('PERPETUAL', `${(_a = order.coin) === null || _a === void 0 ? void 0 : _a.trim()}-USD`),
|
|
44
|
-
order_type: 'LIMIT',
|
|
45
|
-
order_direction: mapOrderDirection(order.side),
|
|
46
|
-
volume: Number(order.sz) || 0,
|
|
47
|
-
price: Number(order.limitPx) || undefined,
|
|
48
|
-
submit_at: Number((_b = order.timestamp) !== null && _b !== void 0 ? _b : Date.now()),
|
|
49
|
-
});
|
|
50
|
-
});
|
|
51
|
-
return {
|
|
52
|
-
money: {
|
|
53
|
-
currency: 'USDC',
|
|
54
|
-
equity: +summary.crossMarginSummary.accountValue,
|
|
55
|
-
free: +summary.withdrawable,
|
|
56
|
-
},
|
|
57
|
-
positions,
|
|
58
|
-
pending_orders,
|
|
59
|
-
};
|
|
60
|
-
};
|
|
61
|
-
/**
|
|
62
|
-
* Get account info for spot account
|
|
63
|
-
*/
|
|
64
|
-
const getSpotAccountInfo = async (credential, account_id) => {
|
|
65
|
-
console.info(`[${formatTime(Date.now())}] Getting spot account info for ${account_id}`);
|
|
66
|
-
const balances = await getUserTokenBalances({ user: getAddressFromCredential(credential) });
|
|
67
|
-
// Map token balances to positions (using spot as "positions")
|
|
68
|
-
const positions = balances.balances
|
|
69
|
-
.filter((balance) => Number(balance.total) > 0)
|
|
70
|
-
.map((balance) => ({
|
|
71
|
-
position_id: `${balance.coin}`,
|
|
72
|
-
datasource_id: 'HYPERLIQUID',
|
|
73
|
-
product_id: encodePath('SPOT', `${balance.coin}-USDC`),
|
|
74
|
-
direction: 'LONG',
|
|
75
|
-
volume: Number(balance.total),
|
|
76
|
-
free_volume: Number(balance.total) - Number(balance.hold),
|
|
77
|
-
position_price: 1,
|
|
78
|
-
closable_price: 1,
|
|
79
|
-
floating_profit: 0,
|
|
80
|
-
valuation: Number(balance.total),
|
|
81
|
-
margin: 0,
|
|
82
|
-
}));
|
|
83
|
-
return {
|
|
84
|
-
money: {
|
|
85
|
-
currency: 'USDC',
|
|
86
|
-
equity: positions.reduce((sum, pos) => sum + pos.valuation, 0),
|
|
87
|
-
free: positions.reduce((sum, pos) => sum + pos.free_volume, 0),
|
|
88
|
-
},
|
|
89
|
-
positions,
|
|
90
|
-
pending_orders: [], // Spot orders would need separate API call
|
|
91
|
-
};
|
|
92
|
-
};
|
|
5
|
+
import { getPerpAccountInfo } from './accounts/perp';
|
|
6
|
+
import { getSpotAccountInfo } from './accounts/spot';
|
|
93
7
|
provideAccountActionsWithCredential(Terminal.fromNodeEnv(), 'HYPERLIQUID', {
|
|
94
8
|
type: 'object',
|
|
95
9
|
required: ['private_key'],
|
|
@@ -101,19 +15,19 @@ provideAccountActionsWithCredential(Terminal.fromNodeEnv(), 'HYPERLIQUID', {
|
|
|
101
15
|
console.info(`[${formatTime(Date.now())}] Listing accounts for ${getAddressFromCredential(credential)}`);
|
|
102
16
|
return [
|
|
103
17
|
{
|
|
104
|
-
account_id: `hyperliquid/${getAddressFromCredential(credential)}/perp
|
|
18
|
+
account_id: `hyperliquid/${getAddressFromCredential(credential)}/perp`,
|
|
105
19
|
},
|
|
106
20
|
{
|
|
107
|
-
account_id: `hyperliquid/${getAddressFromCredential(credential)}/spot
|
|
21
|
+
account_id: `hyperliquid/${getAddressFromCredential(credential)}/spot`,
|
|
108
22
|
},
|
|
109
23
|
];
|
|
110
24
|
},
|
|
111
25
|
getAccountInfo: async (credential, account_id) => {
|
|
112
26
|
console.info(`[${formatTime(Date.now())}] Getting account info for ${account_id}`);
|
|
113
|
-
if (account_id.endsWith('/perp
|
|
27
|
+
if (account_id.endsWith('/perp')) {
|
|
114
28
|
return getPerpAccountInfo(credential, account_id);
|
|
115
29
|
}
|
|
116
|
-
if (account_id.endsWith('/spot
|
|
30
|
+
if (account_id.endsWith('/spot')) {
|
|
117
31
|
return getSpotAccountInfo(credential, account_id);
|
|
118
32
|
}
|
|
119
33
|
throw new Error(`Unsupported account type for account_id: ${account_id}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account-actions-with-credential.js","sourceRoot":"","sources":["../../src/services/account-actions-with-credential.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,
|
|
1
|
+
{"version":3,"file":"account-actions-with-credential.js","sourceRoot":"","sources":["../../src/services/account-actions-with-credential.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAe,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAErE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,mCAAmC,CACjC,QAAQ,CAAC,WAAW,EAAE,EACtB,aAAa,EACb;IACE,IAAI,EAAE,QAAQ;IACd,QAAQ,EAAE,CAAC,aAAa,CAAC;IACzB,UAAU,EAAE;QACV,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;KAChC;CACF,EACD;IACE,YAAY,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE;QACjC,OAAO,CAAC,IAAI,CACV,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,0BAA0B,wBAAwB,CAAC,UAAU,CAAC,EAAE,CAC3F,CAAC;QACF,OAAO;YACL;gBACE,UAAU,EAAE,eAAe,wBAAwB,CAAC,UAAU,CAAC,OAAO;aACvE;YACD;gBACE,UAAU,EAAE,eAAe,wBAAwB,CAAC,UAAU,CAAC,OAAO;aACvE;SACF,CAAC;IACJ,CAAC;IACD,cAAc,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE;QAC/C,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,8BAA8B,UAAU,EAAE,CAAC,CAAC;QAEnF,IAAI,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;YAChC,OAAO,kBAAkB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;SACnD;QACD,IAAI,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;YAChC,OAAO,kBAAkB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;SACnD;QACD,MAAM,IAAI,KAAK,CAAC,4CAA4C,UAAU,EAAE,CAAC,CAAC;IAC5E,CAAC;CACF,CACF,CAAC","sourcesContent":["import { provideAccountActionsWithCredential } from '@yuants/data-account';\nimport { Terminal } from '@yuants/protocol';\nimport { formatTime } from '@yuants/utils';\nimport { ICredential, getAddressFromCredential } from '../api/types';\n\nimport { getPerpAccountInfo } from './accounts/perp';\nimport { getSpotAccountInfo } from './accounts/spot';\n\nprovideAccountActionsWithCredential<ICredential>(\n Terminal.fromNodeEnv(),\n 'HYPERLIQUID',\n {\n type: 'object',\n required: ['private_key'],\n properties: {\n private_key: { type: 'string' },\n },\n },\n {\n listAccounts: async (credential) => {\n console.info(\n `[${formatTime(Date.now())}] Listing accounts for ${getAddressFromCredential(credential)}`,\n );\n return [\n {\n account_id: `hyperliquid/${getAddressFromCredential(credential)}/perp`,\n },\n {\n account_id: `hyperliquid/${getAddressFromCredential(credential)}/spot`,\n },\n ];\n },\n getAccountInfo: async (credential, account_id) => {\n console.info(`[${formatTime(Date.now())}] Getting account info for ${account_id}`);\n\n if (account_id.endsWith('/perp')) {\n return getPerpAccountInfo(credential, account_id);\n }\n if (account_id.endsWith('/spot')) {\n return getSpotAccountInfo(credential, account_id);\n }\n throw new Error(`Unsupported account type for account_id: ${account_id}`);\n },\n },\n);\n"]}
|
|
@@ -1,55 +1,43 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { providePendingOrdersService } from '@yuants/data-order';
|
|
3
|
-
import { Terminal } from '@yuants/protocol';
|
|
4
|
-
import { encodePath } from '@yuants/utils';
|
|
1
|
+
import { encodePath, formatTime } from '@yuants/utils';
|
|
5
2
|
import { getUserOpenOrders, getUserPerpetualsAccountSummary } from '../../api/public-api';
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
export const
|
|
11
|
-
|
|
12
|
-
const mapPosition = (position) => ({
|
|
13
|
-
position_id: `${position.position.coin}-USD`,
|
|
14
|
-
datasource_id: 'HYPERLIQUID',
|
|
15
|
-
product_id: encodePath('PERPETUAL', `${position.position.coin}-USD`),
|
|
16
|
-
direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',
|
|
17
|
-
volume: Math.abs(+position.position.szi),
|
|
18
|
-
free_volume: Math.abs(+position.position.szi),
|
|
19
|
-
position_price: +position.position.entryPx,
|
|
20
|
-
closable_price: Math.abs(+position.position.positionValue / +position.position.szi || 0),
|
|
21
|
-
floating_profit: +position.position.unrealizedPnl,
|
|
22
|
-
valuation: +position.position.positionValue,
|
|
23
|
-
margin: +position.position.marginUsed,
|
|
24
|
-
});
|
|
25
|
-
provideAccountInfoService(terminal, defaultPerpAccountId, async () => {
|
|
3
|
+
import { getAddressFromCredential } from '../../api/types';
|
|
4
|
+
/**
|
|
5
|
+
* Get account info for perpetual account
|
|
6
|
+
*/
|
|
7
|
+
export const getPerpAccountInfo = async (credential, account_id) => {
|
|
8
|
+
console.info(`[${formatTime(Date.now())}] Getting perp account info for ${account_id}`);
|
|
26
9
|
const summary = await getUserPerpetualsAccountSummary({ user: getAddressFromCredential(credential) });
|
|
27
|
-
return {
|
|
28
|
-
money: {
|
|
29
|
-
currency: 'USDC',
|
|
30
|
-
equity: +summary.crossMarginSummary.accountValue,
|
|
31
|
-
free: +summary.withdrawable,
|
|
32
|
-
},
|
|
33
|
-
positions: summary.assetPositions.map(mapPosition),
|
|
34
|
-
};
|
|
35
|
-
}, { auto_refresh_interval: 1000 });
|
|
36
|
-
const mapOrderDirection = (side) => {
|
|
37
|
-
const normalized = side.toUpperCase();
|
|
38
|
-
if (normalized === 'BID' || normalized === 'BUY') {
|
|
39
|
-
return 'OPEN_LONG';
|
|
40
|
-
}
|
|
41
|
-
if (normalized === 'ASK' || normalized === 'SELL') {
|
|
42
|
-
return 'OPEN_SHORT';
|
|
43
|
-
}
|
|
44
|
-
return 'OPEN_LONG';
|
|
45
|
-
};
|
|
46
|
-
providePendingOrdersService(terminal, defaultPerpAccountId, async () => {
|
|
47
10
|
const orders = await getUserOpenOrders({ user: getAddressFromCredential(credential) });
|
|
48
|
-
|
|
11
|
+
// Map positions
|
|
12
|
+
const positions = summary.assetPositions.map((position) => ({
|
|
13
|
+
position_id: `${position.position.coin}-USD`,
|
|
14
|
+
datasource_id: 'HYPERLIQUID',
|
|
15
|
+
product_id: encodePath('PERPETUAL', `${position.position.coin}-USD`),
|
|
16
|
+
direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',
|
|
17
|
+
volume: Math.abs(+position.position.szi),
|
|
18
|
+
free_volume: Math.abs(+position.position.szi),
|
|
19
|
+
position_price: +position.position.entryPx,
|
|
20
|
+
closable_price: Math.abs(+position.position.positionValue / +position.position.szi || 0),
|
|
21
|
+
floating_profit: +position.position.unrealizedPnl,
|
|
22
|
+
valuation: +position.position.positionValue,
|
|
23
|
+
margin: +position.position.marginUsed,
|
|
24
|
+
}));
|
|
25
|
+
// Map orders
|
|
26
|
+
const mapOrderDirection = (side) => {
|
|
27
|
+
const normalized = side.toUpperCase();
|
|
28
|
+
if (normalized === 'BID' || normalized === 'BUY') {
|
|
29
|
+
return 'OPEN_LONG';
|
|
30
|
+
}
|
|
31
|
+
if (normalized === 'ASK' || normalized === 'SELL') {
|
|
32
|
+
return 'OPEN_SHORT';
|
|
33
|
+
}
|
|
34
|
+
return 'OPEN_LONG';
|
|
35
|
+
};
|
|
36
|
+
const pending_orders = orders.map((order) => {
|
|
49
37
|
var _a, _b;
|
|
50
38
|
return ({
|
|
51
39
|
order_id: `${order.oid}`,
|
|
52
|
-
account_id
|
|
40
|
+
account_id,
|
|
53
41
|
product_id: encodePath('PERPETUAL', `${(_a = order.coin) === null || _a === void 0 ? void 0 : _a.trim()}-USD`),
|
|
54
42
|
order_type: 'LIMIT',
|
|
55
43
|
order_direction: mapOrderDirection(order.side),
|
|
@@ -58,5 +46,14 @@ providePendingOrdersService(terminal, defaultPerpAccountId, async () => {
|
|
|
58
46
|
submit_at: Number((_b = order.timestamp) !== null && _b !== void 0 ? _b : Date.now()),
|
|
59
47
|
});
|
|
60
48
|
});
|
|
61
|
-
|
|
49
|
+
return {
|
|
50
|
+
money: {
|
|
51
|
+
currency: 'USD',
|
|
52
|
+
equity: +summary.crossMarginSummary.accountValue,
|
|
53
|
+
free: +summary.withdrawable,
|
|
54
|
+
},
|
|
55
|
+
positions,
|
|
56
|
+
pending_orders,
|
|
57
|
+
};
|
|
58
|
+
};
|
|
62
59
|
//# sourceMappingURL=perp.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"perp.js","sourceRoot":"","sources":["../../../src/services/accounts/perp.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"perp.js","sourceRoot":"","sources":["../../../src/services/accounts/perp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,+BAA+B,EAAE,MAAM,sBAAsB,CAAC;AAC1F,OAAO,EAAE,wBAAwB,EAAe,MAAM,iBAAiB,CAAC;AAExE;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,KAAK,EAAE,UAAuB,EAAE,UAAkB,EAAE,EAAE;IACtF,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,mCAAmC,UAAU,EAAE,CAAC,CAAC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G,CAAC,IAAY,EAAE,EAAE;QACzC,MAAM,UAAU,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACtC,IAAI,UAAU,KAAK,KAAK,IAAI,UAAU,KAAK,KAAK,EAAE;YAChD,OAAO,WAAW,CAAC;SACpB;QACD,IAAI,UAAU,KAAK,KAAK,IAAI,UAAU,KAAK,MAAM,EAAE;YACjD,OAAO,YAAY,CAAC;SACrB;QACD,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC;IAEF,MAAM,cAAc,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;;QAAC,OAAA,CAAC;YAC5C,QAAQ,EAAE,GAAG,KAAK,CAAC,GAAG,EAAE;YACxB,UAAU;YACV,UAAU,EAAE,UAAU,CAAC,WAAW,EAAE,GAAG,MAAA,KAAK,CAAC,IAAI,0CAAE,IAAI,EAAE,MAAM,CAAC;YAChE,UAAU,EAAE,OAAO;YACnB,eAAe,EAAE,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC;YAC9C,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,CAAC;YAC7B,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,SAAS;YACzC,SAAS,EAAE,MAAM,CAAC,MAAA,KAAK,CAAC,SAAS,mCAAI,IAAI,CAAC,GAAG,EAAE,CAAC;SACjD,CAAC,CAAA;KAAA,CAAC,CAAC;IAEJ,OAAO;QACL,KAAK,EAAE;YACL,QAAQ,EAAE,KAAK;YACf,MAAM,EAAE,CAAC,OAAO,CAAC,kBAAkB,CAAC,YAAY;YAChD,IAAI,EAAE,CAAC,OAAO,CAAC,YAAY;SAC5B;QACD,SAAS;QACT,cAAc;KACf,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { IPosition } from '@yuants/data-account';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { getUserOpenOrders, getUserPerpetualsAccountSummary } from '../../api/public-api';\nimport { getAddressFromCredential, ICredential } from '../../api/types';\n\n/**\n * Get account info for perpetual account\n */\nexport const getPerpAccountInfo = async (credential: ICredential, account_id: string) => {\n console.info(`[${formatTime(Date.now())}] Getting perp account info for ${account_id}`);\n\n const summary = await getUserPerpetualsAccountSummary({ user: getAddressFromCredential(credential) });\n const orders = await getUserOpenOrders({ user: getAddressFromCredential(credential) });\n\n // Map positions\n const positions = summary.assetPositions.map(\n (position): IPosition => ({\n position_id: `${position.position.coin}-USD`,\n datasource_id: 'HYPERLIQUID',\n product_id: encodePath('PERPETUAL', `${position.position.coin}-USD`),\n direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',\n volume: Math.abs(+position.position.szi),\n free_volume: Math.abs(+position.position.szi),\n position_price: +position.position.entryPx,\n closable_price: Math.abs(+position.position.positionValue / +position.position.szi || 0),\n floating_profit: +position.position.unrealizedPnl,\n valuation: +position.position.positionValue,\n margin: +position.position.marginUsed,\n }),\n );\n\n // Map orders\n const mapOrderDirection = (side: string) => {\n const normalized = side.toUpperCase();\n if (normalized === 'BID' || normalized === 'BUY') {\n return 'OPEN_LONG';\n }\n if (normalized === 'ASK' || normalized === 'SELL') {\n return 'OPEN_SHORT';\n }\n return 'OPEN_LONG';\n };\n\n const pending_orders = orders.map((order) => ({\n order_id: `${order.oid}`,\n account_id,\n product_id: encodePath('PERPETUAL', `${order.coin?.trim()}-USD`),\n order_type: 'LIMIT',\n order_direction: mapOrderDirection(order.side),\n volume: Number(order.sz) || 0,\n price: Number(order.limitPx) || undefined,\n submit_at: Number(order.timestamp ?? Date.now()),\n }));\n\n return {\n money: {\n currency: 'USD',\n equity: +summary.crossMarginSummary.accountValue,\n free: +summary.withdrawable,\n },\n positions,\n pending_orders,\n };\n};\n"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { encodePath, formatTime } from '@yuants/utils';
|
|
2
|
+
import { getUserTokenBalances } from '../../api/public-api';
|
|
3
|
+
import { getAddressFromCredential } from '../../api/types';
|
|
4
|
+
/**
|
|
5
|
+
* Get account info for spot account
|
|
6
|
+
*/
|
|
7
|
+
export const getSpotAccountInfo = async (credential, account_id) => {
|
|
8
|
+
console.info(`[${formatTime(Date.now())}] Getting spot account info for ${account_id}`);
|
|
9
|
+
const balances = await getUserTokenBalances({ user: getAddressFromCredential(credential) });
|
|
10
|
+
// Map token balances to positions (using spot as "positions")
|
|
11
|
+
const positions = balances.balances
|
|
12
|
+
.filter((balance) => Number(balance.total) > 0)
|
|
13
|
+
.map((balance) => ({
|
|
14
|
+
position_id: `${balance.coin}`,
|
|
15
|
+
datasource_id: 'HYPERLIQUID',
|
|
16
|
+
product_id: encodePath('SPOT', `${balance.coin}-USDC`),
|
|
17
|
+
direction: 'LONG',
|
|
18
|
+
volume: Number(balance.total),
|
|
19
|
+
free_volume: Number(balance.total) - Number(balance.hold),
|
|
20
|
+
position_price: 1,
|
|
21
|
+
closable_price: 1,
|
|
22
|
+
floating_profit: 0,
|
|
23
|
+
valuation: Number(balance.total),
|
|
24
|
+
margin: 0,
|
|
25
|
+
}));
|
|
26
|
+
return {
|
|
27
|
+
money: {
|
|
28
|
+
currency: 'USDC',
|
|
29
|
+
equity: positions.reduce((sum, pos) => sum + pos.valuation, 0),
|
|
30
|
+
free: positions.reduce((sum, pos) => sum + pos.free_volume, 0),
|
|
31
|
+
},
|
|
32
|
+
positions,
|
|
33
|
+
pending_orders: [], // Spot orders would need separate API call
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=spot.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spot.js","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,wBAAwB,EAAe,MAAM,iBAAiB,CAAC;AAExE;;GAEG;AACH,MAAM,CAAC,M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CAAC,GAAW,EAAE,GAAQ,EAAE,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC;SAC5E;QACD,SAAS;QACT,cAAc,EAAE,EAAE,EAAE,2CAA2C;KAChE,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { IPosition } from '@yuants/data-account';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { getUserTokenBalances } from '../../api/public-api';\nimport { getAddressFromCredential, ICredential } from '../../api/types';\n\n/**\n * Get account info for spot account\n */\nexport const getSpotAccountInfo = async (credential: ICredential, account_id: string) => {\n console.info(`[${formatTime(Date.now())}] Getting spot account info for ${account_id}`);\n\n const balances = await getUserTokenBalances({ user: getAddressFromCredential(credential) });\n\n // Map token balances to positions (using spot as \"positions\")\n const positions = balances.balances\n .filter((balance: any) => Number(balance.total) > 0)\n .map(\n (balance: any): IPosition => ({\n position_id: `${balance.coin}`,\n datasource_id: 'HYPERLIQUID',\n product_id: encodePath('SPOT', `${balance.coin}-USDC`),\n direction: 'LONG',\n volume: Number(balance.total),\n free_volume: Number(balance.total) - Number(balance.hold),\n position_price: 1, // USDC as quote currency\n closable_price: 1,\n floating_profit: 0,\n valuation: Number(balance.total),\n margin: 0,\n }),\n );\n\n return {\n money: {\n currency: 'USDC',\n equity: positions.reduce((sum: number, pos: any) => sum + pos.valuation, 0),\n free: positions.reduce((sum: number, pos: any) => sum + pos.free_volume, 0),\n },\n positions,\n pending_orders: [], // Spot orders would need separate API call\n };\n};\n"]}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { addAccountMarket, provideAccountInfoService } from '@yuants/data-account';
|
|
2
|
+
import { providePendingOrdersService } from '@yuants/data-order';
|
|
3
|
+
import { Terminal } from '@yuants/protocol';
|
|
4
|
+
import { getAddressFromCredential, getDefaultCredential } from '../api/types';
|
|
5
|
+
import { getPerpAccountInfo } from './accounts/perp';
|
|
6
|
+
import { getSpotAccountInfo } from './accounts/spot';
|
|
7
|
+
import { cancelOrderAction } from './orders/cancelOrder';
|
|
8
|
+
import { submitOrder } from './orders/submitOrder';
|
|
9
|
+
const terminal = Terminal.fromNodeEnv();
|
|
10
|
+
const credential = getDefaultCredential();
|
|
11
|
+
const walletAddress = getAddressFromCredential(credential).toLowerCase();
|
|
12
|
+
const defaultPerpAccountId = `hyperliquid/${walletAddress}/perp`;
|
|
13
|
+
const defaultSpotAccountId = `hyperliquid/${walletAddress}/spot`;
|
|
14
|
+
addAccountMarket(terminal, { account_id: defaultPerpAccountId, market_id: 'HYPERLIQUID/PERP' });
|
|
15
|
+
addAccountMarket(terminal, { account_id: defaultSpotAccountId, market_id: 'HYPERLIQUID/SPOT' });
|
|
16
|
+
provideAccountInfoService(terminal, defaultPerpAccountId, async () => {
|
|
17
|
+
const info = await getPerpAccountInfo(credential, defaultPerpAccountId);
|
|
18
|
+
return {
|
|
19
|
+
money: info.money,
|
|
20
|
+
positions: info.positions,
|
|
21
|
+
orders: info.pending_orders,
|
|
22
|
+
};
|
|
23
|
+
}, { auto_refresh_interval: 1000 });
|
|
24
|
+
providePendingOrdersService(terminal, defaultPerpAccountId, async () => {
|
|
25
|
+
const info = await getPerpAccountInfo(credential, defaultPerpAccountId);
|
|
26
|
+
return info.pending_orders;
|
|
27
|
+
}, { auto_refresh_interval: 2000 });
|
|
28
|
+
provideAccountInfoService(terminal, defaultSpotAccountId, async () => {
|
|
29
|
+
const info = await getSpotAccountInfo(credential, defaultSpotAccountId);
|
|
30
|
+
return {
|
|
31
|
+
money: info.money,
|
|
32
|
+
positions: info.positions,
|
|
33
|
+
};
|
|
34
|
+
}, { auto_refresh_interval: 5000 });
|
|
35
|
+
terminal.server.provideService('SubmitOrder', {
|
|
36
|
+
required: ['account_id', 'product_id', 'order_type', 'order_direction', 'volume'],
|
|
37
|
+
properties: {
|
|
38
|
+
account_id: { const: defaultPerpAccountId },
|
|
39
|
+
},
|
|
40
|
+
}, async (msg) => {
|
|
41
|
+
return {
|
|
42
|
+
res: {
|
|
43
|
+
code: 0,
|
|
44
|
+
message: 'OK',
|
|
45
|
+
data: await submitOrder(credential, msg.req),
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
});
|
|
49
|
+
terminal.server.provideService('CancelOrder', {
|
|
50
|
+
required: ['account_id', 'order_id', 'product_id'],
|
|
51
|
+
properties: {
|
|
52
|
+
account_id: { const: defaultPerpAccountId },
|
|
53
|
+
},
|
|
54
|
+
}, async (msg) => {
|
|
55
|
+
await cancelOrderAction(credential, msg.req);
|
|
56
|
+
return {
|
|
57
|
+
res: {
|
|
58
|
+
code: 0,
|
|
59
|
+
message: 'OK',
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
});
|
|
63
|
+
//# sourceMappingURL=legacy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"legacy.js","sourceRoot":"","sources":["../../src/services/legacy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAU,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEnD,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AACxC,MAAM,UAAU,GAAG,oBAAoB,EAAE,CAAC;AAC1C,MAAM,aAAa,GAAG,wBAAwB,CAAC,UAAU,CAAC,CAAC,WAAW,EAAE,CAAC;AACzE,MAAM,oBAAoB,GAAG,eAAe,aAAa,OAAO,C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AAY,EAAE,YAAY,EAAE,iBAAiB,EAAE,QAAQ,CAAC;IACjF,UAAU,EAAE;QACV,UAAU,EAAE,EAAE,KAAK,EAAE,oBAAoB,EAAE;KAC5C;CACF,EACD,KAAK,EAAE,GAAG,EAAE,EAAE;IACZ,OAAO;QACL,GAAG,EAAE;YACH,IAAI,EAAE,CAAC;YACP,OAAO,EAAE,IAAI;YACb,IAAI,EAAE,MAAM,WAAW,CAAC,UAAU,EAAE,GAAG,CAAC,GAAG,CAAC;SAC7C;KACF,CAAC;AACJ,CAAC,CACF,CAAC;AAEF,QAAQ,CAAC,MAAM,CAAC,cAAc,CAC5B,aAAa,EACb;IACE,QAAQ,EAAE,CAAC,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC;IAClD,UAAU,EAAE;QACV,UAAU,EAAE,EAAE,KAAK,EAAE,oBAAoB,EAAE;KAC5C;CACF,EACD,KAAK,EAAE,GAAG,EAAE,EAAE;IACZ,MAAM,iBAAiB,CAAC,UAAU,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;IAC7C,OAAO;QACL,GAAG,EAAE;YACH,IAAI,EAAE,CAAC;YACP,OAAO,EAAE,IAAI;SACd;KACF,CAAC;AACJ,CAAC,CACF,CAAC","sourcesContent":["import { addAccountMarket, provideAccountInfoService } from '@yuants/data-account';\nimport { IOrder, providePendingOrdersService } from '@yuants/data-order';\nimport { Terminal } from '@yuants/protocol';\nimport { getAddressFromCredential, getDefaultCredential } from '../api/types';\nimport { getPerpAccountInfo } from './accounts/perp';\nimport { getSpotAccountInfo } from './accounts/spot';\nimport { cancelOrderAction } from './orders/cancelOrder';\nimport { submitOrder } from './orders/submitOrder';\n\nconst terminal = Terminal.fromNodeEnv();\nconst credential = getDefaultCredential();\nconst walletAddress = getAddressFromCredential(credential).toLowerCase();\nconst defaultPerpAccountId = `hyperliquid/${walletAddress}/perp`;\nconst defaultSpotAccountId = `hyperliquid/${walletAddress}/spot`;\n\naddAccountMarket(terminal, { account_id: defaultPerpAccountId, market_id: 'HYPERLIQUID/PERP' });\naddAccountMarket(terminal, { account_id: defaultSpotAccountId, market_id: 'HYPERLIQUID/SPOT' });\n\nprovideAccountInfoService(\n terminal,\n defaultPerpAccountId,\n async () => {\n const info = await getPerpAccountInfo(credential, defaultPerpAccountId);\n return {\n money: info.money,\n positions: info.positions,\n orders: info.pending_orders,\n };\n },\n { auto_refresh_interval: 1000 },\n);\n\nprovidePendingOrdersService(\n terminal,\n defaultPerpAccountId,\n async () => {\n const info = await getPerpAccountInfo(credential, defaultPerpAccountId);\n return info.pending_orders;\n },\n { auto_refresh_interval: 2000 },\n);\n\nprovideAccountInfoService(\n terminal,\n defaultSpotAccountId,\n async () => {\n const info = await getSpotAccountInfo(credential, defaultSpotAccountId);\n return {\n money: info.money,\n positions: info.positions,\n };\n },\n { auto_refresh_interval: 5000 },\n);\n\nterminal.server.provideService<IOrder, { order_id?: string }>(\n 'SubmitOrder',\n {\n required: ['account_id', 'product_id', 'order_type', 'order_direction', 'volume'],\n properties: {\n account_id: { const: defaultPerpAccountId },\n },\n },\n async (msg) => {\n return {\n res: {\n code: 0,\n message: 'OK',\n data: await submitOrder(credential, msg.req),\n },\n };\n },\n);\n\nterminal.server.provideService<IOrder>(\n 'CancelOrder',\n {\n required: ['account_id', 'order_id', 'product_id'],\n properties: {\n account_id: { const: defaultPerpAccountId },\n },\n },\n async (msg) => {\n await cancelOrderAction(credential, msg.req);\n return {\n res: {\n code: 0,\n message: 'OK',\n },\n };\n },\n);\n"]}
|
|
@@ -6,7 +6,7 @@ export const submitOrder = async (credential, order) => {
|
|
|
6
6
|
const res = await placeOrder(credential, { orders: [orderParams] });
|
|
7
7
|
const status = (_c = (_b = (_a = res === null || res === void 0 ? void 0 : res.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.statuses) === null || _c === void 0 ? void 0 : _c[0];
|
|
8
8
|
const orderId = (_h = (_g = (_e = (_d = status === null || status === void 0 ? void 0 : status.resting) === null || _d === void 0 ? void 0 : _d.oid) !== null && _e !== void 0 ? _e : (_f = status === null || status === void 0 ? void 0 : status.filled) === null || _f === void 0 ? void 0 : _f.oid) !== null && _g !== void 0 ? _g : status === null || status === void 0 ? void 0 : status.oid) !== null && _h !== void 0 ? _h : status === null || status === void 0 ? void 0 : status.orderId;
|
|
9
|
-
const error = (res === null || res === void 0 ? void 0 : res.status) !== 'ok' ?
|
|
9
|
+
const error = (res === null || res === void 0 ? void 0 : res.status) !== 'ok' ? `API ERROR: ${JSON.stringify(res)}` : (status === null || status === void 0 ? void 0 : status.error) ? status.error : undefined;
|
|
10
10
|
if (error)
|
|
11
11
|
throw new Error(error);
|
|
12
12
|
if (orderId === undefined)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAiC,EAAE;;IACzG,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,iBAAiB,CAAC,KAAK,CAAC,CAAC;IACvD,MAAM,GAAG,GAAG,MAAM,UAAU,CAAC,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IACpE,MAAM,MAAM,GAAG,MAAA,MAAA,MAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,QAAQ,0CAAE,IAAI,0CAAE,QAAQ,0CAAG,CAAC,CAAC,CAAC;IAClD,MAAM,OAAO,GACX,MAAA,MAAA,MAAA,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,0CAAE,GAAG,mCAAI,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,0CAAE,GAAG,mCAAK,MAA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AAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACxG,IAAI,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;IAClC,IAAI,OAAO,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IAC5E,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,EAAE,CAAC;AACpC,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { placeOrder } from '../../api/private-api';\nimport { ICredential } from '../../api/types';\nimport { buildOrderPayload } from '../../utils';\n\nexport const submitOrder = async (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const { orderParams } = await buildOrderPayload(order);\n const res = await placeOrder(credential, { orders: [orderParams] });\n const status = res?.response?.data?.statuses?.[0];\n const orderId =\n status?.resting?.oid ?? status?.filled?.oid ?? (status as any)?.oid ?? (status as any)?.orderId;\n const error =\n res?.status !== 'ok' ? `API ERROR: ${JSON.stringify(res)}` : status?.error ? status.error : undefined;\n if (error) throw new Error(error);\n if (orderId === undefined) throw new Error('No order ID returned from API');\n return { order_id: `${orderId}` };\n};\n"]}
|
package/dist/utils.js
CHANGED
|
@@ -49,42 +49,33 @@ export const resolveAssetInfo = async (product_id) => {
|
|
|
49
49
|
throw new Error(`Unsupported instrument type: ${instType}`);
|
|
50
50
|
};
|
|
51
51
|
export const roundPrice = (price, instType, szDecimals) => {
|
|
52
|
-
var _a, _b;
|
|
53
52
|
const MAX_DECIMALS = instType === 'PERPETUAL' ? 6 : 8;
|
|
54
53
|
const maxDecimalPlaces = Math.max(0, MAX_DECIMALS - szDecimals);
|
|
55
54
|
if (!Number.isFinite(price)) {
|
|
56
55
|
throw new Error(`Invalid price: ${price}`);
|
|
57
56
|
}
|
|
58
|
-
|
|
59
|
-
return price.toString();
|
|
60
|
-
}
|
|
57
|
+
// Handle significant figures (max 5)
|
|
61
58
|
const priceStr = price.toString();
|
|
62
59
|
const significantFigures = priceStr.replace(/^0+\.?0*/, '').replace(/\./g, '').length;
|
|
63
60
|
let roundedPrice = price;
|
|
64
61
|
if (significantFigures > 5) {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const leadingZeros = (_b = (_a = afterDecimal.match(/^0*/)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
|
|
81
|
-
const precision = leadingZeros + 5;
|
|
82
|
-
roundedPrice = parseFloat(price.toFixed(precision));
|
|
83
|
-
}
|
|
84
|
-
}
|
|
62
|
+
// Logic to round to 5 sig figs
|
|
63
|
+
// This is complex to do perfectly with just numbers, but let's try to be safe
|
|
64
|
+
const magnitude = Math.floor(Math.log10(Math.abs(price)));
|
|
65
|
+
// We want 5 sig figs.
|
|
66
|
+
// e.g. 123456 -> 123460 (mag 5, round to 10^(5-4)=10^1)
|
|
67
|
+
// e.g. 0.00123456 -> 0.0012346 (mag -3, round to 10^(-3-4)=10^-7)
|
|
68
|
+
const factor = Math.pow(10, magnitude - 4);
|
|
69
|
+
roundedPrice = Math.round(price / factor) * factor;
|
|
70
|
+
}
|
|
71
|
+
// Now format to maxDecimalPlaces without scientific notation
|
|
72
|
+
// Use toFixed which returns fixed point notation
|
|
73
|
+
let s = roundedPrice.toFixed(maxDecimalPlaces);
|
|
74
|
+
// Remove trailing zeros and decimal point if integer
|
|
75
|
+
if (s.includes('.')) {
|
|
76
|
+
s = s.replace(/\.?0+$/, '');
|
|
85
77
|
}
|
|
86
|
-
|
|
87
|
-
return finalPrice.toString();
|
|
78
|
+
return s;
|
|
88
79
|
};
|
|
89
80
|
const resolvePrice = async (order, instType, szDecimals, baseCurrency) => {
|
|
90
81
|
if (order.order_type === 'MARKET') {
|
package/dist/utils.js.map
CHANG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C,CAAC,CAAC,KAAK,CAAC;IACjG,OAAO;QACL,SAAS;QACT,WAAW,EAAE;YACX,CAAC,EAAE,SAAS,CAAC,OAAO;YACpB,CAAC,EAAE,KAAK;YACR,CAAC,EAAE,GAAG,KAAK,EAAE;YACb,CAAC,EAAE,GAAG,KAAK,CAAC,MAAM,EAAE;YACpB,CAAC,EAAE,UAAU;YACb,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,EAAE;SACtB;KACF,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,uBAAuB,GAAG,KAAK,EAAE,IAAY,EAAE,KAAc,EAAE,EAAE;IAC5E,MAAM,IAAI,GAAG,CAAC,MAAM,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,CAAE,CAAC;IAClD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAE,CAAC;IAC5B,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IACrC,OAAO,GAAG,GAAG,QAAQ,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IOrder } from '@yuants/data-order';\nimport { decodePath } from '@yuants/utils';\nimport { getAllMids, getPerpetualsMetaData, getSpotMetaData } from './api/public-api';\n\nconst enum InstrumentType {\n PERPETUAL = 'PERPETUAL',\n SPOT = 'SPOT',\n}\n\ntype AssetInfo = { assetId: number; szDecimals: number; instType: InstrumentType; baseCurrency: string };\n\nconst CACHE_TTL = 60_000;\nconst MID_TTL = 5_000;\n\n// Create caches using createCache utility\nconst perpMetaCache = createCache<Map<string, { assetId: number; szDecimals: number }>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing perpetual metadata cache`);\n const meta = await getPerpetualsMetaData();\n const map = new Map<string, { assetId: number; szDecimals: number }>();\n meta.universe.forEach((token, index) =>\n map.set(token.name, { assetId: index, szDecimals: token.szDecimals }),\n );\n return map;\n },\n { expire: CACHE_TTL },\n);\n\nconst spotMetaCache = createCache<Map<string, { assetId: number; szDecimals: number }>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing spot metadata cache`);\n const meta = await getSpotMetaData();\n const map = new Map<string, { assetId: number; szDecimals: number }>();\n meta.tokens.forEach((token) =>\n map.set(token.name, { assetId: token.index, szDecimals: token.szDecimals }),\n );\n return map;\n },\n { expire: CACHE_TTL },\n);\n\nconst midPriceCache = createCache<Map<string, number>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing mid price cache`);\n const mids = await getAllMids();\n const map = new Map<string, number>();\n for (const [coin, price] of Object.entries(mids ?? {})) {\n const value = Number(price);\n if (Number.isFinite(value)) {\n map.set(coin, value);\n }\n }\n return map;\n },\n { expire: MID_TTL },\n);\n\nexport const resolveAssetInfo = async (product_id: string): Promise<AssetInfo> => {\n const [instType, symbol] = decodePath(product_id);\n if (!instType || !symbol) {\n throw new Error(`Invalid product_id: ${product_id}`);\n }\n const baseCurrency = symbol.split('-')[0];\n if (instType === InstrumentType.PERPETUAL) {\n const map = (await perpMetaCache.query('perp'))!;\n const info = map.get(baseCurrency)!;\n return { ...info, instType: InstrumentType.PERPETUAL, baseCurrency };\n }\n if (instType === InstrumentType.SPOT) {\n const map = (await spotMetaCache.query('spot'))!;\n const info = map.get(baseCurrency)!;\n return { ...info, instType: InstrumentType.SPOT, baseCurrency };\n }\n throw new Error(`Unsupported instrument type: ${instType}`);\n};\n\nexport const roundPrice = (price: number, instType: 'PERPETUAL' | 'SPOT', szDecimals: number): string => {\n const MAX_DECIMALS = instType === 'PERPETUAL' ? 6 : 8;\n const maxDecimalPlaces = Math.max(0, MAX_DECIMALS - szDecimals);\n if (!Number.isFinite(price)) {\n throw new Error(`Invalid price: ${price}`);\n }\n if (Number.isInteger(price)) {\n return price.toString();\n }\n const priceStr = price.toString();\n const significantFigures = priceStr.replace(/^0+\\.?0*/, '').replace(/\\./g, '').length;\n let roundedPrice = price;\n if (significantFigures > 5) {\n const decimalIndex = priceStr.indexOf('.');\n if (decimalIndex === -1) {\n const magnitude = Math.floor(Math.log10(Math.abs(price)));\n const factor = Math.pow(10, magnitude - 4);\n roundedPrice = Math.round(price / factor) * factor;\n } else {\n const beforeDecimal = priceStr.substring(0, decimalIndex);\n const afterDecimal = priceStr.substring(decimalIndex + 1);\n if (beforeDecimal !== '0') {\n const integerDigits = beforeDecimal.replace('-', '').length;\n const neededDecimalDigits = Math.max(0, 5 - integerDigits);\n roundedPrice = parseFloat(price.toFixed(neededDecimalDigits));\n } else {\n const leadingZeros = afterDecimal.match(/^0*/)?.[0].length ?? 0;\n const precision = leadingZeros + 5;\n roundedPrice = parseFloat(price.toFixed(precision));\n }\n }\n }\n const finalPrice = parseFloat(roundedPrice.toFixed(maxDecimalPlaces));\n return finalPrice.toString();\n};\n\nconst resolvePrice = async (\n order: IOrder,\n instType: 'PERPETUAL' | 'SPOT',\n szDecimals: number,\n baseCurrency: string,\n) => {\n if (order.order_type === 'MARKET') {\n const mid = await getMidPriceWithSlippage(\n baseCurrency,\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT',\n );\n return roundPrice(mid, instType, szDecimals);\n }\n if (!order.price) {\n throw new Error('price is required for non-market orders');\n }\n return roundPrice(+order.price, instType, szDecimals);\n};\n\nexport const buildOrderPayload = async (order: IOrder) => {\n const assetInfo = await resolveAssetInfo(order.product_id);\n const isBuy = order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT';\n const reduceOnly = order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT';\n const price = await resolvePrice(order, assetInfo.instType, assetInfo.szDecimals, assetInfo.baseCurrency);\n const tif = order.order_type === 'MARKET' ? 'Ioc' : order.order_type === 'MAKER' ? 'Alo' : 'Gtc';\n return {\n assetInfo,\n orderParams: {\n a: assetInfo.assetId,\n b: isBuy,\n p: `${price}`,\n s: `${order.volume}`,\n r: reduceOnly,\n t: { limit: { tif } },\n },\n };\n};\n\nexport const getMidPriceWithSlippage = async (coin: string, isBuy: boolean) => {\n const mids = (await midPriceCache.query('mids'))!;\n const mid = mids.get(coin)!;\n const slippage = isBuy ? 1.05 : 0.95;\n return mid * slippage;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAStF,MAAM,SAAS,GAAG,KAAM,CAAC;AACzB,MAAM,OAAO,GAAG,IAAK,CAAC;AAEtB,0CAA0C;AAC1C,MAAM,aAAa,GAAG,WAAW,CAC/B,KAAK,IAAI,EAAE;IACT,OAAO,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAC;IAClE,MAAM,IAAI,GAAG,MAAM,qBAAqB,EAAE,CAAC;IAC3C,MAAM,GAAG,GAAG,IAAI,GAAG,EAAmD,CAAC;IACvE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CACrC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC,CACtE,CAAC;IACF,OAAO,GAAG,CAAC;AACb,CAAC,EACD,EAAE,MAAM,EAAE,SAAS,EAAE,CACtB,CAAC;AAEF,MAAM,aAAa,GAAG,WAAW,CAC/B,KAAK,IAAI,EAAE;IACT,OAAO,CAAC,IAAI,CAAC,8CAA8C,CAAC,CAAC;IAC7D,MAAM,IAAI,GAAG,MAAM,eAAe,EAAE,CAAC;IACrC,MAAM,GAAG,GAAG,IAAI,GAAG,EAAmD,CAAC;IACvE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,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,CAAC,CAAC,IAAI,CAAC;IACrC,OAAO,GAAG,GAAG,QAAQ,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IOrder } from '@yuants/data-order';\nimport { decodePath } from '@yuants/utils';\nimport { getAllMids, getPerpetualsMetaData, getSpotMetaData } from './api/public-api';\n\nconst enum InstrumentType {\n PERPETUAL = 'PERPETUAL',\n SPOT = 'SPOT',\n}\n\ntype AssetInfo = { assetId: number; szDecimals: number; instType: InstrumentType; baseCurrency: string };\n\nconst CACHE_TTL = 60_000;\nconst MID_TTL = 5_000;\n\n// Create caches using createCache utility\nconst perpMetaCache = createCache<Map<string, { assetId: number; szDecimals: number }>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing perpetual metadata cache`);\n const meta = await getPerpetualsMetaData();\n const map = new Map<string, { assetId: number; szDecimals: number }>();\n meta.universe.forEach((token, index) =>\n map.set(token.name, { assetId: index, szDecimals: token.szDecimals }),\n );\n return map;\n },\n { expire: CACHE_TTL },\n);\n\nconst spotMetaCache = createCache<Map<string, { assetId: number; szDecimals: number }>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing spot metadata cache`);\n const meta = await getSpotMetaData();\n const map = new Map<string, { assetId: number; szDecimals: number }>();\n meta.tokens.forEach((token) =>\n map.set(token.name, { assetId: token.index, szDecimals: token.szDecimals }),\n );\n return map;\n },\n { expire: CACHE_TTL },\n);\n\nconst midPriceCache = createCache<Map<string, number>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing mid price cache`);\n const mids = await getAllMids();\n const map = new Map<string, number>();\n for (const [coin, price] of Object.entries(mids ?? {})) {\n const value = Number(price);\n if (Number.isFinite(value)) {\n map.set(coin, value);\n }\n }\n return map;\n },\n { expire: MID_TTL },\n);\n\nexport const resolveAssetInfo = async (product_id: string): Promise<AssetInfo> => {\n const [instType, symbol] = decodePath(product_id);\n if (!instType || !symbol) {\n throw new Error(`Invalid product_id: ${product_id}`);\n }\n const baseCurrency = symbol.split('-')[0];\n if (instType === InstrumentType.PERPETUAL) {\n const map = (await perpMetaCache.query('perp'))!;\n const info = map.get(baseCurrency)!;\n return { ...info, instType: InstrumentType.PERPETUAL, baseCurrency };\n }\n if (instType === InstrumentType.SPOT) {\n const map = (await spotMetaCache.query('spot'))!;\n const info = map.get(baseCurrency)!;\n return { ...info, instType: InstrumentType.SPOT, baseCurrency };\n }\n throw new Error(`Unsupported instrument type: ${instType}`);\n};\n\nexport const roundPrice = (price: number, instType: 'PERPETUAL' | 'SPOT', szDecimals: number): string => {\n const MAX_DECIMALS = instType === 'PERPETUAL' ? 6 : 8;\n const maxDecimalPlaces = Math.max(0, MAX_DECIMALS - szDecimals);\n if (!Number.isFinite(price)) {\n throw new Error(`Invalid price: ${price}`);\n }\n\n // Handle significant figures (max 5)\n const priceStr = price.toString();\n const significantFigures = priceStr.replace(/^0+\\.?0*/, '').replace(/\\./g, '').length;\n\n let roundedPrice = price;\n if (significantFigures > 5) {\n // Logic to round to 5 sig figs\n // This is complex to do perfectly with just numbers, but let's try to be safe\n const magnitude = Math.floor(Math.log10(Math.abs(price)));\n // We want 5 sig figs.\n // e.g. 123456 -> 123460 (mag 5, round to 10^(5-4)=10^1)\n // e.g. 0.00123456 -> 0.0012346 (mag -3, round to 10^(-3-4)=10^-7)\n const factor = Math.pow(10, magnitude - 4);\n roundedPrice = Math.round(price / factor) * factor;\n }\n\n // Now format to maxDecimalPlaces without scientific notation\n // Use toFixed which returns fixed point notation\n let s = roundedPrice.toFixed(maxDecimalPlaces);\n // Remove trailing zeros and decimal point if integer\n if (s.includes('.')) {\n s = s.replace(/\\.?0+$/, '');\n }\n return s;\n};\n\nconst resolvePrice = async (\n order: IOrder,\n instType: 'PERPETUAL' | 'SPOT',\n szDecimals: number,\n baseCurrency: string,\n) => {\n if (order.order_type === 'MARKET') {\n const mid = await getMidPriceWithSlippage(\n baseCurrency,\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT',\n );\n return roundPrice(mid, instType, szDecimals);\n }\n if (!order.price) {\n throw new Error('price is required for non-market orders');\n }\n return roundPrice(+order.price, instType, szDecimals);\n};\n\nexport const buildOrderPayload = async (order: IOrder) => {\n const assetInfo = await resolveAssetInfo(order.product_id);\n const isBuy = order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT';\n const reduceOnly = order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT';\n const price = await resolvePrice(order, assetInfo.instType, assetInfo.szDecimals, assetInfo.baseCurrency);\n const tif = order.order_type === 'MARKET' ? 'Ioc' : order.order_type === 'MAKER' ? 'Alo' : 'Gtc';\n return {\n assetInfo,\n orderParams: {\n a: assetInfo.assetId,\n b: isBuy,\n p: `${price}`,\n s: `${order.volume}`,\n r: reduceOnly,\n t: { limit: { tif } },\n },\n };\n};\n\nexport const getMidPriceWithSlippage = async (coin: string, isBuy: boolean) => {\n const mids = (await midPriceCache.query('mids'))!;\n const mid = mids.get(coin)!;\n const slippage = isBuy ? 1.05 : 0.95;\n return mid * slippage;\n};\n"]}
|
package/lib/index.d.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import './services/account-actions-with-credential';
|
|
2
|
-
import './services/
|
|
3
|
-
import './services/order-actions-with-credential';
|
|
2
|
+
import './services/legacy';
|
|
4
3
|
import './services/markets/interest-rate';
|
|
5
4
|
import './services/markets/ohlc';
|
|
6
5
|
import './services/markets/product';
|
|
7
6
|
import './services/markets/quote';
|
|
7
|
+
import './services/order-actions-with-credential';
|
|
8
|
+
import './services/orders/cancelOrder';
|
|
9
|
+
import './services/orders/modifyOrder';
|
|
10
|
+
import './services/orders/submitOrder';
|
|
8
11
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,4CAA4C,CAAC;AACpD,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,4CAA4C,CAAC;AACpD,OAAO,mBAAmB,CAAC;AAC3B,OAAO,kCAAkC,CAAC;AAC1C,OAAO,yBAAyB,CAAC;AACjC,OAAO,4BAA4B,CAAC;AACpC,OAAO,0BAA0B,CAAC;AAClC,OAAO,0CAA0C,CAAC;AAClD,OAAO,+BAA+B,CAAC;AACvC,OAAO,+BAA+B,CAAC;AACvC,OAAO,+BAA+B,CAAC"}
|