Python: Modify the TP of an open trade

 

Hello,

I am stuck right now on my script.

I can open an order (see first picture attached) but i can not define a Take profit.

I tried with a number (like 2000 for exemple), I tried with a variable etc. Everytime my order is opened but the TP is 0.0


So, I tried to open my trade and to modify the TP after that with a "mt5.TRADE_ACTION_SLTP" but I need to retrieve the order number (for exemple in my 2nd picture attached "540960570") but I don't really know how to do it...

I tried "History_orders_get" ; "history_orders_total" ; "positions_get" etc. but it always return that I don't have any open position (that's wrong I have an open position and several closed positions which could have been found).

And last thing I tried was to check if I had an error code and I get "code d'erreur = (-10004, 'No IPC connection')" 


If someone have any idea I would be really happy :) thank you

 
DrazJah:


Please, insert code correctly: when editing a post, click   Code and paste your code in the popup window.
 
import MetaTrader5 as mt5
import pandas as pd
from datetime import datetime

#initialisation
mt5.initialize ()

#login to trade account
login = number
password = ""
server = "server"
mt5.login(login, password, server)
price = mt5.symbol_info_tick("GOLDmicro").ask

#get account info
account_info = mt5.account_info()
print(account_info)

#getting specific account data
login_number = account_info.login
balance = account_info.balance
equity = account_info.equity
print()
print("login: ", login_number)
print("balance: ", balance)
print("equity: ", equity)

#send order to the market


price = mt5.symbol_info_tick("GOLDmicro").ask
point = mt5.symbol_info("GOLDmicro").point


request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol" : "GOLDmicro",
        "volume" : 0.1,
        "type" : mt5.ORDER_TYPE_BUY,
        "price" : price,
        "SL" : 0.0,
        "TP": 0.0,
        "deviation" : 200,
        "magic" : 123456,
        "comment" : "TEST",
        "type_time" : mt5.ORDER_TIME_GTC,
        "type_filling" : mt5.ORDER_FILLING_IOC,
}

order = mt5.order_send(request)
print(order)

#Test for position
from_date=datetime(2022,1,1)
to_date=datetime.now()
history_orders=mt5.history_orders_get(from_date, to_date, group="*GOLD*")
if history_orders==None:
    print("code d'erreur={}".format(mt5.last_error()))
elif len(history_orders)>0:
    print("history_orders_get({}, {}, group=\"*GOLD*\")={}".format(from_date,to_date,len(history_orders)))
print()
 

To modify a POSITION you need:

1. Go through all positions

1.1. Select position and only then modify.


How it looks like in pure MQL5:

//+------------------------------------------------------------------+
//| Trailing                                                         |
//|   InpTrailingStop: min distance from price to Stop Loss          |
//+------------------------------------------------------------------+
void Trailing()
  {
   if(InpTrailingStop==0) // Trailing Stop, min distance from price to SL ('0' -> OFF)
      return;
   double freeze=0.0,stops=0.0;
   FreezeStopsLevels(freeze,stops);
   double max_levels=(freeze>stops)?freeze:stops;
   /*
   SYMBOL_TRADE_STOPS_LEVEL determines the number of points for minimum indentation of the
      StopLoss and TakeProfit levels from the current closing price of the open position
   ------------------------------------------------|------------------------------------------
   Buying is done at the Ask price                 |  Selling is done at the Bid price
   ------------------------------------------------|------------------------------------------
   TakeProfit        >= Bid                        |  TakeProfit        <= Ask
   StopLoss          <= Bid                        |  StopLoss          >= Ask
   TakeProfit - Bid  >= SYMBOL_TRADE_STOPS_LEVEL   |  Ask - TakeProfit  >= SYMBOL_TRADE_STOPS_LEVEL
   Bid - StopLoss    >= SYMBOL_TRADE_STOPS_LEVEL   |  StopLoss - Ask    >= SYMBOL_TRADE_STOPS_LEVEL
   ------------------------------------------------------------------------------------------

   SYMBOL_TRADE_FREEZE_LEVEL shows the distance of freezing the trade operations
      for pending orders and open positions in points
   ------------------------|--------------------|--------------------------------------------
   Type of order/position  |  Activation price  |  Check
   ------------------------|--------------------|--------------------------------------------
   Buy Limit order         |  Ask               |  Ask-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL
   Buy Stop order          |  Ask               |  OpenPrice-Ask  >= SYMBOL_TRADE_FREEZE_LEVEL
   Sell Limit order        |  Bid               |  OpenPrice-Bid  >= SYMBOL_TRADE_FREEZE_LEVEL
   Sell Stop order         |  Bid               |  Bid-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL
   Buy position            |  Bid               |  TakeProfit-Bid >= SYMBOL_TRADE_FREEZE_LEVEL
                           |                    |  Bid-StopLoss   >= SYMBOL_TRADE_FREEZE_LEVEL
   Sell position           |  Ask               |  Ask-TakeProfit >= SYMBOL_TRADE_FREEZE_LEVEL
                           |                    |  StopLoss-Ask   >= SYMBOL_TRADE_FREEZE_LEVEL
   ------------------------------------------------------------------------------------------
   */
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions
      if(m_position.SelectByIndex(i))
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
           {
            double price_current = m_position.PriceCurrent();
            double price_open    = m_position.PriceOpen();
            double stop_loss     = m_position.StopLoss();
            double take_profit   = m_position.TakeProfit();
            double ask           = m_symbol.Ask();
            double bid           = m_symbol.Bid();
            //---
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               if(price_current-price_open>=m_trailing_stop+m_trailing_step)
                  if(price_current-m_trailing_stop>=price_open+m_trailing_activate)
                     if(stop_loss<price_current-(m_trailing_stop+m_trailing_step))
                        if(m_trailing_stop>=max_levels && (take_profit-bid>=max_levels || take_profit==0.0))
                          {
                           if(!m_trade.PositionModify(m_position.Ticket(),
                                                      m_symbol.NormalizePrice(price_current-m_trailing_stop),
                                                      take_profit))
                              if(InpPrintLog)
                                 Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify BUY ",m_position.Ticket(),
                                       " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),
                                       ", description of result: ",m_trade.ResultRetcodeDescription());
                           if(InpPrintLog)
                             {
                              RefreshRates();
                              m_position.SelectByIndex(i);
                              PrintResultModify(m_trade,m_symbol,m_position);
                             }
                           continue;
                          }
              }
            else
              {
               if(price_open-price_current>=m_trailing_stop+m_trailing_step)
                  if(price_current+m_trailing_stop<=price_open-m_trailing_activate)
                     if((stop_loss>(price_current+(m_trailing_stop+m_trailing_step))) || (stop_loss==0))
                        if(m_trailing_stop>=max_levels && ask-take_profit>=max_levels)
                          {
                           if(!m_trade.PositionModify(m_position.Ticket(),
                                                      m_symbol.NormalizePrice(price_current+m_trailing_stop),
                                                      take_profit))
                              if(InpPrintLog)
                                 Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify SELL ",m_position.Ticket(),
                                       " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),
                                       ", description of result: ",m_trade.ResultRetcodeDescription());
                           if(InpPrintLog)
                             {
                              RefreshRates();
                              m_position.SelectByIndex(i);
                              PrintResultModify(m_trade,m_symbol,m_position);
                             }
                          }
              }
           }
  }
 

Thank you for your answer,


The problem is, as I explained in the post, that I can't see my open orders in history. It shows me nothing and I don't understand why...


If I understand well, the steps are:

- Open order

- Then, check history orders 

- Select the open order

- Modify TP

I'm beginner in Python so if someone got some part of code to make this I will be very grateful :) 

 
DrazJah # :

Thank you for your answer,


The problem is, as I explained in the post, that I can't see my open orders in history. It shows me nothing and I don't understand why...


If I understand well, the steps are:

- Open order

- Then, check history orders 

- Select the open order

- Modify TP

I'm beginner in Python so if someone got some part of code to make this I will be very grateful :) 

If you are new to Python, why are you trying to get into this language? Learn MQL5 - MQL5 is the native language of the MetaTrader 5 terminal!

 

Because Python is way easier (in my opinion) to learn than MQL5 language.

I tried both and I'm more confident on Python.

BTW I find my open order:

# Obtain open order on GOLD
positions=mt5.positions_get(symbol="GOLDmicro")
if positions==None:
    print("Aucune position sur GOLD, code d'erreur={}".format(mt5.last_error()))
elif len(positions)>0:
    print("Total des positions sur GOLD =",len(positions))
 # affiche toutes les positions ouvertes
    for position in positions:
          print(position)

But I don't understand the request to modify the Take Profit:

I tried something like this but doesn't work... Is there an issue with the structure of the SLTP request or the problem is not the structure but other thing?

Tradeposition = 541048957
position=mt5.positions_get(symbol="GOLDmicro")[-1].ticket
point = mt5.symbol_info("GOLDmicro").point
tick = mt5.symbol_info_tick("GOLDmicro")


sltp_request = {
    "action": mt5.TRADE_ACTION_SLTP,
    "symbol": "GOLDmicro",
    "volume": 0.1,
    "type": mt5.ORDER_TYPE_SELL,
    "position": Tradeposition,
    "tp": 0.0,
    "price": mt5.symbol_info_tick("GOLDmicro").ask,
    "magic": 234000,
    "comment": "Change TP",
    "type_time": mt5.ORDER_TIME_GTC,
    "type_filling": mt5.ORDER_FILLING_IOC,
}
 

You don't know MQL5 and you don't know Python.

What you don't realize is that to work with Python, you must first learn MQL5 - since MQL5 is the native language for the MetaTrader 5 trading terminal! This leads to a logical conclusion: You must learn MQL5. And only when you become a professional, you will probably learn Python.

 

I disagree ..

you can learn one and the other, simultaneously...im doing it as well..

there are limitations, but those are only set by yourself....


dont let anyone tell you " you know nothing"...rather dont give any advice Vlad,

to Draz..  keep on going, dont let anyone dissuade you, especially these so called 'experts'

Reason: