Skip to content

Commit a5bd68f

Browse files
committed
feat: Add LangGraph Hello World example with requirements, README, and tests
1 parent dfe2272 commit a5bd68f

File tree

10 files changed

+782
-0
lines changed

10 files changed

+782
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# Trading System Configuration Example
2+
3+
market_data:
4+
providers:
5+
- name: "PROVIDER_A"
6+
type: "REST_API"
7+
api_key: "${PROVIDER_A_API_KEY}"
8+
base_url: "https://api.provider-a.com/v1"
9+
timeout_ms: 5000
10+
- name: "PROVIDER_B"
11+
type: "WEBSOCKET"
12+
api_key: "${PROVIDER_B_API_KEY}"
13+
ws_endpoint: "wss://stream.provider-b.com"
14+
reconnect_interval_s: 30
15+
16+
trading_platforms:
17+
- name: "EXCHANGE_1"
18+
type: "SPOT"
19+
api_credentials:
20+
key: "${EXCHANGE_1_API_KEY}"
21+
secret: "${EXCHANGE_1_SECRET}"
22+
rate_limits:
23+
requests_per_minute: 60
24+
orders_per_second: 10
25+
- name: "EXCHANGE_2"
26+
type: "FUTURES"
27+
api_credentials:
28+
key: "${EXCHANGE_2_API_KEY}"
29+
secret: "${EXCHANGE_2_SECRET}"
30+
rate_limits:
31+
requests_per_minute: 120
32+
orders_per_second: 20
33+
34+
risk_parameters:
35+
max_drawdown_percent: 5.0
36+
daily_loss_limit_usd: 10000
37+
position_sizing:
38+
max_position_size_percent: 2.0
39+
risk_per_trade_percent: 1.0
40+
volatility_controls:
41+
max_daily_volatility: 0.25
42+
vol_lookback_days: 20
43+
44+
position_limits:
45+
global:
46+
max_notional_usd: 1000000
47+
max_leverage: 3.0
48+
per_asset:
49+
BTC:
50+
max_position_usd: 100000
51+
max_leverage: 2.0
52+
ETH:
53+
max_position_usd: 50000
54+
max_leverage: 2.0
55+
56+
order_execution:
57+
default_order_type: "LIMIT"
58+
time_in_force: "GTC"
59+
execution_algorithms:
60+
twap:
61+
enabled: true
62+
default_duration_minutes: 30
63+
min_participation_rate: 0.1
64+
iceberg:
65+
enabled: true
66+
default_visible_size_percent: 0.2
67+
smart_routing:
68+
enabled: true
69+
min_spread_threshold: 0.001
70+
71+
monitoring:
72+
logging:
73+
level: "INFO"
74+
file_path: "/var/log/trading/system.log"
75+
rotation_size_mb: 100
76+
alerts:
77+
email:
78+
enabled: true
79+
recipients: ["[email protected]"]
80+
slack:
81+
enabled: true
82+
webhook_url: "${SLACK_WEBHOOK_URL}"
83+
channel: "#trading-alerts"
84+
metrics:
85+
prometheus:
86+
enabled: true
87+
port: 9090
88+
statsd:
89+
enabled: false
90+
host: "localhost"
91+
port: 8125
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Market Data Provider Documentation
2+
3+
## Interface
4+
5+
The `AbstractMarketDataProvider` interface defines the standard contract for market data providers:
6+
7+
```python
8+
class AbstractMarketDataProvider:
9+
def get_current_price(self, symbol: str) -> float
10+
def get_historical_data(self, symbol: str, start_date: datetime, end_date: datetime) -> List[Dict]
11+
def subscribe_to_updates(self, symbol: str, callback: Callable[[PriceUpdate], None]) -> None
12+
def unsubscribe(self, symbol: str) -> None
13+
```
14+
15+
## Available Implementations
16+
17+
### SimpleMarketDataProvider
18+
A basic implementation providing simulated market data:
19+
20+
- Maintains in-memory price cache
21+
- Generates synthetic historical data
22+
- Simulates price updates using random walk
23+
- Supports real-time price subscriptions
24+
25+
Configuration:
26+
```python
27+
provider = SimpleMarketDataProvider()
28+
```
29+
30+
### Data Update Frequency
31+
- Real-time price updates: Every 1 second
32+
- Historical data: Daily OHLCV bars
33+
- Cache refresh: On-demand
34+
35+
## Usage Examples
36+
37+
### Getting Current Prices
38+
```python
39+
provider = SimpleMarketDataProvider()
40+
price = provider.get_current_price("AAPL")
41+
```
42+
43+
### Historical Data
44+
```python
45+
history = provider.get_historical_data(
46+
symbol="AAPL",
47+
start_date=datetime(2024, 1, 1),
48+
end_date=datetime(2024, 1, 9)
49+
)
50+
```
51+
52+
### Price Updates Subscription
53+
```python
54+
def price_callback(update: PriceUpdate):
55+
print(f"{update.symbol}: {update.price}")
56+
57+
provider.subscribe_to_updates("AAPL", price_callback)
58+
```
59+
60+
## Caching Behavior
61+
62+
- Current prices cached in memory
63+
- Historical data cached after first request
64+
- Cache invalidation: Manual via provider restart
65+
- No persistent storage
66+
67+
## Error Handling
68+
69+
The provider throws standard exceptions:
70+
- KeyError: Unknown symbol
71+
- ValueError: Invalid date range
72+
- RuntimeError: Provider connection issues
73+
74+
## Best Practices
75+
76+
1. Unsubscribe when done with real-time updates
77+
2. Use date ranges within reasonable bounds
78+
3. Handle provider exceptions gracefully
79+
4. Monitor callback performance
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
# Risk Management System Documentation
2+
3+
## System Overview
4+
5+
The risk management system provides comprehensive trading risk controls through the `RiskManager` class and supporting utilities.
6+
7+
### Core Components
8+
9+
1. **RiskManager**: Central risk management class
10+
2. **PositionConfig**: Risk parameter configuration
11+
3. **RiskLevel**: Risk classification (LOW, MEDIUM, HIGH)
12+
4. **Utility Functions**: Position sizing and risk calculations
13+
14+
## Position and Order Validation
15+
16+
### Position Size Validation
17+
```python
18+
def validate_position_size(size: float, price: float) -> bool
19+
```
20+
Validates if position size is within configured limits:
21+
- Checks against max_position_size
22+
- Considers portfolio value
23+
- Returns boolean validation result
24+
25+
### Stop Level Calculations
26+
```python
27+
def calculate_stop_levels(entry_price: float, risk_level: RiskLevel) -> Tuple[float, float]
28+
```
29+
Determines stop loss and take profit levels based on:
30+
- Entry price
31+
- Risk level multipliers
32+
- Configured risk percentages
33+
- Minimum risk/reward ratio
34+
35+
## Risk Metrics and Calculations
36+
37+
### Position Size Calculation
38+
```python
39+
def calculate_position_size(
40+
account_value: float,
41+
risk_per_trade: float,
42+
entry_price: float,
43+
stop_loss: float
44+
) -> float
45+
```
46+
47+
### Risk/Reward Ratio
48+
```python
49+
def calculate_risk_reward_ratio(
50+
entry_price: float,
51+
stop_loss: float,
52+
take_profit: float
53+
) -> float
54+
```
55+
56+
### Portfolio Metrics
57+
```python
58+
def calculate_portfolio_metrics(
59+
positions: Dict[str, float],
60+
prices: Dict[str, float]
61+
) -> Dict[str, float]
62+
```
63+
Returns:
64+
- Total portfolio value
65+
- Concentration risk
66+
- Largest position percentage
67+
- Number of positions
68+
69+
### Drawdown Monitoring
70+
```python
71+
def update_drawdown(current_value: float) -> bool
72+
```
73+
- Tracks portfolio drawdown
74+
- Validates against maximum limits
75+
- Returns compliance status
76+
77+
## Configuration Options
78+
79+
### Position Configuration
80+
```python
81+
@dataclass
82+
class PositionConfig:
83+
max_position_size: float # Maximum position size as % of portfolio
84+
max_drawdown: float # Maximum allowed drawdown %
85+
risk_per_trade: float # Risk per trade as % of portfolio
86+
min_risk_reward: float # Minimum risk/reward ratio
87+
```
88+
89+
### Risk Levels
90+
```python
91+
class RiskLevel(Enum):
92+
LOW = "low" # Base risk
93+
MEDIUM = "medium" # 1.5x risk multiplier
94+
HIGH = "high" # 2.0x risk multiplier
95+
```
96+
97+
## Best Practices
98+
99+
1. **Position Sizing**
100+
- Always use position calculator
101+
- Consider volatility adjustments
102+
- Respect maximum limits
103+
104+
2. **Stop Levels**
105+
- Set appropriate risk level
106+
- Validate risk/reward ratios
107+
- Use stop level calculator
108+
109+
3. **Portfolio Management**
110+
- Monitor concentration risk
111+
- Track drawdown regularly
112+
- Maintain position diversity
113+
114+
4. **Risk Configuration**
115+
- Document risk parameters
116+
- Review regularly
117+
- Adjust for market conditions
118+
119+
## Implementation Example
120+
121+
```python
122+
# Initialize risk manager
123+
risk_config = PositionConfig(
124+
max_position_size=5.0, # 5% max position
125+
max_drawdown=20.0, # 20% max drawdown
126+
risk_per_trade=1.0, # 1% risk per trade
127+
min_risk_reward=2.0 # 2:1 minimum R/R
128+
)
129+
130+
risk_manager = RiskManager(
131+
portfolio_value=100000.0,
132+
config=risk_config
133+
)
134+
135+
# Calculate position size
136+
position_size = risk_manager.calculate_position_size(
137+
size=1000,
138+
price=100.0,
139+
volatility=15.0
140+
)
141+
142+
# Validate and get stop levels
143+
if risk_manager.validate_position_size(position_size, price=100.0):
144+
stop_loss, take_profit = risk_manager.calculate_stop_levels(
145+
entry_price=100.0,
146+
risk_level=RiskLevel.MEDIUM
147+
)
148+
```
149+
150+
## Error Handling
151+
152+
- Invalid position sizes
153+
- Risk limit breaches
154+
- Drawdown violations
155+
- Configuration errors
156+
157+
## Additional Resources
158+
159+
- Strategy Documentation
160+
- Trading System Integration Guide
161+
- Risk Monitoring Dashboard
162+
- Historical Performance Analysis

0 commit comments

Comments
 (0)