@michaleffffff/mcp-trading-server 2.9.0 → 2.9.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/server.js +2 -2
- package/dist/services/tradeService.js +13 -5
- package/dist/tools/closePosition.js +9 -1
- package/dist/tools/executeTrade.js +11 -1
- package/dist/tools/getPositions.js +58 -4
- package/dist/tools/manageLiquidity.js +7 -4
- package/dist/tools/setTpSl.js +10 -4
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -81,7 +81,7 @@ function zodSchemaToJsonSchema(zodSchema) {
|
|
|
81
81
|
};
|
|
82
82
|
}
|
|
83
83
|
// ─── MCP Server ───
|
|
84
|
-
const server = new Server({ name: "myx-mcp-trading-server", version: "2.9.
|
|
84
|
+
const server = new Server({ name: "myx-mcp-trading-server", version: "2.9.2" }, { capabilities: { tools: {}, resources: {}, prompts: {} } });
|
|
85
85
|
// List tools
|
|
86
86
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
87
87
|
return {
|
|
@@ -181,7 +181,7 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
|
|
|
181
181
|
async function main() {
|
|
182
182
|
const transport = new StdioServerTransport();
|
|
183
183
|
await server.connect(transport);
|
|
184
|
-
logger.info("🚀 MYX Trading MCP Server v2.9.
|
|
184
|
+
logger.info("🚀 MYX Trading MCP Server v2.9.2 running (stdio, pure on-chain, prod ready)");
|
|
185
185
|
}
|
|
186
186
|
main().catch((err) => {
|
|
187
187
|
logger.error("Fatal Server Startup Error", err);
|
|
@@ -13,16 +13,24 @@ function resolveDirection(direction) {
|
|
|
13
13
|
/**
|
|
14
14
|
* 自动推断开启订单的触发类型 (Limit/Stop)
|
|
15
15
|
*/
|
|
16
|
-
function resolveTriggerType(orderType, direction, triggerType) {
|
|
16
|
+
function resolveTriggerType(orderType, direction, isDecrease = false, triggerType) {
|
|
17
17
|
if (triggerType !== undefined && triggerType !== null && triggerType !== 0) {
|
|
18
18
|
return triggerType;
|
|
19
19
|
}
|
|
20
|
-
// LIMIT LONG
|
|
20
|
+
// Opening: LIMIT LONG -> LTE(2), LIMIT SHORT -> GTE(1)
|
|
21
|
+
// Closing: LIMIT LONG -> GTE(1), LIMIT SHORT -> LTE(2)
|
|
21
22
|
if (orderType === OrderType.LIMIT) {
|
|
23
|
+
if (isDecrease) {
|
|
24
|
+
return direction === 0 ? 1 : 2;
|
|
25
|
+
}
|
|
22
26
|
return direction === 0 ? 2 : 1;
|
|
23
27
|
}
|
|
24
|
-
// STOP LONG
|
|
28
|
+
// Opening: STOP LONG -> GTE(1), STOP SHORT -> LTE(2)
|
|
29
|
+
// Closing: STOP LONG -> LTE(2), STOP SHORT -> GTE(1)
|
|
25
30
|
if (orderType === OrderType.STOP) {
|
|
31
|
+
if (isDecrease) {
|
|
32
|
+
return direction === 0 ? 2 : 1;
|
|
33
|
+
}
|
|
26
34
|
return direction === 0 ? 1 : 2;
|
|
27
35
|
}
|
|
28
36
|
return 0; // MARKET order typically uses 0
|
|
@@ -138,7 +146,7 @@ export async function openPosition(client, address, args) {
|
|
|
138
146
|
poolId: args.poolId,
|
|
139
147
|
positionId: args.positionId,
|
|
140
148
|
orderType: args.orderType,
|
|
141
|
-
triggerType: resolveTriggerType(args.orderType, args.direction, args.triggerType),
|
|
149
|
+
triggerType: resolveTriggerType(args.orderType, args.direction, false, args.triggerType),
|
|
142
150
|
direction: dir,
|
|
143
151
|
collateralAmount: collateralRaw,
|
|
144
152
|
size: sizeRaw,
|
|
@@ -184,7 +192,7 @@ export async function closePosition(client, address, args) {
|
|
|
184
192
|
poolId: args.poolId,
|
|
185
193
|
positionId: args.positionId,
|
|
186
194
|
orderType: args.orderType,
|
|
187
|
-
triggerType: resolveTriggerType(args.orderType, args.direction, args.triggerType),
|
|
195
|
+
triggerType: resolveTriggerType(args.orderType, args.direction, true, args.triggerType),
|
|
188
196
|
direction: dir,
|
|
189
197
|
collateralAmount: ensureUnits(args.collateralAmount, quoteDecimals, "collateralAmount"),
|
|
190
198
|
size: ensureUnits(args.size, baseDecimals, "size"),
|
|
@@ -19,18 +19,26 @@ export const closePositionTool = {
|
|
|
19
19
|
price: z.union([z.string(), z.number()]).describe("Price (human or 30-dec raw units)"),
|
|
20
20
|
timeInForce: z.coerce.number().int().describe("TimeInForce: 0=GTC, 1=IOC, 2=FOK"),
|
|
21
21
|
postOnly: z.coerce.boolean().describe("Post-only flag"),
|
|
22
|
-
slippagePct: z.coerce.string().describe(SLIPPAGE_PCT_4DP_DESC),
|
|
22
|
+
slippagePct: z.coerce.string().default("50").describe(SLIPPAGE_PCT_4DP_DESC),
|
|
23
23
|
executionFeeToken: z.string().describe("Execution fee token address"),
|
|
24
24
|
leverage: z.coerce.number().describe("Leverage"),
|
|
25
25
|
},
|
|
26
26
|
handler: async (args) => {
|
|
27
27
|
try {
|
|
28
28
|
const { client, address, signer } = await resolveClient();
|
|
29
|
+
const { chainId } = await resolveClient();
|
|
30
|
+
const poolId = args.poolId;
|
|
31
|
+
// Fetch pool detail to get quoteToken for execution fee
|
|
32
|
+
const poolResponse = await client.markets.getMarketDetail({ chainId, poolId });
|
|
33
|
+
const poolData = poolResponse?.data || (poolResponse?.marketId ? poolResponse : null);
|
|
34
|
+
if (!poolData)
|
|
35
|
+
throw new Error(`Could not find pool metadata for ID: ${poolId}`);
|
|
29
36
|
const mappedArgs = {
|
|
30
37
|
...args,
|
|
31
38
|
direction: mapDirection(args.direction),
|
|
32
39
|
orderType: mapOrderType(args.orderType),
|
|
33
40
|
triggerType: args.triggerType !== undefined ? mapTriggerType(args.triggerType) : undefined,
|
|
41
|
+
executionFeeToken: poolData.quoteToken || args.executionFeeToken
|
|
34
42
|
};
|
|
35
43
|
const raw = await closePos(client, address, mappedArgs);
|
|
36
44
|
const data = await finalizeMutationResult(raw, signer, "close_position");
|
|
@@ -22,7 +22,7 @@ export const executeTradeTool = {
|
|
|
22
22
|
price: z.union([z.string(), z.number()]).describe("Execution or Limit price. e.g. '65000' or 'raw:...'"),
|
|
23
23
|
timeInForce: z.coerce.number().int().describe("0=GTC, 1=IOC, 2=FOK"),
|
|
24
24
|
postOnly: z.coerce.boolean().describe("If true, order only executes as Maker."),
|
|
25
|
-
slippagePct: z.coerce.string().describe(`${SLIPPAGE_PCT_4DP_DESC}.
|
|
25
|
+
slippagePct: z.coerce.string().default("50").describe(`${SLIPPAGE_PCT_4DP_DESC}. Default is 50 (0.5%).`),
|
|
26
26
|
executionFeeToken: z.string().describe("Address of token to pay gas/execution fees (typically USDC)."),
|
|
27
27
|
leverage: z.coerce.number().describe("Leverage multiplier, e.g., 10 for 10x."),
|
|
28
28
|
tpSize: z.union([z.string(), z.number()]).optional().describe("Take Profit size. Use '0' to disable."),
|
|
@@ -35,11 +35,21 @@ export const executeTradeTool = {
|
|
|
35
35
|
handler: async (args) => {
|
|
36
36
|
try {
|
|
37
37
|
const { client, address, signer } = await resolveClient();
|
|
38
|
+
const poolId = args.poolId;
|
|
39
|
+
// Fetch pool detail to get quoteToken for execution fee
|
|
40
|
+
const poolResponse = await client.markets.getMarketDetail({ chainId: await resolveClient().then(r => r.chainId), poolId });
|
|
41
|
+
const poolData = poolResponse?.data || (poolResponse?.marketId ? poolResponse : null);
|
|
42
|
+
if (!poolData)
|
|
43
|
+
throw new Error(`Could not find pool metadata for ID: ${poolId}`);
|
|
38
44
|
const mappedArgs = {
|
|
39
45
|
...args,
|
|
40
46
|
direction: mapDirection(args.direction),
|
|
41
47
|
orderType: mapOrderType(args.orderType),
|
|
42
48
|
triggerType: args.triggerType !== undefined ? mapTriggerType(args.triggerType) : undefined,
|
|
49
|
+
// Normalize positionId
|
|
50
|
+
positionId: (args.positionId === "0" || !args.positionId) ? "" : args.positionId,
|
|
51
|
+
// Enforce executionFeeToken as quoteToken
|
|
52
|
+
executionFeeToken: poolData.quoteToken || args.executionFeeToken
|
|
43
53
|
};
|
|
44
54
|
const raw = await openPosition(client, address, mappedArgs);
|
|
45
55
|
const data = await finalizeMutationResult(raw, signer, "execute_trade");
|
|
@@ -7,13 +7,67 @@ export const getPositionsTool = {
|
|
|
7
7
|
schema: {},
|
|
8
8
|
handler: async () => {
|
|
9
9
|
try {
|
|
10
|
-
const { client, address } = await resolveClient();
|
|
10
|
+
const { client, address, chainId } = await resolveClient();
|
|
11
11
|
const data = await getPositions(client, address);
|
|
12
12
|
const positions = Array.isArray(data) ? data : (Array.isArray(data?.data) ? data.data : []);
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
if (positions.length === 0) {
|
|
14
|
+
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: [] }) }] };
|
|
15
|
+
}
|
|
16
|
+
// 1. Fetch Tickers for all relevant pools
|
|
17
|
+
const poolIds = [...new Set(positions.map((p) => p.poolId))];
|
|
18
|
+
const tickersRes = await client.markets.getTickerList({ chainId, poolIds });
|
|
19
|
+
const tickers = Array.isArray(tickersRes) ? tickersRes : (tickersRes?.data ?? []);
|
|
20
|
+
// 2. Fetch Pool Level Configs to get MM (Maintenance Margin Rate)
|
|
21
|
+
const configs = await Promise.all(poolIds.map(async (pid) => {
|
|
22
|
+
try {
|
|
23
|
+
const res = await client.markets.getPoolLevelConfig(pid, chainId);
|
|
24
|
+
return { poolId: pid, config: res?.levelConfig || res?.data?.levelConfig };
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return { poolId: pid, config: null };
|
|
28
|
+
}
|
|
16
29
|
}));
|
|
30
|
+
const enhancedData = positions.map((pos) => {
|
|
31
|
+
const ticker = tickers.find((t) => t.poolId === pos.poolId);
|
|
32
|
+
const currentPrice = Number(ticker?.price || 0);
|
|
33
|
+
const entryPrice = Number(pos.entryPrice || 0);
|
|
34
|
+
const size = Number(pos.size || 0);
|
|
35
|
+
const collateral = Number(pos.collateralAmount || 0);
|
|
36
|
+
const direction = pos.direction; // 0 = LONG, 1 = SHORT
|
|
37
|
+
const mm = configs.find(c => c.poolId === pos.poolId)?.config?.maintainCollateralRate || 0.02;
|
|
38
|
+
// Estimated PnL
|
|
39
|
+
let estimatedPnl = 0;
|
|
40
|
+
if (direction === 0) { // LONG
|
|
41
|
+
estimatedPnl = (currentPrice - entryPrice) * size;
|
|
42
|
+
}
|
|
43
|
+
else { // SHORT
|
|
44
|
+
estimatedPnl = (entryPrice - currentPrice) * size;
|
|
45
|
+
}
|
|
46
|
+
// ROI
|
|
47
|
+
const roi = collateral > 0 ? (estimatedPnl / collateral) * 100 : 0;
|
|
48
|
+
// Liquidation Price
|
|
49
|
+
// Long: (Entry * Size - Collateral) / (Size * (1 - MM))
|
|
50
|
+
// Short: (Entry * Size + Collateral) / (Size * (1 + MM))
|
|
51
|
+
let liqPrice = 0;
|
|
52
|
+
if (size > 0) {
|
|
53
|
+
if (direction === 0) {
|
|
54
|
+
liqPrice = (entryPrice * size - collateral) / (size * (1 - mm));
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
liqPrice = (entryPrice * size + collateral) / (size * (1 + mm));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (liqPrice < 0)
|
|
61
|
+
liqPrice = 0;
|
|
62
|
+
return {
|
|
63
|
+
...pos,
|
|
64
|
+
directionDesc: getDirectionDesc(pos.direction),
|
|
65
|
+
currentPrice: currentPrice.toString(),
|
|
66
|
+
estimatedPnl: estimatedPnl.toFixed(4),
|
|
67
|
+
roi: roi.toFixed(2) + "%",
|
|
68
|
+
liquidationPrice: liqPrice.toFixed(4)
|
|
69
|
+
};
|
|
70
|
+
});
|
|
17
71
|
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: enhancedData }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
|
|
18
72
|
}
|
|
19
73
|
catch (error) {
|
|
@@ -9,9 +9,9 @@ export const manageLiquidityTool = {
|
|
|
9
9
|
action: z.enum(["deposit", "withdraw"]).describe("'deposit' or 'withdraw'"),
|
|
10
10
|
poolType: z.enum(["BASE", "QUOTE"]).describe("'BASE' or 'QUOTE'"),
|
|
11
11
|
poolId: z.string().describe("Pool ID"),
|
|
12
|
-
amount: z.number().positive().describe("Amount in human-readable units"),
|
|
13
|
-
slippage: z.number().min(0).describe("LP slippage ratio (e.g. 0.01 = 1%)"),
|
|
14
|
-
chainId: z.number().int().positive().optional().describe("Optional chainId override"),
|
|
12
|
+
amount: z.coerce.number().positive().describe("Amount in human-readable units"),
|
|
13
|
+
slippage: z.coerce.number().min(0).describe("LP slippage ratio (e.g. 0.01 = 1%)"),
|
|
14
|
+
chainId: z.coerce.number().int().positive().optional().describe("Optional chainId override"),
|
|
15
15
|
},
|
|
16
16
|
handler: async (args) => {
|
|
17
17
|
try {
|
|
@@ -29,6 +29,9 @@ export const manageLiquidityTool = {
|
|
|
29
29
|
? await baseDeposit(poolId, amount, slippage, args.chainId)
|
|
30
30
|
: await baseWithdraw(poolId, amount, slippage, args.chainId);
|
|
31
31
|
}
|
|
32
|
+
if (!raw) {
|
|
33
|
+
throw new Error(`SDK returned an empty result for liquidity ${action}. This usually occurs if the pool is not in an Active state (state: 2) or if there is a contract-level restriction. Please check pool_info.`);
|
|
34
|
+
}
|
|
32
35
|
const data = await finalizeMutationResult(raw, signer, "manage_liquidity");
|
|
33
36
|
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
|
|
34
37
|
}
|
|
@@ -43,7 +46,7 @@ export const getLpPriceTool = {
|
|
|
43
46
|
schema: {
|
|
44
47
|
poolType: z.enum(["BASE", "QUOTE"]).describe("'BASE' or 'QUOTE'"),
|
|
45
48
|
poolId: z.string().describe("Pool ID"),
|
|
46
|
-
chainId: z.number().int().positive().optional().describe("Optional chainId override"),
|
|
49
|
+
chainId: z.coerce.number().int().positive().optional().describe("Optional chainId override"),
|
|
47
50
|
},
|
|
48
51
|
handler: async (args) => {
|
|
49
52
|
try {
|
package/dist/tools/setTpSl.js
CHANGED
|
@@ -3,7 +3,7 @@ import { resolveClient } from "../auth/resolveClient.js";
|
|
|
3
3
|
import { setPositionTpSl } from "../services/tradeService.js";
|
|
4
4
|
import { finalizeMutationResult } from "../utils/mutationResult.js";
|
|
5
5
|
import { mapDirection, mapTriggerType } from "../utils/mappings.js";
|
|
6
|
-
import {
|
|
6
|
+
import { SLIPPAGE_PCT_4DP_DESC } from "../utils/slippage.js";
|
|
7
7
|
export const setTpSlTool = {
|
|
8
8
|
name: "set_tp_sl",
|
|
9
9
|
description: "Create TP/SL order using SDK-native parameters.",
|
|
@@ -15,9 +15,7 @@ export const setTpSlTool = {
|
|
|
15
15
|
executionFeeToken: z.string().describe("Address of token to pay gas/execution fees."),
|
|
16
16
|
tpTriggerType: z.union([z.number(), z.string()]).optional().describe("0/NONE, 1/GTE, 2/LTE. e.g. 'GTE'."),
|
|
17
17
|
slTriggerType: z.union([z.number(), z.string()]).optional().describe("0/NONE, 1/GTE, 2/LTE. e.g. 'LTE'."),
|
|
18
|
-
slippagePct: z.coerce.string().
|
|
19
|
-
message: "slippagePct must be an integer in [0, 10000] with 4-decimal precision (1 = 0.01%).",
|
|
20
|
-
}).describe(`${SLIPPAGE_PCT_4DP_DESC}. Standard is 100 (1%).`),
|
|
18
|
+
slippagePct: z.coerce.string().default("50").describe(`${SLIPPAGE_PCT_4DP_DESC}. Default is 50 (0.5%).`),
|
|
21
19
|
tpPrice: z.coerce.string().optional().describe("Take Profit trigger price. e.g. '2.5' or 'raw:...' (30 decimals)."),
|
|
22
20
|
tpSize: z.coerce.string().optional().describe("TP size in base tokens. Use '0' to disable."),
|
|
23
21
|
slPrice: z.coerce.string().optional().describe("Stop Loss trigger price. e.g. '2.1' or 'raw:...' (30 decimals)."),
|
|
@@ -26,12 +24,20 @@ export const setTpSlTool = {
|
|
|
26
24
|
handler: async (args) => {
|
|
27
25
|
try {
|
|
28
26
|
const { client, address, signer } = await resolveClient();
|
|
27
|
+
const { chainId } = await resolveClient();
|
|
28
|
+
const poolId = args.poolId;
|
|
29
|
+
// Fetch pool detail to get quoteToken for execution fee
|
|
30
|
+
const poolResponse = await client.markets.getMarketDetail({ chainId, poolId });
|
|
31
|
+
const poolData = poolResponse?.data || (poolResponse?.marketId ? poolResponse : null);
|
|
32
|
+
if (!poolData)
|
|
33
|
+
throw new Error(`Could not find pool metadata for ID: ${poolId}`);
|
|
29
34
|
// Map inputs
|
|
30
35
|
const mappedArgs = {
|
|
31
36
|
...args,
|
|
32
37
|
direction: mapDirection(args.direction),
|
|
33
38
|
tpTriggerType: args.tpTriggerType !== undefined ? mapTriggerType(args.tpTriggerType) : undefined,
|
|
34
39
|
slTriggerType: args.slTriggerType !== undefined ? mapTriggerType(args.slTriggerType) : undefined,
|
|
40
|
+
executionFeeToken: poolData.quoteToken || args.executionFeeToken
|
|
35
41
|
};
|
|
36
42
|
const raw = await setPositionTpSl(client, address, mappedArgs);
|
|
37
43
|
const data = await finalizeMutationResult(raw, signer, "set_tp_sl");
|