Continue to task 2
- User
Continue to task 2
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Continue to task 2
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This system continuously monitors all open positions in real-time, automatically managing risk through position sizing, correlation analysis, and dynamic exit signals. It operates as a background service that processes market data streams and position updates with sub-second latency.
A. Core Components Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Market Data │ │ Position │ │ Risk Engine │
│ Stream │───▶│ Manager │◄──▶│ & Alerts │
│ (WebSocket) │ │ (State Store) │ │ (Rules) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
│ ▼ ▼
│ ┌─────────────────┐ ┌─────────────────┐
│ │ Exit Signal │ │ Order │
└─────────────▶│ Generator │───▶│ Execution │
│ (Algorithms) │ │ Engine │
└─────────────────┘ └─────────────────┘
B. Data Flow (Real-Time Processing Pipeline)
Market Data Ingestion (< 10ms latency)
Position State Management (< 5ms update cycle)
Risk Assessment Engine (< 20ms analysis cycle)
Exit Signal Processing (< 15ms decision cycle)
A. Auto-Position Sizing Algorithm
The system dynamically calculates position sizes based on account risk parameters and current portfolio state.
def calculate_position_size(ticker, entry_price, stop_loss, account_equity,
current_positions, max_risk_per_trade=0.02):
"""
Calculate optimal position size using Kelly Criterion modified for day trading
"""
# Base risk per trade (2% of account)
dollar_risk = account_equity * max_risk_per_trade
# Calculate price risk per share
price_risk_per_share = abs(entry_price - stop_loss)
# Base position size
base_shares = int(dollar_risk / price_risk_per_share)
# Portfolio correlation adjustment
correlation_factor = get_portfolio_correlation_factor(ticker, current_positions)
# Volatility adjustment (reduce size for high-volatility stocks)
atr_factor = get_atr_adjustment_factor(ticker)
# Time decay factor (smaller positions later in day)
time_factor = get_time_decay_factor()
# Final adjusted position size
adjusted_shares = int(base_shares * correlation_factor * atr_factor * time_factor)
return min(adjusted_shares, get_max_shares_by_liquidity(ticker))
B. Correlation Tracking Engine
Maintains real-time correlation matrix to prevent over-concentration in similar moves.
class CorrelationTracker:
def __init__(self, lookback_minutes=30):
self.price_history = {} # ticker -> deque of price changes
self.correlation_matrix = {}
self.lookback_minutes = lookback_minutes
def update_correlation_matrix(self):
"""Update correlation matrix every minute"""
if len(self.price_history) < 2:
return
# Calculate rolling correlation for all position pairs
tickers = list(self.price_history.keys())
for i, ticker1 in enumerate(tickers):
for ticker2 in tickers[i+1:]:
correlation = self.calculate_rolling_correlation(ticker1, ticker2)
self.correlation_matrix[(ticker1, ticker2)] = correlation
def get_portfolio_risk_factor(self, new_ticker, current_positions):
"""Calculate risk amplification from correlation"""
if not current_positions:
return 1.0
max_correlation = 0
for pos_ticker in current_positions:
pair = tuple(sorted([new_ticker, pos_ticker]))
correlation = self.correlation_matrix.get(pair, 0)
max_correlation = max(max_correlation, abs(correlation))
# Reduce position size if high correlation exists
return max(0.5, 1.0 - (max_correlation * 0.5))
C. Portfolio Beta and Exposure Monitoring
class PortfolioMonitor:
def __init__(self):
self.spy_price_history = deque(maxlen=100)
self.position_betas = {}
def calculate_portfolio_beta(self, positions):
"""Calculate real-time portfolio beta vs SPY"""
total_beta_exposure = 0
total_position_value = 0
for ticker, position in positions.items():
beta = self.get_stock_beta(ticker)
position_value = abs(position['shares'] * position['current_price'])
total_beta_exposure += beta * position_value * (1 if position['side'] == 'long' else -1)
total_position_value += position_value
return total_beta_exposure / total_position_value if total_position_value > 0 else 0
def check_beta_alerts(self, portfolio_beta, max_beta=1.5):
"""Alert if portfolio beta exceeds thresholds"""
if abs(portfolio_beta) > max_beta:
return {
'alert_type': 'HIGH_BETA_EXPOSURE',
'current_beta': portfolio_beta,
'recommended_action': 'REDUCE_CORRELATED_POSITIONS'
}
return None
D. Margin Monitoring System
def monitor_margin_usage(account_data, positions, real_time_prices):
"""Real-time margin calculation with alerts"""
# Calculate current buying power
total_position_value = sum(
abs(pos['shares'] * real_time_prices[ticker])
for ticker, pos in positions.items()
)
buying_power_used = total_position_value / 4 # Day trading buying power (4:1)
buying_power_available = account_data['day_trading_buying_power']
usage_percentage = buying_power_used / buying_power_available
alerts = []
if usage_percentage > 0.9:
alerts.append({
'type': 'CRITICAL_MARGIN',
'message': f'Buying power usage at {usage_percentage:.1%}',
'action': 'HALT_NEW_POSITIONS'
})
elif usage_percentage > 0.75:
alerts.append({
'type': 'HIGH_MARGIN',
'message': f'Buying power usage at {usage_percentage:.1%}',
'action': 'REDUCE_POSITION_SIZES'
})
return {
'usage_percentage': usage_percentage,
'alerts': alerts,
'available_buying_power': buying_power_available - buying_power_used
}
A. ATR-Based Trailing Stop System
class ATRTrailingStop:
def __init__(self, atr_multiplier=2.0, min_profit_threshold=0.5):
self.atr_multiplier = atr_multiplier
self.min_profit_threshold = min_profit_threshold # % gain before activating trail
def calculate_stop_level(self, position, current_price, current_atr):
"""Dynamic trailing stop based on ATR"""
entry_price = position['entry_price']
side = position['side'] # 'long' or 'short'
# Calculate current profit percentage
if side == 'long':
profit_pct = (current_price - entry_price) / entry_price
base_stop = current_price - (current_atr * self.atr_multiplier)
else: # short
profit_pct = (entry_price - current_price) / entry_price
base_stop = current_price + (current_atr * self.atr_multiplier)
# Only activate trailing if minimum profit reached
if profit_pct < self.min_profit_threshold / 100:
return position.get('initial_stop', base_stop)
# Update trailing stop (never move against position)
current_stop = position.get('trailing_stop', base_stop)
if side == 'long':
new_stop = max(current_stop, base_stop)
else:
new_stop = min(current_stop, base_stop)
return new_stop
B. Volume Exhaustion Detection
class VolumeExhaustionDetector:
def __init__(self, lookback_bars=10):
self.lookback_bars = lookback_bars
def detect_exhaustion(self, ticker, price_data, volume_data):
"""Detect volume exhaustion patterns"""
if len(volume_data) < self.lookback_bars:
return False
recent_volumes = list(volume_data)[-self.lookback_bars:]
recent_prices = list(price_data)[-self.lookback_bars:]
# Calculate volume trend
volume_trend = self.calculate_trend(recent_volumes)
price_trend = self.calculate_trend(recent_prices)
# Volume exhaustion: declining volume with continued price movement
volume_declining = volume_trend < -0.3 # 30% decline in volume trend
price_extending = abs(price_trend) > 0.1 # Price still trending
# Confirmation: Current volume < 70% of recent average
current_volume = recent_volumes[-1]
avg_volume = sum(recent_volumes[:-1]) / (len(recent_volumes) - 1)
volume_drop = current_volume < (avg_volume * 0.7)
return volume_declining and price_extending and volume_drop
C. VWAP Deviation Exit Strategy
class VWAPDeviationExit:
def __init__(self, deviation_threshold=2.0):
self.deviation_threshold = deviation_threshold # Standard deviations
def calculate_vwap_signal(self, position, current_price, vwap_data):
"""Exit when price deviates significantly from VWAP"""
current_vwap = vwap_data['vwap']
vwap_std = vwap_data['standard_deviation']
# Calculate current deviation in standard deviations
price_deviation = abs(current_price - current_vwap) / vwap_std
side = position['side']
entry_price = position['entry_price']
# For profitable positions, exit on extreme deviation (likely reversal)
if side == 'long' and current_price > entry_price:
if current_price > (current_vwap + (self.deviation_threshold * vwap_std)):
return {
'signal': 'EXIT',
'reason': 'VWAP_EXTREME_DEVIATION_LONG',
'deviation': price_deviation
}
elif side == 'short' and current_price < entry_price:
if current_price < (current_vwap - (self.deviation_threshold * vwap_std)):
return {
'signal': 'EXIT',
'reason': 'VWAP_EXTREME_DEVIATION_SHORT',
'deviation': price_deviation
}
return None
D. Time-Based Exit System
class TimeBasedExits:
def __init__(self):
self.exit_rules = {
'power_hour_exit': {'time': '15:00', 'condition': 'if_profitable'},
'final_exit': {'time': '15:45', 'condition': 'force_exit'},
'lunch_hour_exit': {'time': '12:00', 'condition': 'if_small_position'}
}
def check_time_exits(self, position, current_time):
"""Check if any time-based exit conditions are met"""
entry_time = position['entry_time']
current_price = position['current_price']
entry_price = position['entry_price']
side = position['side']
# Calculate position profit
if side == 'long':
profit_pct = (current_price - entry_price) / entry_price
else:
profit_pct = (entry_price - current_price) / entry_price
# Check each time rule
for rule_name, rule in self.exit_rules.items():
rule_time = datetime.strptime(rule['time'], '%H:%M').time()
if current_time.time() >= rule_time:
if rule['condition'] == 'force_exit':
return {'signal': 'EXIT', 'reason': f'TIME_EXIT_{rule_name.upper()}'}
elif rule['condition'] == 'if_profitable' and profit_pct > 0:
return {'signal': 'EXIT', 'reason': f'TIME_EXIT_PROFITABLE_{rule_name.upper()}'}
elif rule['condition'] == 'if_small_position' and abs(profit_pct) < 0.005:
return {'signal': 'EXIT', 'reason': f'TIME_EXIT_SMALL_{rule_name.upper()}'}
return None
A. Event-Driven Architecture
B. Memory Management
C. Latency Optimization
The system maintains a 99.9% uptime target with failover capabilities and can handle up to 50 concurrent positions across different asset classes.