Skip to main content
Glama
Cognitive-Stack

Volume Wall Detector MCP

fetch-trades

Retrieve recent trades for a specified stock symbol to analyze trading activity and support volume-based price level detection in the Volume Wall Detector MCP server.

Instructions

Fetch recent trades for a symbol

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYesStock symbol to fetch trades for

Implementation Reference

  • Core implementation of fetching recent trades for a given symbol using paginated API calls to /le-table endpoint, parsing into Trade objects with side and time normalization, respecting config limits and rate limiting.
    export const fetchTrades = async (symbol: string): Promise<Trade[]> => {
      const trades: Trade[] = [];
      let lastId: string | undefined;
      
      while (trades.length < config.TRADES_TO_FETCH) {
        const params: Record<string, any> = {
          stockSymbol: symbol,
          pageSize: Math.min(config.PAGE_SIZE, config.TRADES_TO_FETCH - trades.length)
        };
        
        if (lastId) {
          params.lastId = lastId;
        }
        
        const url = `${config.API_BASE_URL}/le-table`;
        const response = await axios.get(url, { headers, params });
        
        const items = response.data.data.items;
        if (!items || items.length === 0) {
          break;
        }
        
        const batchTrades = items.map((item: any) => ({
          trade_id: item._id,
          symbol: item.stockSymbol,
          price: item.price,
          volume: item.vol,
          side: item.side === "bu" || item.side === "sd" ? item.side : "after-hour",
          time: Math.floor(new Date().setHours(
            Number(item.time.split(":")[0]),
            Number(item.time.split(":")[1]),
            Number(item.time.split(":")[2] || 0)
          ) / 1000)
        }));
        
        trades.push(...batchTrades);
        lastId = items[items.length - 1]._id;
        
        // Add small delay to avoid hitting rate limits
        await new Promise(resolve => setTimeout(resolve, 100));
      }
      
      return trades.slice(0, config.TRADES_TO_FETCH);
    }; 
  • Registration of the MCP tool 'fetch-trades' in the exported tools array, defining name, description, input Zod schema, and execute handler that fetches trades via fetchTrades API function and stores them in MongoDB via storeStockData.
    {
      name: "fetch-trades",
      description: "Fetch recent trades for a symbol",
      parameters: z.object({
        symbol: z.string().describe("Stock symbol to fetch trades for")
      }),
      execute: async (args) => {
        const trades = await fetchTrades(args.symbol);
        const result = await storeStockData(trades, "trades");
        return JSON.stringify(result);
      }
    },
  • Zod input schema for the 'fetch-trades' tool, requiring a 'symbol' string parameter.
    parameters: z.object({
      symbol: z.string().describe("Stock symbol to fetch trades for")
    }),
  • Zod schema defining the structure of Trade objects returned by fetchTrades and stored in the database.
    export const TradeSchema = z.object({
      trade_id: z.string(),
      symbol: z.string(),
      price: z.number(),
      volume: z.number(),
      side: z.enum(["bu", "sd", "after-hour"]),
      time: z.number()
    });
  • Helper function to store fetched trades (or order books) into MongoDB, creating indexes, using bulk upsert for trades based on trade_id, and returning storage result which is stringified as tool output.
    export const storeStockData = async (data: OrderBook | Trade[], collectionName: string) => {
      const client = new MongoClient(getMongoUrl());
      
      try {
        await client.connect();
        const db = client.db(config.MONGO_DATABASE);
        const collection = db.collection(collectionName);
        
        // Setup indexes if they don't exist
        if (collectionName === "order_books") {
          await collection.createIndex({ symbol: 1, timestamp: -1 });
        } else if (collectionName === "trades") {
          await collection.createIndex({ symbol: 1, time: -1 });
          await collection.createIndex({ trade_id: 1 }, { unique: true });
        }
        
        if (Array.isArray(data)) {
          if (data.length === 0) {
            return { success: true, inserted_count: 0 };
          }
          
          const operations = data.map(doc => ({
            updateOne: {
              filter: { trade_id: doc.trade_id },
              update: { $set: doc },
              upsert: true
            }
          }));
          
          const result = await collection.bulkWrite(operations);
          return {
            success: true,
            inserted_count: result.upsertedCount + result.modifiedCount
          };
        } else {
          const result = await collection.insertOne(data);
          return {
            success: result.acknowledged,
            inserted_count: result.acknowledged ? 1 : 0
          };
        }
      } catch (error) {
        return {
          success: false,
          error: error instanceof Error ? error.message : "Unknown error"
        };
      } finally {
        await client.close();
      }
    };
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 states the action ('fetch') but doesn't describe traits like whether this is a read-only operation, potential rate limits, authentication needs, or what 'recent' means (e.g., time range, pagination). This leaves significant gaps for a tool that likely queries external data.

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 with zero waste—it directly states the tool's purpose without unnecessary words. It's appropriately sized for a simple tool and front-loaded with the core action.

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 no annotations and no output schema, the description is incomplete for a tool that fetches data. It doesn't explain what 'recent' entails, the return format, or any behavioral context, which are critical for an agent to use it correctly. The simplicity of the tool doesn't compensate for these omissions.

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, with the 'symbol' parameter clearly documented. The description adds no additional meaning beyond what the schema provides (e.g., it doesn't clarify format examples or constraints), so it meets the baseline of 3 where 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 action ('fetch') and target ('recent trades for a symbol'), providing a specific verb+resource combination. However, it doesn't explicitly differentiate from sibling tools like 'analyze-stock' or 'fetch-order-book', which might also involve symbol data, so it misses full sibling 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 like 'analyze-stock' or 'fetch-order-book'. It implies usage for recent trades but offers no exclusions, prerequisites, or context about when it's appropriate, 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

Related 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/Cognitive-Stack/volume-wall-detector-mcp'

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