Get Closed Trades Takeprofit and Stoploss

 

I am trying to read closed Trades Takeprofit and Stoploss values but i dont find ways.

I have use the HistoryDeals way of reading all closed Trades, but for reading takeprofit and stoploss i dont find options like DEAL_TP or DEAL_SL

so 2 questions,

1. why have metaquotes make it so complicate to read this values

2. and how can i read them? but please show me native way i dont want to a link to any libaries where it maybe can be read with, just explain me how i can normaly read it or dont tell it


Look with the following Code i can find and read every lit s that you can need and i ask myself why metaquotes is so s and dont add a DEAL_TP or DEAL_SL option

if(HistorySelect(from_date,to_date) )
     {
     for(int i = HistoryDealsTotal(); i >= 0; i--)
       {
         //---
         deal_ticket = HistoryDealGetTicket(i);
         OrderCloseTime = (datetime)HistoryDealGetInteger(deal_ticket,DEAL_TIME);
         OrderProfit = (double)HistoryDealGetDouble(deal_ticket,DEAL_PROFIT);
         OrderClosePrice = (double)HistoryDealGetDouble(deal_ticket,DEAL_PRICE);
         OrderSymbol = HistoryDealGetString(deal_ticket,DEAL_SYMBOL);
         deal_type = HistoryDealGetInteger(deal_ticket,DEAL_TYPE);
         OrderLots = (double)HistoryDealGetDouble(deal_ticket,DEAL_VOLUME);
         OrderSwap = (double)HistoryDealGetDouble(deal_ticket,DEAL_SWAP);
         OrderComission = (double)HistoryDealGetDouble(deal_ticket,DEAL_COMMISSION);
         Position_ID_OrderTicket_original = HistoryDealGetInteger(deal_ticket,DEAL_POSITION_ID);
         ENUM_DEAL_TYPE OrderType = HistoryDealGetInteger(deal_ticket,DEAL_ENTRY);
         //---
         if(deal_type==DEAL_TYPE_BALANCE) {Balance=OrderProfit;}
         if(OrderType==DEAL_ENTRY_OUT)
           {
             Print(OrderOpenTime+"  "+Position_ID_OrderTicket_original+"  "+OrderSymbol+"  "+OrderLots+"   "+OrderClosePrice+"  "+OrderCloseTime+"   "+OrderProfit);
           }
       }
    }
 
Ok.

Things are complicated when we do not understand. It is not MQ making it hard. It's the general understanding.

Positions - Orders - Deals.

Take the words in their meanings.

Orders are placed. Deals are execute results. Positions are the "managed objects"

So you are searching for deals. Search for the reason of a deal, then you will find your SL and TP deals.

Deals correlate to orders as orders are "wishes" for changes to positions.

They can be/are interlinked with each other.

Find the position identifiers, they are consistent through out all corresponding orders and deals.


I hope this helps.
 
Dominik Egert:
Ok.

Things are complicated when we do not understand. It is not MQ making it hard. It's the general understanding.

Positions - Orders - Deals.

Take the words in their meanings.

Orders are placed. Deals are execute results. Positions are the "managed objects"

So you are searching for deals. Search for the reason of a deal, then you will find your SL and TP deals.

Deals correlate to orders as orders are "wishes" for changes to positions.

They can be/are interlinked with each other.

Find the position identifiers, they are consistent through out all corresponding orders and deals.


I hope this helps.


No did not help.

What do you mean, must one search in Orders History instead of Deals History? If yes i did try that and it showed me 0 for Orders History.

If you want show a example how you would read the Takeprofit and Stoploss of closed tardes and i will test it.

 

The script Print Closed Position might help you.

https://www.mql5.com/en/code/32330


or the other script Export Deals History V1

https://www.mql5.com/en/code/24608

Print Closed Position
Print Closed Position
  • www.mql5.com
Print info about a closed position by its position ticket or identifier.
 

