Nov-09-2024, 06:28 PM
As the picture I am posting indicates, I am trying to have my semi-live tkinter DOGE graph have simple annotations such in the small example to indicate where certain chart patterns form, but I haven't gotten it to work on the tkinter windows, only the Figure 1 standard still window from matplotlib has been able to have these annotations put on it. I have dumbed it down to where it only has to put a single indicator on one or multiple obvious points but it seems that tkinter can not accept the same types of annotations as the matplotlib window. Is there a workaround, or am I getting something wrong? Thanks.
import matplotlib.pyplot as plt import mplfinance as mpf import pandas as pd import time import robin_stocks.robinhood as r import requests from datetime import datetime import pytz import tkinter as tk from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import os # Initialize global variables program_start_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') doge_data = pd.DataFrame() # Initialize empty DataFrame for doge_data current_price = None # Initialize current price def read_credentials(): credentials_path = os.path.join(os.path.dirname(__file__), "credentials.txt") with open(credentials_path, "r") as file: username, password = file.read().strip().split("\n") return username, password def login_to_robinhood(): username, password = read_credentials() try: r.login(username, password) print("Logged in successfully") return True except Exception as e: print("Login failed:", e) return False def fetch_current_price(): try: price_data = r.crypto.get_crypto_quote('DOGE') price = float(price_data['mark_price']) if price_data['mark_price'] else None #print("Current DOGE price:", price) return price except Exception as e: print(f"Error fetching current price: {e}") return None def fetch_historical_data(): end_time = int(time.time()) start_time = end_time - 86400 # 24 hours ago url = 'https://min-api.cryptocompare.com/data/v2/histominute' params = { 'fsym': 'DOGE', 'tsym': 'USD', 'limit': 60, 'toTs': end_time } response = requests.get(url, params=params) if response.status_code == 200: data = response.json()['Data']['Data'] df = pd.DataFrame(data) df['time'] = pd.to_datetime(df['time'], unit='s') df.set_index('time', inplace=True) if 'volumefrom' in df.columns: df.rename(columns={'volumefrom': 'volume'}, inplace=True) df = df[['open', 'high', 'low', 'close', 'volume']] tz = pytz.timezone('America/Chicago') df.index = df.index.tz_localize('UTC').tz_convert(tz) return df else: print("Error fetching historical data:", response.status_code) return pd.DataFrame() def plot_doge_data(): global doge_data, current_price # Declare as global to access and modify the variables # Initialize doge_data and current_price doge_data = fetch_historical_data() current_price = fetch_current_price() if not doge_data.empty and current_price is not None: # Create a Tkinter window root = tk.Tk() root.title("DOGE Candlestick Chart") # Create a figure for the plot and embed it in the Tkinter window fig, ax = plt.subplots(figsize=(10, 6)) # Set figure size canvas = FigureCanvasTkAgg(fig, master=root) canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True) # Keep the window in the background root.wm_attributes("-topmost", False) # Main update loop for plotting def update_plot(): global doge_data, current_price # Use global to modify the variables defined in the outer function ax.clear() # Clear previous plot to refresh # Plot using mplfinance mpf.plot( doge_data, type='candle', style='charles', ax=ax, ylabel='Price (USD)', volume=False, show_nontrading=False ) # Update title and subtitle with current data current_time_str = pd.Timestamp.now(tz='America/Chicago').strftime("%Y-%m-%d %H:%M:%S CST") ax.set_title(f'DOGE Candlestick Chart - Current Price: ${current_price:,.4f}', fontsize=10, pad=20) fig.suptitle(f'Program Start: {program_start_time}\nCurrent Time: {current_time_str}', fontsize=8, y=0.92) canvas.draw() # Update the plot # Refresh data current_price = fetch_current_price() # Update price doge_data = fetch_historical_data() # Refresh data with latest trades root.after(6000, update_plot) # Schedule next update after 200 ms update_plot() # Start the update loop root.mainloop() # Start the Tkinter event loop if __name__ == "__main__": if login_to_robinhood(): plot_doge_data()