Coding help - page 707

 

Dear pro-coders,

I would like to implement "four trades per day / stop trading if Profit Target is reached" feature into my EA.

If the maximum trade limit / profit is reached the EA should wait until the next day to continue trading. 

I wonder if someone could review my code, I have a bit of a "brain freeze" here, so the code

is kind of pseudo code state... ;-)

Thank you in advance! 

  

extern int    MaxShortTrades   = 2;
extern int    MaxLongTrades    = 2;
extern double profitTarget     = 300; // Target in Money

// Count Trades per Day.

   int y;
   int totalOrders = 4;
   datetime toT; // Time of Trade
   datetime doT; // Day of Trade
   datetime now = TimeCurrent();
   datetime boD=now-now%86400; // Beginning of day

 

if (AccountProfit()>= profitTarget)

{

 

for(y=0;y<totalOrders; y++)
     {

      if(OrderSelect(y,SELECT_BY_POS,MODE_HISTORY))
        {
         toT=OrderOpenTime(); // Time of Trade
         doT=toT-toT%86400; // Day of Trade.
         if(doT==boD)
           { // Time of Trade within Current Day.

            for(j=OrdersTotal()-1;j>=0; j--)
              {
               if(OrderType()==OP_BUY)  totalOrders++;  // Check # of long trades.
               if(OrderType()==OP_SELL) totalOrders++; // Check # of short trades
              }

           }
        }
     }


   if(totalOrders<MaxLongTrades  &&  Indicator_LONG_signal) Order=SIGNAL_BUY;
   if(totalOrders<MaxShortTrades && Indicator_SHORT_signal) Order=SIGNAL_SELL;
 
mladen:

In order to check both history (for orders closed at the current day) and opened orders, try like this :

   datetime today = StringToTime(TimeToString(TimeCurrent(),TIME_DATE));
   int totalOrdersLong  = 0, totalOrdersShort = 0;  
      for(int y=OrdersHistoryTotal()-1;y>=0; y--)
      {
         if (OrderSelect(y,SELECT_BY_POS,MODE_HISTORY))
         if (OrderCloseTime()>=today)
         {
            if (OrderType()==OP_BUY)   totalOrdersLong++;
            if (OrderType()==OP_SELL)  totalOrdersShort++;
         }        
      }
      for(int y=OrdersTotal()-1;y>=0; y--)
      {
         if (OrderSelect(y,SELECT_BY_POS,MODE_TRADES))
         if (OrderOpenTime()>=today)
         {
            if (OrderType()==OP_BUY)   totalOrdersLong++;
            if (OrderType()==OP_SELL)  totalOrdersShort++;
         }        
      }

   if(totalOrdersLong <MaxLongTrades  && Indicator_LONG_signal) Order=SIGNAL_BUY;
   if(totalOrdersShort<MaxShortTrades && Indicator_SHORT_signal) Order=SIGNAL_SELL;  

Hi Mladen,

thank you very much for your help, now it has become clearer about how to handle this.

Would it be also possible to check for a "daily profit target"?  Lets say the EA should go for 50.- EUR per day,

if the target per day is reached, it shall stop trading and continue the next day....

 

Something probably like this:

 

extern double profitTarget=50; // Profit Target in money

if (AccountProfit()<= profitTarget)

{
datetime today = StringToTime(TimeToString(TimeCurrent(),TIME_DATE));
   int totalOrdersLong  = 0, totalOrdersShort = 0;  
      for(int y=OrdersHistoryTotal()-1;y>=0; y--)
      {
         if (OrderSelect(y,SELECT_BY_POS,MODE_HISTORY))
         if (OrderCloseTime()>=today)
         {
            if (OrderType()==OP_BUY)   totalOrdersLong++;
            if (OrderType()==OP_SELL)  totalOrdersShort++;
         }        
      }
      for(int y=OrdersTotal()-1;y>=0; y--)
      {
         if (OrderSelect(y,SELECT_BY_POS,MODE_TRADES))
         if (OrderOpenTime()>=today)
         {
            if (OrderType()==OP_BUY)   totalOrdersLong++;
            if (OrderType()==OP_SELL)  totalOrdersShort++;
         }        
      }

   if(totalOrdersLong <MaxLongTrades  && Indicator_LONG_signal) Order=SIGNAL_BUY;
   if(totalOrdersShort<MaxShortTrades && Indicator_SHORT_signal) Order=SIGNAL_SELL;  
}

// Check if Profit Targer for the day is reached, so close all open Opsitions

if (AccountProfit()>= profitTarget)

{
if(OrderSelect(buy_ticket,SELECT_BY_TICKET))
                    {
                     dummyResult=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage*PipMultiplier,MediumSeaGreen);
                     Print("Error closing Buy #",(string)OrderTicket()," Error code ",(string)GetLastError());
                    }
                 }
               else

              if(Order==SIGNAL_CLOSESELL && sell_ticket!=0)
                 {
                  if(OrderSelect(sell_ticket,SELECT_BY_TICKET))
                    {
                     dummyResult=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage*PipMultiplier,DarkOrange);
                     Print("Error closing Sell #",(string)OrderTicket()," Error code ",(string)GetLastError());
                    }
}
 
tfi_markets:

Hi Mladen,

thank you very much for your help, now it has become clearer about how to handle this.

Would it be also possible to check for a "daily profit target"?  Lets say the EA should go for 50.- EUR per day,

if the target per day is reached, it shall stop trading and continue the next day....

 

Something probably like this:

 

extern double profitTarget=50; // Profit Target in money

if (AccountProfit()<= profitTarget)

{
datetime today = StringToTime(TimeToString(TimeCurrent(),TIME_DATE));
   int totalOrdersLong  = 0, totalOrdersShort = 0;  
      for(int y=OrdersHistoryTotal()-1;y>=0; y--)
      {
         if (OrderSelect(y,SELECT_BY_POS,MODE_HISTORY))
         if (OrderCloseTime()>=today)
         {
            if (OrderType()==OP_BUY)   totalOrdersLong++;
            if (OrderType()==OP_SELL)  totalOrdersShort++;
         }        
      }
      for(int y=OrdersTotal()-1;y>=0; y--)
      {
         if (OrderSelect(y,SELECT_BY_POS,MODE_TRADES))
         if (OrderOpenTime()>=today)
         {
            if (OrderType()==OP_BUY)   totalOrdersLong++;
            if (OrderType()==OP_SELL)  totalOrdersShort++;
         }        
      }

   if(totalOrdersLong <MaxLongTrades  && Indicator_LONG_signal) Order=SIGNAL_BUY;
   if(totalOrdersShort<MaxShortTrades && Indicator_SHORT_signal) Order=SIGNAL_SELL;  
}

// Check if Profit Targer for the day is reached, so close all open Opsitions

if (AccountProfit()>= profitTarget)

{
if(OrderSelect(buy_ticket,SELECT_BY_TICKET))
                    {
                     dummyResult=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage*PipMultiplier,MediumSeaGreen);
                     Print("Error closing Buy #",(string)OrderTicket()," Error code ",(string)GetLastError());
                    }
                 }
               else

              if(Order==SIGNAL_CLOSESELL && sell_ticket!=0)
                 {
                  if(OrderSelect(sell_ticket,SELECT_BY_TICKET))
                    {
                     dummyResult=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage*PipMultiplier,DarkOrange);
                     Print("Error closing Sell #",(string)OrderTicket()," Error code ",(string)GetLastError());
                    }
}

Why don't you add some profit collecting (summing) in the loop that is checking for currently opened long and short orders number

Something like this :


      double profitSoFarLong=0,profitSoFarShort=0;  
      for(int y=OrdersTotal()-1;y>=0; y--)
      {
         if (OrderSelect(y,SELECT_BY_POS,MODE_TRADES))
         if (OrderOpenTime()>=today)
         {
            if (OrderType()==OP_BUY)   { totalOrdersLong++;  profitSoFarLong  += OrderProfit()+OrderCommission()+OrderSwap(); }
            if (OrderType()==OP_SELL)  { totalOrdersShort++; profitSoFarShort += OrderProfit()+OrderCommission()+OrderSwap(); }
         }        
      }

And then you can use profitSoFarLong and profitSoFarShort for further control


PS:  if you want to have the total (for closed and opened orders), similar code addition can be added to the already closed orders too)

 

Hi Mladen,

