Cambrian Calculate Risk API

By Cambrian Network risk

GET /api/v1/perp-risk-engine

Perp Risk Engine

Overview

Calculates the probability of liquidation for a leveraged cryptocurrency futures position using Monte Carlo simulation over historical price data. Given a token, entry price, leverage, direction, and risk horizon, the endpoint automatically picks an appropriate historical lookback window and simulates thousands of price paths to estimate liquidation risk and the price level at which liquidation would occur.

Business Value

  • Risk Management: Quantify exact liquidation probabilities before entering leveraged positions to prevent unexpected losses
  • Position Sizing: Optimize leverage levels based on statistical risk assessments and personal risk tolerance
  • Market Intelligence: Understand volatility dynamics and price drift patterns for different tokens across various timeframes
  • Trading Strategy: Make data-driven decisions on entry points, stop losses, and position duration based on probabilistic outcomes
  • Capital Preservation: Avoid overleveraging by visualizing risk distributions and understanding sigma-based safety margins

Endpoint Details

URL:

https://api.cambrian.org/risk/perp-risk-engine

Method: GET Authentication: Required via X-API-Key by external API management, or pay per request with x402. The backend does not inspect caller credentials, and x402 does not require an API key.

Query Parameters

Parameter Type Required Default Description
token_address string Yes - Solana token address
entry_price number Yes - Entry price in USD (must be greater than 0)
leverage number Yes - Leverage multiplier (must be greater than 0, maximum 1000)
direction string Yes - Position direction; must be long or short
risk_horizon string Yes - Risk time horizon; must be one of 1h, 1d, 1w, 1mo

Response Field Descriptions

Response Field Type Description
riskProbability number Estimated probability (0-1) that the position is liquidated within the risk horizon, based on the share of simulated paths that hit the liquidation price
liquidationPrice number USD price at which the position would be liquidated given the entry price, leverage, and direction
entryPrice number Entry price in USD, echoed back from the request
volatility number Historical volatility measure derived from the price data used in the simulation
drift number Historical drift (trend) measure derived from the price data used in the simulation
priceChangeNeeded number Percentage price move required from the current price to reach the liquidation price
sigmasAway number Number of standard deviations between the current price and the liquidation price
simulationDetails object Metadata describing how the Monte Carlo simulation was run
simulationDetails.totalSimulations integer Total number of simulated price paths
simulationDetails.liquidatedPaths integer Number of simulated paths that crossed the liquidation price
simulationDetails.dataPointsUsed integer Number of historical data points used to estimate volatility and drift
simulationDetails.dataInterval string Interval between historical data points used for the simulation
simulationDetails.riskHorizon string Risk horizon used for the simulation, echoed back from the request
visualizationData object Data supporting client-side visualization of the simulation results
visualizationData.histogram object Histogram of simulated final price outcomes
visualizationData.histogram.bins array[number] Bin edges (as a fraction of entry price) for the histogram of simulated final prices
visualizationData.histogram.counts array[integer] Count of simulated paths falling into each histogram bin
visualizationData.histogram.finalPrices array[number] Sample of simulated final prices (as a fraction of entry price) from individual simulation paths
visualizationData.liquidationThreshold number USD liquidation price, provided for plotting alongside the histogram

Examples

1. Long Position Risk Assessment

Calculates the liquidation risk for a 10x leveraged long position opened at $2,800 on a Solana token, over a 1-day risk horizon.

curl -X GET "https://api.cambrian.org/risk/perp-risk-engine?token_address=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&entry_price=2800&leverage=10&direction=long&risk_horizon=1d" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json"

Response:

{
  "riskProbability": 1,
  "liquidationPrice": 2519.8038627038927,
  "entryPrice": 2800,
  "volatility": 0.022190955844549592,
  "drift": -0.03405525985897041,
  "priceChangeNeeded": 0,
  "sigmasAway": 0,
  "simulationDetails": {
    "totalSimulations": 10000,
    "liquidatedPaths": 10000,
    "dataPointsUsed": 672,
    "dataInterval": "variable",
    "riskHorizon": "1d"
  },
  "visualizationData": {
    "histogram": {
      "bins": [
        0.9961838126182556,
        0.9963539242744446,
        0.9965240955352783,
        0.9966942071914673,
        0.996864378452301,
        0.99703449010849,
        0.9972046613693237,
        0.9973747730255127,
        0.9975449442863464,
        0.9977150559425354
      ],
      "counts": [
        4,
        4,
        5,
        6,
        13,
        21,
        34,
        37,
        64,
        92
      ],
      "finalPrices": [
        0.9994016289710999,
        0.999608039855957,
        1.0007919073104858,
        1.00118088722229,
        1.0003645420074463,
        1.0016578435897827,
        0.9973054528236389,
        0.9984804391860962,
        0.9994128942489624,
        0.9994698166847229
      ]
    },
    "liquidationThreshold": 2519.8038627038927
  }
}

The histogram.bins, histogram.counts, and histogram.finalPrices arrays above are limited to their first 10 items for readability; the live response can contain more entries. In this example, all 10,000 simulated paths (liquidatedPaths) crossed the liquidation threshold of $2,519.80, which gives a riskProbability of 1.

x402 Payment Option

This endpoint supports pay-per-use access via the x402 payment protocol (v2) - pay $0.05 USDC per request using blockchain micropayments. No API key required.

Quick Start (TypeScript)

npm install @x402/fetch @x402/evm viem
import { x402Client } from "@x402/core/client";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { wrapFetchWithPayment } from "@x402/fetch";
import { privateKeyToAccount } from "viem/accounts";

const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = new x402Client();
client.register("eip155:*", new ExactEvmScheme(signer));

const fetchWithPayment = wrapFetchWithPayment(fetch, client);
const response = await fetchWithPayment("https://x402.cambrian.org/risk/perp-risk-engine?token_address=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&entry_price=2800&leverage=10&direction=long&risk_horizon=1d");
const data = await response.json();

Quick Start (Python)

pip install "x402[httpx]"
import asyncio
import os
from eth_account import Account
from x402 import x402Client
from x402.http.clients import x402HttpxClient
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact.register import register_exact_evm_client

async def main():
    client = x402Client()
    account = Account.from_key(os.getenv("EVM_PRIVATE_KEY"))
    register_exact_evm_client(client, EthAccountSigner(account))

    async with x402HttpxClient(client) as http:
        response = await http.get("https://x402.cambrian.org/risk/perp-risk-engine?token_address=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&entry_price=2800&leverage=10&direction=long&risk_horizon=1d")
        print(response.json())

asyncio.run(main())

Payment Flow

  1. Send a normal request to the endpoint without an API key.
  2. Server returns 402 Payment Required with payment details.
  3. The x402 SDK signs a payment authorization with your wallet.
  4. The SDK resubmits the request with the signed payment.
  5. Server verifies payment and returns the API response.

The x402 SDK handles steps 2-5 automatically.

Network: Base (chain ID 8453) | Currency: USDC | Price: $0.05 per request