Skip to main content
Glama

calculate_position_size

Calculate optimal position size for Bybit trades using risk percentage, account balance, and stop loss to manage trading risk effectively.

Instructions

Calculate optimal position size based on risk management principles

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
categoryYesCategory (linear, inverse)
symbolYesSymbol (e.g., ETHUSDT)
accountBalanceYesTotal account balance in USDT
riskPercentageYesRisk percentage per trade (e.g., 2 for 2%)
stopLossPriceYesStop loss price
currentPriceNoCurrent price (optional, will fetch if not provided)
leverageNoLeverage to use (optional, defaults to 1x)

Implementation Reference

  • The primary handler function implementing the calculate_position_size tool logic. Computes recommended position quantity based on risk management parameters, fetches market data, validates against instrument lot size filters, and provides detailed calculations and warnings.
    async calculatePositionSize(
      category: string,
      symbol: string,
      accountBalance: number,
      riskPercentage: number,
      stopLossPrice: number,
      currentPrice?: number,
      leverage?: number
    ): Promise<{
      recommendedQty: string;
      maxQty: string;
      riskAmount: number;
      positionValue: number;
      stopLossDistance: number;
      riskRewardRatio?: number;
      takeProfitSuggestion?: number;
      warnings: string[];
      calculations: {
        riskPerTrade: number;
        priceDistance: number;
        basePositionSize: number;
        leveragedPositionSize: number;
        marginRequired: number;
      };
      error?: string;
    }> {
      try {
        // Get current price if not provided
        let price = currentPrice;
        if (!price) {
          const ticker = await this.getTickers(category, symbol);
          if ('error' in ticker) {
            return {
              recommendedQty: '0',
              maxQty: '0',
              riskAmount: 0,
              positionValue: 0,
              stopLossDistance: 0,
              warnings: [],
              calculations: {
                riskPerTrade: 0,
                priceDistance: 0,
                basePositionSize: 0,
                leveragedPositionSize: 0,
                marginRequired: 0
              },
              error: `Failed to get price: ${ticker.error}`
            };
          }
          price = parseFloat(ticker.result.list[0].lastPrice);
        }
    
        // Get instrument info for validation
        const instrumentInfo = await this.getInstrumentsInfo(category, symbol);
        if ('error' in instrumentInfo) {
          return {
            recommendedQty: '0',
            maxQty: '0',
            riskAmount: 0,
            positionValue: 0,
            stopLossDistance: 0,
            warnings: [],
            calculations: {
              riskPerTrade: 0,
              priceDistance: 0,
              basePositionSize: 0,
              leveragedPositionSize: 0,
              marginRequired: 0
            },
            error: `Failed to get instrument info: ${instrumentInfo.error}`
          };
        }
    
        const instrument = instrumentInfo.result.list[0];
        const lotSizeFilter = instrument.lotSizeFilter;
        const minOrderQty = parseFloat(lotSizeFilter.minOrderQty);
        const maxOrderQty = parseFloat(lotSizeFilter.maxOrderQty);
        const qtyStep = parseFloat(lotSizeFilter.qtyStep);
    
        const warnings: string[] = [];
        const usedLeverage = leverage || 1;
    
        // Validate inputs
        if (riskPercentage <= 0 || riskPercentage > 100) {
          warnings.push('Risk percentage should be between 0.1% and 100%');
          riskPercentage = Math.max(0.1, Math.min(100, riskPercentage));
        }
    
        if (riskPercentage > 5) {
          warnings.push('Risk percentage > 5% is considered high risk');
        }
    
        // Calculate risk amount
        const riskAmount = (accountBalance * riskPercentage) / 100;
    
        // Calculate stop loss distance
        const stopLossDistance = Math.abs(price - stopLossPrice);
        const stopLossPercentage = (stopLossDistance / price) * 100;
    
        if (stopLossDistance === 0) {
          return {
            recommendedQty: '0',
            maxQty: '0',
            riskAmount,
            positionValue: 0,
            stopLossDistance: 0,
            warnings: ['Stop loss price cannot equal current price'],
            calculations: {
              riskPerTrade: riskAmount,
              priceDistance: 0,
              basePositionSize: 0,
              leveragedPositionSize: 0,
              marginRequired: 0
            },
            error: 'Invalid stop loss price'
          };
        }
    
        // Calculate position size based on risk
        // Risk Amount = Position Size * Stop Loss Distance
        // Position Size = Risk Amount / Stop Loss Distance
        const basePositionSize = riskAmount / stopLossDistance;
        
        // With leverage, we can control a larger position with less margin
        const leveragedPositionSize = basePositionSize * usedLeverage;
        
        // But we need to ensure we don't exceed our margin capacity
        const marginRequired = (leveragedPositionSize * price) / usedLeverage;
        
        // Adjust if margin required exceeds available balance
        let finalPositionSize = leveragedPositionSize;
        if (marginRequired > accountBalance * 0.8) { // Keep 20% buffer
          finalPositionSize = (accountBalance * 0.8 * usedLeverage) / price;
          warnings.push('Position size reduced due to margin constraints');
        }
    
        // Round to valid quantity step
        let recommendedQty = Math.floor(finalPositionSize / qtyStep) * qtyStep;
        
        // Ensure minimum quantity
        if (recommendedQty < minOrderQty) {
          recommendedQty = minOrderQty;
          warnings.push(`Adjusted to minimum quantity: ${minOrderQty}`);
        }
    
        // Ensure maximum quantity
        if (recommendedQty > maxOrderQty) {
          recommendedQty = maxOrderQty;
          warnings.push(`Adjusted to maximum quantity: ${maxOrderQty}`);
        }
    
        // Format to correct decimal places
        const decimalPlaces = qtyStep.toString().split('.')[1]?.length || 0;
        const formattedQty = recommendedQty.toFixed(decimalPlaces);
        const maxQty = maxOrderQty.toFixed(decimalPlaces);
    
        // Calculate position value and risk-reward suggestions
        const positionValue = recommendedQty * price;
        const actualRiskAmount = recommendedQty * stopLossDistance;
        
        // Suggest take profit at 2:1 risk-reward ratio
        const suggestedTakeProfit = stopLossPrice > price 
          ? price - (2 * stopLossDistance) // Short position
          : price + (2 * stopLossDistance); // Long position
    
        const riskRewardRatio = 2.0; // Default 2:1 ratio
    
        // Add risk management warnings
        if (stopLossPercentage > 10) {
          warnings.push(`Stop loss distance is ${stopLossPercentage.toFixed(1)}% - consider tighter stop loss`);
        }
    
        if (actualRiskAmount > riskAmount * 1.1) {
          warnings.push('Actual risk exceeds target risk due to position size constraints');
        }
    
        return {
          recommendedQty: formattedQty,
          maxQty,
          riskAmount: actualRiskAmount,
          positionValue,
          stopLossDistance,
          riskRewardRatio,
          takeProfitSuggestion: suggestedTakeProfit,
          warnings,
          calculations: {
            riskPerTrade: riskAmount,
            priceDistance: stopLossDistance,
            basePositionSize,
            leveragedPositionSize: finalPositionSize,
            marginRequired: (finalPositionSize * price) / usedLeverage
          }
        };
    
      } catch (error: any) {
        return {
          recommendedQty: '0',
          maxQty: '0',
          riskAmount: 0,
          positionValue: 0,
          stopLossDistance: 0,
          warnings: [],
          calculations: {
            riskPerTrade: 0,
            priceDistance: 0,
            basePositionSize: 0,
            leveragedPositionSize: 0,
            marginRequired: 0
          },
          error: error.message
        };
      }
    }
  • The input schema and tool metadata definition for calculate_position_size, registered in the listTools response. Defines parameters, types, descriptions, and required fields.
    {
      name: 'calculate_position_size',
      description: 'Calculate optimal position size based on risk management principles',
      inputSchema: {
        type: 'object',
        properties: {
          category: {
            type: 'string',
            description: 'Category (linear, inverse)',
          },
          symbol: {
            type: 'string',
            description: 'Symbol (e.g., ETHUSDT)',
          },
          accountBalance: {
            type: 'number',
            description: 'Total account balance in USDT',
          },
          riskPercentage: {
            type: 'number',
            description: 'Risk percentage per trade (e.g., 2 for 2%)',
          },
          stopLossPrice: {
            type: 'number',
            description: 'Stop loss price',
          },
          currentPrice: {
            type: 'number',
            description: 'Current price (optional, will fetch if not provided)',
          },
          leverage: {
            type: 'number',
            description: 'Leverage to use (optional, defaults to 1x)',
          },
        },
        required: ['category', 'symbol', 'accountBalance', 'riskPercentage', 'stopLossPrice'],
      },
    },
  • src/index.ts:1004-1022 (registration)
    The dispatch/registration handler in the CallToolRequestSchema that routes calls to the BybitService.calculatePositionSize method and formats the response.
    case 'calculate_position_size': {
      const result = await this.bybitService.calculatePositionSize(
        typedArgs.category,
        typedArgs.symbol,
        typedArgs.accountBalance,
        typedArgs.riskPercentage,
        typedArgs.stopLossPrice,
        typedArgs.currentPrice,
        typedArgs.leverage
      );
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
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 'risk management principles' but fails to specify critical traits like whether this is a read-only calculation, if it modifies any state, error handling, or performance considerations. This is inadequate for a tool with 7 parameters and potential financial implications.

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 unnecessary words. It is front-loaded and appropriately sized, making it easy for an agent to parse quickly.

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 complexity of a financial calculation tool with 7 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain the output format, error conditions, or how results should be interpreted, leaving significant gaps for an agent to use the tool effectively in context.

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, providing clear documentation for all 7 parameters. The description adds no additional semantic context beyond the schema, such as explaining interactions between parameters (e.g., how 'leverage' affects 'position size') or default behaviors. Baseline 3 is appropriate since the schema does the heavy lifting.

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 as 'Calculate optimal position size based on risk management principles,' which specifies the action (calculate) and resource (position size) with a rationale (risk management). However, it doesn't explicitly differentiate from sibling tools like 'validate_order_quantity' or 'place_order,' which might also involve position sizing aspects, leaving some ambiguity about uniqueness.

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. It lacks context about prerequisites, such as needing market data or account information, and doesn't mention sibling tools like 'validate_order_quantity' for validation or 'place_order' for execution, leaving the agent without clear usage boundaries.

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/kondisettyravi/mcp-bybit-node'

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