Haha. 

OK. Let me try.

void OnTrade()
{
    // Preinit execution state

        const   datetime    time_current                = TimeCurrent();
        static  datetime    on_trade_last_call          = time_current - PeriodSeconds(LIB_USER_INPUT(CustomTimeframe));


    // Update history select scope

        if(!HistorySelect(on_trade_last_call - PeriodSeconds(LIB_USER_INPUT(CustomTimeframe)), time_current))
        { return; }


    // Local storage

        const int       positions_total                 = PositionsTotal();
        const int       orders_total                    = OrdersTotal();
        const int       hist_orders_total               = HistoryOrdersTotal();
        const int       deals_total                     = HistoryDealsTotal();
        const int       history_orders_last             = hist_orders_total - 1;


    // Permanent storage

        static datetime last_deal_processed_timestamp   = NULL;
        static datetime last_history_deal_processed_ts  = NULL;
        static ulong    former_positions_total          = NULL;
        static ulong    former_orders_total             = NULL;
        static ulong    former_history_orders_total     = NULL;
        static ulong    former_history_deals_total      = NULL;


    // Precheck state

        if( (former_positions_total != positions_total)
         || (former_orders_total != orders_total)
         || (former_history_orders_total != hist_orders_total)
         || (former_history_deals_total != deals_total)
         || (history_orders_last < hist_orders_total)
         || (lib_fw::global_pending_server_requests > NULL))
        {
            former_positions_total = positions_total;
            former_orders_total = orders_total;
            former_history_orders_total = hist_orders_total;
            former_history_deals_total = deals_total;
        }
        else
        { return; }



    //////////////////////////////////////
    //
    //  Evaluate current history state
    //
    //  Get first newly added entry
    //  Find open position, if exists
    //


    // Local init

        ulong   recent_history_deal_ticket              = NULL;
        int     pos_cnt                                 = NULL;
        bool    history_altered                         = false;


    // Find first new entry in deal history

        while( (pos_cnt < deals_total)
            && ( (last_deal_processed_timestamp >= HistoryDealGetInteger(HistoryDealGetTicket(pos_cnt), DEAL_TIME)) || (LIB_MAGIC_ID != HistoryDealGetInteger(HistoryDealGetTicket(pos_cnt), DEAL_MAGIC)) )
            && !_StopFlag)
        { pos_cnt++; }
        last_deal_processed_timestamp = (datetime)HistoryDealGetInteger(HistoryDealGetTicket(pos_cnt), DEAL_TIME);


    // Evaluate result

        if(pos_cnt < deals_total)
        {
            // Update timer
            on_trade_last_call = time_current;

            // Get ticket from history
            recent_history_deal_ticket = HistoryDealGetTicket(pos_cnt);
            if(recent_history_deal_ticket == NULL)
            { return; }

            history_altered = true;
        }


    // History has not changed

        if(!history_altered)
        { return; }



    //////////////////////////////////////
    //
    //  Dispatch
    //
    //  Dispatch all changes in
    //  chronological order.
    //


    // Local init

        ulong   order_state                             = (ulong)EMPTY_VALUE;
        ulong   pos_id                                  = (ulong)EMPTY_VALUE;
        ulong   history_deal_ticket                     = (ulong)EMPTY_VALUE;
        ulong   current_position_ticket                 = (ulong)EMPTY_VALUE;
        bool    found                                   = false;


    // Check for multiple history elements

        while((pos_cnt < deals_total) && !_StopFlag)
        {

            // Loop control block

                // Select next unprocessed deal
                history_deal_ticket = HistoryDealGetTicket(pos_cnt);
                if( (history_deal_ticket == NULL)
                 || (!HistoryDealSelect(history_deal_ticket)))
                { pos_cnt++; continue; }

                // Track ticket processing state
                if(last_history_deal_processed_ts <= HistoryDealGetInteger(history_deal_ticket, DEAL_TIME))
                { last_history_deal_processed_ts = (datetime)HistoryDealGetInteger(history_deal_ticket, DEAL_TIME); }
                else
                { pos_cnt++; continue; }


            // Check open positions

                // Initialize state
                current_position_ticket = NULL;
                found                   = false;
                pos_id                  = HistoryDealGetInteger(history_deal_ticket, DEAL_POSITION_ID);

                // Identify corresponding position
                for(int cnt = 0; (cnt < positions_total) && !_StopFlag && !found; cnt++)
                {
                    // Select current ticket
                    current_position_ticket = PositionGetTicket(cnt);
                    PositionSelectByTicket(current_position_ticket);

                    // Evaluate history
                    found = (PositionGetInteger(POSITION_IDENTIFIER) == pos_id);
                }

                // Check result
                if(!found)
                { current_position_ticket = (ulong)EMPTY_VALUE; }



            // Deal processing

                // Local init
                found = false;

                // Identify order and get its state
                for(int cnt = 0; (cnt <= history_orders_last) && !_StopFlag && !found; cnt++)
                {
                    // Select order and check result
                    if(!HistoryOrderSelect(HistoryOrderGetTicket(history_orders_last - cnt)))
                    { continue; }

                    // Check if this is the corresponding open position to this order
                    if(HistoryOrderGetInteger(HistoryOrderGetTicket(history_orders_last - cnt), ORDER_POSITION_ID) == pos_id)
                    {
                        // Query order state
                        found = HistoryOrderGetInteger(HistoryOrderGetTicket(history_orders_last - cnt), ORDER_STATE, order_state);
                    }
                }

                // Check result
                if(!found)
                { order_state = (ulong)EMPTY_VALUE; }


            // Call OnTradeHandler


                //  Call internal handler
                OnTradeHandler(order_state, pos_id, history_deal_ticket, current_position_ticket);


            // Increase pos_cnt
            pos_cnt++;
        }


        // Return
        return;
}


