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();
      }
    };
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