TradingCalc MCP: Options, Forex, Risk Stats, Prediction Markets, On-Chain & Crypto Futures

v2.17.0
io.github.SKalinin909/tradingcalc Checked 1 day ago Published 27 days ago

Deterministic options, forex, risk, on-chain & futures math.

These tools were reported by the server itself during our smoke test (tools/list), not copied from the README.

workflow.run_pnl_planning PnL Planning

Calculate net PnL, ROE, fees and gross profit/loss for a futures trade. Edge cases: entryPrice, exitPrice and size above zero; feeOpenPct and feeClosePct optional fractions from 0 to 0.05 (0.0002 is 0.02%). For inverse contracts size is USD contracts and results are in the base coin. Not covered: funding payments, slippage, liquidation before the exit price is reached, and taxes. Use when user asks "what's my profit/loss on this trade?" Returns: grossPnl, fees, netPnl, netPnlUsdt, roe (%), maxLossBound (only non-null for an inverse/coin-margined short: the finite ceiling on net coin-denominate…

ParameterTypeDescription
entryPrice *numberEntry price (positive)
exitPrice *numberExit price (positive)
side *stringTrade direction
size *numberPosition size: base asset qty for linear, USD contracts for inverse
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. For inverse, pnl/fees are returned in the base coin, not USDT.
feeClosePctnumberClosing fee as fraction
feeOpenPctnumberOpening fee as fraction, e.g. 0.0002 = 0.02%

workflow.run_liquidation_safety Liquidation Safety

Calculate the liquidation price for an isolated-margin futures position with one flat maintenance margin rate (mmr, which you supply from your exchange's tier), unless you use the tiered mode described below. The default is isolated: it does not model a cross account. To get a cross-account figure pass walletBalance, otherMaintenanceMargin and otherUnrealizedPnl (any of them switches to cross, with size required), plus tiers for tiered maintenance margin; there is no separate marginMode parameter. The flat model is generic, for linear and inverse alike, not any one exchange's engine. By defaul…

ParameterTypeDescription
entryPrice *numberEntry price (positive)
leverage *numberLeverage multiplier, e.g. 10 for 10x
side *stringTrade direction: "long" or "short"
contractTypestringlinear = USDT-margined (default), inverse = coin-margined (e.g. Deribit/Bybit/MEXC BTC-settled perps). Tiers and shared collateral: both (inverse: size in USD, bands and balances in the base coin).
liqFeeRatenumberLiquidation fee as a fraction of position value, default 0, max 0.05; added to mmr (e.g. KuCoin 0.0006). Refused in tiered mode.
mmBasestringValue the maintenance margin is taken on: "liquidation" = position value at the liquidation price (default; Bybit, KuCoin, Hyperliquid), "entry" = entry value (MEXC). Refused in tiered mode.
mmrnumberMaintenance margin rate, default 0.005 (0.5%)
otherMaintenanceMarginnumberShared collateral (needs size): maintenance margin of other positions, 0 or more (default 0).
otherUnrealizedPnlnumberShared collateral: unrealized PnL of other positions (default 0, may be negative).
sizenumberPosition size: base units for linear, USD contracts for inverse. Needed for tiered mode (tiers, walletBalance and the other fields select it); ignored otherwise.
tiersarrayTiered mode (needs size): 1 to 50 maintenance margin tiers ascending by upTo (notional cap in quote for linear, in base coin for inverse, above 0; the last band is open-ended: an upTo given on the las…
walletBalancenumberShared collateral (needs size): wallet balance backing the position. Default: the isolated initial margin, size x entry / leverage in quote for linear, size / entry / leverage in the base coin for inv…

workflow.run_breakeven_planning Breakeven Planning

Calculate the break-even exit price that covers all trading fees: this alone, nothing else. Edge cases: entryPrice and sizeBase above zero; feeOpenPct and feeClosePct fractions from 0 to 0.05 (defaults 0.0002 and 0.0005). Fees only. Not covered: funding (use workflow.run_funding_breakeven), slippage and spread. Use when user asks only "what price do I need to just break even?" and nothing more. If the user also gave a stop/target or wants a full trade-safety check, use workflow.run_risk_reward or workflow.run_pre_trade_check instead; both already include this breakeven figure plus more. Return…

ParameterTypeDescription
entryPrice *numberEntry price (positive)
side *stringTrade direction: "long" or "short"
sizeBase *numberPosition size: base asset qty for linear, USD contracts for inverse
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. For inverse, totalFees is returned in the base coin.
feeClosePctnumberClosing fee fraction, default 0.0005
feeOpenPctnumberOpening fee fraction, default 0.0002

workflow.run_position_sizing Position Sizing

Calculate the correct position size given a maximum risk in USDT and a stop-loss price. Edge cases: entryPrice, stopLoss and riskUsdt above zero; leverage above zero (default 1); fees 0 to 0.05; a fee and price combination that makes the risk denominator zero or negative is an error. Not covered: slippage past the stop, funding, exchange lot size and step rounding, and whether the margin is available. Use when user asks "how many coins should I buy?" or "size my position so I risk exactly $X". Returns: positionSize (base), positionUsdt, marginRequired.

ParameterTypeDescription
entryPrice *numberEntry price
riskUsdt *numberMaximum acceptable loss in USDT
side *stringTrade direction: "long" or "short"
stopLoss *numberStop-loss price
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. For inverse, sizeQuote is USD contracts and margin is returned in the base coin.
feeClosePctnumberClosing fee fraction, default 0.0005
feeOpenPctnumberOpening fee fraction, default 0.0002
leveragenumberLeverage, default 1

workflow.run_funding_cost Funding Cost

Calculate the total funding cost (or income) for holding a perpetual futures position. Edge cases: sizeBase, entryPrice and days above zero; fundingRate a fraction per interval (0.0001 is 0.01%), either sign; intervalHours 0.25 to 24 (default 8); if funding exceeds the position notional there is no finite price shift that offsets it, which is an error. Not covered: a funding rate that changes during the hold, and price moves. Use when user asks "how much funding will I pay holding X days?" or "is funding eating my profit?". Returns: totalCost (positive = you pay, negative = you receive; in the…

ParameterTypeDescription
days *numberNumber of days to hold
entryPrice *numberEntry price
fundingRate *numberFunding rate per funding interval as a DECIMAL FRACTION, not a percent: 0.0001 means 0.01%, so a quoted 0.0125% is 0.000125 (per 8h unless intervalHours says otherwise)
side *stringTrade direction: "long" or "short"
sizeBase *numberPosition size in base asset
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. For inverse, sizeBase is USD contracts and cost figures come out in the base coin.
intervalHoursnumberHours between funding payments, which is the period fundingRate covers. Default 8 (3 payments a day); 1 on Hyperliquid, dYdX, Kraken and Backpack, 4 or 2 on some symbols of Binance, Bybit, OKX, Gate,…

primitive.average_entry Average Entry Price

Calculate the weighted average entry price from multiple buy/sell fills (DCA): the bare number only, no breakeven or per-fill breakdown. Edge cases: symbol non-empty; at least one fill, each price and quantity above zero (size is accepted as quantity); leverage above zero is optional. The average is weighted by quantity. Not covered: fees, sells or partial closes (give only the fills still open), and funding. Use when user asks only "what's my average entry?" and wants just that figure. Each fill is { price, quantity } here (workflow.run_dca_entry calls the same field size). For breakeven and…

ParameterTypeDescription
input *objectObject with a "fills" array, e.g. { "fills": [{ "price": 60000, "quantity": 0.5 }, { "price": 58000, "quantity": 1 }] }
symbol *stringTrading pair symbol, e.g. BTCUSDT
contractTypestringlinear = USDT-margined, average is the arithmetic mean (default). inverse = coin-margined, average is the harmonic mean (fill quantity is USD notional).
exchangeCodestringExchange identifier (optional)

workflow.run_exit_target Exit Target

Calculate the exact exit price needed to hit a target PnL or ROE percentage. Edge cases: entryPrice, leverage and sizeBase above zero; targetMode pnl or roe, targetValue any number; fees 0 to 0.05 (defaults 0.0002 and 0.0005); a target that cannot be reached from this position is an error. Not covered: funding, slippage, liquidation before the target, and the chance that price gets there. Use when user asks "at what price do I take profit to make $500?" or "where should I set TP for 20% ROE?". Returns: targetExitPrice.

ParameterTypeDescription
entryPrice *numberEntry price
leverage *numberLeverage multiplier
side *stringTrade direction: "long" or "short"
sizeBase *numberPosition size in base asset
targetMode *string"pnl" = target in USDT, "roe" = target in %
targetValue *numberTarget value (USDT/coin for pnl mode, or %)
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. For inverse, pnl-mode targetValue and outputs are in the base coin.
feeClosePctnumberClosing fee fraction, default 0.0005
feeOpenPctnumberOpening fee fraction, default 0.0002

workflow.run_scenario_planning Scenario Planning

Run a scenario analysis: compute PnL for multiple price-change percentages at once. Edge cases: entryPrice and size above zero; at least one price change in percent; a change of -100 or less is refused for inverse contracts and exactly -100 is allowed for linear only; fees optional (default 0). Not covered: funding, liquidation along the path, slippage, and the probability of each scenario. Use when user asks "show me my P&L if BTC moves -10%, -5%, +5%, +10%". Returns: array of { deltaPct, exitPrice, netPnl, roe }.

ParameterTypeDescription
deltasPct *arrayList of price change percentages, e.g. [-10, -5, 0, 5, 10]. Must be at least -100 (exactly -100 only for linear contracts; inverse contracts need more than -100)
entryPrice *numberEntry price
side *stringTrade direction: "long" or "short"
size *numberPosition size in base asset
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. For inverse, size is USD contracts and pnl/fees come out in the base coin.
feeClosePctnumberClosing fee fraction
feeOpenPctnumberOpening fee fraction

workflow.run_max_leverage Max Leverage

Calculate the maximum leverage that keeps a position within a drawdown limit, from account size, max acceptable drawdown, and asset daily volatility. Edge cases: accountSize and volatilityPct above zero; maxDrawdownPct above 0 and at most 100; mmr 0 to 0.1 (default 0.005). A planning figure from the numbers you give, not a limit set by an exchange. Not covered: gaps and fat-tail moves beyond the volatility you state, exchange maximum leverage and tiers, funding, and fees. Use when user asks "what leverage does a 10% drawdown limit allow on BTC?" or "what leverage fits a 3% daily volatility and…

ParameterTypeDescription
accountSize *numberTotal account size in USDT
maxDrawdownPct *numberMaximum acceptable drawdown as percentage, e.g. 10 for 10%
volatilityPct *numberExpected daily price volatility as percentage, e.g. 3 for 3%
mmrnumberMaintenance margin rate, default 0.005 (0.5%)

primitive.hedge_ratio Hedge Ratio

Calculate the short perpetual futures position size needed to hedge a spot holding. Default USDT-linear: sizes and costs in USD. With contractType "inverse" (coin-margined, needs entryPrice) the short is the same USD contracts and margin and funding come back in the base coin. Edge cases: spotSize above zero (USD value); hedgeRatio 0 to 200 percent (default 100); leverage 1 or more (default 1); fundingRatePct in percent per interval (0.01 is 0.01%, default 0.01); intervalHours 0.25 to 24 (default 8); an inverse contract needs entryPrice. Not covered: basis risk between spot and the perp, rebal…

ParameterTypeDescription
spotSize *numberSpot position value in USDT
contractTypestringlinear = USDT-margined (default). inverse = coin-margined: spotSize stays the USD value of the holding, requiredMargin and the funding costs are returned in the base coin.
entryPricenumberCoin price in USD. Required for contractType inverse (converts the USD margin and funding to coin); ignored for linear.
fundingRatePctnumberCurrent funding rate per funding interval in PERCENT: 0.01 means 0.01%, so a quoted 0.0125% is 0.0125 (per 8h unless intervalHours says otherwise). Used for cost estimate.
hedgeRationumberPercentage of spot to hedge, e.g. 100 for full hedge, 50 for half. Default 100.
intervalHoursnumberHours between funding payments, the period fundingRatePct covers. Default 8 (3 payments a day); 1 on Hyperliquid, dYdX, Kraken and Backpack (per-hour rates); 4 or 2 on some symbols of Binance, Bybit,…
leveragenumberLeverage on the perp short. Default 1.

workflow.run_funding_arbitrage Funding Arbitrage

Calculate funding rate arbitrage profit: annualized yield, net profit, and breakeven days for a long/short basis trade across two exchanges: the bare numbers only, no plain-English verdict. For the same math plus a profitable/marginal/loss verdict, use workflow.run_carry_trade instead. Edge cases: positionSize and durationDays above zero; longFundingRate and shortFundingRate in percent per interval (0.01 is 0.01%), either sign; transferFeePct 0 or more (default 0.1); intervalHours 0.25 to 24 (default 8). Not covered: price divergence between the venues, liquidation of either leg, margin on bot…

ParameterTypeDescription
durationDays *numberHolding period in days
longFundingRate *numberFunding rate on long side (% per interval, positive = you pay)
positionSize *numberPosition size in USDT
shortFundingRate *numberFunding rate on short side (% per interval, positive = you receive)
intervalHoursnumberHours between funding payments, one interval for both legs. Default 8; 1 on Hyperliquid, dYdX, Kraken and Backpack (per-hour rates); 4 or 2 on some symbols. A leg paid on another interval is entered a…
transferFeePctnumberOne-time transfer/setup fee as percentage, e.g. 0.1 for 0.1%

workflow.run_compound_funding Compound Funding

Project capital growth from reinvesting perpetual futures funding income (compounding carry). Edge cases: initialCapital above zero; fundingRatePct in percent per interval (0.01 is 0.01%), either sign; intervalHours a whole number that divides 24 (1, 2, 3, 4, 6, 8, 12 or 24, default 8); durationDays above zero and at most 3650; reinvestPct 0 to 100 (default 100); a result too large to represent is an error. Assumes the rate stays constant. Not covered: a changing rate, fees, taxes, and the capital limits a venue may set. Use when user asks "how much will I make compounding 0.01% funding for 90…

ParameterTypeDescription
durationDays *numberNumber of days to project, up to 3650
fundingRatePct *numberFunding rate per interval in PERCENT: 0.01 means 0.01%, so a quoted 0.0125% is 0.0125, never 0.000125
initialCapital *numberStarting capital in USDT
intervalHoursnumberHours between funding payments, the period fundingRatePct covers, a whole number of hours that divides 24. Default 8; 1 on Hyperliquid, dYdX, Kraken and Backpack (per-hour rates); 4 or 2 on some symbo…
reinvestPctnumberPercentage of funding received that is reinvested each interval, 0-100 (the rest is withdrawn and counts as earned; funding paid always comes out of capital). 100 = full compounding. Default 100.

workflow.run_pre_trade_check Pre Trade Check

Full pre-trade decision card: orchestrates position sizing, breakeven, liquidation, and funding cost in one call. Edge cases: entry_price, leverage above zero; account_balance 0 or more; give desired_size, or stop_loss together with risk_pct, otherwise an error; funding_rate is a decimal per interval (0.0001 is 0.01%) and is read live from the exchange when omitted and exchange (and symbol) are given; hold_hours above zero (default 8); fees 0 to 0.05; mmr 0 to 0.2. Not covered: slippage, tiered margin (use workflow.run_liquidation_live), a funding rate that changes during the hold, and anythin…

ParameterTypeDescription
account_balance *numberTotal account balance in USDT
entry_price *numberEntry price (positive)
leverage *numberLeverage multiplier
risk_pct *numberRisk as % of balance, e.g. 1.0 = 1%
side *stringTrade direction: "long" or "short"
stop_loss *numberStop-loss price (positive)
contractTypestringlinear = USDT-margined (default), inverse = coin-margined (e.g. Bybit BTCUSD). All returned figures (notional, margin, risk_amount, funding_cost_*) stay USD-denominated either way; recommended_size is…
exchangestringExchange code, e.g. "binance" or "bybit". Used to fetch the live funding rate if funding_rate is omitted, and to set funding_interval_hours when that is omitted (1 for Hyperliquid, dYdX, Kraken and Ba…
fee_close_pctnumberClosing fee fraction, default 0.0005
fee_open_pctnumberOpening fee fraction, default 0.0002
funding_interval_hoursnumberHours per funding payment, the period funding_rate covers: 8 on most venues, 1 on Hyperliquid, dYdX, Kraken and Backpack, 4 or 2 on some symbols of Binance, Bybit, OKX, Gate, KuCoin, MEXC, Aster and P…
funding_ratenumberFunding rate per funding interval as decimal, e.g. 0.0001. If omitted, fetched live from exchange.
hold_hoursnumberExpected hold time in hours for overnight shift calc. Default 8.
liqFeeRatenumberLiquidation fee as a fraction of position value, default 0, max 0.05; added to mmr.
mmBasestringValue the maintenance margin is taken on: "liquidation" = position value at the liquidation price (default), "entry" = entry value.
mmrnumberMaintenance margin rate, default 0.005
symbolstringPerpetual symbol, e.g. "BTCUSDT".

workflow.run_risk_reward Risk Reward

Full risk:reward analysis: takes a trade with entry, stop, AND target (all three). Calculates R:R ratio, position size, liquidation price, breakeven, and P&L at both stop and target. Returns a verdict label, strong (3:1+) / good (2:1+) / marginal / poor, which grades the R:R ratio against fixed thresholds and is not a recommendation. For a full setup check tied to a live exchange/symbol (including funding cost), see workflow.run_pre_trade_check; its verdict covers overall setup safety, not just R:R. Edge cases: entry_price, stop_loss, take_profit, account_balance and leverage above zero; risk_…

ParameterTypeDescription
account_balance *numberAccount balance in USDT
entry_price *numberEntry price
leverage *numberLeverage multiplier
risk_pct *numberMax risk as % of account
side *stringTrade direction: "long" or "short"
stop_loss *numberStop-loss price
take_profit *numberTake-profit price
contractTypestringlinear = USDT-margined (default), inverse = coin-margined (e.g. Bybit BTCUSD). position_size/notional are USD notional (contracts) for inverse; pnl_at_stop/pnl_at_target come back denominated in the b…
fee_close_pctnumberClose fee rate (default 0.0005)
fee_open_pctnumberOpen fee rate (default 0.0002)
liqFeeRatenumberLiquidation fee as a fraction of position value, default 0, max 0.05; added to mmr.
mmBasestringValue the maintenance margin is taken on: "liquidation" = position value at the liquidation price (default), "entry" = entry value.
mmrnumberMaintenance margin rate as a fraction, 0 to 0.2 (default 0.005 = 0.5%); not a percent: 0.5% is 0.005, not 0.5

workflow.run_portfolio_risk Portfolio Risk

Aggregates risk across multiple open positions in one call: total notional, total P&L, total margin in use, margin usage as a % of account balance (if given), and which single position sits closest to liquidation. Each position is computed through the same canonical PnL/liquidation math as the single-position tools, then rolled up. Linear (USDT-margined) positions sum into one USD total; inverse (coin-margined) positions are grouped by settlement coin instead, since a BTC-margined P&L cannot be summed with an ETH-margined one without a live conversion rate. Returns a verdict label, healthy / w…

ParameterTypeDescription
positions *arrayOpen positions to aggregate (1 to 50). Each: { side, entry_price, mark_price, size, leverage }, plus optional fees, mmr, mmBase, liqFeeRate, contractType, coin, label.
account_balancenumberOptional account balance in USD, used to compute margin_usage_pct: linear margin plus every inverse position's own margin marked to market at its mark_price, all as one USD total

workflow.run_dca_entry DCA Entry

DCA entry planner: weighted average entry price, breakeven, and per-level contribution from multiple fill prices and sizes. Each fill is { price, size } here (primitive.average_entry calls the same field quantity). Compared with primitive.average_entry, this one adds output for the case where breakeven or the per-level breakdown is also wanted, not just the bare average. Edge cases: 2 to 20 fills (size also accepted as quantity), each price and size above zero; fee_open_pct and fee_close_pct are fractions from 0 to 0.05 (defaults 0.0002 and 0.0005); every fill is on the same side and the same…

ParameterTypeDescription
entries *arrayFills to average (2 to 20). Each: { price, size }, e.g. [{ "price": 60000, "size": 0.5 }, { "price": 58000, "size": 1 }]. Size is base-asset quantity for linear, USD notional (contracts) for inverse.
side *stringTrade direction: "long" or "short"
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. Each fill's size is USD notional (contracts) for inverse; averageEntry is then the harmonic mean of fill prices, not the arithmetic mean.
fee_close_pctnumberClose fee rate (default 0.0005)
fee_open_pctnumberOpen fee rate (default 0.0002)

workflow.run_average_down Average Down

Should-I-average-down check: for an already-open position, compares adding more at a worse price against the always-available alternative of buying the same final total size fresh at today's price. Returns the new blended average entry, liquidation price and breakeven (before vs. after), margin_added (the actual cash/margin required for the add at this leverage, not the full notional), and three risk figures at your stop-loss: existing_risk (what you already risk, before adding), pyramid_risk (what you'd risk after adding), and clean_entry_risk (what a fresh entry at add_price for the same tot…

ParameterTypeDescription
add_price *numberProposed price to add at - also treated as today's current price for the fresh-entry comparison
add_size *numberAdditional size being considered, same unit convention as existing_size
existing_entry_price *numberEntry price of the position already held
existing_size *numberSize already held: base-asset quantity for linear, USD notional (contracts) for inverse
leverage *numberLeverage multiplier
side *stringTrade direction: "long" or "short"
stop_loss *numberStop-loss price (must be below add_price for a long, above it for a short - the position should already be closed otherwise)
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. Risk figures come back denominated in the base coin for inverse.
fee_close_pctnumberClose fee rate (default 0.0005)
fee_open_pctnumberOpen fee rate (default 0.0002)
liqFeeRatenumberLiquidation fee as a fraction of position value, default 0, max 0.05; added to mmr.
mmBasestringValue the maintenance margin is taken on: "liquidation" = position value at the liquidation price (default), "entry" = entry value.
mmrnumberMaintenance margin rate as a fraction, 0 to 0.2 (default 0.005 = 0.5%); not a percent: 0.5% is 0.005, not 0.5

workflow.run_scale_out Scale Out

Scale-out planner: P&L, ROI, and cumulative P&L for each partial exit level. Edge cases: entry_price and total_size above zero; 2 to 10 exits, each price above zero and pct above 0 and at most 100, the pct values summing to at most 100 (less than 100 leaves the rest open); fees are fractions from 0 to 0.05. Not covered: the remainder not sold, funding, slippage, and the chance that each level is reached. Use when user wants to take profit at multiple targets: "close 30% at $90k, 30% at $95k, 40% at $100k, what's my total P&L?". Returns: per-level pnl, weightedAvgExitPrice, totalRoi.

ParameterTypeDescription
entry_price *numberEntry price
exits *arrayPartial exit levels (2 to 10). Each: { price, pct }, e.g. [{ "price": 90000, "pct": 30 }, { "price": 95000, "pct": 70 }]; the pct values must not sum to more than 100.
side *stringTrade direction: "long" or "short"
total_size *numberTotal position size in base currency
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. total_size is USD notional (contracts) for inverse, and per-level pnl comes back denominated in the base coin.
fee_close_pctnumberClose fee rate (default 0.0005)
fee_open_pctnumberOpen fee rate (default 0.0002)

workflow.run_carry_trade Carry Trade

Delta-neutral carry trade (funding arbitrage) analysis, with a profitable/marginal/loss verdict on top of the same math primitive.funding_arb uses. Compared with primitive.funding_arb, this one adds output for the case where a plain-English verdict is wanted, not just the raw numbers. Edge cases: notional and hold_days above zero; funding_rate_long and funding_rate_short are in PERCENT per interval (0.01 means 0.01%), either sign; transfer_fee_pct 0 or more, one way (default 0.1); interval_hours 0.25 to 24 (default 8), one interval for both legs. Not covered: price divergence between the two v…

ParameterTypeDescription
funding_rate_long *numberFunding rate on the long exchange per interval, in percent (0.01 means 0.01%, not 0.0001)
funding_rate_short *numberFunding rate on the short exchange per interval, in percent (0.01 means 0.01%, not 0.0001)
hold_days *numberHold duration in days
notional *numberPosition notional in USDT
interval_hoursnumberHours between funding payments, one interval for both legs (default 8; 1 for hourly venues; 4 or 2 on some symbols). A leg paid on another interval is entered as its rate times (this interval / its ow…
transfer_fee_pctnumberOne-way transfer fee % (default 0.1)

workflow.run_funding_breakeven Funding Breakeven

Price move needed to cover funding cost + fees over a holding period. Edge cases: entry_price, size and hold_hours above zero; funding_rate is a decimal per funding interval (0.0001 is 0.01%), either sign; funding_interval_hours 0.25 to 24 (default 8); fees are fractions from 0 to 0.05. If carry cost exceeds what any price move can offset, the call is an error. Not covered: a funding rate that changes during the hold, mark versus last price, and slippage. Use when user asks "how much does BTC need to move for me to profit after funding?" or "is funding killing my edge on this trade?". Returns:…

ParameterTypeDescription
entry_price *numberEntry price
funding_rate *numberFunding rate per funding interval as a DECIMAL FRACTION, not a percent: 0.0001 means 0.01%, so a quoted 0.0125% is 0.000125
hold_hours *numberHold duration in hours
side *stringTrade direction: "long" or "short"
size *numberPosition size in base currency
contractTypestringlinear = USDT-margined (default), inverse = coin-margined. size is USD notional (contracts) for inverse; notional/funding_cost/fee_total/total_carry_cost come back denominated in the base coin.
fee_close_pctnumberClose fee rate (default 0.0005)
fee_open_pctnumberOpen fee rate (default 0.0002)
funding_interval_hoursnumberHours per funding payment, the period funding_rate covers: 8 (default), 1 on Hyperliquid, dYdX, Kraken and Backpack (per-hour rates), 4 or 2 on some symbols of Binance, Bybit, OKX, Gate, KuCoin, MEXC,…

workflow.run_crypto_profit Crypto Profit

Profit or loss on a spot crypto trade (coins bought and sold outright, no leverage, no funding) after both fees. Give exactly one of investment (total cash spent, buy fee included) or quantity (coins bought). Each fee is a fraction of that fill's trade value (0.001 = 0.1%): the buy fee is paid on top of the coins' cost, the sell fee comes out of the sale value. For a leveraged perpetual futures position see workflow.run_pnl_planning. Edge cases: buyPrice and sellPrice above zero; give exactly one of investment (above zero, buy fee included) or quantity (above zero); buyFeePct and sellFeePct ar…

ParameterTypeDescription
buyPrice *numberPrice paid per coin, in the quote currency (e.g. 60000 for BTC in USD)
sellPrice *numberPrice per coin at the sale, or the price to test, same currency
buyFeePctnumberBuy fee as a fraction of the trade value, 0 to 0.05 (0.001 = 0.1%). Default 0
holdingDaysnumberOptional: days the coins were held; 30 or more also returns the annualized return
investmentnumberTotal cash spent on the buy, buy fee included (e.g. 1000). Give this or quantity, not both
quantitynumberNumber of coins bought (e.g. 0.5). Give this or investment, not both
sellFeePctnumberSell fee as a fraction of the trade value, 0 to 0.05 (0.001 = 0.1%). Default 0

workflow.run_spot_dca Spot DCA

Dollar-cost averaging on a spot coin: the same cash amount bought at each of a list of prices (no leverage, no funding). Returns the coins held, total invested, the average price paid (below the plain average of the prices, because equal cash buys more coins when the price is low), the average cost per coin with the buy fee in it, the break-even sell price and, when currentPrice is given, the value, profit and ROI of selling everything there after the sell fee. amountPerBuy is the cash that leaves the account for one buy, buy fee included. Each fee is a fraction of that fill's trade value (0.0…

ParameterTypeDescription
amountPerBuy *numberCash spent on each buy, buy fee included (e.g. 100)
prices *arrayPrice paid per coin at each buy, in order (1 to 1000 positive numbers, e.g. [60000, 52000, 48000])
buyFeePctnumberBuy fee as a fraction of the trade value, 0 to 0.05 (0.001 = 0.1%). Default 0
currentPricenumberOptional: the price to value the whole position at, same currency as prices
sellFeePctnumberSell fee for the exit, as a fraction of the trade value, 0 to 0.05. Default 0

workflow.run_average_buy_price Average Buy Price

Real entry price of a spot coin bought and sold in several trades: moving average cost, trades in the order they happened, each with its own fee (no leverage, no funding). The buy fee is part of the cost basis; a sale removes coins at the current average and never changes the average of what is left, only a later buy does; selling everything resets it. Selling more than is held at that point is an error naming the trade. Each fee is a fraction of that trade's value (0.001 = 0.1%, at most 0.05). Edge cases: 1 to 1000 trades; price and quantity above zero; a sale before any buy, or above the hol…

ParameterTypeDescription
trades *arrayTrades in the order they happened (1 to 1000)
sellFeePctnumberFee expected when the remaining coins are sold, 0 to 0.05, for the break-even sell price. Default 0

workflow.run_target_sell_price Target Sell Price

The sell price that makes a target ROI or a target profit on a spot trade after both fees: the inverse of workflow.run_crypto_profit. Give exactly one of targetRoiPct (a fraction, 0.25 = 25%, negative for a stop price, above -1) or targetProfit (money; needs investment or quantity). Fees are a fraction of each fill's value (0.001 = 0.1%): the buy fee on top of the coins' cost, the sell fee out of the sale value (each fee at most 0.05); prices may be in any currency and results are in the same one; investment is the total cash spent, buy fee included. sellPrice = buyPrice x (1 + buyFee) x (1 +…

ParameterTypeDescription
buyPrice *numberPrice paid per coin
buyFeePctnumberBuy fee as a fraction of the trade value, 0 to 0.05 (0.001 = 0.1%). Default 0
investmentnumberTotal cash spent on the buy, buy fee included. Give this or quantity, not both
quantitynumberNumber of coins bought. Give this or investment, not both
sellFeePctnumberSell fee as a fraction of the trade value, 0 to 0.05. Default 0
targetProfitnumberTarget profit in money after both fees (negative for a loss limit). Needs investment or quantity. Give this or targetRoiPct, not both
targetRoiPctnumberTarget return as a fraction of the cost (0.25 = 25%), above -1. Give this or targetProfit, not both

workflow.run_present_value Present Value

Present value of a future lump sum, a level payment stream, or both: what money received later is worth today at a discount rate. annualRate is a fraction (0.05 = 5%) split into periodsPerYear equal periods the nominal way (rate per period = annualRate / periodsPerYear); years x periodsPerYear is the number of periods, which must be whole when a payment is given. Payments are level and arrive at the end of each period, or at the start with paymentTiming "begin" (annuity due). Money received is positive, money paid is negative. A bond priced at its coupon rate comes back at its face value. For…

ParameterTypeDescription
annualRate *numberAnnual discount rate as a fraction (0.06 = 6%); may be zero or negative, but the rate per period must stay above -100%
years *numberLength in years, 0 to 1000 (fractions allowed for a lump sum; with payments years x periodsPerYear must be a whole number)
futureValuenumberLump sum received at the end, in any currency. Default 0
paymentnumberLevel payment per period. Default 0
paymentTimingstring"end" (ordinary annuity, default) or "begin" (annuity due, each payment one period earlier)
periodsPerYearintegerCompounding and payment periods per year, 1 to 365. Default 1 (12 = monthly)

workflow.run_future_value Future Value

Future value of a starting sum, regular contributions, or both, grown at a fixed rate: what savings or an investment reach after a number of years. annualRate is a fraction (0.07 = 7%) split into periodsPerYear equal periods the nominal way (rate per period = annualRate / periodsPerYear); years x periodsPerYear is the number of periods, which must be whole when a payment is given. Contributions are level and made at the end of each period, or at the start with paymentTiming "begin". A fixed assumed rate, not a forecast and not a market-return simulation (for a range of outcomes use workflow.ru…

ParameterTypeDescription
annualRate *numberAnnual growth rate as a fraction (0.07 = 7%); may be zero or negative, but the rate per period must stay above -100%
years *numberLength in years, 0 to 1000 (fractions allowed for a lump sum; with payments years x periodsPerYear must be a whole number)
paymentnumberLevel contribution per period. Default 0
paymentTimingstring"end" (default) or "begin" (each contribution one period earlier)
periodsPerYearintegerCompounding and contribution periods per year, 1 to 365. Default 1 (12 = monthly)
presentValuenumberStarting amount, in any currency. Default 0

workflow.run_npv Npv

Net present value of a list of cash flows at a discount rate per period. The first flow is at time 0 and is NOT discounted (the usual textbook NPV; a spreadsheet NPV() function discounts the first value one period, so its result is this one divided by 1 + rate). Money received is positive, money paid is negative. ratePerPeriod must match the spacing of the flows (a monthly rate for monthly flows). To find the rate that makes NPV zero use workflow.run_irr. Edge cases: ratePerPeriod strictly above -1 and at most 1e6, as a fraction per period (0.05 is 5%), not per year; 1 to 1000 cash flows, the…

ParameterTypeDescription
cashFlows *arrayCash flow at time 0, 1, 2, ... (e.g. [-1000, 500, 500, 500]); use 0 for an empty period
ratePerPeriod *numberDiscount rate per period as a fraction (0.1 = 10% per period), above -100%, at most 1e6

workflow.run_irr Irr

Internal rate of return: the rate per period at which the NPV of a list of cash flows is zero (first flow at time 0). The flows need at least one outflow and one inflow. One sign change in the flows (all outflows first, then all inflows) gives exactly one answer, returned as irr with unique true. With several sign changes there can be several rates or none: every rate found is listed in irrs and irr is null even when only one rate was found (reason "unverified"), with reason "multiple_roots" or "none_found" otherwise, so do not quote one rate as the return. With one sign change the search reac…

ParameterTypeDescription
cashFlows *arrayCash flow at time 0, 1, 2, ... with at least one negative and one positive value (e.g. [-1000, 300, 400, 500])
periodsPerYearintegerOptional: periods per year (12 for monthly flows), 1 to 365, to also return the annual effective rate

workflow.run_cagr Cagr

Compound annual growth rate between a beginning and an ending value over a number of years: the constant yearly rate that turns one into the other, (ending / beginning)^(1 / years) - 1. A smoothed average: it hides the path and the volatility in between, and it says nothing about future growth. Both values must be positive. Edge cases: beginningValue and endingValue above zero (a start or end of zero or below has no growth rate); years above zero and at most 1000, a fraction of a year is fine. Not covered: contributions or withdrawals in between (that is not CAGR), the path and volatility betw…

ParameterTypeDescription
beginningValue *numberValue at the start (positive)
endingValue *numberValue at the end (positive), same currency
years *numberYears between them, above 0 and at most 1000 (fractions allowed, e.g. 2.5)

workflow.run_apy_apr_converter Apy Apr Converter

Convert an APR (nominal yearly rate) to an APY (effective yearly rate) or back, for a compounding you choose. APY = (1 + APR / m)^m - 1 for m periods a year, e^APR - 1 when continuous. The same APY is a different APR at every compounding frequency, so the frequency is required: give periodsPerYear (365 daily, 12 monthly) or continuous true, not both. Rates are fractions (0.12 = 12%). It converts rate arithmetic only: it does not include fees, token price moves or the risk that a pool rate changes. Edge cases: rate a fraction from -periodsPerYear (APR) or above -1 (APY) up to 1000; give periods…

ParameterTypeDescription
direction *stringapr_to_apy converts the given APR into an APY; apy_to_apr the reverse
rate *numberThe rate you have, as a fraction per year (0.12 = 12%), up to 1000. An APY must be above -1; an APR must satisfy APR / periodsPerYear above -1
continuousbooleanTrue for continuous compounding; then omit periodsPerYear
periodsPerYearintegerCompounding periods a year, 1 to 365 (12 monthly, 365 daily). Omit when continuous is true

workflow.run_bond_price Bond Price

Price of a plain fixed-rate bond on a coupon date, with Macaulay duration, modified duration, convexity and DV01. Price = sum of the coupons and the face value discounted at the yield per period (yield / frequency), clean price, no accrued interest, so years x frequency must be a whole number of coupon periods. The yield is the nominal yearly yield to maturity compounded frequency times a year (the bond-market convention). Durations are in years, convexity in years squared. DV01 is the price fall for one basis point of yield, a positive number, the slope at the current yield and not a repricin…

ParameterTypeDescription
couponRate *numberAnnual coupon rate as a fraction of face value (0.05 = 5%), 0 to 1; 0 is a zero-coupon bond
years *numberYears to maturity, above 0 and at most 100; years x frequency must be a whole number (5 years semiannual is 10 coupons)
yieldRate *numberNominal yearly yield to maturity as a fraction (0.06 = 6%), compounded frequency times a year; yield / frequency must be above -1
faceValuenumberFace (par) value repaid at maturity, above 0 (default 1000)
frequencyintegerCoupon payments a year, 1 to 12 (default 2: semiannual; 1 annual, 4 quarterly, 12 monthly)

workflow.run_bonding_curve Bonding Curve

Pump.fun-style bonding curve calculator: exact tokens received for a buy, price impact, and graduation progress. Pure constant-product math (Uniswap V2 style) using pump.fun's official virtual-reserve constants: no live lookup needed, works for any token still on the curve (not yet graduated to a real AMM pool). Edge cases: solRaisedSoFar from 0 up to the graduation amount (a graduated token is out of range); solToSpend above zero. Pure constant-product math with pump.fun virtual-reserve constants, no live lookup. Not covered: the pump.fun trading fee unless stated in the result, slippage from…

ParameterTypeDescription
solRaisedSoFar *numberSOL already raised on the curve so far (0 for a brand-new token)
solToSpend *numberSOL amount for this buy

workflow.run_impermanent_loss Impermanent Loss

Impermanent loss for a liquidity-pool position: compares providing liquidity against simply holding the same tokens, at a manually-supplied entry and current price. Two modes: full_range (standard 50/50 constant-product pool, the textbook 2*sqrt(k)/(1+k)-1 closed form) or concentrated (a Uniswap-V3-style position confined to [lowerPrice, upperPrice] - IL is always worse than full_range for the same price move when the range is tight, and the position is fully single-asset, no longer earning fees, once price exits the range). impermanentLossPct is always <= 0 and is measured relative to the quo…

ParameterTypeDescription
currentPrice *numberBase token's current price in quote-token terms
entryPrice *numberBase token's price in quote-token terms when liquidity was deposited
depositValueUsdnumberOptional: USD value deposited at entry, to also report dollar-denominated lpValueUsd/hodlValueUsd/lossUsd
feesEarnedUsdnumberOptional trading fees earned so far in USD (default 0), folded into netResultUsd alongside lossUsd
lowerPricenumberRange lower bound - required for concentrated mode, must be below entryPrice
modestringDefault full_range.
upperPricenumberRange upper bound - required for concentrated mode, must be above entryPrice

workflow.run_options_payoff Options Payoff

Payoff, P&L, and breakeven price for a single-leg Deribit BTC/ETH option (long or short call/put) at a given scenario price at expiry. Deribit BTC/ETH options are coin-settled: premium, P&L, and the max profit/loss caps come back denominated in the base coin (BTC/ETH), not USD; a scenarioPnlUsd convenience field converts the coin P&L back to USD at the scenario price. Coin settlement means a long call's upside is capped (max profit = 1 − premium per unit, not unlimited) while a long put's upside is technically unbounded as price falls toward zero, the mirror image of a USD-settled option's p…

ParameterTypeDescription
optionType *stringOption type: "call" or "put"
position *stringOption position: "long" (bought) or "short" (sold)
quantity *numberNumber of contracts (Deribit BTC/ETH options have contract_size 1.0, so this is coin-denominated size)
scenarioPrice *numberUnderlying price in USD to evaluate the payoff at
strike *numberStrike price in USD
currencystringUnderlying. Default BTC. XAU and XAG (gold, silver) only with exchange binance.
exchangestringVenue whose settlement rules apply. "deribit" (default): BTC/ETH, coin-settled, premium in the base coin. "binance": BTC/ETH/XAU/XAG, USDT-settled, flat payoff max(0, S-K) per unit, premium in USDT (u…
premiumCoinnumberDeribit only. Premium paid/received per contract, in the base coin (matches Deribit's own quoted price, e.g. 0.02 BTC); must be < 1 for a call
premiumUsdtnumberBinance only. Premium paid/received per unit, in USDT (e.g. 1500); must be < strike for a put

workflow.run_black_scholes Black-Scholes Option Price and Greeks

Theoretical European option price and Greeks (delta, gamma, theta, vega, rho) from Black-Scholes, given manual spot/strike/days-to-expiry/volatility/risk-free-rate inputs plus an optional continuous dividend yield for stocks and ETFs (the implied-volatility and option-chain tools do not take one): no live data fetch. The live variant is workflow.run_black_scholes_live, which applies when checking a real Deribit, Binance or Bybit instrument, since that variant also reports how far the instrument's actual quoted price sits from what this formula implies. Prices are USD-denominated (the universal…

ParameterTypeDescription
daysToExpiry *numberCalendar days until expiry (can be fractional)
spot *numberUnderlying spot price, USD
strike *numberStrike price, USD
volatilityPct *numberAnnualized implied volatility in percentage points, e.g. 60 for 60%
dividendYieldPctnumberContinuous dividend yield in percent per year (1.2 means 1.2%), for stock and ETF options. Default 0: crypto has none. Range 0 to 100.
riskFreeRatePctnumberRisk-free rate in percentage points. Default 0: standard crypto-options convention.

workflow.run_option_greeks Option Greeks

First and second order Greeks of a European option from Black-Scholes-Merton, manual inputs only (no live data): everything workflow.run_black_scholes returns (price, delta, gamma, vega, theta, rho) plus the higher-order Greeks vanna, vomma (volga), charm, veta, speed, zomma and color, with an optional continuous dividend yield for stocks and ETFs. Edge cases: daysToExpiry 0.001 to 36500, volatilityPct 0.01 to 1000, spot and strike above zero, riskFreeRatePct and dividendYieldPct 0 to 100; inputs so extreme that a Greek is not a finite number (a strike far from the spot for the volatility and…

ParameterTypeDescription
daysToExpiry *numberCalendar days until expiry (can be fractional), 0.001 to 36500
spot *numberUnderlying spot price
strike *numberStrike price, same units as spot
volatilityPct *numberAnnualized implied volatility in percentage points, e.g. 60 for 60%, 0.01 to 1000
dividendYieldPctnumberContinuous dividend yield in percent per year, 0 to 100. Default 0.
riskFreeRatePctnumberRisk-free rate in percentage points, 0 to 100. Default 0.

workflow.run_straddle_strangle Straddle and Strangle

Payoff, P&L, and both breakeven prices for a long or short straddle/strangle (a call + a put on the same Deribit BTC/ETH underlying, both legs the same direction) at a scenario price. A straddle is callStrike === putStrike; any callStrike > putStrike makes it a strangle, same formula either way. Coin-settled like workflow.run_options_payoff: a long position's max loss is the flat total premium paid (between the strikes, both legs worthless); max profit is technically unbounded, dominated by the put leg's payoff as price falls toward zero. Edge cases: callStrike must be at or above putStrike; s…

ParameterTypeDescription
callStrike *numberCall leg strike, USD. Equal to putStrike for a straddle, higher for a strangle.
position *stringOption position: "long" (bought) or "short" (sold)
putStrike *numberPut leg strike, USD. Must be <= callStrike.
quantity *numberNumber of straddle/strangle units (both legs sized equally)
scenarioPrice *numberUnderlying price in USD to evaluate the payoff at
callPremiumCoinnumberDeribit only. Call leg premium per contract, in the base coin (e.g. 0.02 BTC)
callPremiumUsdtnumberBinance only. Call leg premium per unit, in USDT
currencystringUnderlying. Default BTC. XAU and XAG (gold, silver) only with exchange binance.
exchangestringVenue whose settlement rules apply. "deribit" (default): BTC/ETH, coin-settled, premium in the base coin. "binance": BTC/ETH/XAU/XAG, USDT-settled, flat payoff max(0, S-K) per unit, premium in USDT (u…
putPremiumCoinnumberDeribit only. Put leg premium per contract, in the base coin
putPremiumUsdtnumberBinance only. Put leg premium per unit, in USDT

workflow.run_covered_call_protective_put Covered Call and Protective Put

Covered call (long the coin + short a call against it, for yield) or protective put (long the coin + long a put, for downside insurance) on a Deribit BTC/ETH position. Returns the standard annualized-yield metric (premium ÷ 1 coin, annualized by 365/daysToExpiry) up front: that number doesn't depend on any price scenario. Also returns the USD value of the combined position at a given scenario price: covered call caps upside at strike + premium×scenarioPrice (the premium's own coin-denominated value still scales with price, unlike a textbook USD-settled cap); protective put floors value at st…

ParameterTypeDescription
daysToExpiry *numberCalendar days until expiry; used to annualize the yield/cost
quantity *numberCoin units held / contracts (1:1 covered)
scenarioPrice *numberUnderlying price in USD to evaluate the combined position's value at
spotEntry *numberPrice you acquired/value the underlying coin at, USD; used for the covered-call breakeven vs. cost basis
strategy *string"covered_call" (hold the coin, sell a call against it) or "protective_put" (hold the coin, buy a put as insurance)
strike *numberOption strike, USD
currencystringUnderlying. Default BTC. XAU and XAG (gold, silver) only with exchange binance.
exchangestringVenue whose settlement rules apply. "deribit" (default): BTC/ETH, coin-settled, premium in the base coin. "binance": BTC/ETH/XAU/XAG, USDT-settled, flat payoff max(0, S-K) per unit, premium in USDT (u…
premiumCoinnumberDeribit only. Premium received (covered_call) or paid (protective_put) per contract, in the base coin
premiumUsdtnumberBinance only. Premium received (covered_call) or paid (protective_put) per unit, in USDT; must be < spotEntry for a covered call and < strike for a protective put

workflow.run_spread_payoff Spread Payoff

Payoff, breakeven(s), and max profit/loss for a Deribit BTC/ETH vertical spread (2 legs, same option type, opposite direction, e.g. a bull call spread) or an iron condor/butterfly (4 legs: 2 calls + 2 puts) at a scenario price. Coin-settled, and the max profit/loss are genuinely NOT the flat, textbook USD-settled values: because each leg's own payoff is divided by the settlement price, (1) a debit vertical spread's peak payoff occurs exactly at its short strike, not "anywhere beyond it" - and its profit is a finite WINDOW that closes again at a high enough price, decaying back toward a full lo…

ParameterTypeDescription
legs *arrayExactly 2 legs (same option type, opposite position - a vertical spread) or 4 legs (2 calls + 2 puts - an iron condor/butterfly). Each leg: { optionType: call|put, position: long|short, strike: number…
quantity *numberNumber of spread/condor units
scenarioPrice *numberUnderlying price in USD to evaluate the payoff at
currencystringUnderlying. Default BTC. XAU and XAG (gold, silver) only with exchange binance.
exchangestringVenue whose settlement rules apply. "deribit" (default): BTC/ETH, coin-settled, premium in the base coin. "binance": BTC/ETH/XAU/XAG, USDT-settled, flat payoff max(0, S-K) per unit, premium in USDT (l…

workflow.run_implied_volatility Implied Volatility

Solves for the volatility that makes Black-Scholes reproduce an observed option price (Newton-Raphson with a bisection fallback for cases where vega is too flat to converge, e.g. deep ITM/OTM or very short-dated). Checks the price against its no-arbitrage bounds first and refuses to solve (converged: false + error) rather than return a garbage number when the price is impossible for the given spot/strike/rate. Edge cases: spot, strike, daysToExpiry and targetPriceUsd above zero; riskFreeRatePct 0 to 100; the search range is 0.01 to 1000 volatility points; a price outside the no-arbitrage bound…

ParameterTypeDescription
daysToExpiry *numberCalendar days until expiry (can be fractional)
optionType *stringOption type: "call" or "put"
spot *numberUnderlying spot price, USD
strike *numberStrike price, USD
targetPriceUsd *numberThe observed option price, USD, to solve the implied volatility from
riskFreeRatePctnumberRisk-free rate in percentage points. Default 0: standard crypto-options convention.

workflow.run_barrier_touch Barrier Touch

Probability that the price touches a barrier (a target or a stop level) at ANY time within N days, under geometric Brownian motion (reflection principle with drift). This is not the probability of finishing beyond the level at expiry: at zero log-drift a touch is exactly twice as likely as a finish, and `finishBeyondProbabilityPct` is returned next to it for comparison (the end-of-window question itself is `workflow.run_window_fair_value`). Barrier above spot gives an up-touch, below spot a down-touch. Monitoring is continuous (every instant, not daily closes or candle highs, which touch less…

ParameterTypeDescription
barrier *numberThe level to touch, same units as spot. Above spot: up-touch; below spot: down-touch
daysToExpiry *numberCalendar days in the window (can be fractional, up to 3650)
spot *numberCurrent price, USD (any quote currency)
volatilityPct *numberAnnualized volatility in percentage points (e.g. 60 for 60%), at least 0.01
driftPctnumberAnnualized expected price drift in percentage points. Default 0.

workflow.run_american_option American Option

Price of an AMERICAN put or call (exercisable on any day up to expiry) on a Cox-Ross-Rubinstein binomial tree with early exercise checked at every node, with a continuous dividend yield. Use it for stock and ETF style options; crypto options on Deribit and Binance are European (`workflow.run_black_scholes`). Output: americanPrice, delta, gamma, thetaPerDay (calendar day, read from the tree, typically 0 when exercising now is optimal), intrinsicValue, earlyExerciseNow (a tree reading: exercising now beats holding), europeanPrice (Black-Scholes, same inputs), earlyExercisePremium, europeanTreePr…

ParameterTypeDescription
daysToExpiry *numberCalendar days to expiry (up to 3650)
optionType *stringAmerican call or put
spot *numberCurrent price of the underlying
strike *numberStrike price, same units as spot
volatilityPct *numberAnnualized volatility in percentage points (e.g. 30 for 30%), at most 300
dividendYieldPctnumberContinuous dividend yield in percent per year, 0 to 100. Default 0.
riskFreeRatePctnumberAnnual risk-free rate in percent, 0 to 100. Default 0.
stepsintegerBinomial tree steps, whole number from 50 to 2000. Default 500.

workflow.run_cash_secured_put Cash Secured Put

Cash-secured put on a US stock or ETF, in US dollars with the standard 100-share contract (NOT Deribit and not coin-settled): you sell puts and hold the cash to buy the shares if they are assigned. Returns the premium income, the cash held as collateral (strike x 100 x contracts), the return for the period (premium / collateral) and the simple annualized return by days to expiry (365-day year, not compounded), the effective buy price if assigned (strike minus premium, which is also the breakeven), the net cost of the shares if assigned, the maximum profit (the premium), the maximum loss (share…

ParameterTypeDescription
contracts *integerNumber of contracts sold, a whole number from 1 to 1,000,000
daysToExpiry *numberCalendar days to expiry, 1 to 3650
premium *numberPremium received per share as quoted, USD, 0 or more and below the strike. A contract covers 100 shares, so 2.50 pays 250 dollars per contract.
strike *numberStrike price of the put, USD per share, above 0
scenarioPricenumberOptional: a share price at expiry, USD, 0 or more, to report the P&L at
spotPricenumberOptional: the share price today, USD, above 0, for the comparison with buying now

workflow.run_options_position Options Position

Profit and loss at expiry for a US-style equity, ETF or index option position built from 1 to 4 option legs, in US dollars with the standard contract multiplier of 100 shares (NOT Deribit and not coin-settled: for BTC/ETH options on Deribit use workflow.run_spread_payoff or workflow.run_options_payoff). Each leg: call or put, long or short, strike, premium per share as quoted, contracts. Optional `stock` adds long shares held with the options (covered call, protective put, collar). Prices are the ones you pass in; nothing is fetched. All legs share one expiry (a calendar spread is not computed…

ParameterTypeDescription
legs *arrayOne to four option legs. Each leg: { optionType: call|put, position: long|short, strike: number, premium: number (USD per share), contracts: integer >= 1 (default 1) }.
scenarioPricesarrayExpiry prices (USD per share, 0 or more) to report the position P&L at. Optional.
stockobjectOptional long shares held together with the options: { quantity: whole shares, costPerShare: USD }. 100 shares cover one short call.

workflow.run_strategy_picker Strategy Picker

Ranks option strategies for a price forecast and a volatility view. You give the spot price, the price you expect at expiry, days to expiry and the market implied volatility; optionally your own volatility forecast (default: the market's, so the view is on price only). Every strategy is built from strikes on a grid around spot, each leg priced with Black-Scholes at the one implied volatility (no skew, no dividends), and the best-fitting version of each family is kept: long call, long put, short put (cash-secured), covered call, protective put, long straddle, long strangle, bull call spread, be…

ParameterTypeDescription
daysToExpiry *numberDays to expiry, above 0 and at most 3650
impliedVolPct *numberMarket implied volatility in percent per year (e.g. 30), used to price every option, at most 1000
spot *numberCurrent price of the underlying, from 0.000000001 to 1000000000
targetPrice *numberPrice you expect at expiry (the mean of your view), from 0.000000001 to 1000000000
allowUnlimitedLossbooleanInclude naked short call, short straddle and short strangle. Default false.
forecastVolPctnumberYour own volatility forecast in percent per year. Default: impliedVolPct (no volatility view).
rankBystringRanking key. Default expectedPnl.
riskFreeRatePctnumberAnnual risk-free rate in percent, 0 to 100. Default 0.
strikeStepnumberStrike spacing. Default: a round step that gives about 16 strikes across the range, plus one past each end. The grid must hold 3 to 60 strikes.

workflow.run_window_fair_value Window Fair Value

Theoretical fair value for a time-windowed crypto up/down contract (the shape ADI Predictstreet and Kalshi-style daily crypto markets use: pays out based on whether the settlement price finishes at/above or below a reference price pinned at window open, by a fixed close time): a cash-or-nothing digital option, priced with the standard N(d2) formula. It gives the probability at the close time only, not the probability of touching a level at any point before it (first passage). Time convention: a year is 365 days. Use this when there's no live market price to read (e.g. a venue's contract has re…

ParameterTypeDescription
currentPrice *numberCurrent spot price of the coin, in USD.
minutesToClose *numberMinutes remaining until the window closes/settles.
referencePrice *numberThe reference/pinned price the contract resolves against (the window's open price, or a stated strike).
volatilityPct *numberAnnualized volatility, in percentage points (e.g. 50 for 50%). Required; no live source for this on these contracts.
riskFreeRatePctnumberRisk-free rate in percentage points. Default 0: negligible for these short windows.

workflow.run_forex_pip_value Forex Pip Value

Value of 1 pip for a given forex pair and position size, in that pair's own quote currency (e.g. EUR/USD's pip value comes back in USD, USD/JPY's in JPY): no live FX rate needed, since a pair's pip value is naturally denominated in its own quote currency. Pip size is 0.0001 for non-JPY pairs, 0.01 for JPY-quoted pairs, a universal market convention verified against real broker documentation, not broker-specific. The live variant is workflow.run_forex_pip_value_live, which applies when the account currency differs from the pair's quote currency. Precious-metal pairs (XAU, XAG, XPT, XPD) are ref…

ParameterTypeDescription
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
units *numberPosition size in base-currency units (1 standard lot = 100,000, mini = 10,000, micro = 1,000, nano = 100)

workflow.run_forex_margin_level Forex Margin Level

Free margin and margin level % from account equity and used margin: equity/usedMargin*100, the same stop-out proximity metric every forex platform shows. Returns null (not Infinity) when usedMargin is 0, meaning no open position. Edge cases: equity above zero, usedMargin zero or more; usedMargin of 0 returns marginLevelPct null (no open position), not a large number; equity below used margin gives a level under 100. Not covered: a broker margin-call or stop-out threshold (they differ by broker), pending orders, hedged-position margin offsets, and swap or commission not yet charged. Use when us…

ParameterTypeDescription
equity *numberAccount equity (balance + floating P&L)
usedMargin *numberMargin currently locked by open positions. 0 if none.

workflow.run_forex_breakeven Forex Breakeven

Breakeven price for a forex position accounting for spread and round-trip commission, in pips and in price. Commission is quoted per standard lot (100,000 units) and expressed in the pair's own quote currency; because both commission and pip value scale with lot size, the commission-in-pips figure is independent of position size by construction. Precious-metal pairs (XAU, XAG, XPT, XPD) are refused with an error, because their pip and lot size differ by broker. Edge cases: entryPrice above zero; spreadPips and commissionPerLotRoundTrip zero or more (commission default 0, in the quote currency…

ParameterTypeDescription
entryPrice *numberEntry price in the pair's own quote terms, e.g. 1.0850 for EUR/USD
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
side *stringTrade direction: "long" or "short"
spreadPips *numberSpread at entry, in pips
commissionPerLotRoundTripnumberRound-trip commission per standard lot, in the pair's own quote currency. Default 0 (pure-spread broker model).

workflow.run_forex_pnl Forex PnL

Profit or loss for a closed or hypothetical forex trade, in pips and in the pair's own quote currency, long or short. Precious-metal pairs (XAU, XAG, XPT, XPD) are refused with an error, because their pip and lot size differ by broker. Edge cases: entryPrice, exitPrice and units above zero; The pair is BASE/QUOTE with two different ISO 4217 currency codes, in any letter case; crypto tickers and precious metals (XAU, XAG, XPT, XPD) are refused. A pip is 0.01 for a pair quoted in JPY and 0.0001 for every other pair, and a standard lot is 100,000 units. The result is in the quote currency; a shor…

ParameterTypeDescription
entryPrice *numberEntry price in the pair's own quote terms, e.g. 1.0850 for EUR/USD
exitPrice *numberExit price, same quote convention as the entry price
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
side *stringTrade direction: "long" or "short"
units *numberPosition size in base-currency units

workflow.run_forex_risk_reward Forex Risk Reward

Risk and reward distance in pips from entry/stop/target, and the resulting ratio (reward/risk): a raw number, not a verdict. ratio is null when the stop sits exactly at entry (no risk distance), and also when validSetup is false (stop/target on the wrong side of entry for the given side, e.g. a long with its stop above entry) - check validSetup before trusting the ratio. Precious-metal pairs (XAU, XAG, XPT, XPD) are refused with an error, because their pip and lot size differ by broker. Edge cases: entryPrice, stopPrice and targetPrice above zero; The pair is BASE/QUOTE with two different ISO…

ParameterTypeDescription
entryPrice *numberEntry price in the pair's own quote terms, e.g. 1.0850 for EUR/USD
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
side *stringTrade direction: "long" or "short"
stopPrice *numberStop-loss price, same quote convention as the entry price
targetPrice *numberTake-profit price, same quote convention as the entry price

workflow.run_forex_scenario Forex Scenario

PnL across a range of hypothetical price moves (in pips, signed by actual price direction, not pre-adjusted for side), for a single forex position size, long or short. Precious-metal pairs (XAU, XAG, XPT, XPD) are refused with an error, because their pip and lot size differ by broker. Edge cases: entryPrice and units above zero; deltasPips is a list of at least one signed number of pips (positive means the price rose, whatever the side); a move that takes the exit price to zero or below is not rejected, read exitPrice; The pair is BASE/QUOTE with two different ISO 4217 currency codes, in any l…

ParameterTypeDescription
deltasPips *arrayHypothetical price moves in pips, e.g. [-50, 0, 50]
entryPrice *numberEntry price in the pair's own quote terms, e.g. 1.0850 for EUR/USD
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
side *stringTrade direction: "long" or "short"
units *numberPosition size in base-currency units

workflow.run_fibonacci_levels Fibonacci Levels

Fibonacci retracement and extension price levels from a swing high and low, for any asset (forex, stocks, crypto): retracement 0, 23.6, 38.2, 50, 61.8, 78.6 and 100 percent and extension 127.2, 161.8, 200 and 261.8 percent, as prices. direction "up" measures a rise from the low to the high, "down" a fall from the high to the low; 0 percent is the end of the swing and 100 percent its start. A level at or below zero (an extension of a steep fall) comes back as price null. The ratios are a charting convention, not a forecast. Pure price arithmetic, no pair or market data. Edge cases: high and low…

ParameterTypeDescription
direction *string"up": the swing rose from the low to the high; "down": it fell from the high to the low
high *numberSwing high price (positive, above the low, at most 1e300)
low *numberSwing low price (positive, below the high)

workflow.run_forex_average_entry Forex Average Entry

Size-weighted (arithmetic) average entry price across multiple forex fills. Edge cases: at least 1 fill; every price and units above zero; pair is BASE/QUOTE with two different ISO 4217 codes (a metal such as XAU/USD is accepted here because no pip is needed). The average is weighted by units, not by cash. Not covered: swap, commission, spread, fills in different pairs, and closing fills (buys only). Use when user asks "what's my average entry after these fills?". Returns: totalUnits, totalCost, avgEntry.

ParameterTypeDescription
fills *arrayFills to average, each with a price and a size in base-currency units
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"

workflow.run_forex_margin_required Forex Margin Required

Notional and margin required for a forex position, in the pair's own quote currency: no live FX rate needed. The live variant is workflow.run_forex_margin_required_live, which applies when the account currency differs from the pair's quote currency. Edge cases: units, price and leverage above zero (leverage 50 means 50:1); the pair is BASE/QUOTE with two different ISO 4217 codes (no pip is needed, so a metal pair is accepted). Margin is notional / leverage in the quote currency. Not covered: broker margin tiers, per-instrument leverage caps, hedge offsets, and conversion to the account currenc…

ParameterTypeDescription
leverage *numberLeverage multiplier, e.g. 50 for 50:1
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
price *numberEntry or current price
units *numberPosition size in base-currency units

workflow.run_forex_currency_converter Forex Currency Converter

Converts an amount between currencies using a manually supplied rate: no live data fetch. The live variant is workflow.run_forex_currency_converter_live, which has the rate fetched automatically. Edge cases: rate above zero; amount may be zero or negative (it is converted as given); the tool takes the amount and the rate only, no currency codes. Not covered: bank or broker markups, fees, rounding rules of a particular provider, and the direction of the rate (you must supply the rate that applies from the first to the second currency). Use when user already knows the exact rate they want applie…

ParameterTypeDescription
amount *numberAmount in the source currency
rate *numberExchange rate to apply (1 unit of source currency = rate units of target currency)

workflow.run_forex_swap_cost Forex Swap Cost

Total swap/rollover cost (or credit) for holding a forex position overnight, in the pair's own quote currency: no live FX rate needed. Swap rates are broker-set with no free live feed available, so swapPerLotPerNight is always a manual input (quoted per standard lot, matching how commission is quoted in workflow.run_forex_breakeven), not fetched. Negative = cost (you pay), positive = credit (you receive). The live variant is workflow.run_forex_swap_cost_live, which applies when the account currency differs from the pair's quote currency. Precious-metal pairs (XAU, XAG, XPT, XPD) are refused wi…

ParameterTypeDescription
nights *integerNumber of nights the position is held
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
swapPerLotPerNight *numberSwap rate per standard lot (100,000 units) per night, in the pair's quote currency. Negative = cost, positive = credit. Broker-set: get this from the user's broker platform, there is no live source fo…
units *numberPosition size in base-currency units

workflow.run_forex_correlation Forex Correlation

Correlation coefficient and minimum-variance hedge ratio between two price series of matching length, computed on daily % returns (not raw price levels, which would give spuriously high correlation between two unrelated but both-trending series). hedgeRatio follows Hull's standard futures-hedging formula: cov(returns1,returns2)/var(returns2), "how many units of series 2 per unit of series 1 minimizes the combined position's variance." No live data fetch: supply the two price series directly. The live variant is workflow.run_forex_correlation_live, which has both series fetched automatically fo…

ParameterTypeDescription
rates1 *arrayFirst price series, chronological order, one price per date
rates2 *arraySecond price series, chronological order, same length and same dates as rates1

workflow.run_var_cvar VaR and CVaR

Parametric Value at Risk (VaR) and Conditional VaR / Expected Shortfall (CVaR), the variance-covariance method (assumes normally distributed returns), plus Modified VaR (Cornish-Fisher skew/kurtosis correction, Boudt/Peterson/Croux) when a return series is supplied. Supply either a return series or a mean/stdev pair directly, at a confidence level. Output is at the same periodicity as the input (no automatic annualization) - a daily return series gives a daily VaR/CVaR. Edge cases: give returns (at least 2 values) or both mean and stdev (stdev zero or more), never neither; confidence strictly…

ParameterTypeDescription
confidencenumberConfidence level, 0-1 exclusive (default 0.95)
meannumberMean return, if not supplying returns[] directly
returnsarrayReturn series (e.g. daily % returns as decimals). Provide this OR mean+stdev, not both.
stdevnumberStandard deviation of returns, if not supplying returns[] directly

workflow.run_sharpe_stats Sharpe Ratio Statistics

Sharpe ratio with the Lo (2002) serial-correlation-aware annualization correction, computed in its lag-1 form rather than the full multi-lag sum (the naive sqrt(periods_per_year) scaling overstates or understates the true annualized Sharpe when returns are autocorrelated), plus the Probabilistic Sharpe Ratio (Bailey & Lopez de Prado): the probability the true Sharpe exceeds a benchmark, adjusted for the sample's skewness/kurtosis and length, not just its point estimate. Edge cases: at least 3 returns; periods_per_year from 1 to 100,000,000 (default 365, the crypto convention); benchmark_sharpe…

ParameterTypeDescription
returns *arrayReturn series, one value per period
benchmark_sharpenumberBenchmark Sharpe ratio for the PSR test, same periodicity as returns (default 0)
periods_per_yearnumberPeriods per year for annualization (default 365, crypto convention - trades every day). Any number from 1 to 100 million, e.g. 365.25.

workflow.run_hurst_exponent Hurst Exponent

Hurst exponent via rescaled-range (R/S) analysis: is this return/price series trending/persistent (H>0.5, a move tends to be followed by a move in the same direction), mean-reverting/anti-persistent (H<0.5), or consistent with a random walk (H~0.5)? Edge cases: at least 32 values; min_window a whole number of at least 4 (default 8); a series too short to give at least 3 window sizes at that min_window is an error. Takes returns, not price levels. Not covered: confidence intervals for H, bias correction for short samples, other estimators (DFA, wavelets). R/S estimates are noisy on short series…

ParameterTypeDescription
values *arrayReturn series (not raw price levels)
min_windownumberSmallest R/S analysis window size (default 8)

workflow.run_cointegration Cointegration Test

Engle-Granger two-step cointegration test for a pair of price series: do they share a long-run equilibrium relationship (their spread is stationary/mean-reverting)? The standard pairs-trading signal test. Returns the cointegrating regression's hedge ratio (beta) and an ADF t-statistic on the residuals, compared against 1%/5%/10% critical values. Edge cases: x and y each at least 20 values and the same length, one observation per date (otherwise an error); constant residuals (zero variance) are an error; the test is one direction (y regressed on x), Engle-Granger. Not covered: more than two ser…

ParameterTypeDescription
x *arraySecond price series, same length and dates as y
y *arrayFirst price series (the dependent variable in the cointegrating regression)

workflow.run_portfolio_tearsheet Portfolio Tearsheet

Core risk/return tearsheet from a single return series: annualized return (compounded, not linear) and volatility, Sharpe (plain + Lo 2002-corrected + Pezier-White skew/kurtosis-adjusted), Sortino, max drawdown, Calmar ratio, the drawdown-ratio cluster (Ulcer Index/Martin ratio, Pain Index/Pain ratio, Burke ratio + modified), Omega-Sharpe ratio, Upside Potential Ratio, skewness, kurtosis, Probabilistic Sharpe Ratio, win rate, best/worst single-period return. Edge cases: at least 3 returns; periods_per_year 1 to 100,000,000 (default 365); mar (minimum acceptable return per period) and benchmark…

ParameterTypeDescription
returns *arrayReturn series, one value per period
benchmark_sharpenumberBenchmark Sharpe ratio for the PSR figure, same periodicity as returns (default 0)
marnumberMinimum acceptable return for the Sortino ratio, same periodicity as returns (default 0)
periods_per_yearnumberPeriods per year for annualization (default 365). Any number from 1 to 100 million, e.g. 365.25.

workflow.run_garch GARCH Volatility

GARCH(1,1) volatility model, fit by maximum likelihood on a return series: estimates omega/alpha/beta (the variance-persistence parameters) and forecasts next-period volatility. Edge cases: at least 50 returns; a flat series is an error; non-finite values are refused. Output is per period of the input (no annualization). Not covered: asymmetric models (GJR, EGARCH), fat-tailed errors (the fit is Gaussian maximum likelihood), multi-step forecasts, and a guarantee that the optimizer finds the global maximum. Use when user asks "what's my GARCH volatility forecast?" or "how persistent is volatili…

ParameterTypeDescription
returns *arrayReturn series, one value per period, at least 50 values (GARCH needs real sample depth to identify persistence)

workflow.run_risk_parity Risk Parity Weights

Risk-parity (equal or custom risk contribution) portfolio weights for N assets: given a covariance matrix (or N return series to compute one from), finds long-only weights where each asset contributes its target share of total portfolio risk. Edge cases: give either returns (at least 2 assets, each series at least 2 values and all the same length) or a square covariance matrix (2 by 2 or larger), never neither; risk_budgets must be positive, finite, one per asset (they are normalized, so they need not sum to 1); an asset with zero or negative variance is an error; non-finite values are an erro…

ParameterTypeDescription
covariancearrayDirect NxN covariance matrix, if not supplying returns[][] directly.
returnsarrayOne return series per asset (2+ assets, all series the same length). Provide this OR covariance, not both.
risk_budgetsarrayTarget risk share per asset, one per asset (need not sum to 1, normalized internally). Default: equal (1/N each).

workflow.run_dsr Deflated Sharpe Ratio

Deflated Sharpe Ratio (Bailey & Lopez de Prado): given how many strategy variants you tried (and how correlated they are), what Sharpe ratio would the *best of N* clear by luck alone, and does your actual strategy still clear that higher bar? Edge cases: returns at least 3; give either trial_sharpes (at least 2 values, per period; identical values are an error) or n_trials (a whole number from 2 to 1e9); avg_correlation 0 to below 1 (default 0) works only with n_trials; null_mean works only with trial_sharpes; an effective trial count of 1 or less is an error. Not covered: the real number of t…

ParameterTypeDescription
returns *arrayThe candidate strategy's own return series
avg_correlationnumberAverage pairwise correlation between trials, 0-1 (default 0 = independent). Only used with n_trials; lowers the effective trial count via Kish's design effect.
n_trialsnumberNumber of strategy variants tried, if trial_sharpes were not tracked individually. Assumes trial Sharpes with mean 0 and variance 1 (per-period units): too strict for daily series, prefer trial_sharpe…
null_meanbooleanOnly used with trial_sharpes. true = centre the luck threshold on 0 (zero-skill null) instead of on the trials' own mean Sharpe; the spread still comes from the trials. Default false.
trial_sharpesarrayObserved Sharpe ratios of all N trials tried, if tracked. Takes priority over n_trials if both are given.

workflow.run_kelly_frontier Kelly Growth-Security Frontier

Kelly growth-security frontier (MacLean, Ziemba & Blazenko 1992): for a strategy compounding at a fraction lambda of full Kelly, the probability wealth ever falls to a fraction alpha of its starting value is P = alpha^(2/lambda-1). Provide either lambda_fraction (to compute that probability) or max_probability (to solve for the largest lambda that keeps the ruin probability at or below it). Edge cases: alpha strictly between 0 and 1; give exactly one of lambda_fraction (above 0) or max_probability (strictly between 0 and 1), not both and not neither. Not covered: the edge of a real strategy an…

ParameterTypeDescription
alpha *numberFraction of starting capital, 0-1 exclusive (e.g. 0.5 = "ever falls to half my starting bankroll")
lambda_fractionnumberFraction of full Kelly being bet (1 = full Kelly, 0.5 = half Kelly). Provide this OR max_probability, not both.
max_probabilitynumberTarget ceiling on the ruin probability, 0-1 exclusive. Provide this to solve for the safe lambda_fraction instead of supplying it directly.

workflow.run_unsmoothing Return Unsmoothing

Return "unsmoothing" for infrequently-marked/illiquid or appraisal-based series: Getmansky-Lo-Makarov (2004) MA(2) smoothing index plus Blundell-Ward (1987) AR(1) volatility inflation, two complementary models answering "this return series looks smoother than it really is; what's the true volatility?". Edge cases: at least 20 returns; a flat series is an error; if the MA(2) fit does not converge from any starting point, or the lag-1 autocorrelation is 1 or more (Blundell-Ward inflation undefined), the call is an error. Not covered: more than 2 lags of smoothing, tax and fee effects, and proof…

ParameterTypeDescription
returns *arrayThe observed (possibly smoothed) return series, at least 20 values

workflow.run_evt_tail_risk EVT Tail Risk

Extreme Value Theory tail risk (Peaks-Over-Threshold): fits a Generalized Pareto Distribution to the losses beyond a high threshold via Grimshaw's (1993) profile-likelihood MLE, then extrapolates VaR/Expected Shortfall at the requested confidence, without assuming a normal distribution. Edge cases: at least 100 finite returns; threshold_percentile strictly between 0 and 100 (default 90); confidence strictly between 0 and 1 (default 0.99); at least 10 returns beyond the threshold, otherwise an error; if the tail fit does not converge, the call is an error suggesting another threshold. Not cover…

ParameterTypeDescription
returns *arrayReturn series, one value per period, at least 100 values (POT needs real sample depth in the tail)
confidencenumberVaR/ES confidence level, 0-1 exclusive. Default 0.99. Must satisfy 1-confidence < the threshold's own exceedance rate.
threshold_percentilenumberPercentile (0-100 exclusive) of the loss distribution used as the POT threshold u. Default 90.

workflow.run_monte_carlo Monte Carlo Simulation

Monte Carlo simulation of a portfolio: geometric Brownian motion with a contribution (or withdrawal) at the end of every step, up to 10,000 paths (paths x steps at most 5 million), deterministic for a given seed. Returns the spread of final values (percentiles 5 to 95, mean with its standard error and the exact expected value, probability of ending below the net amount invested, probability of ending a step at or below a ruin level) and a fan of 5th, 50th and 95th percentile bands over time, instead of one number. A value that would go below zero is floored at zero. Constant return and volatil…

ParameterTypeDescription
annualReturnPct *numberExpected growth mu in percentage points per year, -100 to 500.
initialValue *numberStarting value, 0 to 1e12. 0 is allowed only with a positive contribution.
volatilityPct *numberAnnual volatility sigma in percentage points, 0 to 500.
years *numberHorizon in years, above 0 and at most 50. years x stepsPerYear must be a whole number.
contributionPerStepnumberAdded at the END of every step; negative is a withdrawal. Default 0.
pathsintegerSimulated paths, 100 to 10000 (paths x steps at most 5 million). Default 2000.
ruinBelownumberA path counts as ruined once it ends a step at or below this value. Default 0.
seedintegerRandom seed, 0 to 4294967295; the same input and seed give the same result. Default 1.
stepsPerYearintegerSteps (and contributions) per year, 1 to 365. Default 12.

workflow.run_event_study Event Study

Event study with a placebo: is the average return after your events (a listing, an unlock, a signal firing) different from the average return of the same window started on random non-event dates? Give event_returns and placebo_returns in the same units; optional event_tickers and placebo_tickers (one per return) cluster the standard error by ticker, because events on one coin are not independent draws. Returns the effect (event mean minus placebo mean), Welch t-test, permutation p-value (exact when the number of splits is small, otherwise seeded random shuffles; two-sided as scipy.stats.permut…

ParameterTypeDescription
event_returns *arrayOne return per event over the event window, any consistent unit (percent or fraction). 2 to 5000 values.
placebo_returns *arrayReturns over a window of the same length started on random dates without an event. 2 to 5000 values; event and placebo together at most 5000.
alphanumberSignificance level for the verdict, above 0 and below 0.5. Default 0.05.
event_tickersarrayOptional, one ticker per event return, used to cluster. Omitted: every event is its own cluster.
n_permutationsintegerRandom shuffles when the exact test is too large, 1000 to 100000. Default 10000.
placebo_tickersarrayOptional, one ticker per placebo return. Omitted: every placebo is its own cluster.
seedintegerSeed for the shuffles, 0 to 4294967295; same input and seed give the same result. Default 1.

workflow.run_orderbook_impact Orderbook Impact

Order-book "walk the book" impact/capacity: given order-book levels (price, size in base-asset units) and EITHER a target notional or an impact budget in bps, computes VWAP and price impact for that size, or (via bisection) the largest notional that stays inside the impact budget. Edge cases: bids and asks each at least 1 level (price, size in base units, any order); side buy or sell; give exactly one of notional_usd or impact_budget_bps, both above zero. A book too thin for the size returns book_sufficient false and no VWAP. Not covered: a book that moves while you trade, hidden liquidity, yo…

ParameterTypeDescription
asks *arrayAsk levels as [price, size_base] pairs, any order
bids *arrayBid levels as [price, size_base] pairs, any order
side *string"buy" walks the asks, "sell" walks the bids
impact_budget_bpsnumberMax acceptable impact in bps; solves for the largest notional within it. Provide this OR notional_usd, not both.
notional_usdnumberTarget notional to walk the book for. Provide this OR impact_budget_bps, not both.

workflow.run_open_analysis Market Profile: Open Analysis

Market Profile open analysis: where and how price opened vs the prior session value area. Use for "how did BTC open today?" / "what does the open imply for the session?". Returns: open_location, open_type (OD/OTD/ORR/OAIR) with description/implication, confidence, key_levels (VAH/VAL/VPOC/IB), tails (session-high/low rejection tails and single prints), scenario_framing (bullish/bearish/neutral), invalidation level. Candles come from the venue when candles[] is omitted (past sessions are cached, so repeats are fast); supplying candles[] makes the run network-free and reproducible. session_date…

ParameterTypeDescription
instrument *stringSymbol, e.g. BTCUSDT
session_date *stringSession date YYYY-MM-DD (UTC); must be before today (a completed session)
venue *stringExchange to fetch candles from when candles[] not supplied
candlesarrayOptional OHLCV for the session; omit to fetch from venue (reproducible + 0 COGS when supplied)
prev_candlesarrayOptional OHLCV for the previous session
timeframestringCandle timeframe (default 15m)
value_area_rulenumberValue-area fraction 0.5–0.9 (default 0.70)

workflow.run_session_structure Market Profile: Session Structure

Market Profile day-type classifier: trend / balance / neutral_trend / normal / normal_var, from TPO, initial balance, range extension and value migration. Use for "is this a trend day or a balance day?". Returns: structure (the day-type label), description, bias, key_signals, key_levels (VAH/VAL/VPOC/IB/session high-low), tails (session-high/low rejection tails and single prints), scenario_framing, invalidation level. Candles come from the venue when candles[] is omitted (past sessions are cached, so repeats are fast); supplying candles[] makes the run network-free and reproducible. session_da…

ParameterTypeDescription
instrument *stringSymbol, e.g. BTCUSDT
session_date *stringSession date YYYY-MM-DD (UTC); must be before today (a completed session)
venue *stringExchange to fetch candles from when candles[] not supplied
candlesarrayOptional OHLCV for the session; omit to fetch from venue (reproducible + 0 COGS when supplied)
prev_candlesarrayOptional OHLCV for the previous session
timeframestringCandle timeframe (default 15m)
value_area_rulenumberValue-area fraction 0.5–0.9 (default 0.70)

workflow.run_value_migration Market Profile: Value Migration

Market Profile value-area migration across sessions: is value migrating up, down, or overlapping (directional conviction vs balance)? Use for "is value moving higher day over day?". Returns: state, direction, migration_pct, key_levels (current vs. prior session VAH/VAL/VPOC), tails (session-high/low rejection tails and single prints), scenario_framing, invalidation level. Candles come from the venue when candles[] is omitted (past sessions are cached, so repeats are fast); supplying candles[] makes the run network-free and reproducible. session_date must be a completed UTC session, before toda…

ParameterTypeDescription
instrument *stringSymbol, e.g. BTCUSDT
session_date *stringSession date YYYY-MM-DD (UTC); must be before today (a completed session)
venue *stringExchange to fetch candles from when candles[] not supplied
candlesarrayOptional OHLCV for the session; omit to fetch from venue (reproducible + 0 COGS when supplied)
lookback_sessionsnumberSessions to compare, 1–5 (default 1)
prev_candlesarrayOptional OHLCV for the previous session
timeframestringCandle timeframe (default 15m)
value_area_rulenumberValue-area fraction 0.5–0.9 (default 0.70)

workflow.run_breakout_acceptance Market Profile: Breakout Acceptance

Market Profile breakout acceptance: did price accept (hold) beyond the value area / range, or reject back inside (fakeout)? Optional buy/sell delta. Use for "did the break above VAH get accepted?". Returns: state, accepted (boolean), direction, confidence, key_levels (VAH/VAL/VPOC), scenario_framing, invalidation level. Candles come from the venue when candles[] is omitted (past sessions are cached, so repeats are fast); supplying candles[] makes the run network-free and reproducible. session_date must be a completed UTC session, before today; a session with no candles returns an error. Edge c…

ParameterTypeDescription
instrument *stringSymbol, e.g. BTCUSDT
session_date *stringSession date YYYY-MM-DD (UTC); must be before today (a completed session)
venue *stringExchange to fetch candles from when candles[] not supplied
candlesarrayOptional OHLCV for the session; omit to fetch from venue (reproducible + 0 COGS when supplied)
include_deltabooleanInclude buy/sell delta analysis (default true)
prev_candlesarrayOptional OHLCV for the previous session
timeframestringCandle timeframe (default 15m)
value_area_rulenumberValue-area fraction 0.5–0.9 (default 0.70)

workflow.run_token_risk_check Token Risk Check

Token rug-pull MECHANISM check for a Solana token (mint address): can the deployer still mint supply, freeze wallets, pull liquidity, swap metadata, or has RugCheck flagged a known scam pattern (e.g. copycat token)? Fetches live facts from RugCheck (GoPlus as fallback) and returns a transparently-weighted composite score. Deliberately does NOT score holder concentration or "whale dump" impact: those are properties of any liquid market (a legit protocol's top holders are routinely treasury/vesting/exchange wallets), not rug signals; they are returned separately as informational market_context.…

ParameterTypeDescription
mint *stringSolana token mint address (base58)

workflow.run_swap_price_impact Swap Price Impact

Live price-impact quote for a Solana token swap: routed through Jupiter (the same aggregator real swaps use) across every pool it knows about, not a single-pool estimate. Works in both directions: side "sell" (default) sells a token into USDC or SOL, side "buy" spends USDC or SOL to buy the token. Edge cases: mint a valid Solana base58 address (32 to 48 characters); amount above zero; side sell (default) or buy; outputAsset USDC (default) or SOL. Quotes come live from Jupiter and are a moment in time; an unknown token or no route returns routable false with an error and no figures. Solana only…

ParameterTypeDescription
amount *numberAmount to swap, in human units (not raw base units): tokens when side is sell, units of outputAsset to spend when side is buy
mint *stringSolana mint address of the token being sold or bought (base58)
outputAssetstringThe quote asset: received when selling, paid with when buying. Default USDC.
sidestringsell: sell the token for outputAsset (default). buy: spend outputAsset to buy the token.

workflow.run_market_cap_comparison Market Cap Comparison

Compares two tokens' live market caps (Solana or any of 5 EVM chains; the two tokens can be on different chains) and projects what an investment would be worth if the first token's market cap matched the second's. Narrative-agnostic ("if X reaches Y's market cap"): works for any token pair, not tied to one hype cycle or one chain. A snapshot ratio, not a forecast: assumes fixed supply on both sides. Edge cases: investmentUsd above zero; each token is a chain (solana, ethereum, base, bsc, arbitrum or polygon, default solana) plus an address; a token whose market cap cannot be read returns compa…

ParameterTypeDescription
compareToMint *stringAddress of the token whose market cap to compare against
investmentUsd *numberInvestment amount in USD
tokenMint *stringAddress of the token you hold or are evaluating (base58 for Solana, 0x... for EVM chains)
compareToChainstringChain of the comparison token. Default solana. Can differ from tokenChain.
tokenChainstringChain of the token you hold. Default solana.

workflow.run_impermanent_loss_live Impermanent Loss (Live)

Live variant of workflow.run_impermanent_loss: fetches each token's current live USD price (Solana or any of 5 EVM chains) and derives currentPrice as their ratio, instead of it being supplied manually. entryPrice stays a manual, historical input (a fact the caller must supply, not something a live quote should overwrite), same convention as every other live-capable tool in this product. Edge cases: same input rules as workflow.run_impermanent_loss, except currentPrice is derived from the live USD prices of the two tokens (each on solana, ethereum, base, bsc, arbitrum or polygon); if either pr…

ParameterTypeDescription
baseMint *stringAddress of the base token
entryPrice *numberBase token's price in quote-token terms when liquidity was deposited (manual - a historical fact)
quoteMint *stringAddress of the quote token
baseChainstringChain of the base (volatile) token. Default solana.
depositValueUsdnumberOptional: USD value deposited at entry
feesEarnedUsdnumberOptional trading fees earned so far in USD (default 0)
lowerPricenumberRange lower bound - required for concentrated mode
modestringDefault full_range.
quoteChainstringChain of the quote token. Default solana.
upperPricenumberRange upper bound - required for concentrated mode

workflow.run_wallet_flag_check Wallet Flag Check

Checks a wallet address (Solana or any of 5 EVM chains) against independent flag databases: GoPlus (malicious-address categories, all chains), Webacy (address analysis + sanctions check, all chains), and ScamSniffer (public phishing/drainer blacklist, EVM chains only), and returns each source's own facts separately, never merged into one invented score. Edge cases: chain solana (default), ethereum, base, bsc, arbitrum or polygon; the address must fit the chain; ScamSniffer covers EVM chains only and is marked not applicable on Solana; a source that fails or has no key is reported as unavailabl…

ParameterTypeDescription
walletAddress *stringWallet address (base58 for Solana, 0x... for EVM chains)
chainstringChain of the wallet address. Default solana.

workflow.run_odds_converter Odds Converter

Converts one probability into decimal odds, American odds, and breakeven win rate: either from a manually supplied probability, or from one market read live from Kalshi, Polymarket, ADI Predictstreet, Limitless, or Myriad (five independent crypto-price prediction market venues, all public keyless market data). One market on one venue per call; it does not compare prices across venues (to compare the same bet on two or more venues, see workflow.run_spread_reader). When a Kalshi, Polymarket, Limitless, or Myriad source is supplied, also returns the vig (the exchange's built-in edge), computed fr…

ParameterTypeDescription
adiSymbolstringAn ADI Predictstreet market symbol (e.g. BTC1D-20260920T0000). Currently always returns available:false; these contracts have no live trading volume yet.
kalshiTickerstringA Kalshi market ticker (e.g. KXBTCY-27JAN0100-T149999.99) to fetch a live price from. One market only; for the same bet on several venues use workflow.run_spread_reader.
limitlessSlugstringA Limitless Exchange market slug, from the market URL (e.g. btc-up-or-down-5-min-1790249100), to fetch a live price from. On-chain (Base), mostly short-duration (5min/15min/daily) crypto up/down contr…
myriadSlugstringA Myriad Markets market slug, from the market URL (e.g. eth-at-three-digits-when-bitcoin-goes-below-50k), to fetch a live price from. On-chain (Abstract L2); not every market has a Yes/No outcome, som…
polymarketSlugstringA Polymarket market slug, from the market URL (e.g. will-bitcoin-reach-100k-in-september-2026), to fetch a live price from. One market only; for the same bet on several venues use workflow.run_spread_…
probabilitynumberProbability as a decimal 0-1 (e.g. 0.35). Use this OR one of the live sources below, not both.

workflow.run_spread_reader Spread Reader

Reads the same real-world bet's live price from 2-5 prediction-market venues at once (Kalshi, Polymarket, ADI Predictstreet, Limitless, Myriad) in a single call and reports the spread between the cheapest and most expensive. Takes every venue's identifier together in quotes[], for example one Kalshi ticker and one Polymarket slug for the same bet, and returns the venue with the lowest yes midpoint price, before fees and depth. The caller supplies each venue's own identifier for what they've confirmed is the same underlying bet; this tool never auto-matches events across venues, only reads and…

ParameterTypeDescription
quotes *arrayOne entry per venue you want to compare: 2 to 5 total, all in this one call (a Kalshi ticker and a Polymarket slug for the same bet are two entries). Each must genuinely be the same real-world bet; th…

workflow.run_cross_venue_arbitrage Cross Venue Arbitrage

Checks 2-5 quotes for the SAME real-world binary bet across venues (or manually-supplied probabilities) for a direction-independent price gap at the quoted prices: "Yes" at whichever venue quotes it cheapest, "No" at whichever venue quotes "Yes" most expensively (its own "No" price is assumed to be 1 minus its own "Yes" price, the standard complementary-binary convention). Reports isArbitrage, the cost to lock in $1 of guaranteed payout, the locked-in profit and ROI at the quoted prices for a given stake, and which venue quotes each side. feeFractionPerLeg (older name feePctPerLeg, same fracti…

ParameterTypeDescription
stakeUsd *numberTotal capital to deploy across both legs
feeFractionPerLegnumberOptional per-leg trading fee as a FRACTION of the price: 0.01 means 1%, 0.001 means 0.1%, 0.02 means 2%; maximum 0.2 (20%). Default 0. Use this field for any fee.
feePctPerLegnumberOlder name of feeFractionPerLeg, kept so existing callers keep working; the value is the same FRACTION, not a percent (0.01 is 1%). Prefer feeFractionPerLeg.
manualProbabilitiesPctarrayManual mode: 2-5 probabilities (0.01-99.99) already known for the same bet across different venues, when you don't want a live fetch. Provide this OR quotes, not both.
quotesarrayLive mode: one entry per venue, 2-5 total. Provide this OR manualProbabilitiesPct, not both.

workflow.run_market_implied_odds Market Implied Odds

Reads Kalshi's full live BTC or ETH year-end price ladder (a set of mutually-exclusive prediction markets covering the whole price range) and reports what the market itself implies: the median (50th-percentile) price bucket, the single most-likely (mode) bucket, and the probability of ending the year at or above any real bucket boundary. Deliberately does not compute an expected value or interpolate inside a bucket: the top/bottom buckets are open-ended, so any point estimate there would need an invented assumption; every number this tool returns traces back to one live, sourced price. Edge ca…

ParameterTypeDescription
coinstringWhich coin's year-end ladder to read. Default BTC.
thresholdUsdnumberOptional price threshold: returns the probability of ending the year at or above the nearest real bucket boundary at or below this value.

workflow.run_black_scholes_live Black-Scholes Option Price and Greeks (Live)

Black-Scholes theoretical price and Greeks for a REAL, live option instrument on Deribit (BTC/ETH, coin-settled) Binance (BTC, ETH, XAU, XAG, USDT-settled) or Bybit (BTC, ETH, USDT-settled): pulls that instrument's own spot, strike, days to expiry, and implied volatility from the venue, then reports how far the venue's actual quoted mark price sits from what Black-Scholes implies at that IV (priceDiscrepancyPct). This is the trust-check tool: "is this exchange's quoted price consistent with its own volatility assumption?", not an estimate, a live formula cross-check. Edge cases: European Black…

ParameterTypeDescription
instrumentName *stringExact instrument name: Deribit BTC-27FEB27-90000-C, Binance BTC-261225-90000-C (expiry YYMMDD), Bybit BTC-25DEC26-90000-C-USDT (expiry DMMMYY). Get one from the venue's options chain; this tool does n…
exchangestringVenue of the instrument. Default deribit.
riskFreeRatePctnumberRisk-free rate in percentage points, Deribit only. Default 0: standard crypto-options convention. Binance states its own rate for each contract and the price uses that one; a value here is not used fo…

workflow.run_max_pain Max Pain

Max pain of an option expiry: the settlement price at which holders of all calls and puts together would be paid the least, from the open interest per strike (1 contract = 1 unit of the underlying). Two modes. LIVE (omit strikes): reads one expiry's open interest from Deribit (BTC, ETH; coin-settled, payouts shown in USD), Binance (BTC, ETH, XAU, XAG; USDT) or Bybit (BTC, ETH; USDT); one venue per result, venues are never merged; omit expiry to get the nearest expiry that has open interest. An expiry with no open interest yet, or where the venue leaves a contract's open interest unstated, come…

ParameterTypeDescription
exchangestringLive mode: venue to read. Default deribit. Not with strikes.
expirystringLive mode: expiry as YYMMDD, e.g. 261225. Omit for the nearest expiry that has open interest. Not with strikes.
spotPricenumberYour own data: optional price today, adds the distance from max pain to it
strikesarrayYour own data: one row per strike, { strike: number > 0, callOpenInterest: number >= 0, putOpenInterest: number >= 0 }. A strike is listed once; at least one open interest must be above 0.
underlyingstringLive mode: Deribit BTC or ETH; Binance BTC, ETH, XAU or XAG; Bybit BTC or ETH. Default BTC. Not with strikes.

workflow.run_forex_pip_value_live Forex Pip Value (Live)

Value of 1 pip for a forex pair and position size, converted to a given account currency via a live FX rate: TrueFX for its 10 quoted majors (genuinely live tick data), frankfurter.app daily ECB reference rate as the fallback for every other currency (30 total). Precious-metal pairs (XAU, XAG, XPT, XPD) are refused with an error, because their pip and lot size differ by broker. Edge cases: same input rules as workflow.run_forex_pip_value; when no rate is found for the account currency, available is false and no figure is returned. The rate is a TrueFX tick or a daily ECB reference rate, not a…

ParameterTypeDescription
accountCurrency *string3-letter account currency code, e.g. "GBP"
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
units *numberPosition size in base-currency units

workflow.run_liquidation_live Liquidation (Live)

Liquidation price of a perpetual position using the exchange's own live maintenance-margin tiers for the symbol (Binance, Bybit, Hyperliquid, Gate, KuCoin, Bitget, OKX): the tier table is fetched, then the same tiered formula as workflow.run_liquidation_safety with tiers runs on it, so you do not supply tiers. Edge cases: symbol exactly as the venue writes it; an unknown symbol or an unreachable venue returns available false with an error; liqPrice is null when the position cannot be liquidated. Not covered: isolated-margin variants a venue may offer, the exact tier the venue uses (ours is a s…

ParameterTypeDescription
entryPrice *numberEntry price in the quote currency
exchange *stringExchange whose tiers are read
leverage *numberLeverage used, sets the isolated initial margin when walletBalance is left out
side *stringPosition side
size *numberBase units for a linear symbol, USD contracts for a coin-margined one
symbol *stringSymbol as the exchange writes it, e.g. BTCUSDT (Binance, Bybit, Bitget), BTC_USDT (Gate), BTC (Hyperliquid), XBTUSDTM (KuCoin), BTCUSD_PERP (Binance coin-margined), BTCUSDT or BTC-USDT-SWAP (OKX)
liqFeeRatenumberOKX only: the forced-liquidation fee OKX adds to its maintenance ratio, a fraction (the taker fee rate, for example 0.0005). Refused for other exchanges.
otherMaintenanceMarginnumberCross margin: maintenance margin of the other positions, default 0
otherUnrealizedPnlnumberCross margin: unrealized PnL of the other positions, default 0, may be negative
walletBalancenumberCross margin: wallet balance backing the position. Default: the isolated initial margin.

workflow.run_ladder_max_leg Ladder Max Leg

Largest equal leg, in whole contracts, for a scale-in ladder of D legs (linear perpetuals, cross margin). Edge cases: linear perpetuals and cross margin only; legs, step or steps, equity and leverage must describe a real ladder, and an unknown symbol or an unreachable exchange gives available false. Result is capped at 10,000,000 contracts. Not covered: isolated margin, inverse contracts, fees, funding, slippage between legs, and the exchange own liquidation engine; liq_buffer is our model of cross margin. Use when user asks "how many contracts per leg can I put on a ladder of 8 legs at 3x wit…

ParameterTypeDescription
ctSize *numberBase units per contract, e.g. 0.01 for OKX BTC-USDT-SWAP
currentPrice *numberPrice of leg 1 (the existing position is valued from here)
equity *numberAccount equity in the quote currency at currentPrice
legs *integerD: total legs, the existing position counts as leg 1
side *stringLadder side
bufferPctnumberliq_buffer: required distance of the liquidation price beyond the last leg, a fraction
exchangestringliq_buffer: exchange whose tiers are read
existingCtintegerContracts already held on the ladder side, default 0
leveragenumberLeverage cap on gross exposure / equity. Required for mode leverage; not used by mode liq_buffer
liqFeeRatenumberliq_buffer, OKX only: forced-liquidation fee rate, a fraction
modestringWhich definition of "the leg fits"; default leverage
oppositeCtintegerContracts held on the other side, default 0
oppositeMaintenanceMarginnumberliq_buffer: maintenance margin of the other side, default 0
stepnumberOne fraction for every gap between legs, 0.01 for 1%
stepsarrayOne fraction per gap, legs - 1 values (instead of step)
symbolstringliq_buffer: symbol as the exchange writes it

workflow.run_forex_margin_required_live Forex Margin Required (Live)

Notional and margin required for a forex position, converted to a given account currency via a live FX rate (same TrueFX/frankfurter.app source as workflow.run_forex_pip_value_live). Edge cases: same input rules as workflow.run_forex_margin_required; when no rate is found for the account currency, available is false and no figure is returned. The rate is a TrueFX tick or a daily ECB reference rate, not a dealer quote. Not covered: broker margin tiers and margin offsets on hedged positions. Use when user asks "how much margin do I need in my account currency?" and the account currency differs f…

ParameterTypeDescription
accountCurrency *string3-letter account currency code, e.g. "GBP"
leverage *numberLeverage multiplier, e.g. 50 for 50:1
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
price *numberEntry or current price
units *numberPosition size in base-currency units

workflow.run_forex_position_size_live Forex Position Size (Live)

Position size (units and standard lots) from a risk amount and stop distance, in a given account currency, via a live FX rate to convert pip value into that currency (same TrueFX/frankfurter.app source as the other forex _live tools). Never has a meaningful account-currency-agnostic form: sizing a position from a risk budget genuinely requires knowing what 1 pip is worth in the currency that budget is denominated in. Precious-metal pairs (XAU, XAG, XPT, XPD) are refused with an error, because their pip and lot size differ by broker. Edge cases: entryPrice, stopPrice and riskAmount above zero;…

ParameterTypeDescription
accountCurrency *string3-letter account currency code, e.g. "USD"
entryPrice *numberEntry price in the pair's own quote terms, e.g. 1.0850 for EUR/USD
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
riskAmount *numberAmount to risk, in accountCurrency
stopPrice *numberStop-loss price, same quote convention as the entry price

workflow.run_forex_currency_converter_live Forex Currency Converter (Live)

Converts an amount between currencies using a live FX rate: TrueFX for its 10 quoted majors (genuinely live tick data), frankfurter.app daily ECB reference rate as the fallback for every other currency pair (30 total). Edge cases: amount may be zero or negative (converted as given); from and to are ISO 4217 codes; the same currency on both sides returns the amount with source identity; no rate found gives available false and no figure. The rate is a TrueFX tick or a daily ECB reference rate, not what a bank or broker would give you. Not covered: markups, fees and rounding rules of a provider.…

ParameterTypeDescription
amount *numberAmount in the source currency
from *string3-letter source currency code, e.g. "USD"
to *string3-letter target currency code, e.g. "EUR"

workflow.run_forex_swap_cost_live Forex Swap Cost (Live)

Total swap/rollover cost (or credit) for holding a forex position overnight, converted to a given account currency via a live FX rate (same TrueFX/frankfurter.app source as the other forex _live tools). swapPerLotPerNight is still always a manual input: swap rates are broker-set, with no free live feed available for them. Precious-metal pairs (XAU, XAG, XPT, XPD) are refused with an error, because their pip and lot size differ by broker. Edge cases: same input rules as workflow.run_forex_swap_cost (nights a whole number, swap any sign); when no rate is found for the account currency, available…

ParameterTypeDescription
accountCurrency *string3-letter account currency code, e.g. "GBP"
nights *integerNumber of nights the position is held
pair *stringCurrency pair in BASE/QUOTE format, e.g. "EUR/USD"
swapPerLotPerNight *numberSwap rate per standard lot per night, in the pair's quote currency. Negative = cost, positive = credit.
units *numberPosition size in base-currency units

workflow.run_forex_correlation_live Forex Correlation (Live)

Correlation coefficient and minimum-variance hedge ratio between two forex pairs, fetched live: historical daily rates for both pairs over the given lookback window (frankfurter.app's daily ECB reference time series, business days only), aligned by matching date, computed on daily % returns. hedgeRatio follows Hull's standard futures-hedging formula: "how many units of pair2 per unit of pair1 minimizes the combined position's variance." Edge cases: days is a whole number from 14 to 365 (default 30) of calendar days, so fewer trading days are used; both pairs must be BASE/QUOTE of two different…

ParameterTypeDescription
pair1 *stringFirst currency pair in BASE/QUOTE format, e.g. "EUR/USD"
pair2 *stringSecond currency pair in BASE/QUOTE format, e.g. "GBP/USD"
daysintegerCalendar days to look back, 14-365. Default 30. Business-day-only data means fewer actual points than this number.

workflow.run_price_consensus Price Consensus

Cross-exchange agreement check for one perpetual futures price: fetches the same asset USDT/USDC-margined perpetual from a reference set of 7 liquid exchanges (Binance, Bybit, OKX, Gate, KuCoin, Hyperliquid, MEXC; the chosen one is compared against the rest) and reports the median of the others, the spread across all, and how far the chosen exchange sits from that median. Says the exchanges disagree instead of guessing: status is agree (under 0.25%), warn (0.25% to 1%), diverge (1% or more) or insufficient (fewer than 3 other exchanges returned a comparable contract; inverse, dated and unliste…

ParameterTypeDescription
exchange *stringExchange code of the price being checked, e.g. bybit, binance, okx, gate, kucoin, hyperliquid, mexc
symbol *stringThat exchange's own perpetual symbol, e.g. BTCUSDT (bybit/binance), ETH-USDT-SWAP (okx), BTCUSDC (hyperliquid)

workflow.run_prediction_market_edge Prediction Market Edge

Compares your own probability estimate for an event against a prediction market's price (manual entry, or a live Kalshi ticker, Limitless slug, or Myriad slug) and sizes a bet using fractional Kelly criterion bet sizing (default: quarter-Kelly, a standard conservative haircut on full Kelly, stated explicitly as a convention). Returns a zero Kelly stake whenever your probability doesn't exceed the market's price: no edge. Edge cases: yourProbabilityPct 0.01 to 99.99; give exactly one of marketProbabilityPct (0.01 to 99.99) or a kalshiTicker, limitlessSlug or myriadSlug; bankrollUsd above zero;…

ParameterTypeDescription
bankrollUsd *numberBankroll available for this bet, in USD
yourProbabilityPct *numberYour own probability estimate, 0.01-99.99
kalshiTickerstringA Kalshi market ticker to fetch the market probability from live instead of supplying it manually.
kellyFractionCapnumberFraction of full Kelly to actually stake, 0.01-1. Default 0.25 (quarter-Kelly).
limitlessSlugstringA Limitless Exchange market slug to fetch the market probability from live instead of supplying it manually.
marketProbabilityPctnumberThe market's probability (price), 0.01-99.99. Use this OR one of the live sources below, not both.
myriadSlugstringA Myriad Markets market slug to fetch the market probability from live instead of supplying it manually. Not every market has a Yes/No outcome.

system.verify Verify Calculations

Run the full regression suite: 60 canonical test vectors (linear and inverse/coin-margined) across all 12 calculators, and return a pass/fail report with counts and timestamp. Useful as a health check before relying on results in production workflows.

system.pubkey Signing Public Key

Return the ECDSA P-256 public key (PEM + JWK) and canonical signing format used to sign tool responses, so results can be verified offline without calling back to TradingCalc. Every tools/call result includes a signed second content block when signing is configured; also available at GET /api/mcp/pubkey.

system.batch Batch

Run up to 10 calls of other tools in one request and get all results back together, in order. Each entry is {name, arguments} exactly as for a single call; each result carries its own signature block, so every one verifies on its own. The batch call itself is free: every entry counts as one call against the daily limit. A failed entry does not stop the others (it comes back with an error), except that once the daily limit is reached or the batch has run for about 20 seconds, the entries after that point are not run and not counted: the reply says so for each, so send them again. A batch cannot…

ParameterTypeDescription
calls *array1 to 10 calls