Skip to main content

trader_bot/strategy/
holding.rs

1//! Holding strategy implementation.
2//!
3//! The holding strategy maintains a position in an asset up to a configured
4//! maximum percentage or absolute value of the portfolio. This is a passive
5//! strategy that buys when under-allocated and can optionally sell when
6//! over-allocated.
7
8use super::traits::{MarketState, Strategy, StrategyAction, StrategyDecision};
9use crate::domain::Order;
10use async_trait::async_trait;
11use rust_decimal::Decimal;
12use serde::{Deserialize, Serialize};
13use tracing::{debug, trace};
14
15/// Configuration for a holding strategy.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct HoldingConfig {
18    /// The symbol to hold.
19    pub symbol: String,
20
21    /// Target allocation as percentage of portfolio (0-100).
22    /// If set, this takes precedence over absolute_value.
23    pub target_percent: Option<Decimal>,
24
25    /// Target allocation as absolute value in base currency.
26    pub absolute_value: Option<Decimal>,
27
28    /// Maximum allowed deviation from target before rebalancing (percentage points).
29    pub tolerance_percent: Decimal,
30
31    /// Whether to sell when over-allocated.
32    pub allow_sell: bool,
33
34    /// Minimum trade size in lots.
35    pub min_trade_lots: u32,
36
37    /// Whether the strategy is enabled.
38    pub enabled: bool,
39}
40
41impl Default for HoldingConfig {
42    fn default() -> Self {
43        Self {
44            symbol: String::new(),
45            target_percent: None,
46            absolute_value: None,
47            tolerance_percent: Decimal::new(5, 1), // 0.5%
48            allow_sell: false,
49            min_trade_lots: 1,
50            enabled: true,
51        }
52    }
53}
54
55impl HoldingConfig {
56    /// Creates a new holding config for a symbol with a target percentage.
57    #[must_use]
58    pub fn with_percent(symbol: impl Into<String>, target_percent: Decimal) -> Self {
59        Self {
60            symbol: symbol.into(),
61            target_percent: Some(target_percent),
62            ..Default::default()
63        }
64    }
65
66    /// Creates a new holding config for a symbol with an absolute value target.
67    #[must_use]
68    pub fn with_absolute(symbol: impl Into<String>, absolute_value: Decimal) -> Self {
69        Self {
70            symbol: symbol.into(),
71            absolute_value: Some(absolute_value),
72            ..Default::default()
73        }
74    }
75
76    /// Sets the tolerance percentage.
77    #[must_use]
78    pub fn with_tolerance(mut self, tolerance: Decimal) -> Self {
79        self.tolerance_percent = tolerance;
80        self
81    }
82
83    /// Enables or disables selling when over-allocated.
84    #[must_use]
85    pub fn with_allow_sell(mut self, allow: bool) -> Self {
86        self.allow_sell = allow;
87        self
88    }
89
90    /// Sets the minimum trade size in lots.
91    #[must_use]
92    pub fn with_min_trade_lots(mut self, lots: u32) -> Self {
93        self.min_trade_lots = lots;
94        self
95    }
96
97    /// Enables or disables the strategy.
98    #[must_use]
99    pub fn with_enabled(mut self, enabled: bool) -> Self {
100        self.enabled = enabled;
101        self
102    }
103}
104
105/// Holding strategy that maintains a target allocation.
106#[derive(Debug)]
107pub struct HoldingStrategy {
108    config: HoldingConfig,
109}
110
111impl HoldingStrategy {
112    /// Creates a new holding strategy with the given configuration.
113    #[must_use]
114    pub fn new(config: HoldingConfig) -> Self {
115        Self { config }
116    }
117
118    /// Returns the configuration.
119    #[must_use]
120    pub fn config(&self) -> &HoldingConfig {
121        &self.config
122    }
123
124    /// Calculates the target value for this holding.
125    fn calculate_target_value(&self, total_portfolio_value: Decimal) -> Decimal {
126        self.config.target_percent.map_or_else(
127            || self.config.absolute_value.unwrap_or(Decimal::ZERO),
128            |target_percent| total_portfolio_value * target_percent / Decimal::from(100),
129        )
130    }
131
132    /// Determines if we need to buy or sell based on current vs target allocation.
133    fn calculate_action(
134        &self,
135        state: &MarketState,
136        total_portfolio_value: Decimal,
137    ) -> StrategyDecision {
138        if !self.config.enabled {
139            return StrategyDecision::hold_with_reason("Strategy disabled");
140        }
141
142        let target_value = self.calculate_target_value(total_portfolio_value);
143        if target_value.is_zero() {
144            return StrategyDecision::hold_with_reason("No target value configured");
145        }
146
147        // Calculate current value
148        let current_value = state
149            .position
150            .as_ref()
151            .map_or(Decimal::ZERO, |p| p.market_value().amount());
152
153        let diff_value = target_value - current_value;
154        let diff_percent = if total_portfolio_value.is_zero() {
155            Decimal::ZERO
156        } else {
157            (diff_value.abs() / total_portfolio_value) * Decimal::from(100)
158        };
159
160        trace!(
161            "{}: current={}, target={}, diff={} ({}%)",
162            self.config.symbol,
163            current_value,
164            target_value,
165            diff_value,
166            diff_percent
167        );
168
169        // Check if within tolerance
170        if diff_percent <= self.config.tolerance_percent {
171            return StrategyDecision::hold_with_reason("Within tolerance");
172        }
173
174        // Get current price for lot calculation
175        let price = match state.last_price {
176            Some(p) if !p.is_zero() => p,
177            _ => return StrategyDecision::hold_with_reason("No price available"),
178        };
179
180        // Calculate lots needed
181        let lots_needed = (diff_value.abs() / price).floor();
182        let lots_u32 = lots_needed.to_string().parse::<u32>().unwrap_or(0);
183
184        if lots_u32 < self.config.min_trade_lots {
185            return StrategyDecision::hold_with_reason("Trade size below minimum");
186        }
187
188        let mut decision = StrategyDecision::new();
189
190        if diff_value > Decimal::ZERO {
191            // Need to buy
192            if state.available_cash >= diff_value {
193                debug!(
194                    "Holding strategy: buying {} lots of {} at ~{}",
195                    lots_u32, self.config.symbol, price
196                );
197                decision.add_action(StrategyAction::market_buy(&self.config.symbol, lots_u32));
198                decision = decision.with_reason("Under-allocated, buying to target");
199            } else {
200                return StrategyDecision::hold_with_reason("Insufficient cash");
201            }
202        } else if self.config.allow_sell {
203            // Need to sell
204            let position_lots = state.position_lots();
205            let lots_to_sell = lots_u32.min(position_lots);
206            if lots_to_sell > 0 {
207                debug!(
208                    "Holding strategy: selling {} lots of {}",
209                    lots_to_sell, self.config.symbol
210                );
211                decision.add_action(StrategyAction::market_sell(
212                    &self.config.symbol,
213                    lots_to_sell,
214                ));
215                decision = decision.with_reason("Over-allocated, selling to target");
216            } else {
217                return StrategyDecision::hold_with_reason("No position to sell");
218            }
219        } else {
220            return StrategyDecision::hold_with_reason("Over-allocated but sell not allowed");
221        }
222
223        decision
224    }
225}
226
227#[async_trait]
228impl Strategy for HoldingStrategy {
229    fn name(&self) -> &str {
230        "Holding Strategy"
231    }
232
233    fn id(&self) -> &str {
234        &self.config.symbol
235    }
236
237    async fn decide(&self, state: &MarketState) -> StrategyDecision {
238        // For holding strategy, we need the total portfolio value to calculate target
239        // This is typically passed via the state or we estimate from available info
240        let total_value = state.available_cash
241            + state
242                .position
243                .as_ref()
244                .map_or(Decimal::ZERO, |p| p.market_value().amount());
245
246        self.calculate_action(state, total_value)
247    }
248
249    async fn on_order_filled(&mut self, _order: &Order) {
250        // Holding strategy doesn't track individual fills
251    }
252
253    async fn on_order_cancelled(&mut self, _order: &Order) {
254        // Holding strategy doesn't track individual cancellations
255    }
256
257    async fn reset(&mut self) {
258        // Holding strategy is stateless, nothing to reset
259    }
260
261    fn symbols(&self) -> Vec<String> {
262        vec![self.config.symbol.clone()]
263    }
264
265    fn is_enabled(&self) -> bool {
266        self.config.enabled
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use rust_decimal_macros::dec;
274
275    #[test]
276    fn test_holding_config_with_percent() {
277        let config = HoldingConfig::with_percent("AAPL", dec!(20))
278            .with_tolerance(dec!(1))
279            .with_allow_sell(true);
280
281        assert_eq!(config.symbol, "AAPL");
282        assert_eq!(config.target_percent, Some(dec!(20)));
283        assert_eq!(config.tolerance_percent, dec!(1));
284        assert!(config.allow_sell);
285    }
286
287    #[test]
288    fn test_holding_config_with_absolute() {
289        let config = HoldingConfig::with_absolute("GOOGL", dec!(10000));
290
291        assert_eq!(config.symbol, "GOOGL");
292        assert_eq!(config.absolute_value, Some(dec!(10000)));
293        assert!(config.target_percent.is_none());
294    }
295
296    #[test]
297    fn test_calculate_target_value_percent() {
298        let config = HoldingConfig::with_percent("AAPL", dec!(25));
299        let strategy = HoldingStrategy::new(config);
300
301        let target = strategy.calculate_target_value(dec!(100000));
302        assert_eq!(target, dec!(25000));
303    }
304
305    #[test]
306    fn test_calculate_target_value_absolute() {
307        let config = HoldingConfig::with_absolute("AAPL", dec!(15000));
308        let strategy = HoldingStrategy::new(config);
309
310        let target = strategy.calculate_target_value(dec!(100000));
311        assert_eq!(target, dec!(15000));
312    }
313
314    #[tokio::test]
315    async fn test_strategy_symbols() {
316        let config = HoldingConfig::with_percent("MSFT", dec!(10));
317        let strategy = HoldingStrategy::new(config);
318
319        assert_eq!(strategy.symbols(), vec!["MSFT".to_string()]);
320    }
321
322    #[tokio::test]
323    async fn test_strategy_disabled() {
324        let config = HoldingConfig::with_percent("AAPL", dec!(10)).with_enabled(false);
325        let strategy = HoldingStrategy::new(config);
326
327        let state = MarketState::new("AAPL", "USD").with_cash(dec!(10000));
328        let decision = strategy.decide(&state).await;
329
330        assert!(decision.is_hold());
331        assert_eq!(decision.reason(), Some("Strategy disabled"));
332    }
333}