JSON-RPC API Documentation

Comprehensive guide to our JSON-RPC API endpoints, including the new portfolio analysis features.

MCP Financial JSON-RPC API Documentation

Overview

The MCP Financial API provides comprehensive financial analysis tools through a JSON-RPC 2.0 interface. This document outlines the available methods, their parameters, and expected responses.

Base URL: /api/jsonrpc

Authentication

Authentication is required for most endpoints. Include your API key in the request headers:

Authorization: Bearer YOUR_API_KEY

JSON-RPC Request Format

All requests should follow the JSON-RPC 2.0 specification:

{
  "jsonrpc": "2.0",
  "method": "method.name",
  "params": {
    "param1": "value1",
    "param2": "value2"
  },
  "id": "request-id"
}

JSON-RPC Response Format

Successful responses:

{
  "jsonrpc": "2.0",
  "id": "request-id",
  "result": {
    // Result data
  }
}

Error responses:

{
  "jsonrpc": "2.0",
  "id": "request-id",
  "error": {
    "code": -32000,
    "message": "Error message"
  }
}

Service Discovery Methods

discover.getAvailableMetrics

List all available financial metrics.

Parameters: - category (optional): Filter metrics by category - creator_id (optional): Filter metrics by creator - is_custom (optional): Filter by custom/standard metrics

Response:

{
  "metrics": [
    {
      "id": "metric_id",
      "name": "Metric Name",
      "description": "Metric description",
      "formula": "Formula",
      "parameters": {},
      "category": "Category"
    }
  ]
}

discover.getMetricSchema

Get detailed schema for a specific metric.

Parameters: - metric_id (required): ID of the metric

Response:

{
  "metric": {
    "id": "metric_id",
    "name": "Metric Name",
    "description": "Metric description",
    "formula": "Formula",
    "parameters": {},
    "category": "Category",
    "is_custom": false,
    "creator_id": null
  }
}

Financial Calculation Methods

finance.calculateRatio

Calculate a financial ratio.

Parameters: - ratio_type (required): Type of ratio (e.g., "debt_to_equity", "current_ratio") - numerator (required if not using stored data): Numerator value - denominator (required if not using stored data): Denominator value - year (optional): Year to use for stored financial data

Response:

{
  "ratio_type": "debt_to_equity",
  "ratio": 0.75,
  "numerator": 1000,
  "denominator": 1333.33,
  "interpretation": "The company has a healthy debt-to-equity ratio of 0.75, indicating moderate leverage."
}

finance.analyzeStatement

Analyze a financial statement.

Parameters: - statement_text (required): Text of the financial statement to analyze

Response:

{
  "metrics": {
    "revenue": 1000000,
    "expenses": 800000,
    "net_income": 200000
  },
  "ratios": {
    "profit_margin": 0.2,
    "expense_ratio": 0.8
  },
  "analysis": "The company shows a healthy profit margin of 20%..."
}

Marketstack API Methods

marketstack.getLatestPrice

Get the latest price data for one or more symbols.

Parameters: - symbols (required): Single symbol or comma-separated list of symbols - exchange (optional): Filter by exchange - limit (optional): Limit number of results - offset (optional): Offset for pagination

Response:

{
  "success": true,
  "data": [
    {
      "symbol": "AAPL",
      "name": "Apple Inc.",
      "exchange": "NASDAQ",
      "close": 185.92,
      "date": "2025-03-14"
    }
  ],
  "pagination": {
    "limit": 100,
    "offset": 0,
    "count": 1,
    "total": 1
  }
}

marketstack.getHistoricalData

Get historical stock data for one or more symbols.

Parameters: - symbols (required): Single symbol or comma-separated list of symbols - date_from (optional): Start date in YYYY-MM-DD format - date_to (optional): End date in YYYY-MM-DD format - exchange (optional): Filter by exchange - sort (optional): Sort direction ("ASC" or "DESC") - limit (optional): Limit number of results - offset (optional): Offset for pagination

Response:

{
  "success": true,
  "data": [
    {
      "symbol": "AAPL",
      "name": "Apple Inc.",
      "exchange": "NASDAQ",
      "open": 184.50,
      "high": 186.00,
      "low": 183.75,
      "close": 185.92,
      "volume": 30456789,
      "date": "2025-03-14"
    }
  ],
  "pagination": {
    "limit": 100,
    "offset": 0,
    "count": 1,
    "total": 1
  },
  "analysis": {
    "start_price": 150.25,
    "end_price": 185.92,
    "price_change": 35.67,
    "percent_change": 23.74,
    "trend": "up"
  }
}

marketstack.getEODData

Get end-of-day stock data.

Parameters: - symbols (required): Single symbol or comma-separated list of symbols - date (optional): Specific date in YYYY-MM-DD format - exchange (optional): Filter by exchange - sort (optional): Sort direction ("ASC" or "DESC") - limit (optional): Limit number of results - offset (optional): Offset for pagination

Response:

{
  "success": true,
  "data": [
    {
      "symbol": "AAPL",
      "name": "Apple Inc.",
      "exchange": "NASDAQ",
      "open": 184.50,
      "high": 186.00,
      "low": 183.75,
      "close": 185.92,
      "volume": 30456789,
      "date": "2025-03-14"
    }
  ],
  "pagination": {
    "limit": 100,
    "offset": 0,
    "count": 1,
    "total": 1
  }
}

Technical Indicators Methods

technicals.rsi

Calculate Relative Strength Index (RSI) for price data.

Parameters: - prices (required): Array of price data objects with date and close price - window (optional): Period for RSI calculation, default is 14

Response:

{
  "rsi_values": [
    {
      "date": "2025-03-01",
      "rsi": 65.42
    }
  ],
  "current_rsi": 65.42,
  "interpretation": "The current RSI of 65.42 indicates that the asset is approaching overbought conditions."
}

technicals.macd

Calculate Moving Average Convergence Divergence (MACD).

Parameters: - prices (required): Array of price data objects with date and close price - fast_period (optional): Fast EMA period, default is 12 - slow_period (optional): Slow EMA period, default is 26 - signal_period (optional): Signal EMA period, default is 9

Response:

{
  "macd_values": [
    {
      "date": "2025-03-01",
      "macd": 2.15,
      "signal": 1.75,
      "histogram": 0.40
    }
  ],
  "current_macd": 2.15,
  "current_signal": 1.75,
  "current_histogram": 0.40,
  "interpretation": "MACD is above the signal line and showing positive momentum."
}

technicals.bollinger

Calculate Bollinger Bands.

Parameters: - prices (required): Array of price data objects with date and close price - window (optional): Window for moving average, default is 20 - num_std (optional): Number of standard deviations, default is 2.0

Response:

{
  "bollinger_values": [
    {
      "date": "2025-03-01",
      "upper": 195.30,
      "middle": 185.50,
      "lower": 175.70
    }
  ],
  "current_upper": 195.30,
  "current_middle": 185.50,
  "current_lower": 175.70,
  "interpretation": "Price is in the middle of the Bollinger Bands, indicating neutral volatility."
}

technicals.movingAverages

Calculate Moving Averages.

Parameters: - prices (required): Array of price data objects with date and close price - short_window (optional): Short MA window, default is 50 - long_window (optional): Long MA window, default is 200

Response:

{
  "ma_values": [
    {
      "date": "2025-03-01",
      "ma_short": 182.50,
      "ma_long": 165.75
    }
  ],
  "current_ma_short": 182.50,
  "current_ma_long": 165.75,
  "interpretation": "Short-term MA above long-term MA indicates bullish trend."
}

technicals.returns

Calculate returns and related metrics.

Parameters: - prices (required): Array of price data objects with date and close price - risk_free_rate (optional): Risk-free rate for Sharpe ratio, default is 0.02

Response:

{
  "daily_returns": [
    {
      "date": "2025-03-01",
      "return": 0.0125
    }
  ],
  "mean_daily_return": 0.0015,
  "annualized_return": 0.378,
  "volatility": 0.20,
  "sharpe_ratio": 1.89,
  "max_drawdown": 0.15,
  "interpretation": "Asset shows strong returns with good risk-adjusted performance."
}

Portfolio Analysis Methods

portfolio.createPortfolio

Create a new portfolio.

Parameters: - portfolio_name (required): Name for the portfolio

Response:

{
  "success": true,
  "portfolio_name": "Tech Portfolio",
  "message": "Portfolio 'Tech Portfolio' created successfully"
}

portfolio.addHolding

Add a stock holding to a portfolio.

Parameters: - portfolio_name (required): Name of the portfolio - symbol (required): Stock symbol - shares (required): Number of shares - cost_basis (optional): Cost basis per share

Response:

