Skip to main content
Glama

analyzeTradingPerformance

Analyze cryptocurrency trading performance for configured accounts, evaluating metrics over specified periods to assess strategy effectiveness and identify improvement opportunities.

Instructions

Analyze trading performance for a configured account

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
accountNameYesAccount name defined in the configuration file (e.g., 'bybit_main')
symbolNoOptional trading symbol (e.g., 'BTC/USDT') to filter trades
periodNoAnalysis period: '7d', '30d', '90d', or 'all'30d

Implementation Reference

  • The main handler function that fetches trades from the CCXT exchange instance for the given account, period, and optional symbol, checks support, computes 'since' timestamp, calls analyzeTradeData helper, and returns JSON analysis or error.
    async ({ accountName, symbol, period }) => {
      try {
        const exchange = ccxtServer.getExchangeInstance(accountName);
    
        // fetchMyTrades 메서드가 지원되는지 확인
        if (!exchange.has["fetchMyTrades"]) {
          return {
            content: [
              {
                type: "text",
                text: `Account '${accountName}' (Exchange: ${exchange.id}) does not support fetching personal trades for analysis`,
              },
            ],
            isError: true,
          };
        }
    
        // 기간에 따른 since 값 계산
        const now = Date.now();
        let since;
        switch (period) {
          case "7d":
            since = now - 7 * 24 * 60 * 60 * 1000; // 7일
            break;
          case "30d":
            since = now - 30 * 24 * 60 * 60 * 1000; // 30일
            break;
          case "90d":
            since = now - 90 * 24 * 60 * 60 * 1000; // 90일
            break;
          case "all":
            since = undefined; // 전체 데이터
            break;
        }
    
        // 거래 데이터 가져오기
        const trades = await exchange.fetchMyTrades(symbol, since, undefined);
    
        // 기본 분석 지표 계산
        const analysis = analyzeTradeData(trades, period);
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(analysis, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error analyzing trading performance for account '${accountName}': ${
                (error as Error).message
              }`,
            },
          ],
          isError: true,
        };
      }
    }
  • Zod schema defining input parameters: accountName (required string), symbol (optional string), period (enum with default '30d').
    {
      accountName: z
        .string()
        .describe(
          "Account name defined in the configuration file (e.g., 'bybit_main')"
        ),
      symbol: z
        .string()
        .optional()
        .describe("Optional trading symbol (e.g., 'BTC/USDT') to filter trades"),
      period: z
        .enum(["7d", "30d", "90d", "all"])
        .default("30d")
        .describe("Analysis period: '7d', '30d', '90d', or 'all'"),
    },
  • Direct MCP server.tool() registration of 'analyzeTradingPerformance' with description, input schema, and handler function.
    server.tool(
      "analyzeTradingPerformance",
      "Analyze trading performance for a configured account",
      {
        accountName: z
          .string()
          .describe(
            "Account name defined in the configuration file (e.g., 'bybit_main')"
          ),
        symbol: z
          .string()
          .optional()
          .describe("Optional trading symbol (e.g., 'BTC/USDT') to filter trades"),
        period: z
          .enum(["7d", "30d", "90d", "all"])
          .default("30d")
          .describe("Analysis period: '7d', '30d', '90d', or 'all'"),
      },
      async ({ accountName, symbol, period }) => {
        try {
          const exchange = ccxtServer.getExchangeInstance(accountName);
    
          // fetchMyTrades 메서드가 지원되는지 확인
          if (!exchange.has["fetchMyTrades"]) {
            return {
              content: [
                {
                  type: "text",
                  text: `Account '${accountName}' (Exchange: ${exchange.id}) does not support fetching personal trades for analysis`,
                },
              ],
              isError: true,
            };
          }
    
          // 기간에 따른 since 값 계산
          const now = Date.now();
          let since;
          switch (period) {
            case "7d":
              since = now - 7 * 24 * 60 * 60 * 1000; // 7일
              break;
            case "30d":
              since = now - 30 * 24 * 60 * 60 * 1000; // 30일
              break;
            case "90d":
              since = now - 90 * 24 * 60 * 60 * 1000; // 90일
              break;
            case "all":
              since = undefined; // 전체 데이터
              break;
          }
    
          // 거래 데이터 가져오기
          const trades = await exchange.fetchMyTrades(symbol, since, undefined);
    
          // 기본 분석 지표 계산
          const analysis = analyzeTradeData(trades, period);
    
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(analysis, null, 2),
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error analyzing trading performance for account '${accountName}': ${
                  (error as Error).message
                }`,
              },
            ],
            isError: true,
          };
        }
      }
    );
  • src/server.ts:375-375 (registration)
    Top-level call to registerAnalysisTools(server, ccxtServer) which registers the analyzeTradingPerformance tool among others in CcxtMcpServer constructor.
    registerAnalysisTools(this.server, this);
  • Helper function called by the handler to compute detailed trading performance metrics from raw trades array, including win rate, profits/losses, fees, profit factor, trading period stats. Note: uses simplified profit calculation.
    function analyzeTradeData(trades: any[], period: string) {
      if (!trades || trades.length === 0) {
        return {
          period,
          totalTrades: 0,
          message: "No trades found for the specified period.",
        };
      }
    
      // 거래 데이터 정렬 (시간순)
      trades.sort((a, b) => a.timestamp - b.timestamp);
    
      // 기본 지표 계산
      let totalProfit = 0;
      let totalLoss = 0;
      let winCount = 0;
      let lossCount = 0;
      let totalFees = 0;
      let largestWin = 0;
      let largestLoss = 0;
      let totalVolume = 0;
    
      // 거래별 분석
      trades.forEach((trade) => {
        // 수수료 계산
        const fee = trade.fee?.cost || 0;
        totalFees += fee;
    
        // 거래량 계산
        totalVolume += trade.amount * trade.price;
    
        // 손익 계산 (단순화된 버전 - 실제로는 포지션 추적 필요)
        const cost = trade.amount * trade.price;
        const profit = trade.side === "buy" ? -cost : cost; // 매우 단순화된 계산
    
        if (profit > 0) {
          totalProfit += profit;
          winCount++;
          largestWin = Math.max(largestWin, profit);
        } else if (profit < 0) {
          totalLoss += Math.abs(profit);
          lossCount++;
          largestLoss = Math.max(largestLoss, Math.abs(profit));
        }
      });
    
      const totalTrades = trades.length;
      const winRate = totalTrades > 0 ? (winCount / totalTrades) * 100 : 0;
      const netProfit = totalProfit - totalLoss - totalFees;
      const profitFactor = totalLoss > 0 ? totalProfit / totalLoss : totalProfit > 0 ? Infinity : 0;
    
      // 거래 패턴 분석
      const firstTradeDate = new Date(trades[0].timestamp);
      const lastTradeDate = new Date(trades[trades.length - 1].timestamp);
      const tradingDurationDays = (lastTradeDate.getTime() - firstTradeDate.getTime()) / (1000 * 60 * 60 * 24);
      const tradesPerDay = tradingDurationDays > 0 ? totalTrades / tradingDurationDays : totalTrades;
    
      return {
        period,
        totalTrades,
        winCount,
        lossCount,
        winRate: winRate.toFixed(2) + "%",
        totalProfit: totalProfit.toFixed(8),
        totalLoss: totalLoss.toFixed(8),
        netProfit: netProfit.toFixed(8),
        totalFees: totalFees.toFixed(8),
        profitFactor: profitFactor.toFixed(2),
        largestWin: largestWin.toFixed(8),
        largestLoss: largestLoss.toFixed(8),
        totalVolume: totalVolume.toFixed(2),
        tradingPeriod: {
          firstTrade: firstTradeDate.toISOString(),
          lastTrade: lastTradeDate.toISOString(),
          durationDays: tradingDurationDays.toFixed(1),
          tradesPerDay: tradesPerDay.toFixed(1),
        }
      };
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'configured account' but does not specify required permissions, data sources, computational cost, or output format. For a tool with no annotations, this leaves significant behavioral gaps.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose. It is appropriately sized and front-loaded, with no wasted words, though it could be slightly more informative without losing conciseness.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description is incomplete for a tool with 3 parameters and sibling tools. It does not explain what 'analyze' returns (e.g., metrics, reports), behavioral traits, or how it differs from similar tools, leaving the agent with insufficient context for effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents parameters like 'accountName', 'symbol', and 'period'. The description adds no additional meaning beyond the schema, such as explaining how 'accountName' relates to configuration or what 'analyze' entails. Baseline 3 is appropriate as the schema handles parameter documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states the purpose as 'Analyze trading performance for a configured account', which is clear but vague. It specifies the verb ('analyze') and resource ('trading performance'), but does not distinguish it from siblings like 'analyzeConsecutiveProfitLoss' or 'analyzePeriodicReturns', leaving ambiguity about what specific aspects of performance are analyzed.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives. The description lacks context on prerequisites (e.g., needing a configured account), exclusions, or comparisons to sibling tools like 'calculateWinRate', leaving the agent without usage direction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/lazy-dinosaur/ccxt-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server