You have fixed the "AutoFiboAutoTrend" indicator for me and it works well. Would it be possible to add an audio alert with notification when the direction of the fibo changes from "up" to "down"? Pls see the images 1 + 2

Thank you Lea

Files:
Fibo 1.jpg  19 kb
Fibo 2.jpg  45 kb
 
mladen:

Why don't you add some profit collecting (summing) in the loop that is checking for currently opened long and short orders number

Something like this :


      double profitSoFarLong=0,profitSoFarShort=0;  
      for(int y=OrdersTotal()-1;y>=0; y--)
      {
         if (OrderSelect(y,SELECT_BY_POS,MODE_TRADES))
         if (OrderOpenTime()>=today)
         {
            if (OrderType()==OP_BUY)   { totalOrdersLong++;  profitSoFarLong  += OrderProfit()+OrderCommission()+OrderSwap(); }
            if (OrderType()==OP_SELL)  { totalOrdersShort++; profitSoFarShort += OrderProfit()+OrderCommission()+OrderSwap(); }
         }        
      }

And then you can use profitSoFarLong and profitSoFarShort for further control


PS:  if you want to have the total (for closed and opened orders), similar code addition can be added to the already closed orders too)

Hi Mladen,

thank you very much for you help!

I have implemented the code like this:

// Trades per Day and Profit Target

   datetime today = StringToTime(TimeToString(TimeCurrent(),TIME_DATE));
   int totalOrdersLong  = 0, totalOrdersShort = 0;  
   int x;
      for(x=OrdersHistoryTotal()-1;x>=0; x--)
      {
         if (OrderSelect(x,SELECT_BY_POS,MODE_HISTORY))
         if (OrderCloseTime()>=today)
         {
            if (OrderType()==OP_BUY)   totalOrdersLong++;
            if (OrderType()==OP_SELL)  totalOrdersShort++;
         }        
      }
      for(x=OrdersTotal()-1;x>=0; x--)
      {
         if (OrderSelect(x,SELECT_BY_POS,MODE_TRADES))
         if (OrderOpenTime()>=today)
         {
            if (OrderType()==OP_BUY)   totalOrdersLong++;
            if (OrderType()==OP_SELL)  totalOrdersShort++;
         }            
      
      }
      
   double profitSoFarLong=0,profitSoFarShort=0;  
      for(x=OrdersTotal()-1;x>=0; x--)
      {
         if (OrderSelect(x,SELECT_BY_POS,MODE_TRADES))
         if (OrderOpenTime()>=today)
         {
            if (OrderType()==OP_BUY)   { totalOrdersLong++;  profitSoFarLong  += OrderProfit()+OrderCommission()+OrderSwap(); }
            if (OrderType()==OP_SELL)  { totalOrdersShort++; profitSoFarShort += OrderProfit()+OrderCommission()+OrderSwap(); }
         }        
      }
  
// EA STOP if Profit is Reached.

if (profitSoFarLong>50 || profitSoFarLong>50)
{
            if(OrderType()==OP_BUY)  { dummyResult = OrderClose(OrderTicket(),OrderLots(),MarketInfo(s_symbol,MODE_ASK),0,CLR_NONE); }
            if(OrderType()==OP_SELL) { dummyResult = OrderClose(OrderTicket(),OrderLots(),MarketInfo(s_symbol,MODE_BID),0,CLR_NONE); }

      Print ("Account Profit Reached. All Open Trades Have Been Closed");
      return(0);
  
   Sleep(3600); // one hour

}
 
Rajiv:
please help me mladen. SLIPPAGE  is  not working in attached  EA

Rajiv

Slippage is at its correct place in the OrderSend() calls - try using some bigger value and test it then, since the code usage of it is OK

 

Please help me... It possible write to .csv file every "Close" whith all exporting  means 
in code this indicator
 

void RSI_output(string SymbolName,int PeriodMinutes)