{
  "success": true,
  "portfolio_name": "Tech Portfolio",
  "symbol": "AAPL",
  "shares": 10,
  "cost_basis": 180.0,
  "message": "Added 10 shares of AAPL to portfolio 'Tech Portfolio'",
  "current_value": {
    "total_value": 1859.20,
    "holdings": {
      "AAPL": {
        "shares": 10,
        "current_price": 185.92,
        "value": 1859.20,
        "cost_basis": 180.0,
        "total_cost": 1800.0,
        "profit_loss": 59.20,
        "profit_loss_pct": 3.29
      }
    }
  }
}

portfolio.removeHolding

Remove a stock holding from a portfolio.

Parameters: - portfolio_name (required): Name of the portfolio - symbol (required): Stock symbol to remove

Response:

{
  "success": true,
  "portfolio_name": "Tech Portfolio",
  "symbol": "AAPL",
  "message": "Removed AAPL from portfolio 'Tech Portfolio'",
  "current_value": {
    "total_value": 0,
    "holdings": {}
  }
}

portfolio.calculateValue

Calculate the current value of a portfolio.

Parameters: - portfolio_name (required): Name of the portfolio

Response:

{
  "total_value": 9876.54,
  "holdings": {
    "AAPL": {
      "shares": 10,
      "current_price": 185.92,
      "value": 1859.20,
      "cost_basis": 180.0,
      "total_cost": 1800.0,
      "profit_loss": 59.20,
      "profit_loss_pct": 3.29,
      "allocation": 18.83
    },
    "MSFT": {
      "shares": 15,
      "current_price": 337.50,
      "value": 5062.50,
      "cost_basis": 320.0,
      "total_cost": 4800.0,
      "profit_loss": 262.50,
      "profit_loss_pct": 5.47,
      "allocation": 51.26
    },
    "GOOG": {
      "shares": 20,
      "current_price": 147.74,
      "value": 2954.80,
      "cost_basis": 140.0,
      "total_cost": 2800.0,
      "profit_loss": 154.80,
      "profit_loss_pct": 5.53,
      "allocation": 29.91
    }
  },
  "as_of": "2025-03-14 21:15:30"
}

portfolio.optimize

Optimize a portfolio using various methods.

Parameters: - portfolio_name (required): Name of the portfolio - optimization_method (optional): Method to use ("efficient_frontier", "min_volatility", "max_sharpe", "hrp", "cla"), default is "efficient_frontier" - risk_free_rate (optional): Risk-free rate for Sharpe ratio, default is 0.02 - target_return (optional): Target return for efficient frontier optimization

Response:

{
  "success": true,
  "portfolio_name": "Tech Portfolio",
  "optimization_method": "max_sharpe",
  "optimization_parameters": {
    "risk_free_rate": 0.02,
    "target_return": null
  },
  "performance_metrics": {
    "expected_annual_return": 0.25,
    "expected_annual_volatility": 0.18,
    "sharpe_ratio": 1.28,
    "diversification_score": 0.85,
    "weights": {
      "AAPL": 0.35,
      "MSFT": 0.40,
      "GOOG": 0.25
    }
  },
  "discrete_allocation": {
    "allocation": {
      "AAPL": 188,
      "MSFT": 118,
      "GOOG": 169
    },
    "remaining_cash": 52.08
  }
}

portfolio.getAllocation

Get a discrete allocation for a specific portfolio value.

Parameters: - portfolio_name (required): Name of the portfolio - total_value (optional): Total value to allocate, default is 100000 - optimized (optional): Whether to use optimized weights or current weights, default is true

Response:

{
  "success": true,
  "portfolio_name": "Tech Portfolio",
  "total_value": 100000,
  "optimized": true,
  "allocation": {
    "allocation": {
      "AAPL": 188,
      "MSFT": 118,
      "GOOG": 169
    },
    "remaining_cash": 52.08
  }
}

portfolio.generateReport

Generate a comprehensive portfolio report.

Parameters: - portfolio_name (required): Name of the portfolio

Response:

{
  "success": true,
  "portfolio_name": "Tech Portfolio",
  "report": {
    "summary": {
      "portfolio_name": "Tech Portfolio",
      "total_value": 9876.54,
      "num_holdings": 3,
      "created_at": "2025-03-14",
      "as_of": "2025-03-14 21:15:30"
    },
    "performance_metrics": {
      "expected_return": 0.25,
      "annual_volatility": 0.18,
      "sharpe_ratio": 1.28,
      "sortino_ratio": 1.75,
      "max_drawdown": 0.18,
      "diversification_score": 0.85
    },
    "holdings": {
      "AAPL": {
        "shares": 10,
        "current_price": 185.92,
        "value": 1859.20,
        "cost_basis": 180.0,
        "allocation": 18.83
      },
      "MSFT": {
        "shares": 15,
        "current_price": 337.50,
        "value": 5062.50,
        "cost_basis": 320.0,
        "allocation": 51.26
      },
      "GOOG": {
        "shares": 20,
        "current_price": 147.74,
        "value": 2954.80,
        "cost_basis": 140.0,
        "allocation": 29.91
      }
    },
    "optimized_weights": {
      "AAPL": 0.35,
      "MSFT": 0.40,
      "GOOG": 0.25
    },
    "discrete_allocation": {
      "allocation": {
        "AAPL": 188,
        "MSFT": 118,
        "GOOG": 169
      },
      "remaining_cash": 52.08
    },
    "plots": {
      "allocation_pie": "/static/portfolio_outputs/Tech_Portfolio_allocation_pie.png",
      "efficient_frontier": "/static/portfolio_outputs/Tech_Portfolio_efficient_frontier.png",
      "performance_comparison": "/static/portfolio_outputs/Tech_Portfolio_performance.png",
      "correlation_heatmap": "/static/portfolio_outputs/Tech_Portfolio_correlation.png"
    }
  }
}

Error Codes

Code Message Description
-32600 Invalid Request The JSON sent is not a valid Request
-32601 Method not found The method does not exist
-32602 Invalid params Invalid method parameters
-32603 Internal error Internal JSON-RPC error
-32000 Server error Custom server error
-32001 Authentication error Authentication failed
-32002 Rate limit exceeded Too many requests
-32003 Permission denied Insufficient permissions
-32004 Resource not found Requested resource not found
-32005 External API error Error in external API call

Examples

Example 1: Get the latest price for Apple stock

Request:

{
  "jsonrpc": "2.0",
  "method": "marketstack.getLatestPrice",
  "params": {
    "symbols": "AAPL"
  },
  "id": "1"
}

Response:

{
  "jsonrpc": "2.0",
  "id": "1",
  "result": {
    "success": true,
    "data": [
      {
        "symbol": "AAPL",
        "name": "Apple Inc.",
        "exchange": "NASDAQ",
        "close": 185.92,
        "date": "2025-03-14"
      }
    ],
    "pagination": {
      "limit": 100,
      "offset": 0,
      "count": 1,
      "total": 1
    }
  }
}

Example 2: Create a portfolio and add holdings

Create Portfolio Request:

{
  "jsonrpc": "2.0",
  "method": "portfolio.createPortfolio",
  "params": {
    "portfolio_name": "Tech Portfolio"
  },
  "id": "2"
}

Add Holding Request:

{
  "jsonrpc": "2.0",
  "method": "portfolio.addHolding",
  "params": {
    "portfolio_name": "Tech Portfolio",
    "symbol": "AAPL",
    "shares": 10,
    "cost_basis": 180.0
  },
  "id": "3"
}

Example 3: Optimize a portfolio

Request:

{
  "jsonrpc": "2.0",
  "method": "portfolio.optimize",
  "params": {
    "portfolio_name": "Tech Portfolio",
    "optimization_method": "max_sharpe",
    "risk_free_rate": 0.02
  },
  "id": "4"
}

SDK Integration

We provide client SDKs for easy integration with our API:

Python SDK

The Python SDK provides a clean, Pythonic interface to our JSON-RPC API.

Installation

pip install mcpfinancials

Usage

from mcpfinancials import MCPClient

# Initialize client with your API key
client = MCPClient(api_key="your_api_key")

# Create a portfolio
result = client.portfolio.create_portfolio("Tech Portfolio")
print(f"Portfolio created: {result['portfolio_name']}")

# Add holdings
client.portfolio.add_holding("Tech Portfolio", "AAPL", 10, 180.0)
client.portfolio.add_holding("Tech Portfolio", "MSFT", 15, 320.0)
client.portfolio.add_holding("Tech Portfolio", "GOOG", 20, 140.0)

# Get portfolio value
value = client.portfolio.calculate_value("Tech Portfolio")
print(f"Total portfolio value: ${value['total_value']:.2f}")

# Optimize portfolio
optimization = client.portfolio.optimize("Tech Portfolio", optimization_method="max_sharpe")
print("Optimized weights:")
for symbol, weight in optimization['performance_metrics']['weights'].items():
    print(f"  {symbol}: {weight:.2%}")

