import time
import requests
from binance.client import Client

# Binance API credentials
api_key = 'WFIEaBuUafZ9ldAiMHLZ4Z1qHdVnpoDUVZM8MughMf6zmbSqGx5pEmQFBJysjwFp'  # Optional for public data
api_secret = 'C9HtmLk7fBCidyJI2lPtUbYhj4T0FdmJ0NE0LLipFiwUSR7euf1TEzJblEx1O6oA'  # Optional for public data

# Initialize Binance client
client = Client(api_key, api_secret)

# Define the threshold for disparity (e.g., 0.05 for 5%)
DISPARITY_THRESHOLD = 0.05

# Nextcloud Talk configuration
NEXTCLOUD_URL = 'https://1984.algometic.com'  # Replace with your Nextcloud URL
NEXTCLOUD_USERNAME = 'larry'  # Replace with your Nextcloud username
NEXTCLOUD_PASSWORD = 'jEr6f-8Q5y5-nsSdA-koWsk-58jRT'  # Replace with your app password
TALK_CONVERSATION_TOKEN = 'jg65znzn'  # Replace with your Talk conversation token

# Function to fetch current prices of BTC and ETH
def get_prices():
    btc_price = float(client.get_symbol_ticker(symbol='BTCUSDT')['price'])
    eth_price = float(client.get_symbol_ticker(symbol='ETHUSDT')['price'])
    return btc_price, eth_price

# Function to calculate disparity
def calculate_disparity(btc_price, eth_price):
    parity = eth_price / btc_price
    return parity

# Function to send alert to Nextcloud Talk
def send_alert_to_talk(message):
    talk_api_url = f"{NEXTCLOUD_URL}/ocs/v2.php/apps/spreed/api/v1/chat/{TALK_CONVERSATION_TOKEN}"
    
    headers = {
        'OCS-APIRequest': 'true',
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    }
    
    payload = {
        'message': message,
    }
    
    try:
        response = requests.post(
            talk_api_url,
            headers=headers,
            json=payload,
            auth=(NEXTCLOUD_USERNAME, NEXTCLOUD_PASSWORD)
        )
        response.raise_for_status()  # Raise an error for bad responses
        print(f"Alert sent to Nextcloud Talk: {message}")
    except requests.exceptions.RequestException as e:
        print(f"Failed to send alert to Nextcloud Talk: {e}")

# Main monitoring loop
def monitor_disparity():
    while True:
        try:
            btc_price, eth_price = get_prices()
            parity = calculate_disparity(btc_price, eth_price)
            
            print(f"BTC Price: {btc_price}, ETH Price: {eth_price}, Parity: {parity}")
            
            if parity > (1 + DISPARITY_THRESHOLD):
                send_alert_to_talk(f"ETH is overvalued compared to BTC! Parity: {parity}")
            elif parity < (1 - DISPARITY_THRESHOLD):
                send_alert_to_talk(f"ETH is undervalued compared to BTC! Parity: {parity}")
            
            time.sleep(60)  # Check every 60 seconds
        
        except Exception as e:
            print(f"Error: {e}")
            time.sleep(60)

if __name__ == "__main__":
    monitor_disparity()