Skip to main content
Glama
guangxiangdebizi

FinanceMCP

margin_trade

Access margin trading data including target stocks, trade summaries, details, and securities lending information. Retrieve specific data by stock code, date range, or exchange for financial analysis.

Instructions

获取融资融券相关数据,支持多种数据类型:标的股票、交易汇总、交易明细、转融券汇总等

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
data_typeYes数据类型,可选值:margin_secs(融资融券标的股票)、margin(融资融券交易汇总)、margin_detail(融资融券交易明细)、slb_len_mm(做市借券交易汇总)
end_dateNo结束日期,格式YYYYMMDD,如'20240131'(可选,默认为当前日期)
exchangeNo交易所代码,可选值:SSE(上海证券交易所)、SZSE(深圳证券交易所)、BSE(北京证券交易所),仅margin_secs接口使用
start_dateYes起始日期,格式YYYYMMDD,如'20240101'
ts_codeNo股票代码,如'000001.SZ'、'600000.SH'等(部分接口可选)

Implementation Reference

  • The async run method that implements the core handler logic for the 'margin_trade' tool. It validates inputs, calls appropriate Tushare API fetch functions based on data_type, formats the response, and handles errors.
    async run(args: { 
      data_type: string;
      ts_code?: string;
      start_date: string;
      end_date?: string;
      exchange?: string;
    }) {
      try {
        console.log('融资融券数据查询参数:', args);
        
        const TUSHARE_API_KEY = TUSHARE_CONFIG.API_TOKEN;
        const TUSHARE_API_URL = TUSHARE_CONFIG.API_URL;
        
        if (!TUSHARE_API_KEY) {
          throw new Error('请配置TUSHARE_TOKEN环境变量');
        }
    
        let data;
        let formattedOutput;
    
        switch (args.data_type) {
          case 'margin_secs':
            // 融资融券标的(盘前更新)
            data = await fetchMarginSecs(args, TUSHARE_API_KEY, TUSHARE_API_URL);
            formattedOutput = formatMarginSecs(data, args);
            break;
            
          case 'margin':
            // 融资融券交易汇总
            if (!args.ts_code) {
              throw new Error('融资融券交易汇总查询需要提供股票代码(ts_code)');
            }
            data = await fetchMarginSummary(args, TUSHARE_API_KEY, TUSHARE_API_URL);
            formattedOutput = formatMarginSummary(data, args);
            break;
            
          case 'margin_detail':
            // 融资融券交易明细
            if (!args.ts_code) {
              throw new Error('融资融券交易明细查询需要提供股票代码(ts_code)');
            }
            data = await fetchMarginDetail(args, TUSHARE_API_KEY, TUSHARE_API_URL);
            formattedOutput = formatMarginDetail(data, args);
            break;
            
          case 'slb_len_mm':
            // 做市借券交易汇总
            data = await fetchSlbLenMm(args, TUSHARE_API_KEY, TUSHARE_API_URL);
            formattedOutput = formatSlbLenMm(data, args);
            break;
            
          default:
            throw new Error(`不支持的数据类型: ${args.data_type}`);
        }
    
        if (!data || data.length === 0) {
          throw new Error(`未找到相关融资融券数据`);
        }
        
        return {
          content: [{ type: "text", text: formattedOutput }]
        };
    
      } catch (error) {
        console.error('融资融券数据查询错误:', error);
        return {
          content: [{ 
            type: "text", 
            text: `查询融资融券数据时发生错误: ${error instanceof Error ? error.message : '未知错误'}` 
          }]
        };
      }
    }
  • The input schema (parameters) defining the expected arguments for the margin_trade tool, including data_type, ts_code, dates, and exchange.
    parameters: {
      type: "object",
      properties: {
        data_type: {
          type: "string",
          description: "数据类型,可选值:margin_secs(融资融券标的股票)、margin(融资融券交易汇总)、margin_detail(融资融券交易明细)、slb_len_mm(做市借券交易汇总)"
        },
        ts_code: {
          type: "string",
          description: "股票代码,如'000001.SZ'、'600000.SH'等(部分接口可选)"
        },
        start_date: {
          type: "string",
          description: "起始日期,格式YYYYMMDD,如'20240101'"
        },
        end_date: {
          type: "string",
          description: "结束日期,格式YYYYMMDD,如'20240131'(可选,默认为当前日期)"
        },
        exchange: {
          type: "string",
          description: "交易所代码,可选值:SSE(上海证券交易所)、SZSE(深圳证券交易所)、BSE(北京证券交易所),仅margin_secs接口使用"
        }
      },
      required: ["data_type", "start_date"]
  • src/index.ts:319-325 (registration)
    Tool dispatch/registration in the stdio MCP server's CallToolRequestHandler switch statement, extracting args and calling marginTrade.run().
    case "margin_trade": {
      const data_type = String(request.params.arguments?.data_type);
      const ts_code = request.params.arguments?.ts_code ? String(request.params.arguments.ts_code) : undefined;
      const start_date = String(request.params.arguments?.start_date);
      const end_date = request.params.arguments?.end_date ? String(request.params.arguments.end_date) : undefined;
      const exchange = request.params.arguments?.exchange ? String(request.params.arguments.exchange) : undefined;
      return await marginTrade.run({ data_type, ts_code, start_date, end_date, exchange });
  • Tool dispatch/registration in the HTTP MCP server's tools/call handler switch statement, extracting args and calling marginTrade.run().
    case 'margin_trade':
      return await marginTrade.run({
        data_type: String(args?.data_type),
        ts_code: args?.ts_code ? String(args.ts_code) : undefined,
        start_date: String(args?.start_date),
        end_date: args?.end_date ? String(args.end_date) : undefined,
        exchange: args?.exchange ? String(args.exchange) : undefined,
      });
  • Helper function callTushareAPI used by all fetch functions in margin_trade to make authenticated POST requests to Tushare API, parse responses, and handle timeouts/errors.
    async function callTushareAPI(params: any, apiUrl: string, apiName: string) {
      console.log(`请求${apiName}数据,参数:`, params.params);
    
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), TUSHARE_CONFIG.TIMEOUT);
    
      try {
        const response = await fetch(apiUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(params),
          signal: controller.signal
        });
    
        clearTimeout(timeoutId);
    
        if (!response.ok) {
          throw new Error(`Tushare API请求失败: ${response.status}`);
        }
    
        const data = await response.json();
    
        if (data.code !== 0) {
          throw new Error(`Tushare API错误: ${data.msg}`);
        }
    
        if (!data.data || !data.data.items || data.data.items.length === 0) {
          return [];
        }
    
        const fieldsArray = data.data.fields;
        const resultData = data.data.items.map((item: any) => {
          const result: Record<string, any> = {};
          fieldsArray.forEach((field: string, index: number) => {
            result[field] = item[index];
          });
          return result;
        });
    
        console.log(`成功获取到${resultData.length}条${apiName}数据记录`);
        return resultData;
    
      } catch (error) {
        clearTimeout(timeoutId);
        throw error;
      }
    }

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/guangxiangdebizi/FinanceMCP'

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