Skip to main content
Glama

calculateWinRate

Calculate win rate and profit metrics for cryptocurrency trading accounts over specified periods. Analyze trading performance by account and symbol to evaluate strategy effectiveness.

Instructions

Calculate win rate and profit metrics 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', or 'all'30d

Implementation Reference

  • Registration of the 'calculateWinRate' MCP tool using server.tool, including schema and handler
    server.tool(
      "calculateWinRate",
      "Calculate win rate and profit metrics 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", "all"])
          .default("30d")
          .describe("Analysis period: '7d', '30d', 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 win rate calculation`,
                },
              ],
              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 "all":
              since = undefined; // 전체 데이터
              break;
          }
    
          // 거래 데이터 가져오기
          const trades = await exchange.fetchMyTrades(symbol, since, undefined);
    
          // 승률 및 수익률 계산
          const metrics = calculateWinRateAndProfitMetrics(trades);
    
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(metrics, null, 2),
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error calculating win rate for account '${accountName}': ${
                  (error as Error).message
                }`,
              },
            ],
            isError: true,
          };
        }
      }
    );
  • Zod input schema for calculateWinRate tool parameters: accountName (required), symbol (optional), period (7d|30d|all, 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", "all"])
        .default("30d")
        .describe("Analysis period: '7d', '30d', or 'all'"),
    },
  • Tool handler: fetches trades for the account/symbol/period using CCXT, calls calculateWinRateAndProfitMetrics, returns JSON metrics
    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 win rate calculation`,
              },
            ],
            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 "all":
            since = undefined; // 전체 데이터
            break;
        }
    
        // 거래 데이터 가져오기
        const trades = await exchange.fetchMyTrades(symbol, since, undefined);
    
        // 승률 및 수익률 계산
        const metrics = calculateWinRateAndProfitMetrics(trades);
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(metrics, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error calculating win rate for account '${accountName}': ${
                (error as Error).message
              }`,
            },
          ],
          isError: true,
        };
      }
    }
  • Helper function that processes trade data into positions, computes win rate, profit/loss metrics, expectancy, consecutive streaks, etc.
    function calculateWinRateAndProfitMetrics(trades: any[]) {
      if (!trades || trades.length === 0) {
        return {
          totalTrades: 0,
          message: "No trades found for the specified period.",
        };
      }
    
      // 거래를 시간순으로 정렬
      trades.sort((a, b) => a.timestamp - b.timestamp);
    
      // 포지션별 거래 그룹화 (매우 단순화된 버전)
      // 실제로는 더 복잡한 포지션 추적 로직이 필요할 수 있음
      const positions: any[] = [];
      let currentPosition: any = null;
    
      trades.forEach((trade) => {
        if (!currentPosition) {
          currentPosition = {
            symbol: trade.symbol,
            side: trade.side,
            entryTime: trade.datetime,
            entryPrice: trade.price,
            amount: trade.amount,
            cost: trade.amount * trade.price,
            fees: trade.fee?.cost || 0,
            exitTime: null,
            exitPrice: null,
            profit: null,
          };
        } else if (currentPosition.side !== trade.side && currentPosition.symbol === trade.symbol) {
          // 반대 방향 거래는 포지션 종료로 간주
          currentPosition.exitTime = trade.datetime;
          currentPosition.exitPrice = trade.price;
          
          // 손익 계산 (매우 단순화된 버전)
          if (currentPosition.side === "buy") {
            // 매수 후 매도
            currentPosition.profit = (trade.price - currentPosition.entryPrice) * currentPosition.amount - currentPosition.fees - (trade.fee?.cost || 0);
          } else {
            // 매도 후 매수
            currentPosition.profit = (currentPosition.entryPrice - trade.price) * currentPosition.amount - currentPosition.fees - (trade.fee?.cost || 0);
          }
          
          positions.push(currentPosition);
          currentPosition = null;
        } else {
          // 같은 방향 거래는 포지션에 추가 (average down/up)
          const newAmount = currentPosition.amount + trade.amount;
          const newCost = currentPosition.cost + (trade.amount * trade.price);
          currentPosition.entryPrice = newCost / newAmount;
          currentPosition.amount = newAmount;
          currentPosition.cost = newCost;
          currentPosition.fees += trade.fee?.cost || 0;
        }
      });
    
      // 완료된 포지션만 분석
      const completedPositions = positions.filter(p => p.exitTime !== null);
      
      if (completedPositions.length === 0) {
        return {
          totalTrades: trades.length,
          completedPositions: 0,
          message: "No completed positions found for analysis.",
        };
      }
    
      // 기본 지표 계산
      let winCount = 0;
      let lossCount = 0;
      let totalProfit = 0;
      let totalLoss = 0;
      let maxConsecutiveWins = 0;
      let maxConsecutiveLosses = 0;
      let currentConsecutiveWins = 0;
      let currentConsecutiveLosses = 0;
      
      completedPositions.forEach(position => {
        if (position.profit > 0) {
          winCount++;
          totalProfit += position.profit;
          currentConsecutiveWins++;
          currentConsecutiveLosses = 0;
          maxConsecutiveWins = Math.max(maxConsecutiveWins, currentConsecutiveWins);
        } else {
          lossCount++;
          totalLoss += Math.abs(position.profit);
          currentConsecutiveLosses++;
          currentConsecutiveWins = 0;
          maxConsecutiveLosses = Math.max(maxConsecutiveLosses, currentConsecutiveLosses);
        }
      });
    
      const totalPositions = completedPositions.length;
      const winRate = (winCount / totalPositions) * 100;
      const averageWin = winCount > 0 ? totalProfit / winCount : 0;
      const averageLoss = lossCount > 0 ? totalLoss / lossCount : 0;
      const profitFactor = totalLoss > 0 ? totalProfit / totalLoss : totalProfit > 0 ? Infinity : 0;
      const expectancy = (winRate / 100 * averageWin) - ((100 - winRate) / 100 * averageLoss);
      
      // R-multiple 계산 (평균 수익 / 평균 손실)
      const rMultiple = averageLoss > 0 ? averageWin / averageLoss : 0;
    
      return {
        totalTrades: trades.length,
        completedPositions: totalPositions,
        winCount,
        lossCount,
        winRate: winRate.toFixed(2) + "%",
        profitFactor: profitFactor.toFixed(2),
        netProfit: (totalProfit - totalLoss).toFixed(8),
        averageWin: averageWin.toFixed(8),
        averageLoss: averageLoss.toFixed(8),
        rMultiple: rMultiple.toFixed(2),
        expectancy: expectancy.toFixed(8),
        maxConsecutiveWins,
        maxConsecutiveLosses,
        firstTradeDate: completedPositions[0].entryTime,
        lastTradeDate: completedPositions[completedPositions.length - 1].exitTime,
      };
    }
  • src/server.ts:375-375 (registration)
    Calls registerAnalysisTools which registers the calculateWinRate tool among others in the main CcxtMcpServer
    registerAnalysisTools(this.server, this);
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'calculate' but doesn't specify whether this is a read-only operation, if it requires authentication, what the output format looks like, or any rate limits. This leaves significant gaps in understanding how the tool behaves, especially for a tool that likely involves data analysis.

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

Conciseness5/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 without any wasted words. It is appropriately sized and front-loaded, making it easy for an agent to parse quickly and understand the core function.

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 the tool's complexity (involving calculations for win rate and profit metrics), no annotations, and no output schema, the description is incomplete. It fails to explain what the output includes (e.g., specific metrics, format) or any behavioral aspects like data sources or computation methods, 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?

The input schema has 100% description coverage, so the schema already documents all parameters thoroughly. The description adds no additional meaning beyond what's in the schema, such as explaining how 'accountName' relates to configuration or the implications of the 'period' options. Thus, it meets the baseline score without compensating for any gaps.

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

Purpose4/5

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

The description clearly states the tool's purpose with a specific verb ('calculate') and resource ('win rate and profit metrics'), making it easy to understand what it does. However, it doesn't explicitly distinguish this tool from its siblings like 'analyzeTradingPerformance' or 'analyzePeriodicReturns', which might offer similar functionality, so it misses the highest score.

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?

The description provides no guidance on when to use this tool versus alternatives, such as the sibling tools 'analyzeTradingPerformance' or 'analyzePeriodicReturns'. It lacks context about prerequisites, exclusions, or specific scenarios where this tool is preferred, leaving the agent with no 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