{

   int size=iBars(SymbolName,PeriodMinutes);                                      if(size==0)  return;

   int handle=FileOpen(SymbolName+PeriodMinutes+"_RSI.csv",FILE_WRITE|FILE_CSV);  if (handle<0)return;


   FileWrite(handle,"Time seconds;Time;Open;Low;High;Close;Volume;RSI");

   for (int i=size-1;i>=0;i--)

      {

        FileWrite(handle,iTime(SymbolName,PeriodMinutes,i),TimeToStr(iTime(SymbolName,PeriodMinutes,i))

,iOpen(SymbolName,PeriodMinutes,i),iLow(SymbolName,PeriodMinutes,i),iHigh(SymbolName,PeriodMinutes,i)

,iClose(SymbolName,PeriodMinutes,i),iVolume(SymbolName,PeriodMinutes,i),iCustom(SymbolName,PeriodMinutes,"RSI",0,i));

      }

   FileClose(handle);      

   return;

}

int start() { RSI_output(_Symbol,_Period); return(0); }

 I want to save to .csv file every "close"  without hovering and the update file again. Just finishing a file on one line .. every minute, for example))))))) PLEASE PLEASE PLEASE. Give me working instrument for interaction whith R. 

 
kostumer27:

Please help me... It possible write to .csv file every "Close" whith all exporting  means 
in code this indicator
 

void RSI_output(string SymbolName,int PeriodMinutes)

{

   int size=iBars(SymbolName,PeriodMinutes);                                      if(size==0)  return;

   int handle=FileOpen(SymbolName+PeriodMinutes+"_RSI.csv",FILE_WRITE|FILE_CSV);  if (handle<0)return;


   FileWrite(handle,"Time seconds;Time;Open;Low;High;Close;Volume;RSI");

   for (int i=size-1;i>=0;i--)

      {

        FileWrite(handle,iTime(SymbolName,PeriodMinutes,i),TimeToStr(iTime(SymbolName,PeriodMinutes,i))

,iOpen(SymbolName,PeriodMinutes,i),iLow(SymbolName,PeriodMinutes,i),iHigh(SymbolName,PeriodMinutes,i)

,iClose(SymbolName,PeriodMinutes,i),iVolume(SymbolName,PeriodMinutes,i),iCustom(SymbolName,PeriodMinutes,"RSI",0,i));

      }

   FileClose(handle);      

   return;

}

int start() { RSI_output(_Symbol,_Period); return(0); }

 I want to save to .csv file every "close"  without hovering and the update file again. Just finishing a file on one line .. every minute, for example))))))) PLEASE PLEASE PLEASE. Give me working instrument for interaction whith R. 

You mean on every new bar?
 
Yes. the history of what is on the schedule + 1 bar (& my iCustom indicators). just ask without rewriting the file forever.
Stable file + each bar ))) All =)
 
kostumer27:
Yes. the history of what is on the schedule + 1 bar (& my iCustom indicators). just ask without rewriting the file forever.
Stable file + each bar ))) All =)

Here is a version that has an option - should it rewrite the old data file or should it always create a new file for each new bar

#property indicator_chart_window
#property indicator_buffers 0

extern bool RewriteOldData=true;
void RSI_output(string symbolName,int PeriodMinutes, datetime time)
{
   string name = (RewriteOldData) ? symbolName+PeriodMinutes : symbolName+PeriodMinutes+(string)(time/60);
   int size  =iBars(symbolName,PeriodMinutes);                if(size==0)  return;
   int handle=FileOpen(name+"_RSI.csv",FILE_WRITE|FILE_CSV);  if (handle<0)return;


   FileWrite(handle,"Time seconds;Time;Open;Low;High;Close;Volume;RSI");
   for (int i=size-1;i>=0;i--)
        FileWrite(handle,iTime(symbolName,PeriodMinutes,i),TimeToStr(iTime(symbolName,PeriodMinutes,i))
               ,iOpen(symbolName,PeriodMinutes,i),iLow(symbolName,PeriodMinutes,i),iHigh(symbolName,PeriodMinutes,i)
               ,iClose(symbolName,PeriodMinutes,i),iVolume(symbolName,PeriodMinutes,i),iCustom(symbolName,PeriodMinutes,"RSI",0,i));
   FileFlush(handle);              
   FileClose(handle);      
   return;

}
int start()
{
   static datetime lastTime=0;
               if (lastTime!=Time[0])  RSI_output(_Symbol,_Period,Time[0]);
                   lastTime= Time[0];
   return(0);
}

It is an indicator, and all you have to do is to set the RewriteOldData parameter and let it work

Files:
Reason: