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
| Name | Required | Description | Default |
|---|---|---|---|
| symbol | Yes | Stock symbol to fetch trades for |
Input Schema (JSON Schema)
{
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": false,
"properties": {
"symbol": {
"description": "Stock symbol to fetch trades for",
"type": "string"
}
},
"required": [
"symbol"
],
"type": "object"
}
Implementation Reference
- src/services/api.ts:36-79 (handler)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); };
- src/services/tools.ts:22-33 (registration)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); } },
- src/services/tools.ts:25-27 (schema)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") }),
- src/types/tools.ts:31-38 (schema)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() });
- src/services/mongodb.ts:16-65 (helper)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(); } };