Skip to main content
Glama
patch-ridermg48

TradingView MCP Server

top_gainers

Identify top-performing assets on cryptocurrency exchanges using Bollinger Band analysis across multiple timeframes to support trading decisions.

Instructions

Return top gainers for an exchange and timeframe using bollinger band analysis.

Args:
    exchange: Exchange name like KUCOIN, BINANCE, BYBIT, etc.
    timeframe: One of 5m, 15m, 1h, 4h, 1D, 1W, 1M
    limit: Number of rows to return (max 50)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
exchangeNoKUCOIN
timeframeNo15m
limitNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Primary handler for the 'top_gainers' tool. Registered with @mcp.tool(). Sanitizes input parameters, invokes the _fetch_trending_analysis helper to retrieve data, sorts by gain percentage, and returns formatted list of top gainers with symbols, change percentages, and indicators.
    @mcp.tool()
    def top_gainers(exchange: str = "KUCOIN", timeframe: str = "15m", limit: int = 25) -> list[dict]:
        """Return top gainers for an exchange and timeframe using bollinger band analysis.
        
        Args:
            exchange: Exchange name like KUCOIN, BINANCE, BYBIT, etc.
            timeframe: One of 5m, 15m, 1h, 4h, 1D, 1W, 1M
            limit: Number of rows to return (max 50)
        """
        exchange = sanitize_exchange(exchange, "KUCOIN")
        timeframe = sanitize_timeframe(timeframe, "15m")
        limit = max(1, min(limit, 50))
        
        rows = _fetch_trending_analysis(exchange, timeframe=timeframe, limit=limit)
        # Convert Row objects to dicts properly
        return [{
            "symbol": row["symbol"],
            "changePercent": row["changePercent"], 
            "indicators": dict(row["indicators"])
        } for row in rows]
  • Key helper function implementing the data fetching and processing logic for top gainers. Loads exchange symbols, fetches TradingView analysis in batches, computes Bollinger Band metrics, filters, sorts by change percentage descending, and returns top limited rows in Row format. Called by top_gainers.
    def _fetch_trending_analysis(exchange: str, timeframe: str = "5m", filter_type: str = "", rating_filter: int = None, limit: int = 50) -> List[Row]:
        """Fetch trending coins analysis similar to the original app's trending endpoint."""
        if not TRADINGVIEW_TA_AVAILABLE:
            raise RuntimeError("tradingview_ta is missing; run `uv sync`.")
        
        symbols = load_symbols(exchange)
        if not symbols:
            raise RuntimeError(f"No symbols found for exchange: {exchange}")
        
        # Process symbols in batches due to TradingView API limits
        batch_size = 200  # Considering API limitations
        all_coins = []
        
        screener = EXCHANGE_SCREENER.get(exchange, "crypto")
        
        # Process symbols in batches
        for i in range(0, len(symbols), batch_size):
            batch_symbols = symbols[i:i + batch_size]
            
            try:
                analysis = get_multiple_analysis(screener=screener, interval=timeframe, symbols=batch_symbols)
            except Exception as e:
                continue  # If this batch fails, move to the next one
                
            # Process coins in this batch
            for key, value in analysis.items():
                try:
                    if value is None:
                        continue
                        
                    indicators = value.indicators
                    metrics = compute_metrics(indicators)
                    
                    if not metrics or metrics.get('bbw') is None:
                        continue
                    
                    # Apply rating filter if specified
                    if filter_type == "rating" and rating_filter is not None:
                        if metrics['rating'] != rating_filter:
                            continue
                    
                    all_coins.append(Row(
                        symbol=key,
                        changePercent=metrics['change'],
                        indicators=IndicatorMap(
                            open=metrics.get('open'),
                            close=metrics.get('price'),
                            SMA20=indicators.get("SMA20"),
                            BB_upper=indicators.get("BB.upper"),
                            BB_lower=indicators.get("BB.lower"),
                            EMA50=indicators.get("EMA50"),
                            RSI=indicators.get("RSI"),
                            volume=indicators.get("volume"),
                        )
                    ))
                    
                except (TypeError, ZeroDivisionError, KeyError):
                    continue
        
        # Sort all coins by change percentage
        all_coins.sort(key=lambda x: x["changePercent"], reverse=True)
        
        return all_coins[:limit]
  • TypedDict schema defining the structure of each row in the top_gainers response: symbol, changePercent, and indicators map.
    class Row(TypedDict):
    	symbol: str
    	changePercent: float
    	indicators: IndicatorMap
  • Imports for supporting helpers: compute_metrics for indicator calculations, load_symbols for exchange symbols, and validators for input sanitization and constants used in top_gainers implementation.
    from tradingview_mcp.core.services.indicators import compute_metrics
    from tradingview_mcp.core.services.coinlist import load_symbols
    from tradingview_mcp.core.utils.validators import sanitize_timeframe, sanitize_exchange, EXCHANGE_SCREENER, ALLOWED_TIMEFRAMES
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 the analysis method ('bollinger band analysis') and a constraint ('max 50' for limit), but lacks critical details: it doesn't specify what 'top gainers' means (e.g., price percentage change?), whether this is a read-only operation, potential rate limits, or data freshness. For a financial analysis tool with no annotations, this is insufficient.

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 well-structured and appropriately sized. The first sentence states the purpose clearly, followed by a bullet-point-like 'Args' section that efficiently documents parameters. There's no redundant information, and the content is front-loaded with the core functionality.

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

Completeness3/5

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

Given the tool's complexity (financial analysis with 3 parameters), no annotations, but an output schema exists, the description is moderately complete. It covers the purpose and parameters adequately, but lacks behavioral context (e.g., how 'top gainers' is calculated, data sources). The output schema likely handles return values, so that gap is mitigated, but overall it's minimal for a tool with no annotations.

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

Parameters4/5

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

Schema description coverage is 0%, so the description must compensate. It adds meaningful semantics: it explains 'exchange' with examples (KUCOIN, BINANCE, BYBIT), 'timeframe' with allowed values (5m, 15m, etc.), and 'limit' with its max constraint (50). This goes beyond the schema's basic titles and defaults, providing practical context for all three parameters.

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: 'Return top gainers for an exchange and timeframe using bollinger band analysis.' It specifies the verb ('return'), resource ('top gainers'), and methodology ('bollinger band analysis'), which distinguishes it from generic analysis tools. However, it doesn't explicitly differentiate from sibling tools like 'top_losers' beyond the obvious gainers vs. losers distinction.

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 doesn't mention sibling tools like 'bollinger_scan' or 'volume_breakout_scanner', nor does it specify scenarios where this tool is preferred or excluded. The only contextual information is the parameter descriptions, which don't constitute usage guidelines.

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/patch-ridermg48/tradingview-mcp'

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