-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_loader.py
More file actions
1501 lines (1127 loc) · 45.1 KB
/
Copy pathconfig_loader.py
File metadata and controls
1501 lines (1127 loc) · 45.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Configuration Loader for Trading Platform
This module provides Pydantic-based configuration loading, validation, and
typed object exposure for a comprehensive trading platform supporting multiple
asset classes, data sources, brokers, models, risk management, and execution.
Integrates with:
- OpenBB Platform
- Third-party data providers (Polygon, crypto exchanges)
- Broker APIs (Alpaca, Interactive Brokers)
- Machine learning models
- Risk management systems
- Execution engines
Author: Trading Platform Team
Version: 1.0.0
"""
import json
import os
import sys
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from pydantic import (
AnyUrl,
BaseModel,
ConfigDict,
Field,
SecretStr,
field_validator,
model_validator,
)
# Import python-dotenv for .env file support
try:
from dotenv import load_dotenv
DOTENV_AVAILABLE = True
except ImportError:
DOTENV_AVAILABLE = False
load_dotenv = None
class EnvironmentType(str, Enum):
"""Environment configuration types"""
DEVELOPMENT = "development"
TESTING = "testing"
STAGING = "staging"
PRODUCTION = "production"
class BackoffStrategy(str, Enum):
"""Rate limiting backoff strategies"""
EXPONENTIAL = "exponential"
LINEAR = "linear"
FIXED = "fixed"
class LogLevel(str, Enum):
"""Logging levels"""
DEBUG = "DEBUG"
INFO = "INFO"
WARNING = "WARNING"
ERROR = "ERROR"
CRITICAL = "CRITICAL"
class LogFormat(str, Enum):
"""Log output formats"""
JSON = "json"
TEXT = "text"
class OrderType(str, Enum):
"""Order types for trading"""
MARKET = "MARKET"
LIMIT = "LIMIT"
STOP = "STOP"
STOP_LIMIT = "STOP_LIMIT"
TRAIL = "TRAIL"
OCO = "OCO"
class TimeInForce(str, Enum):
"""Time in force options"""
DAY = "DAY"
GTC = "GTC"
IOC = "IOC"
FOK = "FOK"
class CryptoType(str, Enum):
"""Cryptocurrency trading types"""
SPOT = "spot"
MARGIN = "margin"
FUTURE = "future"
# Core Configuration Models
class CredentialsConfig(BaseModel):
"""API Credentials configuration with environment variable support
Supports multiple ways to provide credentials with precedence order:
1. Environment variables (highest precedence)
2. Direct values from CLI/config override
3. JSON configuration defaults (lowest precedence)
"""
api_key: Optional[str] = Field(None, min_length=8, max_length=128)
secret: Optional[SecretStr] = Field(None, min_length=16, max_length=256)
passphrase: Optional[SecretStr] = Field(None, min_length=8, max_length=64)
environment_variable: Optional[str] = None
# New fields for enhanced secrets handling
env_prefix: Optional[str] = Field(
None, description="Environment variable prefix for auto-discovery"
)
vault_path: Optional[str] = Field(None, description="HashiCorp Vault secret path")
@model_validator(mode="before")
@classmethod
def validate_credentials(cls, values):
"""Ensure either direct credentials or environment variable is provided
Handles precedence order:
1. Environment variables (resolved from ${VAR} patterns)
2. Direct credential values
3. Fallback validation
"""
if isinstance(values, dict):
api_key = values.get("api_key")
secret = values.get("secret")
env_var = values.get("environment_variable")
env_prefix = values.get("env_prefix")
# If environment_variable contains the ${} pattern, treat it as unresolved
# If it's a regular string, treat it as resolved credential
if env_var and env_var.startswith("${") and env_var.endswith("}"):
# Validate environment variable pattern
import re
if not re.match(r"^\$\{[A-Z_][A-Z0-9_]*\}$", env_var):
raise ValueError(f"Invalid environment variable pattern: {env_var}")
elif env_var:
# Environment variable has been resolved - treat as api_key
values["api_key"] = env_var
values["environment_variable"] = None
elif env_prefix:
# Try to auto-discover credentials using prefix
prefix_upper = env_prefix.upper()
if not api_key:
api_key = os.getenv(f"{prefix_upper}_API_KEY") or os.getenv(
f"{prefix_upper}_KEY"
)
if api_key:
values["api_key"] = api_key
if not secret:
secret_val = os.getenv(f"{prefix_upper}_SECRET") or os.getenv(
f"{prefix_upper}_API_SECRET"
)
if secret_val:
values["secret"] = secret_val
passphrase_val = values.get("passphrase")
if not passphrase_val:
passphrase_val = os.getenv(f"{prefix_upper}_PASSPHRASE")
if passphrase_val:
values["passphrase"] = passphrase_val
elif not (api_key and secret):
raise ValueError(
"Either environment_variable, env_prefix, or both api_key and secret must be provided"
)
return values
class RateLimitConfig(BaseModel):
"""Rate limiting configuration"""
requests_per_second: float = Field(default=10.0, gt=0.1, le=1000)
requests_per_hour: int = Field(default=1000, ge=1, le=100000)
burst_limit: int = Field(default=5, ge=1, le=100)
backoff_strategy: BackoffStrategy = BackoffStrategy.EXPONENTIAL
class ConnectionConfig(BaseModel):
"""Connection configuration parameters"""
timeout: int = Field(default=30, ge=1, le=300)
retry_attempts: int = Field(default=3, ge=0, le=10)
retry_delay: float = Field(default=1.0, ge=0.1, le=60.0)
heartbeat_interval: int = Field(default=30, ge=5, le=300)
reconnect_delay: int = Field(default=5, ge=1, le=60)
class RiskLimitsConfig(BaseModel):
"""Risk management limits configuration"""
max_position_size: float = Field(default=0.05, gt=0.001, le=1.0)
max_daily_loss: float = Field(default=0.02, gt=0.001, le=1.0)
stop_loss: Optional[float] = Field(default=0.015, gt=0.001, le=0.5)
take_profit: Optional[float] = Field(default=0.03, gt=0.001, le=1.0)
max_drawdown: Optional[float] = Field(default=0.1, gt=0.001, le=1.0)
class LogConfig(BaseModel):
"""Logging configuration"""
level: LogLevel = LogLevel.INFO
format: LogFormat = LogFormat.JSON
file_path: Optional[str] = Field(None, pattern=r"^[\w\-\.\/\\:]+\.(log|txt)$")
max_file_size: str = Field(default="100MB", pattern=r"^\d+[KMGT]?B$")
backup_count: int = Field(default=10, ge=1, le=100)
# Data Provider Models
class OpenBBConfig(BaseModel):
"""OpenBB Platform integration configuration"""
credentials: CredentialsConfig
websocket_url: AnyUrl = "wss://websocket.openbb.co"
rate_limits: Optional[RateLimitConfig] = None
connection: Optional[ConnectionConfig] = None
symbols: Optional[Dict[str, List[str]]] = None
class PolygonConfig(BaseModel):
"""Polygon.io market data configuration"""
credentials: CredentialsConfig
websocket_url: AnyUrl = "wss://socket.polygon.io"
rate_limits: Optional[RateLimitConfig] = None
class CryptoExchangeConfig(BaseModel):
"""Base cryptocurrency exchange configuration"""
credentials: CredentialsConfig
sandbox: bool = True
symbols: Optional[List[str]] = None
class BinanceConfig(CryptoExchangeConfig):
"""Binance exchange configuration"""
default_type: CryptoType = CryptoType.SPOT
class CoinbaseConfig(CryptoExchangeConfig):
"""Coinbase exchange configuration"""
pass
class BybitConfig(CryptoExchangeConfig):
"""Bybit exchange configuration"""
pass
class CryptoExchangesConfig(BaseModel):
"""Cryptocurrency exchanges configuration"""
binance: Optional[BinanceConfig] = None
coinbase: Optional[CoinbaseConfig] = None
bybit: Optional[BybitConfig] = None
class AlternativeDataConfig(BaseModel):
"""Alternative data sources configuration"""
defi_protocols: Optional[Dict[str, Any]] = None
social_sentiment: Optional[Dict[str, Any]] = None
class DataProvidersConfig(BaseModel):
"""Data providers configuration"""
openbb: Optional[OpenBBConfig] = None
polygon: Optional[PolygonConfig] = None
crypto_exchanges: Optional[CryptoExchangesConfig] = None
alternative_data: Optional[AlternativeDataConfig] = None
class DatabaseConfig(BaseModel):
"""Database configuration"""
type: str = "postgresql"
connection_string: str = Field(..., min_length=10)
pool_size: int = Field(default=20, ge=1, le=100)
timeout: int = Field(default=60, ge=1, le=300)
class CacheConfig(BaseModel):
"""Cache configuration"""
type: str = "redis"
host: str = "localhost"
port: int = Field(default=6379, ge=1, le=65535)
ttl: int = Field(default=1800, ge=1)
class StorageConfig(BaseModel):
"""Storage configuration"""
database: Optional[DatabaseConfig] = None
cache: Optional[CacheConfig] = None
class DataConfig(BaseModel):
"""Complete data configuration"""
providers: Optional[DataProvidersConfig] = None
storage: Optional[StorageConfig] = None
# Broker Models
class AlpacaConfig(BaseModel):
"""Alpaca broker configuration"""
credentials: CredentialsConfig
base_url: AnyUrl = "https://paper-api.alpaca.markets"
supported_assets: List[str] = ["stocks", "etfs", "options", "crypto"]
class InteractiveBrokersConfig(BaseModel):
"""Interactive Brokers configuration"""
account_id: str = Field(..., min_length=5, max_length=20)
gateway_host: str = "localhost"
gateway_port: int = Field(default=7497, ge=1, le=65535)
client_id: int = Field(default=1, ge=1, le=32)
supported_assets: List[str] = ["stocks", "options", "futures", "forex", "bonds"]
class BrokerConnectionsConfig(BaseModel):
"""Broker connections configuration"""
alpaca: Optional[AlpacaConfig] = None
interactive_brokers: Optional[InteractiveBrokersConfig] = None
class OAuthConfig(BaseModel):
"""OAuth configuration"""
provider: str = "auth0"
client_id: str = Field(..., min_length=10)
redirect_uri: AnyUrl
scopes: List[str] = ["read:portfolio", "write:trades", "read:market_data"]
class AuthenticationConfig(BaseModel):
"""Authentication configuration"""
oauth: Optional[OAuthConfig] = None
class BrokersConfig(BaseModel):
"""Complete brokers configuration"""
connections: Optional[BrokerConnectionsConfig] = None
authentication: Optional[AuthenticationConfig] = None
# Models Configuration
class XGBoostModelConfig(BaseModel):
"""XGBoost model configuration"""
weight: float = Field(default=0.35, gt=0.0, le=1.0)
params: Dict[str, Any] = {
"objective": "reg:squarederror",
"max_depth": 8,
"learning_rate": 0.08,
"n_estimators": 1500,
}
class EnsembleConfig(BaseModel):
"""Ensemble model configuration"""
prediction_horizon: str = "1h"
models: Dict[str, Any] = {}
feature_engineering: Dict[str, Any] = {}
class PPOConfig(BaseModel):
"""PPO (Proximal Policy Optimization) configuration"""
training_iterations: int = Field(default=2000, ge=100)
checkpoint_frequency: int = Field(default=200, ge=10)
config: Dict[str, Any] = {"lr": 0.0005, "gamma": 0.995, "clip_param": 0.2}
class ReinforcementLearningConfig(BaseModel):
"""Reinforcement learning configuration"""
ppo: Optional[PPOConfig] = None
class SentimentModelConfig(BaseModel):
"""Individual sentiment model configuration"""
model_name: str = Field(..., min_length=5)
weight: float = Field(default=1.0, gt=0.0, le=1.0)
class SentimentAnalysisConfig(BaseModel):
"""Sentiment analysis configuration"""
models: Dict[str, SentimentModelConfig] = {}
processing: Dict[str, Any] = {"max_length": 512, "batch_size": 64}
class MachineLearningConfig(BaseModel):
"""Machine learning models configuration"""
ensemble: Optional[EnsembleConfig] = None
reinforcement_learning: Optional[ReinforcementLearningConfig] = None
sentiment_analysis: Optional[SentimentAnalysisConfig] = None
class DerivativesPricingConfig(BaseModel):
"""Derivatives pricing models configuration"""
black_scholes: Dict[str, float] = {"risk_free_rate": 0.05, "dividend_yield": 0.015}
monte_carlo: Dict[str, int] = {"simulations": 50000, "time_steps": 252}
class PricingConfig(BaseModel):
"""Pricing models configuration"""
derivatives: Optional[DerivativesPricingConfig] = None
class ModelsConfig(BaseModel):
"""Complete models configuration"""
machine_learning: Optional[MachineLearningConfig] = None
pricing: Optional[PricingConfig] = None
# Risk Management Models
class KillSwitchConfig(BaseModel):
"""Emergency kill switch configuration"""
enabled: bool = True
threshold: float = Field(default=0.08, gt=0.0, le=1.0)
check_interval: int = Field(default=5, ge=1, le=60)
class RiskMonitoringConfig(BaseModel):
"""Risk monitoring configuration"""
real_time: bool = True
update_interval: int = Field(default=15, ge=1, le=300)
kill_switch: Optional[KillSwitchConfig] = None
class KYCAMLConfig(BaseModel):
"""KYC/AML compliance configuration"""
enabled: bool = True
provider: str = "jumio"
transaction_monitoring: bool = True
class ComplianceReportingConfig(BaseModel):
"""Compliance reporting configuration"""
trade_reporting: bool = True
position_reporting: bool = True
frequency: str = "daily"
class ComplianceConfig(BaseModel):
"""Compliance configuration"""
kyc_aml: Optional[KYCAMLConfig] = None
reporting: Optional[ComplianceReportingConfig] = None
class RiskLimitsGroupConfig(BaseModel):
"""Risk limits group configuration"""
portfolio_level: Optional[RiskLimitsConfig] = None
asset_class_level: Optional[Dict[str, RiskLimitsConfig]] = None
position_level: Optional[Dict[str, Any]] = None
class RiskConfig(BaseModel):
"""Complete risk management configuration"""
limits: Optional[RiskLimitsGroupConfig] = None
monitoring: Optional[RiskMonitoringConfig] = None
compliance: Optional[ComplianceConfig] = None
# Execution Models
class RetryConfig(BaseModel):
"""Retry configuration for orders"""
max_attempts: int = Field(default=3, ge=1, le=10)
retry_delay: float = Field(default=1.5, ge=0.1, le=60.0)
class OrderManagementConfig(BaseModel):
"""Order management configuration"""
order_types: List[OrderType] = [OrderType.MARKET, OrderType.LIMIT, OrderType.STOP]
time_in_force: TimeInForce = TimeInForce.DAY
retry_config: Optional[RetryConfig] = None
class SlippageControlConfig(BaseModel):
"""Slippage control configuration"""
max_slippage_warning: float = Field(default=0.015, gt=0.0, le=1.0)
tolerance: float = Field(default=0.008, gt=0.0, le=1.0)
class TWAPConfig(BaseModel):
"""TWAP algorithm configuration"""
enabled: bool = True
time_window: int = Field(default=120, ge=1, le=1440)
class VWAPConfig(BaseModel):
"""VWAP algorithm configuration"""
enabled: bool = True
participation_rate: float = Field(default=0.15, gt=0.0, le=1.0)
class AlgorithmsConfig(BaseModel):
"""Trading algorithms configuration"""
twap: Optional[TWAPConfig] = None
vwap: Optional[VWAPConfig] = None
class ExecutionConfig(BaseModel):
"""Complete execution configuration"""
order_management: Optional[OrderManagementConfig] = None
slippage_control: Optional[SlippageControlConfig] = None
algorithms: Optional[AlgorithmsConfig] = None
# Backtesting Models
class BenchmarkConfig(BaseModel):
"""Benchmark configuration for backtesting"""
symbol: str = "SPY"
enabled: bool = True
class BacktestEngineConfig(BaseModel):
"""Backtesting engine configuration"""
framework: str = "custom"
performance_metrics: List[str] = [
"sharpe",
"sortino",
"max_drawdown",
"calmar",
"win_rate",
"profit_factor",
]
benchmark: Optional[BenchmarkConfig] = None
class HistoricalRangeConfig(BaseModel):
"""Historical data range configuration"""
training_days: int = Field(default=90, ge=1)
min_data_points: int = Field(default=2000, ge=100)
class DataHandlingConfig(BaseModel):
"""Backtesting data handling configuration"""
historical_range: Optional[HistoricalRangeConfig] = None
survivorship_bias: bool = True
class CrossValidationConfig(BaseModel):
"""Cross-validation configuration"""
enabled: bool = True
folds: int = Field(default=7, ge=2, le=20)
class WalkForwardConfig(BaseModel):
"""Walk-forward validation configuration"""
enabled: bool = True
window_size: int = Field(default=120, ge=1)
step_size: int = Field(default=14, ge=1)
class ValidationConfig(BaseModel):
"""Validation configuration"""
cross_validation: Optional[CrossValidationConfig] = None
walk_forward: Optional[WalkForwardConfig] = None
class BacktestConfig(BaseModel):
"""Complete backtesting configuration"""
engine: Optional[BacktestEngineConfig] = None
data_handling: Optional[DataHandlingConfig] = None
validation: Optional[ValidationConfig] = None
symbols: Optional[List[str]] = None
# System Configuration Models
class ComputeConfig(BaseModel):
"""Compute resources configuration"""
cpu_threads: int = Field(default=16, ge=1, le=128)
worker_processes: int = Field(default=8, ge=1, le=64)
memory_limit: str = Field(default="16GB", pattern=r"^\d+[KMGT]?B$")
class CORSConfig(BaseModel):
"""CORS configuration"""
allowed_origins: List[str] = [
"http://localhost:3000",
"http://localhost:8080",
"https://trading.example.com",
]
allowed_methods: List[str] = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
class NetworkingConfig(BaseModel):
"""Networking configuration"""
cors: Optional[CORSConfig] = None
class InfrastructureConfig(BaseModel):
"""Infrastructure configuration"""
compute: Optional[ComputeConfig] = None
networking: Optional[NetworkingConfig] = None
class ComponentLogConfig(BaseModel):
"""Individual component logging configuration"""
level: LogLevel = LogLevel.INFO
format: LogFormat = LogFormat.JSON
file_path: str = Field(..., pattern=r"^[\w\-\.\/\\:]+\.(log|txt)$")
max_file_size: str = Field(default="100MB", pattern=r"^\d+[KMGT]?B$")
backup_count: int = Field(default=10, ge=1, le=100)
class LoggingConfig(BaseModel):
"""System logging configuration"""
application: Optional[ComponentLogConfig] = None
components: Optional[Dict[str, ComponentLogConfig]] = None
class PrometheusConfig(BaseModel):
"""Prometheus monitoring configuration"""
enabled: bool = True
port: int = Field(default=9090, ge=1, le=65535)
scrape_interval: str = "10s"
class GrafanaConfig(BaseModel):
"""Grafana dashboard configuration"""
enabled: bool = True
port: int = Field(default=3000, ge=1, le=65535)
admin_credentials: Optional[CredentialsConfig] = None
class MonitoringConfig(BaseModel):
"""System monitoring configuration"""
prometheus: Optional[PrometheusConfig] = None
grafana: Optional[GrafanaConfig] = None
class VaultConfig(BaseModel):
"""HashiCorp Vault configuration"""
enabled: bool = True
url: AnyUrl = "https://vault.trading-platform.internal:8200"
auth_method: str = "kubernetes"
class EncryptionConfig(BaseModel):
"""Encryption configuration"""
at_rest: bool = True
in_transit: bool = True
algorithm: str = "AES-256"
class SecurityConfig(BaseModel):
"""Security configuration"""
vault: Optional[VaultConfig] = None
encryption: Optional[EncryptionConfig] = None
class SlackConfig(BaseModel):
"""Slack notifications configuration"""
enabled: bool = True
credentials: CredentialsConfig
channels: Dict[str, str] = {
"critical": "#trading-critical",
"executions": "#trading-executions",
"risk": "#trading-risk-alerts",
}
class TelegramConfig(BaseModel):
"""Telegram notifications configuration"""
enabled: bool = True
credentials: CredentialsConfig
chat_id: str = Field(..., min_length=5)
class NotificationsConfig(BaseModel):
"""Notifications configuration"""
slack: Optional[SlackConfig] = None
telegram: Optional[TelegramConfig] = None
class FeatureFlagsConfig(BaseModel):
"""Feature flags configuration"""
enable_paper_trading: bool = True
enable_backtesting_mode: bool = True
enable_dry_run: bool = True
enable_position_sizing: bool = True
enable_slippage_control: bool = True
class SystemConfig(BaseModel):
"""Complete system configuration"""
infrastructure: Optional[InfrastructureConfig] = None
logging: Optional[LoggingConfig] = None
monitoring: Optional[MonitoringConfig] = None
security: Optional[SecurityConfig] = None
notifications: Optional[NotificationsConfig] = None
environment: EnvironmentType = EnvironmentType.DEVELOPMENT
feature_flags: Optional[FeatureFlagsConfig] = None
# Main Configuration Model
class ConfigMetadata(BaseModel):
"""Configuration metadata"""
version: str = Field(default="1.0.0", pattern=r"^\d+\.\d+\.\d+$")
name: Optional[str] = Field(None, min_length=1, max_length=100)
environment: EnvironmentType = EnvironmentType.DEVELOPMENT
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
class TradingPlatformConfig(BaseModel):
"""
Main configuration model for the trading platform
This model represents the complete configuration structure for a
multi-asset trading platform with comprehensive validation rules.
"""
model_config = ConfigDict(
extra="forbid",
validate_assignment=True,
str_strip_whitespace=True,
use_enum_values=True,
)
schema_: Optional[str] = Field(None, alias="$schema")
metadata: Optional[ConfigMetadata] = None
data: Optional[DataConfig] = None
brokers: Optional[BrokersConfig] = None
models: Optional[ModelsConfig] = None
risk: Optional[RiskConfig] = None
execution: Optional[ExecutionConfig] = None
backtest: Optional[BacktestConfig] = None
system: Optional[SystemConfig] = None
@field_validator("system")
@classmethod
def validate_production_requirements(cls, v, info):
"""Ensure production environments have proper security and monitoring"""
if hasattr(info, "data") and info.data:
metadata = info.data.get("metadata")
if (
metadata
and hasattr(metadata, "environment")
and metadata.environment == EnvironmentType.PRODUCTION
):
if not v or not v.security or not v.monitoring:
raise ValueError(
"Production environment requires security and monitoring configuration"
)
return v
# Configuration Loader Class
class ConfigurationLoader:
"""
Configuration loader with validation and environment-specific handling
Provides methods to load, validate, and expose configuration settings
as strongly-typed Pydantic objects with integration support for OpenBB
and other financial data platforms.
Supports configuration precedence order:
1. Environment variables (highest precedence)
2. CLI flag overrides (medium precedence)
3. JSON configuration defaults (lowest precedence)
"""
def __init__(
self,
config_path: Optional[Union[str, Path]] = None,
env_file: Optional[Union[str, Path]] = None,
):
"""
Initialize configuration loader
Args:
config_path: Path to configuration file (JSON/YAML)
env_file: Path to .env file for environment variable loading
"""
self.config_path = Path(config_path) if config_path else None
self.env_file = Path(env_file) if env_file else None
self._config: Optional[TradingPlatformConfig] = None
self._env_overrides: Dict[str, Any] = {}
self._cli_overrides: Dict[str, Any] = {}
# Load .env file if available
self._load_env_file()
def load_config(
self,
config_path: Optional[Union[str, Path]] = None,
validate: bool = True,
cli_overrides: Optional[Dict[str, Any]] = None,
) -> TradingPlatformConfig:
"""
Load configuration from file with environment and CLI overrides
Applies configuration in precedence order:
1. Environment variables (highest precedence)
2. CLI flag overrides (medium precedence)
3. JSON configuration defaults (lowest precedence)
Args:
config_path: Path to configuration file
validate: Whether to validate the configuration
cli_overrides: Dictionary of CLI flag overrides
Returns:
Validated TradingPlatformConfig object
Raises:
FileNotFoundError: If config file doesn't exist
ValueError: If configuration is invalid
json.JSONDecodeError: If JSON is malformed
"""
if config_path:
self.config_path = Path(config_path)
# Store CLI overrides
if cli_overrides:
self._cli_overrides = cli_overrides
if not self.config_path or not self.config_path.exists():
raise FileNotFoundError(f"Configuration file not found: {self.config_path}")
# Load configuration data (step 3 - lowest precedence)
config_data = self._load_config_file()
# Apply CLI overrides (step 2 - medium precedence)
config_data = self._apply_cli_overrides(config_data)
# Resolve environment variables (step 1 - highest precedence)
config_data = self._resolve_environment_variables(config_data)
# Apply direct environment variable overrides
config_data = self._apply_environment_overrides(config_data)
# Create and validate configuration
try:
self._config = TradingPlatformConfig(**config_data)
if validate:
self._validate_integrations()
self._log_precedence_info()
return self._config
except Exception as e:
raise ValueError(f"Configuration validation failed: {str(e)}")
def _load_config_file(self) -> Dict[str, Any]:
"""Load configuration from JSON file"""
try:
with open(self.config_path, "r", encoding="utf-8") as file:
return json.load(file)
except json.JSONDecodeError as e:
raise json.JSONDecodeError(
f"Invalid JSON in config file: {str(e)}", e.doc, e.pos
)
def _load_env_file(self):
"""
Load environment variables from .env file if available
Searches for .env files in the following order:
1. Explicitly provided env_file path
2. .env file in the same directory as config file
3. .env file in current working directory
4. .env file in parent directories (up to 3 levels)
"""
if not DOTENV_AVAILABLE:
return
env_files_to_try = []
# Add explicitly provided env file
if self.env_file and self.env_file.exists():
env_files_to_try.append(self.env_file)
# Add .env file in config directory
if self.config_path:
config_dir_env = self.config_path.parent / ".env"
if config_dir_env.exists():
env_files_to_try.append(config_dir_env)
# Add .env file in current directory and parent directories
current_dir = Path.cwd()
for i in range(4): # Check current + 3 parent levels
env_file = current_dir / ".env"
if env_file.exists() and env_file not in env_files_to_try:
env_files_to_try.append(env_file)
current_dir = current_dir.parent
if current_dir == current_dir.parent: # Reached filesystem root
break
# Load the first found .env file
for env_file in env_files_to_try:
try:
load_dotenv(
env_file, override=False
) # Don't override existing env vars
print(f"✅ Loaded environment variables from: {env_file}")
break
except Exception as e:
print(f"⚠️ Failed to load .env file {env_file}: {e}")
continue
def _apply_cli_overrides(self, data: Dict[str, Any]) -> Dict[str, Any]: