Skip to main content
Glama
phuihock

TA-Lib MCP Server

by phuihock

calculate_ema

Calculate Exponential Moving Average (EMA) for financial market analysis using TA-Lib technical indicators to identify price trends and support trading decisions.

Instructions

Calculate Exponential Moving Average (EMA).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
kwargsYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Primary execution handler for the calculate_ema tool. Registered via @mcp.tool() decorator. Delegates computation to EMAIndicator from registry.
    @mcp.tool()
    async def calculate_ema(
        close: List[float],
        timeperiod: int = 20
    ) -> Dict[str, Any]:
        """Calculate Exponential Moving Average (EMA).
        
        Args:
            close: List of closing prices
            timeperiod: Number of periods for average (default: 20)
            
        Returns:
            Dictionary with EMA values and metadata
        """
        try:
            # Get indicator from registry
            indicator = registry.get_indicator("ema")
            if not indicator:
                raise ValueError("EMA indicator not found")
            
            # Create market data
            market_data = MarketData(close=close)
            
            # Calculate indicator
            result = await indicator.calculate(market_data, {"timeperiod": timeperiod})
            
            if result.success:
                return {
                    "success": True,
                    "values": result.values,
                    "metadata": result.metadata,
                }
            else:
                return {
                    "success": False,
                    "error": result.error_message,
                }
                
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
            }
  • EMAIndicator class containing the core EMA calculation logic, input schema, and metadata handling used by the tool handler.
    class EMAIndicator(BaseIndicator):
        """Exponential Moving Average (EMA) indicator implementation."""
        
        def __init__(self):
            """Initialize EMA indicator."""
            super().__init__(
                name="ema",
                description="Exponential Moving Average (EMA) - gives more weight to recent prices"
            )
        
        @property
        def input_schema(self) -> Dict[str, Any]:
            return {
                "type": "object",
                "properties": {
                    "close_prices": {
                        "type": "array",
                        "items": {"type": "number"},
                        "description": "List of closing prices"
                    },
                    "timeperiod": {
                        "type": "integer",
                        "default": 20,
                        "description": "Number of periods for EMA calculation"
                    }
                },
                "required": ["close_prices"]
            }
        
        async def calculate(
            self, 
            market_data: MarketData, 
            options: Dict[str, Any] = None
        ) -> IndicatorResult:
            """Calculate EMA indicator."""
            if options is None:
                options = {}
            
            timeperiod = options.get("timeperiod", 20)
            close_prices = market_data.close
            
            if len(close_prices) < timeperiod:
                return IndicatorResult(
                    indicator_name=self.name,
                    success=False,
                    values={},
                    error_message=f"Not enough data points. Need at least {timeperiod}, got {len(close_prices)}"
                )
            
            # Calculate EMA
            # Multiplier: (2 / (timeperiod + 1))
            multiplier = 2.0 / (timeperiod + 1)
            
            # Initialize EMA with SMA of first timeperiod values
            ema_values = []
            initial_sma = sum(close_prices[:timeperiod]) / timeperiod
            ema_values.append(initial_sma)
            
            # Calculate EMA for remaining values
            for i in range(timeperiod, len(close_prices)):
                ema = (close_prices[i] - ema_values[-1]) * multiplier + ema_values[-1]
                ema_values.append(ema)
            
            return IndicatorResult(
                indicator_name=self.name,
                success=True,
                values={"ema": ema_values},
                metadata={
                    "timeperiod": timeperiod,
                    "multiplier": multiplier,
                    "input_points": len(close_prices),
                    "output_points": len(ema_values)
                }
            )
  • Registration of the EMAIndicator in the global indicator registry, enabling registry.get_indicator('ema') in the handler.
    registry.register("ema", EMAIndicator)
  • JSON schema definition for inputs to the EMA calculation.
    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "close_prices": {
                    "type": "array",
                    "items": {"type": "number"},
                    "description": "List of closing prices"
                },
                "timeperiod": {
                    "type": "integer",
                    "default": 20,
                    "description": "Number of periods for EMA calculation"
                }
            },
            "required": ["close_prices"]
        }
Behavior1/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. 'Calculate' implies a read-only computation, but the description doesn't specify whether this requires data inputs, what format the output takes, potential errors, or computational characteristics. It lacks any context about what gets calculated, data sources, or performance considerations.

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 extremely concise—a single sentence with no wasted words. It's front-loaded with the core purpose. However, this conciseness comes at the cost of completeness, as noted in other dimensions.

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 (technical indicator calculation with 1 undocumented parameter) and the presence of an output schema (which might help with return values), the description is incomplete. It doesn't address the undocumented parameter, lacks behavioral context, and doesn't differentiate from many siblings. While the output schema might cover return values, the description doesn't provide enough context for effective tool selection and use.

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

Parameters1/5

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

The input schema has 1 parameter (kwargs) with 0% schema description coverage, meaning the schema provides no documentation. The description adds no parameter information beyond the tool name—it doesn't explain what 'kwargs' should contain (e.g., price data, period length), expected format, or examples. This fails to compensate for the complete lack of schema 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 'Calculate Exponential Moving Average (EMA)' clearly states the mathematical operation (calculate) and specific technical indicator (EMA), which is a specific verb+resource. However, it doesn't distinguish this tool from its many sibling technical indicator calculation tools (like calculate_sma, calculate_wma, calculate_rsi, etc.), leaving the agent to guess when EMA is specifically needed versus other moving averages or indicators.

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. With 17 sibling tools for various technical indicators, there's no mention of EMA's specific use cases (e.g., trend-following, smoothing price data), when to prefer it over other moving averages (like SMA or DEMA), or any prerequisites. The agent must infer usage from the tool name alone.

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/phuihock/mcp-talib'

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