Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to draw candlesticks on canvas #440

Closed
hanfon2020 opened this issue Sep 2, 2021 · 4 comments
Closed

How to draw candlesticks on canvas #440

hanfon2020 opened this issue Sep 2, 2021 · 4 comments
Labels
question Further information is requested

Comments

@hanfon2020
Copy link

hanfon2020 commented Sep 2, 2021

How to draw the mplfinance cnadlesticks drawing to the canvas instead of generating the blank canvas k-line drawing as shown in the figure, but drawing it in the plot output bar of python,how to correct it?

import time
import pandas as pd
import matplotlib
import mplfinance as mpf
import matplotlib.pyplot as plt
import sqlite3
import datetime
import abstract
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from tkinter import *
import tkinter as tk
win=tk.Tk()
win.geometry("950x850")
#figure=plt.figure()
#ax=figure.add_subplot(111)
strtemp=""
str1=""
str3=""
str2=""
i=0
iday = []
conn = sqlite3.connect('indexfuturecom.sqlite') # 建立資料庫連線
strtemp= "select * from table1"
df = pd.read_sql(strtemp,conn,parse_dates=True)
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
iday=df.loc['2001-01-02  08:46:00':'2021-07-31  13:45:00',:]


def Plot_data():
    fig = mpf.figure(figsize=(1,1), dpi=100)
    chart=fig.add_subplot(111)
    canvas=tk.Canvas(win,background='white',width=900,height=800)
    chart_canvas = FigureCanvasTkAgg(fig, master=win)
    chart_canvas.get_tk_widget().place(relx = .05, rely=.25)
    kwargs=dict(title='Candle plot',figratio=(15,10),figscale=5)
    mc=mpf.make_marketcolors(up='red',down='green',edge='i',wick='i',volume='in',inherit=True)
    s=mpf.make_mpf_style(gridaxis='both',gridstyle='-.',y_on_right=False,marketcolors=mc)   
    mpf.plot(iday,type='candle',style=s, volume=True,addplot=[])

Plot_data()
win.mainloop()

ouptpu

@hanfon2020 hanfon2020 added the question Further information is requested label Sep 2, 2021
@hanfon2020
Copy link
Author

hanfon2020 commented Sep 2, 2021

I used the trial and error method myself and found that plog_data function was changed to the following

def Plot_data():
    fig = mpf.figure(figsize=(1,1), dpi=100)
    chart=fig.add_subplot(111)
    chart_canvas=tk.Canvas(win,background='white',width=900,height=800)

    kwargs=dict(title='Candle plot',figratio=(15,10),figscale=5)
    mc=mpf.make_marketcolors(up='red',down='green',edge='i',wick='i',volume='in',inherit=True)
    s=mpf.make_mpf_style(gridaxis='both',gridstyle='-.',y_on_right=False,marketcolors=mc)   
    fig,ax=mpf.plot(iday,type='candle',tight_layout=True,style=s, volume=True,returnfig = True)
    chart_canvas = FigureCanvasTkAgg(fig,master=win)
    chart_canvas.draw()
    chart_canvas.get_tk_widget().place(relx = .05, rely=.25)

Then the required output form appears:
Uploading carvas.jpg…

@DanielGoldfarb
Copy link
Collaborator

DanielGoldfarb commented Sep 2, 2021

There are two ways to do this. The second approach you have above is generally better because it does not limit mplfinance functionality (as does the first approach). This second approach is to set returnfig=True, and then use the Figure returned to create the canvas, as you have done chart_canvas = FigureCanvasTkAgg(fig,master=win)

The first approach where you create the Figure first, can work but limits some mplfinance functionality. It also requires that you pass in the Axes object to mpf.plot(): After chart=fig.add_subplot(111) then mpf.plot(iday,type='candle',style=s, volume=True,addplot=[]) should be:

mpf.plot(iday,type='candle',style=s, volume=True,ax=chart)

Notice also that I have removed addplot=[]. Passing in an empty addplot list has undefined behavior.

Again, just to emphasize, the second approach (returnfig=True) is generally easier to use, and allows mplfinance to do more of the work for you.

@DanielGoldfarb
Copy link
Collaborator

Let me know if you have any further questions.

@chebbah05028
Copy link

chebbah05028 commented Nov 14, 2022

import pandas as pd
import numpy as np
import matplotlib.dates as mpl_dates
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import matplotlib.pyplot as plt
import mplfinance as mpf
from MT5lib import  Currency
import MetaTrader5 as mt5
import time  
from threading import Timer  
import Indicators as ind
#from tkinter import *
import tkinter as tk
#import IctAlg as ict
class _Timer(Timer):  
    def run(self):  
        while not self.finished.wait(self.interval):  
            self.function(*self.args,**self.kwargs)  


def Plot_data():
    iday = Currency('gbpjpy'.upper()).M5

    fig = mpf.figure(figsize=(1,1), dpi=100)
    chart=fig.add_subplot(111)
    chart_canvas=tk.Canvas(win,background='white',width=900,height=800)

    kwargs=dict(title='Candle plot',figratio=(15,10),figscale=5)
    mc=mpf.make_marketcolors(up='red',down='green',edge='i',wick='i',volume='in',inherit=True)
    #s=mpf.make_mpf_style(gridaxis='both',gridstyle='-.',y_on_right=False,marketcolors=mc)   
    fig,ax=mpf.plot(iday,type='candle',tight_layout=True,returnfig = True)
    chart_canvas = FigureCanvasTkAgg(fig,master=win)
    chart_canvas.draw()
    chart_canvas.get_tk_widget().place(relx = .05, rely=.25)



if __name__ == '__main__':
    win=tk.Tk()
    win.geometry("950x850")
    Read_Data_timer = _Timer(1,Plot_data)
    Read_Data_timer.start() #recalling run  

  
    win.mainloop()
    
    
    Read_Data_timer.cancel()

/////////////////////////////////////////////////
But there is a warning how can I remove it

  f = plt.figure(FigureClass=Mpf_Figure,*args,**kwargs)
C:\Users\Medinfo\anaconda3\envs\MT5ALGO\lib\site-packages\mplfinance\_styles.py:24: MatplotlibDeprecationWarning: The seaborn styles shipped by Matplotlib are deprecated since 3.6, as they no longer correspond to the styles shipped by seaborn. However, they will remain available as 'seaborn-v0_8-<style>'. Alternatively, directly use the seaborn API instead.
  plt.style.use(style['base_mpl_style'])
C:\Users\Medinfo\anaconda3\envs\MT5ALGO\lib\site-packages\mplfinance\_styles.py:24: MatplotlibDeprecationWarning: The seaborn styles shipped by Matplotlib are deprecated since 3.6, as they no longer correspond to the styles shipped by seaborn. However, they will remain available as 'seaborn-v0_8-<style>'. Alternatively, directly use the seaborn API instead.
  plt.style.use(style['base_mpl_style'])
C:\Users\Medinfo\anaconda3\envs\MT5ALGO\lib\site-packages\mplfinance\plotting.py:454: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail.
  fig = plt.figure()
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File "C:\Users\Medinfo\anaconda3\envs\MT5ALGO\lib\site-packages\matplotlib\_pylab_helpers.py", line 82, in destroy_all
    manager.destroy()
  File "C:\Users\Medinfo\anaconda3\envs\MT5ALGO\lib\site-packages\matplotlib\backends\_backend_tk.py", line 548, in destroy
    self.window.update()
  File "C:\Users\Medinfo\anaconda3\envs\MT5ALGO\lib\tkinter\__init__.py", line 1314, in update
    self.tk.call('update')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants