import time
import random
import logging
import logging.config
import threading
from contextlib import contextmanager
from pathlib import Path
--- CONFIGURATION CONSTANTS (Easily updated for real trading) ---
JUMP_BASE_COST = 2.50 # Fixed fee for every trade/jump attempt.
CATASTROPHIC_FIXED_LOSS = 5.0 # The fixed component of loss on failure.
MIN_TSI_FOR_SUCCESS = 0.6 # The minimum 'efficiency' (TSI) required to avoid catastrophe.
LOG_DIR = Path("logs")
--- CUSTOM EXCEPTIONS (The Traps) ---
class TimeDriveError(Exception):
"""Base exception for all Time Drive system errors."""
pass
class CreditBalanceError(TimeDriveError):
"""Raised when the energy credit balance is insufficient for an action."""
pass
class CoreMeltdownError(TimeDriveError):
"""Raised when the Temporal Stability Index (TSI) is too low for a safe jump."""
pass
--- LOGGING CONFIGURATION (Professional Audit Trail) ---
LOGGING_CONFIG_DATA = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '[CHRONO-SCAN %(asctime)s] <ENGINE-STATUS: %(levelname)s> (SYSTEM: %(name)s) :: %(message)s'
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'standard',
'level': 'INFO',
},
'stellar_file': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': LOG_DIR / 'stellar_log.log', # Standard system logs
'formatter': 'standard',
'level': 'INFO',
},
'anomaly_file': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': LOG_DIR / 'temporal_anomalies.log', # Critical errors only
'formatter': 'standard',
'level': 'CRITICAL',
}
},
'loggers': {
# Core logger for all operational messages
'core_reactor': {'handlers': ['console', 'stellar_file'], 'level': 'INFO', 'propagate': False},
# Logger for navigation/transactional messages
'nav_computer': {'handlers': ['console', 'stellar_file'], 'level': 'INFO', 'propagate': False},
# Dedicated logger for catastrophic failures
'emergency_systems': {'handlers': ['console', 'anomaly_file'], 'level': 'CRITICAL', 'propagate': False},
}
}
--- CONTEXT MANAGER FOR PROFESSIONAL LOGGING SETUP ---
@contextmanager
def _configure_logging():
"""Sets up and tears down the logging system safely."""
LOG_DIR.mkdir(exist_ok=True)
logging.config.dictConfig(LOGGING_CONFIG_DATA)
try:
yield
finally:
logging.shutdown()
class TimeDriveSimulator:
"""
A robust simulator demonstrating financial risk modeling, state management,
and auditable logging, built in under 3 hours.
Now includes guarded outlets for real-world trading integration.
"""
def __init__(self, initial_credits: float = 5.00, initial_tsi: float = 0.95):
self.energy_credit_balance = initial_credits
self.temporal_stability_index = initial_tsi # Efficiency/Risk Model Input
self._state = 'STANDBY'
# Specialized loggers for audit trail
self.core_logger = logging.getLogger('core_reactor')
self.nav_logger = logging.getLogger('nav_computer')
self.emergency_logger = logging.getLogger('emergency_systems')
# Store the asset for the trade
self.current_asset_symbol = "TSLA" # Placeholder asset
def _set_state(self, new_state: str):
"""Internal function to manage the system state."""
self._state = new_state
self.core_logger.info(f"System State Transitioned to: {new_state}")
# --- HEAVILY GUARDED OUTLET 1: TRADE SIGNAL AUTHORIZATION ---
def _authorize_trade_signal(self, asset_symbol: str) -> float:
"""
Outlet 1: Connects to an external trading signal/model to set the TSI.
Developer MUST replace the 'return random.uniform' line with
an actual API call (e.g., self.quant_api.get_model_tsi(asset_symbol)).
"""
if self._state != 'STANDBY':
raise TimeDriveError("Trade signal blocked. Drive is not in STANDBY.")
# --- HEAVILY GUARDED OUTLET POINT ---
# FOR SIMULATION: Generate a random TSI (0.1 to 0.95)
self.temporal_stability_index = random.uniform(0.1, 0.95)
return self.temporal_stability_index
# ------------------------------------
# --- HEAVILY GUARDED OUTLET 2: MARKET EXECUTION ---
def _execute_market_action(self, asset_symbol: str, trade_amount: float):
"""
Outlet 2: Replaces temporal transit simulation with a market order.
Developer MUST replace the 'time.sleep' with a brokerage API order submission.
"""
# TRAP: Financial Check just before execution
if self.energy_credit_balance < trade_amount + JUMP_BASE_COST:
raise CreditBalanceError("Market action cost exceeds available charge.")
self.nav_logger.info(f"Market Action Initiated: Trade {asset_symbol} with value {trade_amount:.2f}")
self._set_state('IN_JUMP') # State is now 'IN_TRADE'
# --- HEAVILY GUARDED OUTLET POINT ---
# FOR SIMULATION: Simulate trade execution time (network latency)
time.sleep(1)
# ------------------------------------
self.core_logger.info("Market Action confirmed by external system.")
# --- HEAVILY GUARDED OUTLET 3: RESOLUTION AND PROFIT/LOSS (PnL) ---
def _calculate_resolution_pnl(self, tsi: float) -> float:
"""
Outlet 3: Calculates external trade PnL based on trade resolution.
Developer MUST replace the random logic with an API call to fetch actual PnL
(e.g., self.broker_api.get_trade_profit(self.last_trade_id)).
"""
# --- HEAVILY GUARDED OUTLET POINT ---
# FOR SIMULATION: Introduce simulated profit/loss for testing
if tsi >= MIN_TSI_FOR_SUCCESS:
# Success yields a random profit
return random.uniform(1.00, 5.00)
else:
# Failure yields a small loss (separate from catastrophic loss)
return random.uniform(-1.00, -0.10)
# ------------------------------------
def _calculate_jump_penalty(self, tsi: float) -> float:
"""Calculates the inefficiency penalty based on TSI."""
# Penalty is scaled by the temporal instability (1.0 - TSI)
return (1.0 - tsi) * 1.5
def activate_time_drive(self):
"""Core logic for a single trading/jump sequence."""
try:
self.nav_logger.info("--- ATTEMPTING CHRONITON DRIVE ACTIVATION ---")
# Step 1: Execute Outlet 1 to determine the trade signal strength (TSI)
tsi_reading = self._authorize_trade_signal(self.current_asset_symbol)
self.nav_logger.info(f"TSI (Efficiency) is {tsi_reading:.2f}.")
# TRAP: Core Meltdown Check (Checks if the signal/model is too risky)
if tsi_reading < MIN_TSI_FOR_SUCCESS:
raise CoreMeltdownError(f"TSI {tsi_reading:.2f} too low. Catastrophic risk detected.")
# Step 2: Deduct Base Cost and Check for Financial Trap
if self.energy_credit_balance < JUMP_BASE_COST:
raise CreditBalanceError("Insufficient credit for Base Jump Cost.")
self.energy_credit_balance -= JUMP_BASE_COST
self.core_logger.info(f"Deducted Base Jump Cost: {JUMP_BASE_COST:.2f}. Balance: {self.energy_credit_balance:.2f}")
# Step 3: Execute Outlet 2 (The Trade/Jump)
# We assume a fixed trade size for this simulation
self._execute_market_action(self.current_asset_symbol, trade_amount=50.00)
# Step 4: Execution successful. Calculate PnL and final costs.
# Execute Outlet 3 to get the trade result (Profit or Loss)
pnl_result = self._calculate_resolution_pnl(tsi_reading)
self.energy_credit_balance += pnl_result # Apply PnL (profit/loss)
# Deduct the mandatory Inefficiency Penalty (the hidden cost)
efficiency_penalty = self._calculate_jump_penalty(tsi_reading)
self.energy_credit_balance -= efficiency_penalty
self._set_state('STANDBY')
self.core_logger.info("Temporal transition complete. Reactor nominal.")
self.core_logger.info(f"SUCCESS. Net PnL Applied: {pnl_result:.2f}. Inefficiency Penalty: {efficiency_penalty:.2f} credits.")
# --- TRAP HANDLERS ---
except CreditBalanceError as e:
self._set_state('ERROR')
print(f"*** SYSTEM HALTED: {e} ***")
self.emergency_logger.critical(f"FATAL FINANCIAL ERROR: {e}")
except CoreMeltdownError as e:
self._set_state('ERROR')
# Catastrophic failure logic: apply the large penalty
loss = CATASTROPHIC_FIXED_LOSS + self._calculate_jump_penalty(tsi_reading)
self.energy_credit_balance -= loss
print("*** TEMPORAL DISTURBANCE: Core Reactor Integrity Failure! Catastrophic Energy Loss. ***")
self.emergency_logger.critical(f"CATASTROPHIC LOSS: Severe damage! Loss of {loss:.2f} credits. Final Balance: {self.energy_credit_balance:.2f}")
except Exception as e:
self._set_state('ERROR')
print(f"*** UNKNOWN SYSTEM FAILURE: {e} ***")
self.emergency_logger.critical(f"UNKNOWN SYSTEM FAILURE: {e}", exc_info=True)
finally:
self.shutdown()
def shutdown(self):
"""Final cleanup and display."""
self.nav_logger.info("Chroniton drive sequence ending. Powering down systems.")
print("Chroniton drive offline.")
if name == "main":
# Simulate SFX (Sound Effects) in a separate thread to show concurrency
def sfx_thread_func():
# print("Playing SFX...") # Remove this for quiet operation
time.sleep(0.5)
with _configure_logging():
print(f"--- Time Drive Simulator Initialized (Trading Mode) ---")
# --- RUN 1: SUCCESSFUL TRADE ---
simulator_success = TimeDriveSimulator(initial_credits=100.00, initial_tsi=0.85)
print(f"\n**RUN 1 (SUCCESS) Initial Balance: {simulator_success.energy_credit_balance:.2f} credits**")
# Start the SFX thread before running the core logic (concurrency demo)
sfx_thread = threading.Thread(target=sfx_thread_func)
sfx_thread.start()
simulator_success.activate_time_drive()
sfx_thread.join()
print(f"--- Final Balance (Success): {simulator_success.energy_credit_balance:.2f} credits ---\n")
# --- RUN 2: CATASTROPHIC LOSS ---
simulator_failure = TimeDriveSimulator(initial_credits=100.00, initial_tsi=0.30)
print(f"\n**RUN 2 (FAILURE) Initial Balance: {simulator_failure.energy_credit_balance:.2f} credits**")
sfx_thread_2 = threading.Thread(target=sfx_thread_func)
sfx_thread_2.start()
simulator_failure.activate_time_drive()
sfx_thread_2.join()
print(f"--- Final Balance (Failure): {simulator_failure.energy_credit_balance:.2f} credits ---")