Stop trading after reaching daily Profit/Loss

 

Hello everyone,


I am trying to code a function to return the accumulated daily Profit/Loss, but I cant make the code work. Can any guru here be so kind to help me? I Appreciate!


double ProfitAll(datetime& XHoraPrimeiroCandle, double& XProfit)
   {
   int err=0;
   if (IsFirstBar())
      {
      XHoraPrimeiroCandle = iTime(_Symbol,_Period,0);
      }

   HistorySelect(XHoraPrimeiroCandle,TimeCurrent());

   Comment("Hora: ",XHoraPrimeiroCandle,"Profit: ", XProfit);
   for(int i = HistoryDealsTotal()-1; i >= 0; i--)
      {
      ulong ticket = HistoryDealGetTicket(i);
      string symbol = HistoryDealGetString(ticket,DEAL_SYMBOL);
      ulong magic = HistoryDealGetInteger(ticket,DEAL_MAGIC);
      ulong order = HistoryDealGetInteger(ticket,DEAL_ORDER);
      long dealType = HistoryDealGetInteger(ticket,DEAL_ENTRY);
      long orderType = HistoryDealGetInteger(ticket,DEAL_TYPE);
      double profitAtual = HistoryDealGetDouble(ticket,DEAL_PROFIT);
      
      if(symbol == _Symbol && magic == magicNum && dealType == DEAL_ENTRY_OUT)
         {
         XProfit = XProfit + profitAtual;
         }
      else
         {
         Print("Falha em selecionar ordem");
         err = GetLastError();
         Print("Erro encontado ao selecionar ordem, erro número "+(string)err);
         }
      }      
   return XProfit;  
   }
 
Just looking at the code, there is nothing obvious. What is "not working" ?
 
Alain Verleyen:
Just looking at the code, there is nothing obvious. What is "not working" ?
Hey Alain. It is ERR_TRADE_DEAL_NOT_FOUND. I have changed the function a lot of different ways, but it just doesnt find any order in the history.
 
gustgdp:
Hey Alain. It is ERR_TRADE_DEAL_NOT_FOUND. I have changed the function a lot of different ways, but it just doesnt find any order in the history.

You run it on a Daily chart ?

      XHoraPrimeiroCandle = iTime(_Symbol,_Period,0);
 
Alain Verleyen:

You run it on a Daily chart ?

It is on the M5 chart.


For instance, this piece of code below returns:


History: 1, 2, 3, 4...according to number of items in history. The only item working well.

Ticket: 2 (and stays stuck at 2 from the first order)

Symbol: WDO@N (this one is also OK)

Order: 2 (same as ticket)

DealType: 0 (stuck)

OrderType: 1 (stuck)

Profit: 0 (stuck)



double ProfitAll(datetime& XHoraPrimeiroCandle, double& XProfit)
   {
   int err=0;
   if (IsFirstBar())
      {
      XHoraPrimeiroCandle = iTime(_Symbol,_Period,0);
      }

   HistorySelect(XHoraPrimeiroCandle,TimeCurrent());
 
   for(int i = HistoryDealsTotal()-1; i >= 0; i--)
      {
      long ticket = HistoryDealGetTicket(i);
      string symbol = HistoryDealGetString(ticket,DEAL_SYMBOL);
      long magic = HistoryDealGetInteger(ticket,DEAL_MAGIC);
      long order = HistoryDealGetInteger(ticket,DEAL_ORDER);
      double dealType = HistoryDealGetInteger(ticket,DEAL_ENTRY);
      double orderType = HistoryDealGetInteger(ticket,DEAL_TYPE);
      double profitAtual = HistoryDealGetDouble(ticket,DEAL_PROFIT);

  Comment("Hora: ",XHoraPrimeiroCandle,"\nHistory: ",HistoryDealsTotal(),"\nTicket: ",ticket,"\nSymbol: ",symbol,"\nOrder: ",order,"\nDealType: ",dealType,"\nOrderType: ",orderType,"\nProfit: ",profitAtual);


}
 

Hi guys I think this is related to this topic hope someone can help me out :)


I would like to set rules for my trading account.


Daily loss/gain limit setting

Example: Equity = €1000. If Equity hits €950 (-5%) all open positions close, all open orders get cancelled and no more positions can be opened on this trading day.

Once Equity cross €1025 (+2,5%) the daily loss limit loss moves to €1000 (+-0%)
Once Equity cross €1050 (+5%) daily loss limit moves to €1025 (+2,5%) and so forth until the max daily profit is reached with +25% resulting again in closing of all open positions and cancelling all open orders for this trading day.


Setting max. trades per timeframe

Limiting the opening of positions. Example 3 positions max each 30minutes.


p.s. I will give a nice tip for the one who can explain and help setting this up for me :)

 

hi i need  a code about daily trade limit. like in specific time range take only 1 trade.

 

This is my solution. I use it for Prop firms and works nice.

//+------------------------------------------------------------------+
//| Load Libraries                                                   |
//+------------------------------------------------------------------+
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>  
#include <Trade\AccountInfo.mqh>
#include <Trade\DealInfo.mqh>
#include <Trade\OrderInfo.mqh>

CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
CAccountInfo   m_account;                    // object of CAccountInfo class
CDealInfo      m_deal;                       // object of CDealInfo class
COrderInfo     m_order;                      // object of COrderInfo class

bool daily_profit_check = false;
input double DailyProfit_Target = 5; // Daily Profit Target (%)

int OnInit(){
        EventSetMillisecondTimer(100);//Control per 1 seconds
}

void OnDeinit(const int reason){
        EventKillTimer();
}

void OnTimer(){
        CheckDailyProfitTarget();//Check if the daily target is reached
}

void OnTick(){
        if(isNewDay() == true){//If new day, reset daily profit
                daily_profit_check = false;
        }

        if(daily_profit_check == false){
                //Your Custom signals
                //Robot will stop if daily profit is reached.
        }
}


//-------Custom Functions----------//
bool isNewDay(){
        bool newDay = false;
        MqlDateTime str_datetime;
        TimeToStruct(TimeCurrent(),str_datetime);
        static int prevday = 0;
        int currday = str_datetime.day;
   
        if(prevday == currday){
                newDay = false;
        }else if(prevday !=currday){
                prevday = currday;
                newDay = true;
        }
  
        return (newDay);
}

double Daily_Balance(){ // New Day's Balance
        double DailyBalance = AccountInfoDouble(ACCOUNT_BALANCE);
        double Res = 0;
   
        datetime starttime = iTime(Symbol(), PERIOD_D1, 0);
        if (HistorySelect(starttime, TimeCurrent()))
        {
                for (int i = HistoryDealsTotal() - 1; i >= 0; i--)
                {
                        ulong Ticket = HistoryDealGetTicket(i);
                        long entry =HistoryDealGetInteger(Ticket,DEAL_ENTRY);
                        if(Ticket && entry)
                        {
                                Res += HistoryDealGetDouble(Ticket, DEAL_PROFIT);
                                Res += HistoryDealGetDouble(Ticket, DEAL_COMMISSION);
                                Res += HistoryDealGetDouble(Ticket, DEAL_SWAP);
                        }
                }
        }
   
        if(Res != 0){
                DailyBalance = DailyBalance - Res;
        }

        return(DailyBalance);
}

void CheckDailyProfitTarget(){
        double equity = AccountInfoDouble(ACCOUNT_EQUITY);
        double last_balance = Daily_Balance();
        double ProfitPercent = (equity - last_balance) / last_balance*100;
   
        if(ProfitPercent>=DailyProfit_Target){
                if(PositionsTotal()>0){
                        CLOSE_ALL();
                        Print("Daily Profit Target is reached. ALL positions are closed. Robot is stopped."); 
                }
                if(OrdersTotal()>0){
                        DELETE_ORDERS();
                        Print("Daily Profit Target is reached. ALL pending orders are deleted. Robot is stopped."); 
                }
                daily_profit_check = true;// Daily Target is reached. 
        }

}
void CLOSE_ALL()
{
   for(int i=PositionsTotal()-1; i>=0; i--){
      if(m_position.SelectByIndex(i)){
         if(m_position.Symbol()==Symbol()){
            if(!m_trade.PositionClose(m_position.Ticket())){
               Print(__FILE__," ",__FUNCTION__,", ERROR: ","CTrade.PositionClose ",m_position.Ticket());
            }
         }
      }
   } 
}

void DELETE_ORDERS()
{
   for(int i=OrdersTotal()-1; i>=0; i--){
      if(m_order.SelectByIndex(i)){
         if(m_order.Symbol()==Symbol()){
            if(!m_trade.OrderDelete(m_order.Ticket())){
               Print(__FILE__," ",__FUNCTION__,", ERROR: ","CTrade.OrderDelete ",m_order.Ticket());
            }
         }
      }
   }  
}