Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro

fix/nan-prices-cli-demo-mode
py 60 lines 1.95 KB
Raw
1 """Position sizing and risk management."""
2
3 from __future__ import annotations
4
5
6 class PositionSizer:
7 """Fixed-fractional position sizing.
8
9 Risks a fixed fraction of capital per trade, with optional
10 stop-loss and take-profit levels.
11 """
12
13 def __init__(
14 self,
15 risk_per_trade: float = 0.02,
16 stop_loss_pct: float = 0.05,
17 take_profit_pct: float = 0.10,
18 ) -> None:
19 if not 0 < risk_per_trade <= 1:
20 raise ValueError("risk_per_trade must be between 0 and 1")
21 self.risk_per_trade = risk_per_trade
22 self.stop_loss_pct = stop_loss_pct
23 self.take_profit_pct = take_profit_pct
24
25 def calculate_size(self, capital: float, entry_price: float, stop_price: float) -> int:
26 """Calculate position size based on risk.
27
28 Args:
29 capital: Current capital.
30 entry_price: Entry price per share.
31 stop_price: Stop-loss price per share.
32
33 Returns:
34 Number of shares to trade (integer, floored).
35 """
36 risk_amount = capital * self.risk_per_trade
37 risk_per_share = abs(entry_price - stop_price)
38 if risk_per_share == 0:
39 return 0
40 return int(risk_amount / risk_per_share)
41
42 def should_exit(self, entry_price: float, current_price: float, position: int) -> bool:
43 """Check if stop-loss or take-profit has been hit.
44
45 Args:
46 entry_price: Original entry price.
47 current_price: Current market price.
48 position: Current position (positive=long, negative=short).
49
50 Returns:
51 True if the position should be closed.
52 """
53 if position == 0:
54 return False
55
56 pnl_pct = (current_price - entry_price) / entry_price
57 if position > 0:
58 return pnl_pct <= -self.stop_loss_pct or pnl_pct >= self.take_profit_pct
59 else:
60 return pnl_pct >= self.stop_loss_pct or pnl_pct <= -self.take_profit_pct