Skip to main content

RiskMonitor

Struct RiskMonitor 

Source
pub struct RiskMonitor { /* private fields */ }
Expand description

Evaluates multiple RiskRules on each equity update and returns all breaches.

Implementations§

Source§

impl RiskMonitor

Source

pub fn new(initial_equity: Decimal) -> Self

Creates a new RiskMonitor with no rules and the given initial equity.

Source

pub fn add_rule(self, rule: impl RiskRule + 'static) -> Self

Adds a rule to the monitor (builder pattern).

Source

pub fn update(&mut self, equity: Decimal) -> Vec<RiskBreach>

Updates equity and returns all triggered breaches.

Source

pub fn drawdown_pct(&self) -> Decimal

Returns the current drawdown percentage without triggering an update.

Source

pub fn current_equity(&self) -> Decimal

Returns the current equity value without triggering an update.

Source

pub fn peak_equity(&self) -> Decimal

Returns the peak equity seen so far.

Source

pub fn reset(&mut self, initial_equity: Decimal)

Resets the internal drawdown tracker to initial_equity.

Source

pub fn rule_count(&self) -> usize

Returns the number of rules registered with this monitor.

Source

pub fn reset_peak(&mut self)

Resets the drawdown peak to the current equity.

Delegates to DrawdownTracker::reset_peak. Useful at session boundaries when you want drawdown measured from the current level, not the all-time high.

Source

pub fn is_in_drawdown(&self) -> bool

Returns true if equity is currently below the recorded peak (i.e. in drawdown).

Source

pub fn worst_drawdown_pct(&self) -> Decimal

Returns the worst (highest) drawdown percentage seen since construction or last reset.

Source

pub fn equity_history_len(&self) -> usize

Returns the total number of equity updates processed since construction or last reset.

Source

pub fn drawdown_duration(&self) -> usize

Returns the number of consecutive equity updates since the last peak (drawdown duration).

Source

pub fn breach_count(&self) -> usize

Returns the total number of rule breaches triggered since construction or last reset.

Source

pub fn max_drawdown_pct(&self) -> Decimal

Returns the maximum drawdown percentage seen since construction or last reset.

Alias for worst_drawdown_pct.

Source

pub fn drawdown_tracker(&self) -> &DrawdownTracker

Returns a shared reference to the internal DrawdownTracker.

Useful when callers need direct access to tracker state (e.g., worst drawdown) without going through the monitor’s forwarding accessors.

Source

pub fn check(&self, equity: Decimal) -> Vec<RiskBreach>

Checks all rules against equity without updating the peak or current equity.

Useful for prospective checks (e.g., “would this trade breach a rule?”) where you do not want to alter tracked state.

Source

pub fn has_breaches(&self, equity: Decimal) -> bool

Returns true if any rule would breach at the given equity level.

Equivalent to !self.check(equity).is_empty() but short-circuits on the first breach and avoids allocating a Vec.

Source

pub fn win_rate(&self) -> Option<Decimal>

Returns the fraction of equity updates where equity was not in drawdown.

win_rate = (updates_not_in_drawdown) / total_updates Returns None when no updates have been made.

Source

pub fn calmar_ratio(&self, annualised_return_pct: f64) -> Option<f64>

Calmar ratio: annualised_return / max_drawdown_pct.

Returns None when max drawdown is zero (no drawdown observed) or when max_drawdown_pct is zero.

annualised_return should be expressed as a percentage (e.g., 15.0 for 15%).

Source

pub fn consecutive_gain_updates(&self) -> usize

Returns the current consecutive run of equity updates where equity increased.

Resets to zero on any non-increasing update. Useful for detecting sustained rallies.

Source

pub fn equity_at_risk(&self, pct: Decimal) -> Decimal

Returns the absolute loss implied by pct percent drawdown from current peak equity.

Useful for position-sizing calculations: “how much can I lose at X% drawdown?” Returns Decimal::ZERO when peak equity is zero.

Source

pub fn trailing_stop_level(&self, pct: Decimal) -> Decimal

Returns the equity level at which a trailing stop would trigger.

Computes peak_equity * (1 - pct / 100). If the current equity falls below this level the position should be reduced or closed.

Example: trailing_stop_level(10) on a peak of 100_000 returns 90_000.

Source

pub fn var_pct(returns: &[Decimal], confidence_pct: Decimal) -> Option<Decimal>

Computes historical Value-at-Risk at confidence_pct percent confidence.

Sorts returns ascending and returns the value at the (1 - confidence_pct/100) quantile — the loss exceeded only (100 - confidence_pct)% of the time. Example: var_pct(&returns, dec!(95)) gives the 5th-percentile return.

Returns None when returns is empty.

Source

pub fn tail_risk_pct( returns: &[Decimal], confidence_pct: Decimal, ) -> Option<Decimal>

Expected Shortfall (CVaR) — the mean return of the worst (100 - confidence_pct)% of returns.

This is the average loss beyond the VaR threshold, giving a better picture of tail risk. Returns None when returns is empty or confidence_pct is 100.

§Example

tail_risk_pct(&returns, dec!(95)) → mean of the worst 5% of returns.

Source

pub fn profit_factor(returns: &[Decimal]) -> Option<Decimal>

Computes the profit factor: gross_wins / gross_losses from a series of trade returns.

returns should contain per-trade P&L values (positive = win, negative = loss).

Returns None if there are no losing trades (to avoid division by zero) or if returns is empty.

Source

pub fn omega_ratio(returns: &[Decimal], threshold: Decimal) -> Option<Decimal>

Computes the Omega Ratio for a given threshold return.

Ω = Σmax(r - threshold, 0) / Σmax(threshold - r, 0)

Returns None if all returns are above the threshold (no downside) or if returns is empty.

Source

pub fn kelly_fraction( win_rate: Decimal, avg_win: Decimal, avg_loss: Decimal, ) -> Option<Decimal>

Computes the Kelly Criterion fraction: optimal bet size as a fraction of bankroll.

f* = win_rate - (1 - win_rate) / (avg_win / avg_loss)

Returns None if avg_loss is zero (undefined). Negative values indicate the strategy has negative expectancy.

Source

pub fn annualized_return( returns: &[Decimal], periods_per_year: usize, ) -> Option<f64>

Annualised return from a series of per-period returns.

annualized = ((1 + mean_return)^periods_per_year) - 1

Returns None if returns is empty or periods_per_year == 0.

Source

pub fn tail_ratio(returns: &[Decimal]) -> Option<f64>

Tail ratio: 95th-percentile gain divided by the absolute 5th-percentile loss.

Measures the ratio of upside tail to downside tail. Values > 1 indicate the positive tail is larger; < 1 indicate the negative tail dominates.

Returns None if returns has fewer than 20 observations (minimum for meaningful quantiles).

Source

pub fn skewness(returns: &[Decimal]) -> Option<f64>

Skewness of returns (third standardised moment).

Positive skew means the distribution has a longer right tail; negative skew means a longer left tail.

Returns None if fewer than 3 observations are provided or standard deviation is zero.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.