# Generate portfolio report with visualizations
report = client.portfolio.generate_report("Tech Portfolio")
print(f"Portfolio report generated. Plots available in {report['report']['plots']}")

JavaScript/TypeScript SDK

Our JavaScript/TypeScript SDK is available for both browser and Node.js environments.

Installation

npm install mcpfinancials
# or
yarn add mcpfinancials

Usage

import { MCPClient } from 'mcpfinancials';

// Initialize client with your API key
const client = new MCPClient({ apiKey: 'your_api_key' });

// Create a portfolio
async function managePortfolio() {
  try {
    // Create portfolio
    const portfolio = await client.portfolio.createPortfolio({
      portfolio_name: 'Tech Portfolio'
    });
    console.log(`Portfolio created: ${portfolio.portfolio_name}`);

    // Add holdings
    await client.portfolio.addHolding({
      portfolio_name: 'Tech Portfolio',
      symbol: 'AAPL',
      shares: 10,
      cost_basis: 180.0
    });

    // Get current value
    const value = await client.portfolio.calculateValue({
      portfolio_name: 'Tech Portfolio'
    });
    console.log(`Total portfolio value: $${value.total_value.toFixed(2)}`);

    // Optimize portfolio
    const optimization = await client.portfolio.optimize({
      portfolio_name: 'Tech Portfolio',
      optimization_method: 'max_sharpe'
    });

    console.log('Optimized weights:');
    const weights = optimization.performance_metrics.weights;
    Object.keys(weights).forEach(symbol => {
      console.log(`  ${symbol}: ${(weights[symbol] * 100).toFixed(2)}%`);
    });
  } catch (error) {
    console.error('Error:', error);
  }
}

managePortfolio();

R SDK

Our R SDK provides seamless integration with R for financial analysis.

Installation

install.packages("mcpfinancials")

Usage

library(mcpfinancials)

# Initialize client with your API key
client <- MCPClient$new(api_key = "your_api_key")

# Create a portfolio
portfolio <- client$portfolio$create_portfolio("Tech Portfolio")
print(paste("Portfolio created:", portfolio$portfolio_name))

# Add holdings
client$portfolio$add_holding("Tech Portfolio", "AAPL", 10, 180.0)
client$portfolio$add_holding("Tech Portfolio", "MSFT", 15, 320.0)
client$portfolio$add_holding("Tech Portfolio", "GOOG", 20, 140.0)

# Get portfolio value
value <- client$portfolio$calculate_value("Tech Portfolio")
print(paste("Total portfolio value: $", round(value$total_value, 2)))

# Optimize portfolio
optimization <- client$portfolio$optimize("Tech Portfolio", optimization_method = "max_sharpe")
print("Optimized weights:")
weights <- optimization$performance_metrics$weights
for (symbol in names(weights)) {
  print(paste("  ", symbol, ":", round(weights[[symbol]] * 100, 2), "%"))
}

# Generate portfolio report with visualizations
report <- client$portfolio$generate_report("Tech Portfolio")
print(paste("Portfolio report generated. Plots available in", report$report$plots$allocation_pie))

Direct HTTP Integration

If you prefer to integrate directly with our API without using an SDK, you can make standard HTTP requests to our JSON-RPC endpoint:

import requests

api_key = "your_api_key"
api_url = "https://mcpfinancials.com/api/jsonrpc"

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

# Example: Create a portfolio
payload = {
    "jsonrpc": "2.0",
    "method": "portfolio.createPortfolio",
    "params": {
        "portfolio_name": "Tech Portfolio"
    },
    "id": "1"
}

response = requests.post(api_url, json=payload, headers=headers)
result = response.json()
print(result)

For example, in Python:

from mcp_python import MCPClient

client = MCPClient(api_key="your_api_key")

# Get latest stock price
latest_price = client.marketstack.get_latest_price("AAPL")

# Create portfolio and add holdings
portfolio = client.portfolio.create("Tech Portfolio")
portfolio.add_holding("AAPL", 10, 180.0)
portfolio.add_holding("MSFT", 5, 320.0)

# Optimize portfolio
optimization = portfolio.optimize(method="max_sharpe")
print(f"Expected return: {optimization.expected_return}")
print(f"Sharpe ratio: {optimization.sharpe_ratio}")

Conclusion

This documentation covers the main methods available through our JSON-RPC API. For additional support, please contact our support team.

Need Help?

If you have any questions about our JSON-RPC API or need assistance with integration, please don't hesitate to contact our support team.

Resources