Skip to main content
Glama
Xxx00xxX33

FinanceMCP

by Xxx00xxX33

margin_trade

Retrieve margin trading data including eligible stocks, transaction summaries, detailed trades, and securities lending information to analyze leveraged investment activities in financial markets.

Instructions

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

Input Schema

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

Implementation Reference

  • Core handler function for the 'margin_trade' tool. Dispatches to specific data fetchers based on 'data_type', calls Tushare API via helpers, formats results, 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 : '未知错误'}` 
          }]
        };
      }
    }
  • Input schema defining parameters 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:229-233 (registration)
    Registration of margin_trade tool in the ListTools handler, exposing name, description, and inputSchema.
    {
      name: marginTrade.name,
      description: marginTrade.description,
      inputSchema: marginTrade.parameters
    },
  • src/index.ts:360-367 (registration)
    Dispatch registration in CallToolRequestSchema handler, extracting arguments and invoking 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 normalizeResult(await marginTrade.run({ data_type, ts_code, start_date, end_date, exchange }));
    }
  • Core helper function that makes HTTP POST requests to Tushare API, parses responses, and converts to structured data. Used by all fetch functions.
    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;
      }
    }
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 describes what data can be retrieved but lacks critical behavioral details: it doesn't specify if this is a read-only operation, mention rate limits, authentication needs, or describe the response format. For a data retrieval tool with multiple parameters and no annotations, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise and front-loaded, stating the core purpose in the first clause and listing data types efficiently. It uses a single sentence with no wasted words, making it easy to parse. However, it could be slightly more structured by separating purpose from data type examples.

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 tool's complexity (5 parameters, no output schema, no annotations), the description is incomplete. It covers what data can be retrieved but lacks information on behavioral traits, output format, and usage context. For a financial data tool with multiple data types and parameters, more guidance is needed to ensure proper agent invocation.

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?

Schema description coverage is 100%, so the schema fully documents all parameters. The description adds minimal value beyond the schema by listing data types (e.g., 标的股票, 交易汇总) that correspond to the data_type parameter, but it doesn't provide additional syntax, format, or usage context. Baseline 3 is appropriate as 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 tool's purpose: '获取融资融券相关数据' (get margin trading related data). It specifies the verb (获取/get) and resource (融资融券相关数据/margin trading related data), making the action explicit. However, it doesn't distinguish this tool from its siblings (e.g., stock_data, money_flow) in terms of domain specificity beyond listing data types.

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. It lists supported data types but doesn't explain scenarios for choosing this tool over siblings like stock_data or money_flow, nor does it mention prerequisites or exclusions. Usage is implied through the data types but not explicitly stated.

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

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