Skip to main content
Glama
qeinfinity

Binance MCP Server

get_market_data

Retrieve comprehensive cryptocurrency market data for trading pairs on Binance spot or futures markets to analyze prices and trends.

Instructions

Get comprehensive market data for a trading pair

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYesTrading pair symbol (e.g., BTCUSDT)
typeYesMarket type

Implementation Reference

  • Core handler function that fetches spot market data or comprehensive futures data (including ticker, open interest, funding rate, mark price, and recent liquidations) from Binance REST API endpoints using axios with exponential backoff retry logic.
    public async getMarketData(symbol: string, type: 'spot' | 'futures'): Promise<any> {
      try {
        logger.info(`Getting ${type} market data for ${symbol}`);
    
        if (type === 'spot') {
          const data = await this.executeWithRetry(() =>
            this.axiosInstance.get(`${config.SPOT_REST_URL}/ticker/24hr`, {
              params: { symbol: symbol.toUpperCase() }
            }).then(response => response.data)
          );
          logger.info('Successfully fetched spot market data');
          return data;
        }
    
        // For futures, fetch all relevant data in parallel
        logger.info('Fetching futures data from multiple endpoints...');
        
        try {
          const [
            marketData,
            openInterest,
            fundingData,
            liquidations
          ] = await Promise.all([
            // Basic market data
            this.executeWithRetry(() =>
              this.axiosInstance.get(`${config.FUTURES_REST_URL}/ticker/24hr`, {
                params: { symbol: symbol.toUpperCase() }
              }).then(response => {
                logger.info('Successfully fetched futures ticker data');
                return response.data;
              })
            ),
            // Open interest
            this.executeWithRetry(() =>
              this.axiosInstance.get(`${config.FUTURES_REST_URL}/openInterest`, {
                params: { symbol: symbol.toUpperCase() }
              }).then(response => {
                logger.info('Successfully fetched open interest data');
                return response.data;
              })
            ),
            // Premium index (funding rate)
            this.executeWithRetry(() =>
              this.axiosInstance.get(`${config.FUTURES_REST_URL}/premiumIndex`, {
                params: {
                  symbol: symbol.toUpperCase()
                }
              }).then(response => {
                logger.info('Successfully fetched funding rate data');
                return response.data;
              })
            ),
            // Recent liquidations
            this.executeWithRetry(() =>
              this.axiosInstance.get(`${config.FUTURES_REST_URL}/forceOrders`, {
                params: {
                  symbol: symbol.toUpperCase(),
                  startTime: Date.now() - 24 * 60 * 60 * 1000,
                  limit: 100
                }
              }).then(response => {
                logger.info('Successfully fetched liquidations data');
                return response.data;
              })
            )
          ]);
    
          logger.info('Successfully fetched all futures data, combining responses...');
    
          // Combine all futures data with correct field mappings
          const combinedData = {
            ...marketData,
            openInterest: openInterest.openInterest,
            fundingRate: fundingData.lastFundingRate,
            markPrice: fundingData.markPrice,
            nextFundingTime: fundingData.nextFundingTime,
            liquidations24h: liquidations.length,
            liquidationVolume24h: liquidations.reduce((sum: number, order: any) => 
              sum + parseFloat(order.executedQty), 0
            )
          };
    
          logger.info('Successfully combined futures data');
          return combinedData;
    
        } catch (error) {
          logger.error('Error in futures data Promise.all:', error);
          throw error;
        }
    
      } catch (error) {
        logger.error('Error fetching market data:', error);
        throw new APIError('Failed to fetch market data', error as Error);
      }
    }
  • src/index.ts:47-65 (registration)
    MCP tool registration including name, description, and input schema definition for get_market_data.
    {
      name: "get_market_data",
      description: "Get comprehensive market data for a trading pair",
      inputSchema: {
        type: "object",
        properties: {
          symbol: { 
            type: "string", 
            description: "Trading pair symbol (e.g., BTCUSDT)" 
          },
          type: { 
            type: "string", 
            enum: ["spot", "futures"], 
            description: "Market type" 
          }
        },
        required: ["symbol", "type"]
      }
    },
  • Top-level MCP tool handler that validates input parameters using type guard and delegates to the BinanceRestConnector's getMarketData method, returning JSON-formatted response.
    case "get_market_data": {
      if (!isMarketDataParams(request.params.arguments)) {
        throw new Error('Invalid market data parameters');
      }
      const { symbol, type } = request.params.arguments;
      const data = await restConnector.getMarketData(symbol, type);
      return {
        content: [{
          type: "text",
          text: JSON.stringify(data, null, 2)
        }]
      };
    }
  • TypeScript interface and type guard for validating get_market_data input parameters.
    export interface MarketDataParams {
      symbol: string;
      type: 'spot' | 'futures';
    }
    
    export interface KlineParams {
      symbol: string;
      type: 'spot' | 'futures';
      interval: string;
      limit?: number;
    }
    
    export interface StreamParams {
      symbol: string;
      type: 'spot' | 'futures';
      streams: string[];
    }
    
    export interface FuturesDataParams {
      symbol: string;
    }
    
    export class APIError extends Error {
      constructor(message: string, public readonly cause?: Error) {
        super(message);
        this.name = 'APIError';
      }
    }
    
    // Type guards
    export function isMarketDataParams(params: any): params is MarketDataParams {
      return (
        typeof params === 'object' &&
        typeof params.symbol === 'string' &&
        (params.type === 'spot' || params.type === 'futures')
      );
    }
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 states the tool 'gets' data, implying a read-only operation, but doesn't cover critical aspects like rate limits, authentication needs, data freshness, or error handling. For a tool with no annotations, this leaves significant gaps in understanding its behavior.

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 fluff. It's appropriately sized and front-loaded, making it easy to parse quickly, with every word contributing to understanding 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 complexity of market data tools and the lack of annotations and output schema, the description is insufficient. It doesn't explain what 'comprehensive market data' includes (e.g., prices, volumes), return formats, or how it differs from siblings. For a tool with no structured behavioral data, more context is needed to guide 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 description adds no specific meaning beyond what the input schema provides. With 100% schema description coverage, the schema already documents both parameters ('symbol' and 'type') clearly, including examples and enums. The description doesn't elaborate on parameter interactions or usage, so it meets the baseline for high schema coverage without adding value.

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 ('Get') and resource ('comprehensive market data for a trading pair'), making it easy to understand what it does. However, it doesn't explicitly differentiate from sibling tools like 'get_klines' or 'get_futures_funding_rate', which also retrieve market-related data, so it falls short of a perfect 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. With siblings like 'get_klines' (likely for historical data) and 'get_futures_funding_rate' (specific to futures), there's no indication of context, prerequisites, or exclusions, leaving the agent to guess based on tool names 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/qeinfinity/binance-mcp-server'

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