void OnTradeHandler(const ulong order_state, const ulong pos_id, const ulong history_deal_ticket, const ulong current_position_ticket)
{
    // Evaluate deal reason

        const ENUM_DEAL_REASON deal_reason = (ENUM_DEAL_REASON)HistoryDealGetInteger(history_deal_ticket, DEAL_REASON);


    // Select by state

        switch((uint)order_state)
        {
            // An order has been added
            case ORDER_STATE_STARTED:
            case ORDER_STATE_PLACED:

            // An order has been updated
            case ORDER_STATE_PARTIAL:
            case ORDER_STATE_FILLED:


                // Evaluate deal reason

                    switch(deal_reason)
                    {
                        case DEAL_REASON_SL:
                        case DEAL_REASON_TP:
                        case DEAL_REASON_EXPERT:

                                                        //* [ Some code here ] *//


                            break;
                    }


                // Order handler


                                        //* [ Some code here ] *//
                

                    // Exit success
                    break;


                        // Cancelled handlers
                        case ORDER_STATE_CANCELED:
                        case ORDER_STATE_REJECTED:
                        case ORDER_STATE_EXPIRED:
                        case ORDER_STATE_REQUEST_MODIFY:

                                // Evaluate deal reason

                                        switch(deal_reason)
                                        {
                                                case DEAL_REASON_EXPERT:

                                                        //* [ Some code here ] *//

                                                        break;
                                        }


                        // Unhandled 
                        case ORDER_STATE_REQUEST_ADD:
                        case ORDER_STATE_REQUEST_CANCEL:                        
                        default:

        }


    // Return
    return;
};


No guarantee. Ive just extracted this code from my current EA and removed all the error ahndling as wel las all the function calls to further processing.

It should give you at least an understanding of how you can approach your "issue"


Have fun.

 

