class MT5TradingBot:
    def __init__(self, config):
        self.config = config
        self.symbol = config['symbol']
        
        self.lot_size = config['lot_size']
        self.sl_points = config['sl_points']
        self.tp_points = config['tp_points']
        self.risk_per_trade = config['risk_per_trade']
        self.trade_session_start = config['trade_session_start']
        self.trade_session_end = config['trade_session_end']
        self.log_file = config['log_file']
        self.initialize_mt5()

    def initialize_mt5(self):
        """Initialize the MT5 platform and login."""
        if not mt5.initialize():
            raise RuntimeError(f"MT5 initialization failed: {mt5.last_error()}")
        if not mt5.login(
            self.config['account_login'],
            self.config['account_password'],
            self.config['account_server']
        ):
            raise RuntimeError(f"MT5 login failed: {mt5.last_error()}")
        print("Connected to MetaTrader 5")

    def fetch_data(self, num_candles=500):
        """Fetch historical market data."""
        rates = mt5.copy_rates_from_pos(self.symbol, self.timeframe, 0, num_candles)
        if rates is None:
            raise RuntimeError(f"Failed to fetch data for {self.symbol}: {mt5.last_error()}")
        df = pd.DataFrame(rates)
        df['time'] = pd.to_datetime(df['time'], unit='s')
        return df

    def calculate_indicators(self, df):
        """Calculate technical indicators."""
        df['MA20'] = df['close'].rolling(window=20).mean()
        df['RSI'] = 100 - (100 / (1 + df['close'].pct_change().rolling(window=14).mean()))
        return df

    def find_support_resistance(self, df, period=20):
        """Identify support and resistance levels."""
        df['Support'] = df['low'].rolling(window=period).min()
        df['Resistance'] = df['high'].rolling(window=period).max()
        return df

    def calculate_lot_size(self, account_balance):
        """Calculate lot size based on risk management rules."""
        risk_amount = account_balance * (self.risk_per_trade / 100)
        lot_size = risk_amount / (self.sl_points * 10)
        return max(0.01, round(lot_size, 2))

    def place_trade(self, action, lot_size):
        """Execute a buy or sell trade."""
        price = mt5.symbol_info_tick(self.symbol).ask if action == 'buy' else mt5.symbol_info_tick(self.symbol).bid
        order_type = mt5.ORDER_BUY if action == 'buy' else mt5.ORDER_SELL
        deviation = 10  # Price deviation in points

        request = {
            "action": mt5.TRADE_ACTION_DEAL,
            "symbol": self.symbol,
            "volume": lot_size,
            "type": order_type,
            "price": price,
            "sl": price - self.sl_points if action == 'buy' else price + self.sl_points,
            "tp": price + self.tp_points if action == 'buy' else price - self.tp_points,
            "deviation": deviation,
            "magic": 123456,
            "comment": "TradingBot",
            "type_time": mt5.ORDER_TIME_GTC,
            "type_filling": mt5.ORDER_FILLING_IOC,
        }
        result = mt5.order_send(request)
        if result.retcode != mt5.TRADE_RETCODE_DONE:
            self.log(f"Trade failed: {result}")
        else:
            self.log(f"Trade placed: {result}")
        return result

    def log(self, message):
        """Log messages to a file and console."""
        with open(self.log_file, "a") as f:
            f.write(f"{datetime.now()} - {message}\n")
        print(message)

    def trading_logic(self):
        """Core trading logic."""
        # Fetch account balance
        account_info = mt5.account_info()
        if account_info is None:
            raise RuntimeError("Failed to fetch account info")
        account_balance = account_info.balance

        # Fetch and analyze data
        data = self.fetch_data()
        data = self.calculate_indicators(data)
        data = self.find_support_resistance(data)

        # Get the last row
        last_row = data.iloc[-1]
        lot_size = self.calculate_lot_size(account_balance)

        # Trading logic
        if last_row['close'] > last_row['Resistance']:
            self.log(f"Condition met: BUY at {last_row['close']}")
            self.place_trade('buy', lot_size)
        elif last_row['close'] < last_row['Support']:
            self.log(f"Condition met: SELL at {last_row['close']}")
            self.place_trade('sell', lot_size)

    def run(self):
        """Main loop for running the bot."""
        try:
            while True:
                current_time = datetime.now().strftime("%H:%M")
                if self.trade_session_start <= current_time <= self.trade_session_end:
                    self.trading_logic()
                else:
                    self.log(f"Outside trading session: {current_time}")
                time.sleep(60)  # Run every minute
        except Exception as e:
            self.log(f"Error: {e}")
        finally:
            mt5.shutdown()
            self.log("Bot stopped")


if __name__ == "__main__":
    CONFIG = {
        "account_login": 253779,
        "account_password": "5bed9j!J",
        "account_server": "DooTechnology-Demo",
        "symbol": "EURUSD",
               "lot_size": 0.1,
        "sl_points": 100,
        "tp_points": 200,
        "risk_per_trade": 1.0,
        "trade_session_start": "08:00",
        "trade_session_end": "20:00",
        "log_file": "trading_bot_log.txt",
    }


 
by

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling