EA fails to remove trade

 

Hi everyone, I am a beginning EA creator and trying to figure out the very basics of creating an EA with MQL5/python. To start off, my EA should place an order when dragging it on the graph and close the trade if it did not hit the SL or TP within 10 seconds (keep in mind I just built this EA for training reasons and I do not think it will be profitable or something haha). So, when I drag this code to the graph, it succesfully places the order, however it immediately seems to remove the script and does not close the order after 10 seconds. Does anybody know how to fix this? I am using the following code: 

import datetime as dt
import MetaTrader5 as mt5
import time

# Connect
if not mt5.initialize():
    print("Failed to initialize MT5")
    mt5.shutdown()
    quit()

# Parameters
symbol = "EURUSD"  # Pair
lot_size = 5.1  # Lot size
stop_loss = 100  # Stop loss size in pips
take_profit = 200  # Take profit size in pips

# Valide pair check
if not mt5.symbol_select(symbol):
    print(f"Symbol '{symbol}' is not available")
    mt5.shutdown()
    quit()

# Current bid and ask price
tick_info = mt5.symbol_info_tick(symbol)
current_bid_price = tick_info.bid
current_ask_price = tick_info.ask

# Stop loss and take profit levels for buy order based on the ask price
stop_loss_price = current_ask_price - stop_loss * mt5.symbol_info(symbol).point
take_profit_price = current_ask_price + take_profit * mt5.symbol_info(symbol).point

# Trade request buy order
request = {
    "action": mt5.TRADE_ACTION_DEAL,
    "symbol": symbol,
    "volume": lot_size,
    "type": mt5.ORDER_TYPE_BUY,
    "price": current_bid_price,
    "sl": stop_loss_price,
    "tp": take_profit_price,
    "deviation": 2,
    "magic": 0,
    "comment": "",
    "type_time": mt5.ORDER_TIME_GTC,
    "type_filling": mt5.ORDER_FILLING_IOC
}

# Send buy order
result = mt5.order_send(request)

# Check if the trade request was successful
if result.retcode == mt5.TRADE_RETCODE_DONE:
    print("Trade request successful")
    order_ticket = result.order
    start_time = time.time()

    # Monitor the order for 10 seconds
    while time.time() - start_time < 10:
        # Check if the order has been closed
        orders = mt5.orders_get(symbol=symbol)
        order = next((o for o in orders if o.ticket == order_ticket), None)
        if order is None:
            print("Order closed")
            break
        time.sleep(1)

    # If the order is still open after 10 seconds, close it
    orders = mt5.orders_get(symbol=symbol)
    order = next((o for o in orders if o.ticket == order_ticket), None)
    if order is not None:
        close_request = {
            "action": mt5.TRADE_ACTION_DEAL,
            "symbol": symbol,
            "volume": lot_size,
            "type": mt5.ORDER_TYPE_SELL,
            "position": order.position,
            "price": current_bid_price,
            "deviation": 2
        }
        close_result = mt5.order_send(close_request)
        if close_result.retcode == mt5.TRADE_RETCODE_DONE:
            print("Order closed due to timeout")

else:
    print(f"Trade request failed with error code: {result.retcode}")

mt5.shutdown()

Many thanks in advance!!

 
MoneyBoy13:
if result.retcode == mt5.TRADE_RETCODE_DONE:     print("Trade request successful")

Did you check that your code effectively detect the new trade ? Otherwise said is the close request executed by fails or it's not executed at all ?

You should start to print "order" values.

 

Hi Alain,

I do not think I fully understand you yet. Could you somehow clarify a little bit more? Would be really helpful :)

 
MoneyBoy13 #:

Hi Alain,

I do not think I fully understand you yet. Could you somehow clarify a little bit more? Would be really helpful :)

...does not close the order after 10 second...

You need to find why. To start with is the code to close the order has been executed but gave an error ?

if order is not None:

or was it not executed at all ?

 

Hi Alain, 

No the order executes perfectly. When I drag it on, it places an buy order. However, when I look in the journal (after it placed an buy order) I see: Buy order placed, and script removed. So somehow, it looks like it seems to think the script is 'done' after placing the buy-order. Does this make sense to you?

 
Or do I need to be in another environment to keep a script active for a longer time? I am reading something about an IDE?
 
MoneyBoy13 #:

Hi Alain, 

No the order executes perfectly. When I drag it on, it places an buy order. However, when I look in the journal (after it placed an buy order) I see: Buy order placed, and script removed. So somehow, it looks like it seems to think the script is 'done' after placing the buy-order. Does this make sense to you?

I wasn't talking about the initial order, but the order to close.

Is it really you who coded this script ?

 

Yes, I really coded this myself. But then again, I am a beginner: The part of placing a buy order also took me a while as well and when I look back at what I coded first it does not make sense either. So, I can imagine the second part (closing the order) does not make sense for an experienced programmer. 

Coming back to your question: it does not give an error but does not place the order to close at all. It removes the script after placing the buy order immediately. 

 
MoneyBoy13 #:

Yes, I really coded this myself. But then again, I am a beginner: The part of placing a buy order also took me a while as well and when I look back at what I coded first it does not make sense either. So, I can imagine the second part (closing the order) does not make sense for an experienced programmer. 

Coming back to your question: it does not give an error but does not place the order to close at all. It removes the script after placing the buy order immediately. 

Ok. So if your code doesn't work as expected you need to track the source of the problem.

What is printed in the log ?

What is the result of a trade request (an order) ?

You are trying to detect "an order", but what you need to close is a position.

 

Yes, I tried to do so. If I start my trade bot it places the order succesfully. Then I checked the log and it mentions:

1.  trade placed succesfully. 
2. Script removed.

So what I am trying to say is: I am thinking the script somehow thinks it is done after it placed the buy order and removes the script. So I am trying to seek is an answer on the question: Do I need to adjust my code somehow so that it does not think it is done after the buy order is placed.

Reason: