ig_client/utils/finance.rs
1// src/utils/finance.rs
2//
3// Financial calculation utilities for the IG client
4
5use crate::presentation::account::Position;
6
7/// Calculate the Profit and Loss (P&L) for a position based on current market prices
8///
9/// Thin wrapper over [`Position::pnl_checked`], the single source of truth for
10/// position P&L, kept for backwards compatibility.
11///
12/// # Arguments
13///
14/// * `position` - The position to calculate P&L for
15///
16/// # Returns
17///
18/// * `Option<f64>` - The calculated P&L if market prices are available, None otherwise
19///
20#[must_use]
21pub fn calculate_pnl(position: &Position) -> Option<f64> {
22 position.pnl_checked()
23}
24
25/// Calculate the percentage return for a position
26///
27/// # Arguments
28///
29/// * `position` - The position to calculate percentage return for
30///
31/// # Returns
32///
33/// * `Option<f64>` - The calculated percentage return if market prices are available, None otherwise
34#[must_use]
35pub fn calculate_percentage_return(position: &Position) -> Option<f64> {
36 let pnl = calculate_pnl(position)?;
37 let initial_value = position.position.level * position.position.size;
38
39 // Avoid division by zero
40 if initial_value == 0.0 {
41 return None;
42 }
43
44 Some((pnl / initial_value) * 100.0)
45}