202 lines
6.4 KiB
Python
202 lines
6.4 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Simple Hedge Execution Script
|
|
Executes hedges based on manual parameters
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import json
|
|
import time
|
|
from datetime import datetime
|
|
|
|
# Add current directory to path for imports
|
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.append(current_dir)
|
|
|
|
def execute_simple_hedge():
|
|
"""Execute a simple hedge trade"""
|
|
print("🔧 Simple Hedge Execution")
|
|
print("=" * 40)
|
|
|
|
# Load environment
|
|
try:
|
|
from dotenv import load_dotenv
|
|
load_dotenv(override=True)
|
|
|
|
rpc_url = os.environ.get("MAINNET_RPC_URL")
|
|
private_key = os.environ.get("MAIN_WALLET_PRIVATE_KEY") or os.environ.get("PRIVATE_KEY")
|
|
|
|
if not rpc_url or not private_key:
|
|
print("❌ Missing RPC URL or Private Key")
|
|
return False
|
|
|
|
print(f"✅ Environment loaded")
|
|
print(f" RPC: {rpc_url[:20]}...")
|
|
print(f" Key: {private_key[:10]}...")
|
|
|
|
except Exception as e:
|
|
print(f"❌ Error loading environment: {e}")
|
|
return False
|
|
|
|
# Get token parameters
|
|
print("\n📝 Enter Hedge Parameters:")
|
|
|
|
# Use default WETH address for Arbitrum
|
|
token_address = input("Token address (default: WETH): ").strip()
|
|
if not token_address:
|
|
token_address = "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"
|
|
|
|
try:
|
|
hedge_amount = float(input("Hedge amount in ETH: ").strip())
|
|
if hedge_amount <= 0:
|
|
print("❌ Amount must be positive")
|
|
return False
|
|
except ValueError:
|
|
print("❌ Invalid amount")
|
|
return False
|
|
|
|
print(f"\n🎯 Hedge Parameters:")
|
|
print(f" Token: {token_address}")
|
|
print(f" Amount: {hedge_amount} ETH")
|
|
|
|
# Confirm execution
|
|
confirm = input("\nExecute hedge? (y/N): ").strip().lower()
|
|
if confirm != 'y':
|
|
print("❌ Hedge execution cancelled")
|
|
return False
|
|
|
|
# Initialize Web3 and execute hedge
|
|
try:
|
|
from web3 import Web3
|
|
from eth_account import Account
|
|
|
|
# Connect to blockchain
|
|
w3 = Web3(Web3.HTTPProvider(rpc_url))
|
|
if not w3.is_connected():
|
|
print("❌ Failed to connect to RPC")
|
|
return False
|
|
|
|
account = Account.from_key(private_key)
|
|
print(f"✅ Connected to Chain ID: {w3.eth.chain_id}")
|
|
print(f"✅ Wallet: {account.address}")
|
|
|
|
# Import hedge execution function
|
|
from uniswap_manager import execute_hedge_sync
|
|
|
|
# Initialize router contract (simplified for testing)
|
|
# For actual execution, router contract would be initialized properly
|
|
|
|
print("\n🔄 Executing hedge...")
|
|
|
|
# For demonstration, we'll simulate the hedge execution
|
|
# In production, this would call execute_hedge_sync with proper contracts
|
|
|
|
# Simulate hedge execution
|
|
hedge_info = {
|
|
"token_address": token_address,
|
|
"token_symbol": "WETH",
|
|
"hedge_amount": hedge_amount,
|
|
"token_amount_wei": int(hedge_amount * (10 ** 18)),
|
|
"transaction_hash": "0x" + "0" * 64, # Mock transaction hash
|
|
"timestamp": datetime.now().isoformat(),
|
|
"status": "executed_simulated"
|
|
}
|
|
|
|
# Record hedge execution
|
|
trades_file = "logs/trades.json"
|
|
os.makedirs("logs", exist_ok=True)
|
|
|
|
# Load existing trades
|
|
trades = []
|
|
if os.path.exists(trades_file):
|
|
try:
|
|
with open(trades_file, 'r') as f:
|
|
trades = json.load(f)
|
|
except:
|
|
trades = []
|
|
|
|
# Add new hedge execution
|
|
trades.append({
|
|
"timestamp": hedge_info["timestamp"],
|
|
"action": "hedge_execute",
|
|
"token_address": hedge_info["token_address"],
|
|
"token_symbol": hedge_info["token_symbol"],
|
|
"amount": hedge_info["hedge_amount"],
|
|
"transaction_hash": hedge_info["transaction_hash"],
|
|
"status": "simulated"
|
|
})
|
|
|
|
# Save to file
|
|
with open(trades_file, 'w') as f:
|
|
json.dump(trades, f, indent=2)
|
|
|
|
print(f"✅ Hedge executed successfully (simulated):")
|
|
print(f" Token: {hedge_info['token_symbol']} ({hedge_info['token_address']})")
|
|
print(f" Amount: {hedge_info['hedge_amount']:.6f}")
|
|
print(f" Tx Hash: {hedge_info['transaction_hash']}")
|
|
print(f" Time: {hedge_info['timestamp']}")
|
|
print(f"📝 Recorded in {trades_file}")
|
|
|
|
return True
|
|
|
|
except ImportError as e:
|
|
print(f"❌ Missing dependencies: {e}")
|
|
print(" Install with: pip install web3 eth-account")
|
|
return False
|
|
except Exception as e:
|
|
print(f"❌ Error executing hedge: {e}")
|
|
return False
|
|
|
|
def show_recent_hedges():
|
|
"""Show recent hedge executions"""
|
|
print("\n📊 Recent Hedge Executions:")
|
|
print("-" * 40)
|
|
|
|
trades_file = "logs/trades.json"
|
|
if not os.path.exists(trades_file):
|
|
print("No hedge executions found")
|
|
return
|
|
|
|
try:
|
|
with open(trades_file, 'r') as f:
|
|
trades = json.load(f)
|
|
|
|
# Show last 5 hedges
|
|
recent_trades = trades[-5:] if len(trades) > 5 else trades
|
|
|
|
for trade in recent_trades:
|
|
timestamp = trade.get("timestamp", "Unknown")
|
|
action = trade.get("action", "Unknown")
|
|
token = trade.get("token_symbol", "Unknown")
|
|
amount = trade.get("amount", 0)
|
|
status = trade.get("status", "Unknown")
|
|
|
|
print(f"📅 {timestamp}")
|
|
print(f" Action: {action}")
|
|
print(f" Token: {token}")
|
|
print(f" Amount: {amount:.6f}")
|
|
print(f" Status: {status}")
|
|
print()
|
|
|
|
except Exception as e:
|
|
print(f"❌ Error reading trades: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
print("🔧 CLP Auto Hedger - Manual Hedge Execution")
|
|
print("=" * 50)
|
|
|
|
show_recent_hedges()
|
|
|
|
choice = input("\nOptions:\n1. Execute new hedge\n2. Exit\nChoice (1-2): ").strip()
|
|
|
|
if choice == "1":
|
|
success = execute_simple_hedge()
|
|
if success:
|
|
print("\n✅ Hedge execution completed successfully!")
|
|
else:
|
|
print("\n❌ Hedge execution failed!")
|
|
else:
|
|
print("👋 Goodbye!")
|
|
|
|
sys.exit(0) |