Files
uniswap_auto_clp/todo/CLP_SCALPER_HEDGER_ANALYSIS.md
DiTus 5ca16ec33f 🎯 Initial commit: Uniswap Auto CLP trading system
Core Components:
- uniswap_manager.py: V3 concentrated liquidity position manager
- clp_hedger.py: Hyperliquid perpetuals hedging bot
- requirements.txt: Python dependencies
- .gitignore: Security exclusions for sensitive data
- doc/: Project documentation
- tools/: Utility scripts and Git agent

Features:
- Automated liquidity provision on Uniswap V3 (WETH/USDC)
- Delta-neutral hedging using Hyperliquid perpetuals
- Position lifecycle management (open/close/rebalance)
- Automated backup and version control system

Security:
- Private keys and tokens excluded from version control
- Environment variables properly handled
- Automated security validation for backups

Git Agent:
- Hourly automated backups to separate branches
- Keep last 100 backups (~4 days coverage)
- Detailed change tracking and parameter monitoring
- Push to Gitea server automatically
- Manual main branch control preserved
- No performance tracking for privacy
- No notifications for simplicity

Files Added:
- git_agent.py: Main automation script
- agent_config.json: Configuration with Gitea settings
- git_utils.py: Git operations wrapper
- backup_manager.py: Backup branch management
- change_detector.py: File change analysis
- cleanup_manager.py: 100-backup rotation
- commit_formatter.py: Detailed commit messages
- README_GIT_AGENT.md: Complete usage documentation
2025-12-19 20:30:48 +01:00

12 KiB

CLP Scalper Hedger Architecture and Price Range Management

Overview

The clp_scalper_hedger.py is a sophisticated automated trading system designed for delta-zero hedging - completely eliminating directional exposure while maximizing fee generation. It monitors CLP positions and automatically executes hedges when market conditions trigger position exits from defined price ranges.

Core Architecture

1. Configuration Layer

  • Price Range Zones: Strategic bands (Bottom, Close, Top) with different behaviors
  • Multi-Timeframe Velocity: Calculates price momentum across different timeframes (1s, 5s, 25s)
  • Dynamic Thresholds: Automatically adjusts protection levels based on volatility
  • Capital Safety: Position size limits and dynamic risk management
  • Strategy States: Normal, Overhedge, Emergency, Velocity-based

2. Price Monitoring & Detection

The system constantly monitors current prices and compares them against position parameters:

Range Calculation Logic (Lines 742-830):

# Check Range
is_out_of_range = False
status_str = "IN RANGE"
if current_tick < pos_details['tickLower']:
    is_out_of_range = True
    status_str = "OUT OF RANGE (BELOW)"
elif current_tick >= pos_details['tickUpper']:
    is_out_of_range = True
    status_str = "OUT OF RANGE (ABOVE)"

Key Variables:

  • current_tick: Current pool tick from Uniswap V3
  • pos_details['tickLower'] and pos_details['tickUpper']: Position boundaries
  • is_out_of_range: Boolean flag determining if position needs action

Automatic Close Trigger (Lines 764-770):

if pos_type == 'AUTOMATIC' and CLOSE_POSITION_ENABLED and is_out_of_range:
    logger.warning(f"⚠️ CLOSE TRIGGERED: Position {token_id} OUT OF RANGE | Delta-Zero hedge unwind required")

Configuration Control:

  • CLOSE_POSITION_ENABLED = True: Enable automatic closing
  • CLOSE_IF_OUT_OF_RANGE_ONLY = True: Close only when out of range
  • REBALANCE_ON_CLOSE_BELOW_RANGE = True: Rebalance 50% WETH→USDC on below-range closes

3. Zone-Based Edge Protection

The system divides the price space into three strategic zones:

Zone Configuration (Lines 801-910):

# Bottom Hedge Zone: 0.0-1.5% (Always Active)
ZONE_BOTTOM_HEDGE_LIMIT = 1  # Disabled for testing
ZONE_CLOSE_START = 10.0
ZONE_CLOSE_END = 11.0

# Top Hedge Zone: Disabled by default
ZONE_TOP_HEDGE_START = 10.0  
ZONE_TOP_HEDGE_END = 11.0

Dynamic Price Buffer (Lines 370-440):

def get_dynamic_price_buffer(self):
    if not MOMENTUM_ADJUSTMENT_ENABLED:
        return PRICE_BUFFER_PCT
    
    current_price = self.last_price if self.last_price else 0.0
    momentum_pct = self.get_price_momentum_pct(current_price)
    
    base_buffer = PRICE_BUFFER_PCT
    
    # Adjust buffer based on momentum and position direction
    if self.original_order_side == "BUY":
        if momentum_pct > 0.002:  # Strong upward momentum
            dynamic_buffer = base_buffer * 2.0
        elif momentum_pct < -0.002:  # Moderate upward momentum
            dynamic_buffer = base_buffer * 1.5
        else:  # Neutral or downward momentum
            dynamic_buffer = base_buffer
    elif self.original_order_side == "SELL":
        if momentum_pct < -0.002:  # Strong downward momentum
            dynamic_buffer = base_buffer * 2.0
        else:  # Neutral or upward momentum
            dynamic_buffer = base_buffer
    
    return min(dynamic_buffer, MAX_PRICE_BUFFER_PCT)

4. Multi-Timeframe Velocity Analysis

Velocity Calculation (Lines 1002-1089):

The system tracks price movements across multiple timeframes to detect market momentum and adjust protection thresholds:

def get_price_momentum_pct(self, current_price):
    # Calculate momentum percentage over last 5 intervals
    if not hasattr(self, 'price_momentum_history'):
        return 0.0
    
    recent_prices = self.price_momentum_history[-5:]
    if len(recent_prices) < 2:
        return 0.0
    
    # Current velocity (1-second change)
    velocity_1s = (current_price - recent_prices[-1]) / recent_prices[-1]
    velocity_5s = sum(abs(current_price - recent_prices[i]) / recent_prices[-1] for i in range(5)) / 4
    
    # 5-second average (smoother signal)
    velocity_5s_avg = sum(recent_prices[i:i+1] for i in range(4)) / 4
    
    # Choose velocity based on market conditions
    if abs(velocity_1s) > 0.005:  # Strong momentum
        price_velocity = velocity_1s  # Use immediate change
    elif abs(velocity_5s_avg) > 0.002:  # Moderate momentum  
        price_velocity = velocity_5s_avg  # Use smoothed average
    else:
        price_velocity = 0.0  # Use zero velocity (default)
    
    # Calculate momentum percentage (1% = 1% price change)
    momentum_pct = (current_price - self.last_price) / self.last_price if self.last_price else 0.0

5. Advanced Strategy Logic

Position Zone Awareness (Lines 784-850):

# Active Position Zone Check
in_hedge_zone = (price >= clp_low_range and price <= clp_high_range)

Dynamic Threshold Calculation (Lines 440-500):

# Dynamic multiplier based on position value
dynamic_threshold_multiplier = 1.0  # 3x for standard leverage
dynamic_threshold = min(dynamic_threshold, target_value / DYNAMIC_THRESHOLD_MULTIPLIER)

Enhanced Edge Detection (Lines 508-620):

# Multi-factor edge detection with zone context
distance_from_bottom = ((current_price - position['range_lower']) / range_width) * 100
distance_from_top = ((position['range_upper'] - current_price) / range_width) * 100

edge_proximity_pct = min(distance_from_bottom, distance_from_top) if in_range_width > 0 else 0

6. Real-Time Market Integration

Live Price Feeds (Lines 880-930):

# Initialize price tracking
self.last_price = None
self.last_price_for_velocity = None
self.price_momentum_history = []
self.velocity_history = []

7. Order Management System

Precision Trading (Lines 923-1100):

# High-precision decimal arithmetic
from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP

def safe_decimal_from_float(value):
    if value is None:
        return Decimal('0')
    return Decimal(str(value))

def validate_trade_size(size, sz_decimals, min_order_value=10.0, price=3000.0):
    """Validate trade size meets minimum requirements"""
    if size <= 0:
        return 0.0
    
    rounded_size = round_to_sz_decimals_precise(size, sz_decimals)
    order_value = rounded_size * price
    
    if order_value < min_order_value:
        return 0.0
    
    return max(rounded_size, MIN_ORDER_VALUE_USD)

7. Comprehensive Zone Management

Active Zone Protection (Always Active - 100%):

  • Close Zone (Disabled - 0%): Activates when position approaches lower bound
  • Top Zone (Disabled - 0%): Never activates

Multi-Strategy Support (Configurable):

  • Conservative: Risk-averse with tight ranges
  • Balanced: Moderate risk with standard ranges
  • Aggressive: Risk-tolerant with wide ranges

8. Emergency Protections

Capital Safety Limits:

  • MIN_ORDER_VALUE_USD: $10 minimum trade size
  • MAX_HEDGE_MULTIPLIER: 2.8x leverage limit
  • LARGE_HEDGE_MULTIPLIER: Emergency 2.8x multiplier for large gaps

9. Performance Optimizations

Smart Order Routing:

  • Taker/Passive: Passive vs active order placement
  • Price Impact Analysis: Avoids excessive slippage
  • Fill Probability: Optimizes order placement for high fill rates

10. Price Movement Examples

Price Increase Detection:

  1. Normal Uptrend (+2% over 10s): Zone expansion, normal hedge sizing
  2. Sharp Rally (+8% over 5s): Zone expansion, aggressive hedging
  3. Crash Drop (-15% over 1s): Emergency hedge, zone protection bypass
  4. Gradual Recovery (+1% over 25s): Systematic position reduction

Zone Transition Events:

  1. Entry Zone Crossing: Price moves from inactive → active zone
  2. Active Zone Optimization: Rebalancing within active zone
  3. Exit Zone Crossing: Position closing as price exits active zone

Key Configuration Parameters

# Core Settings (Lines 20-120)
COIN_SYMBOL = "ETH"
CHECK_INTERVAL = 1  # Optimized for high-frequency monitoring
LEVERAGE = 5  # 3x leverage for delta-zero hedging
STATUS_FILE = "hedge_status.json"

# Price Zones (Lines 160-250)
BOTTOM_HEDGE_LIMIT = 0.0    # Bottom zone always active (0-1.5% range)
ZONE_CLOSE_START = 10.0    # Close zone activation point (1.0%)
ZONE_CLOSE_END = 11.0    # Close zone deactivation point (11.0%)
TOP_HEDGE_START = 10.0    # Top zone activation point (10.0%)
TOP_HEDGE_END = 11.0    # Top zone deactivation point (11.0%)

# Strategy Zones (Lines 251-350)
STRATEGY_BOTTOM_ZONE = 0.0   # 0% - 1.5% (conservative)
STRATEGY_CLOSE_ZONE = 0.0     # 1.0% - 0.5% (moderate)
STRATEGY_TOP_ZONE = 0.0      # Disabled (aggressive)
STRATEGY_ACTIVE_ZONE = 1.25    # 1.25% - 2.5% (enhanced active)

# Edge Protection (Lines 370-460)
EDGE_PROXIMITY_PCT = 0.05      # 5% range edge proximity for triggering
VELOCITY_THRESHOLD_PCT = 0.005     # 0.5% velocity threshold for emergency
POSITION_OPEN_EDGE_PROXIMITY_PCT = 0.07   # 7% edge proximity for position monitoring
POSITION_CLOSED_EDGE_PROXIMITY_PCT = 0.025  # 3% edge proximity for closed positions

# Capital Safety (Lines 460-500)
MIN_THRESHOLD_ETH = 0.12      # Minimum $150 ETH position size
MIN_ORDER_VALUE_USD = 10.0    # Minimum $10 USD trade value
DYNAMIC_THRESHOLD_MULTIPLIER = 1.3  # Dynamic threshold adjustment
LARGE_HEDGE_MULTIPLIER = 2.0     # 2x multiplier for large movements

# Velocity Monitoring (Lines 1000-1089)
VELOCITY_WINDOW_SHORT = 5       # 5-second velocity window
VELOCITY_WINDOW_MEDIUM = 25       # 25-second velocity window
VELOCITY_WINDOW_LONG = 100       # 100-second velocity window

# Multi-Timeframe Options (Lines 1090-1120)
VELOCITY_TIMEFRAMES = [1, 5, 25, 100]  # 1s, 5s, 25s, 100s

11. Operation Flow Examples

Normal Range Operations:

# Price: $3200 (IN RANGE - Active Zone 1.25%)
# Action: Normal hedge sizing, maintain position
# Status: "IN RANGE | ACTIVE ZONE"

# Price: $3150 (OUT OF RANGE BELOW - Close Zone)
# Action: Emergency hedge unwind, position closure
# Status: "OUT OF RANGE (BELOW) | CLOSING"

# Price: $3250 (OUT OF RANGE ABOVE - Emergency Close)  
# Action: Immediate liquidation, velocity-based sizing
# Status: "OUT OF RANGE (ABOVE) | EMERGENCY CLOSE"

12. Advanced Configuration Examples

Conservative Strategy:

# Risk management with tight zones
STRATEGY_BOTTOM_ZONE = 0.0   # 0% - 1.5% (very tight range)
STRATEGY_ACTIVE_ZONE = 0.5   # 0.5% - 0.5% (moderate active zone)
STRATEGY_TOP_ZONE = 0.0   # Disabled (too risky)

Balanced Strategy:

# Standard risk management
STRATEGY_BOTTOM_ZONE = 0.0   # 0% - 1.5% (tight range)
STRATEGY_ACTIVE_ZONE = 1.0   # 1.0% - 1.5% (moderate active zone)
STRATEGY_TOP_ZONE = 0.0   # 0.0% - 1.5% (moderate active zone)

Aggressive Strategy:

# High-performance with wider zones
STRATEGY_BOTTOM_ZONE = 0.0   # 0% - 1.5% (tight for safety)
STRATEGY_ACTIVE_ZONE = 1.5   # 1.5% - 1.5% (enhanced active zone)
STRATEGY_TOP_ZONE = 1.5   # 1.5% - 1.5% (enabled top zone for scaling)

13. Monitoring and Logging

Real-Time Status Dashboard:

The system provides comprehensive logging for:

  • Zone transitions: When positions enter/exit zones
  • Velocity events: Sudden price movements
  • Hedge executions: All automated hedging activities
  • Performance metrics: Fill rates, slippage, profit/loss
  • Risk alerts: Position size limits, emergency triggers

14. Key Benefits

Risk Management:

  • Capital Protection: Hard limits prevent over-leveraging
  • Edge Awareness: Multi-factor detection prevents surprise losses
  • Volatility Protection: Dynamic thresholds adapt to market conditions
  • Position Control: Precise management of multiple simultaneous positions

Fee Generation:

  • Range Trading: Positions generate fees while price ranges
  • Delta-Neutral: System eliminates directional bias
  • High Frequency: More opportunities for fee collection

Automated Operation:

  • 24/7 Monitoring: Continuous market surveillance
  • Immediate Response: Fast reaction to price changes
  • No Manual Intervention: System handles all hedging automatically

This sophisticated system transforms the simple CLP model into a fully-automated delta-zero hedging machine with enterprise-grade risk management and performance optimization capabilities.