Marubozu Candlestick Patterns: #Python Coding for Algorithmic Trading #finance #metatrader5

import datetime
import pytz
import pandas as pd
import MetaTrader5 as mt5
import numpy as np
import matplotlib.pyplot as plt

mt5.initialize()
mt5.login("********", "MetaQuotes-Demo", "*****")
frame_M15 = mt5.TIMEFRAME_M15 # 15-minute time
frameframe_M30 = mt5.TIMEFRAME_M30 # 30-minute time frame
frame_H1 = mt5.TIMEFRAME_H1 # Hourly time frame
frame_H4 = mt5.TIMEFRAME_H4 # 4-hour time frame
frame_D1 = mt5.TIMEFRAME_D1 # Daily time frame
frame_W1 = mt5.TIMEFRAME_W1 # Weekly time frame
frame_M1 = mt5.TIMEFRAME_MN1 # Monthly time frame
assets = ['EURUSD', 'USDCHF', 'GBPUSD', 'USDCAD', 'BTCUSD']#,'ETHUSD' 'XAUUSD', 'XAGUSD', 'SP500m', 'UK100']
def get_quotes(time_frame, year=2024, month=1, day=1, asset="EURUSD"):
    if not mt5.initialize():
        print("initialize() failed, error code =", mt5.last_error())
        quit()

    timezone = pytz.timezone("America/New_York")

# America/New_York
# Europe/London
# Europe/Paris
# Asia/Tokyo
# Australia/Sydney


    time_from = datetime.datetime(year, month, day, tzinfo=timezone)
    time_to = datetime.datetime.now(timezone) + datetime.timedelta(days=1)

    print(f"Fetching data for {asset} from {time_from} to {time_to} with timeframe {time_frame}")

    rates = mt5.copy_rates_range(asset, time_frame, time_from, time_to)

    if rates is None:
        print(f"No data for {asset} in the specified range.")
        return None

    rates_frame = pd.DataFrame(rates)
    return rates_frame
def mass_import(asset_index, time_frame):
    asset = assets[asset_index]
    data = get_quotes(frame_D1 if time_frame == 'D1' else frame_H1, 2024, 6, 1, asset=asset)

    if data is None or data.empty:
        print(f"No data returned for {asset} on {time_frame} timeframe.")
        return None

    # print(f"Data for {asset} on {time_frame} timeframe:\n", data.head())
    data_values = data.iloc[:, 1:5].values.round(decimals=5)
    print(data_values)
    return data_values
# Fetch data for ETHUSD on the Daily time frame
my_data = mass_import(1, 'D1')
# print(my_data)
if my_data is not None:
    print("Fetched Data:\n", my_data)
else:
    print("No data fetched.")
def add_column(data, times):
    for i in range(1, times + 1):
        new = np.zeros((len(data), 1), dtype = float)
        data = np.append(data, new, axis = 1)
    return data
# - If the close price is greater than the open price, the high price equals the close price, 
#       and the low price equals the open price, then we generate a buy signal.



# - If the close price is lower than the open price, the high price equals the open price, 
#       and the low price equals the close price, then we generate a sell signal."



def signal(data, open_column, high_column, low_column, close_column, buy_column, sell_column):
    data = add_column(data, 5)
    for i in range(len(data)):
        try:
            # Bullish pattern
            if data[i, close_column] > data[i, open_column] and data[i, high_column] == data[i, close_column] and data[i, low_column] == data[i, open_column] and data[i, buy_column] == 0:
                    data[i + 1, buy_column] = 1
            # Bearish pattern
            elif data[i, close_column] < data[i, open_column] and data[i, high_column] == data[i, open_column] and data[i, low_column] == data[i, close_column] and data[i, sell_column] == 0:
                    data[i + 1, sell_column] = -1
        except IndexError:
            pass
    return data
def ohlc_plot_candles(data, window): #500 last 500 records
    sample= data[-window:]
    for i in range(len(sample)):
        plt.vlines(x = i, ymin = sample[i, 2], ymax = sample[i, 1],color = 'black', linewidth = 1)
        if sample[i, 3] > sample[i, 0]:
            plt.vlines(x = i, ymin = sample[i, 0], ymax = sample[i, 3],color = 'green', linewidth = 3)
        if sample[i, 3] < sample[i, 0]:
            plt.vlines(x = i, ymin = sample[i, 3], ymax = sample[i, 0],color = 'red', linewidth = 3)
        else:
            plt.vlines(x = i, ymin = sample[i, 3], ymax = sample[i, 0] + 0.00003, color = 'black', linewidth = 1.00)
    plt.grid()
def plot_signal_chart(data, position, buy_column, sell_column, window=500):
    data = signal(my_data, 0, 1, 2, 3, 4, 5)
    sample = data[-window:]
    fig, ax = plt.subplots(figsize=(12, 6))  # Adjust figure size for better proportion
    ohlc_plot_candles(sample, window)
    for i in range(len(sample)):
        if sample[i, buy_column] == 1:
            ax.annotate('Buy', xy=(i, sample[i, position]), xytext=(i, sample[i, position] + 0.0001),
                        arrowprops=dict(facecolor='green', shrink=0.05, width=1, headwidth=2, headlength=1),
                        horizontalalignment='center', verticalalignment='bottom')
        elif sample[i, sell_column] == -1:
            ax.annotate('Sell', xy=(i, sample[i, position]), xytext=(i, sample[i, position] - 0.0001),
                        arrowprops=dict(facecolor='red', shrink=0.05, width=1, headwidth=2, headlength=1),
                        horizontalalignment='center', verticalalignment='top')
    plt.show()
my_data = rounding(my_data, 5)
print(my_data)
plot_signal_chart(my_data, 0, 4, 5, window = 100)