Ok guys, that was clear that nobody will be able to show a simple solution like it can be done with mt4, i dont understand the mind of this metaquotes people how they can make so easy things so complicate no wonder that most people dont want to use mt5, if they would have make mt5 so easy to use like mt4 years ago everybody would have use mt5

ok this script maybe can show something:  Export Deals History V1 

i will try out when i have time again

 
Email Account:

Ok guys, that was clear that nobody will be able to show a simple solution like it can be done with mt4, i dont understand the mind of this metaquotes people how they can make so easy things so complicate no wonder that most people dont want to use mt5, if they would have make mt5 so easy to use like mt4 years ago everybody would have use mt5

ok this script maybe can show something:  Export Deals History V1 

i will try out when i have time again

Well, you know, its always the same. People like you make me get up from my couch, interrupt my evening so I can provide you with a solution and all you are up to is keeping complaining about how bad your life is.


In fact, Ive provided you a solution, you could easily integrate into your code and still not even capable of a simple, thank you.

it states clearly //* Some code here *// 

But i guess its not satisfactory to not complain, is it.

Have a nice evening.

 

Try this I use like that.

void _stopLoseTakeprofitCheck()

{



//--- request trade history

   HistorySelect(0,TimeCurrent());
//--- create objects
  
   uint     total=HistoryDealsTotal();
   ulong    ticket=0;
   double   price;
   string   symbol;
   long     type;
   long     entry;
   string _comment;
   string direction;
   string _result;
//--- for all deals
   for(uint i=0;i<total;i++)
     {
      //--- try to get deals ticket
      if((ticket=HistoryDealGetTicket(i))>0)
        {
         //--- get deals properties
         price =HistoryDealGetDouble(ticket,DEAL_PRICE);
         time  =(datetime)HistoryDealGetInteger(ticket,DEAL_TIME);
         symbol=HistoryDealGetString(ticket,DEAL_SYMBOL);
         type  =HistoryDealGetInteger(ticket,DEAL_TYPE);
         entry =HistoryDealGetInteger(ticket,DEAL_ENTRY);
         profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);
          _comment =HistoryDealGetString(ticket,DEAL_COMMENT);
         
         if(type==0)
           {
            direction = "Buy";
           }
           if(type==1)
           {
            direction = "Sell";
           }
           if( _comment[1]!=NULL && _comment [1]==115) // it returns ASCI character 115 it means "S"  Comment [SL 1.3746"]
           {
            _result = "SL";
           }
           if( _comment[1]!=NULL && _comment [1]==116)  //it returns ASCI character 115 it means "T"  Comment [TP 1.3799"]
           {
            _result = "TP";
           }
           /*----------------------------------------------------------------------------------------------------------------------+

          if( _comment[1]==NULL )  //it returns NULL and it meaning of the position was closed as manualy or by EA. 
           {
            _result = " "; // 
           }
          */  ---------------------------------------------------------------------------------------------------------------------------+
         //--- only for current symbol
         if(symbol==Symbol())
           {
             
              Alert(Symbol()+ " ___ " + ticket+ "____"+ direction +"________ " + _result  + " _____" " ______ :" +price);
             
           }
        }
     }

}
 

ENUM_DEAL_PROPERTY_DOUBLE

Identifier

Description

Type

DEAL_VOLUME

Deal volume

double

DEAL_PRICE

Deal price

double

DEAL_COMMISSION

Deal commission

double

DEAL_SWAP

Cumulative swap on close

double

DEAL_PROFIT

Deal profit

double

DEAL_FEE

Fee for making a deal charged immediately after performing a deal

double

DEAL_SL

Stop Loss level

  • Entry and reversal deals use the Stop Loss values from the original order based on which the position was opened or reversed
  • Exit deals use the Stop Loss of a position as at the time of position closing

double

DEAL_TP

Take Profit level

  • Entry and reversal deals use the Take Profit values from the original order based on which the position was opened or reversed
  • Exit deals use the Take Profit value of a position as at the time of position closing

double

.
Reason: