DailyScalpingEAv1.0hATR01

Author: Skyline 2007
Price Data Components
Series array that contains open time of each barSeries array that contains open prices of each barSeries array that contains close prices for each bar
Orders Execution
It can change open orders parameters, due to possible stepping strategyChecks for the total of closed ordersIt Closes Orders by itself It automatically opens orders when conditions are reachedChecks for the total of open orders
Indicators Used
Indicator of the average true range
0 Views
0 Downloads
0 Favorites

Profitability Reports

GBP/USD Oct 2024 - Jan 2025
74.00 %
Total Trades 77
Won Trades 34
Lost trades 43
Win Rate 0.44 %
Expected payoff -54.62
Gross Profit 11907.00
Gross Loss -16113.00
Total Net Profit -4206.00
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
41.00 %
Total Trades 84
Won Trades 31
Lost trades 53
Win Rate 0.37 %
Expected payoff -80.49
Gross Profit 4749.00
Gross Loss -11510.00
Total Net Profit -6761.00
-100%
-50%
0%
50%
100%
DailyScalpingEAv1.0hATR01
//+-----------------------------------------------------------------------------+
//|                                                    Daily Scalping v1.0h.mq4 |
//|                                                                Skyline 2007 |
//|                                                                             |
//+-----------------------------------------------------------------------------+
#property copyright "Skyline 2007"
#property link      ""
#include <stdlib.mqh>

// v1.0  (07 Feb 2007) : Start Project 
// v1.0a (07 Feb 2007) : Add GMT_Shift variable
// v1.0b (16 Feb 2007) : Added MagicNumber routine based on pair and timeframe
// v1.0c (17 Feb 2007) : Added routine TotalOrders to count only active order related to current EA (Thanks to Vitalykk)
//                       Added routine OrdersLossInDay to control losses in the same day. Users have the option to change how much loss trade they want setting external variable MaxLossesTradesPerDay.
// v1.0d (19 Feb 2007) : Fixed bug that prevent , when an order was not dispatched, to open reverse trade correctly. 
//                       Handled the case of doji candle that EA now will ignore to determine the trend situation from last 3 candles.
// v1.0e (19 Feb 2007) : Fixed bug on CheckTrend for doji candle routine (Thanks to Vitalykk)
//                       Added function OrdersTakeProfit to avoid EA enter again the market until next day.
// v1.0f (07 Mar 2007) : Midnight order will be opened until 00:01
// v1.0g (09 Mar 2007) : Removed v1.0f limit about order opening.Introducing FirstOrderDone to handle the first order.
// v1.0h (20 Mar 2007) : Fixed error on SL and added comment in case of error opening order to better debug EA.
//                       Add global variables MidnightOrderOpened, TradeStatus to avoid losing variable values if recompile after EA is on chart.
//                       Add TrailingStop routine, if =0 Trailing is disable otherwise it will trail using TrailingStop pips.

//---- Definizione parametri esterni 
extern double    GMT_Shift              = 0;
extern int       HourToCloseOrders      = 17;
extern int       Fridayclose            = 22;
extern bool      SundayCandleExists     = true;
extern int       DaysToReverse          = 3;
extern double    Lots                   = 1.0; 
extern bool      UseMoneyManagement     = false;
extern int       Risk                   = 0;
extern int       Slippage               = 3;
extern int       MaxLossesTradesPerDay  = 2; 
extern double    ATR_Period             = 6;
extern double    StopLoss_ATR           = 0.7; 
extern double    TakeProfit_ATR         = 0.7;      
extern double    BreakEvenAfterPips_ATR = 0.7;
extern int       TrailingStopType       = 2;
extern int       TrailingStop           = 0;


//----- Definizione parametri interni 
// Definition Global Variable
// MidnightOrderOpened = 0 not assigned (first EA run), =1 order still to be opened, =2 order already opened
// TradeStatus         = 0 Trades disabled , = 1 Open only Buy orders , = 2 Open only Sell orders
static int TradeStatus = 0; //0 = Trades disabilitati , 1 = Solo Buy permessi, 2 = Solo Sell permessi 
int MagicNumber;
int BreakEvenAfterPips = 900;  
int TakeProfit         = 900;
int StopLoss           = 900; 

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
// int start()
//   {
//    string TradeMode,Temp;

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   string TradeMode,Temp;
   manageOpened(); // Happens at every tick.

    if ( Bars < 100 ) {
        return(0); 
     }
    
  
    double N = NormalizeDouble ((iATR(NULL,1440,ATR_Period,1)),Digits);
    double N2 = NormalizeDouble ((iATR(NULL,1440,ATR_Period,2)),Digits);
    
    if  (SundayCandleExists == true && DayOfWeek() == 1)
     {TakeProfit = NormalizeDouble((TakeProfit_ATR*N2)/Point,0);      //Where to take profit out at
      StopLoss = NormalizeDouble((StopLoss_ATR*N2)/Point,0);      //Stoploss
      BreakEvenAfterPips = NormalizeDouble((BreakEvenAfterPips_ATR*N2)/Point,0);         // When to move to B/E
      //TrailingStop = NormalizeDouble((TrailingStop_ATR*N2)/Point,0);
     }
    else 
     {TakeProfit = NormalizeDouble((TakeProfit_ATR*N)/Point,0);      //Where to take profit out at
      StopLoss = NormalizeDouble((StopLoss_ATR*N)/Point,0);      //Stoploss
      BreakEvenAfterPips = NormalizeDouble((BreakEvenAfterPips_ATR*N)/Point,0);         // When to move to B/E
      //TrailingStop = NormalizeDouble((TrailingStop_ATR*N)/Point,0);
     }
   // Calcola dimensione Lot in base all'Equity
   
   // Calcola dimensione Lot in base all'Equity
   if (UseMoneyManagement==true) Lots = CalcolaLot(Risk);   
   
   // Calcola MagicNumber a seconda della coppia e timeframe 
   MagicNumber = MagicFromSymbol();
    
   // Gestione variabile globale 
   GlobalVariable();
   
   // Attiva ordine alle 00:00 GMT 
   OpenOrderMidnight(Lots);
 
   // Controlla ordini chiusi in perdita
   OrdersLossInDay();
   
   // Controlla se TP è stato raggiunto 
   OrdersTakeProfit();
   
   // Attiva ordini successivi
   OpenNextOrders(Lots);
   
   // Chiude ordini allo scadere di HourToCloseOrders
   CloseAllOrders(HourToCloseOrders);
   
   // Effettua il TrailingStop
   TrailingStop();
    
   // Commenti

   if (GlobalVariableGet("TradeStatus_"+MagicNumber)         == 0) {TradeMode = "NONE";}
   if (GlobalVariableGet("TradeStatus_"+MagicNumber)         == 1) {TradeMode = "BUY";}
   if (GlobalVariableGet("TradeStatus_"+MagicNumber)         == 2) {TradeMode = "SELL";}
   if (GlobalVariableGet("MidnightOrderOpened_"+MagicNumber) == 0) {Temp      = "NOT ASSIGNED";}
   if (GlobalVariableGet("MidnightOrderOpened_"+MagicNumber) == 1) {Temp      = "TO BE OPENED";}
   if (GlobalVariableGet("MidnightOrderOpened_"+MagicNumber) == 2) {Temp      = "ALREADY OPENED";}
      
   Comment("\nDaily Scalping EA v1.0h (Skyline 2007)",
           "\nCompiled version on 20 Mar 2007 with ART MOD by C.E.O.",
           "\n\n---------------------------------------",
           "\nMagicNumber : ",MagicNumber,
           "\nMidnight Order : ",Temp,
           "\nNext Trade : ",TradeMode,  
           //"\nStopLevel : ",MarketInfo(Symbol(),MODE_STOPLEVEL), 
           //"\nMathMod(24+GMT_Shift,24) :",MathMod(24+GMT_Shift,24),
           //"\nMathMod(HourToCloseOrders+GMT_Shift,24) : ",MathMod(HourToCloseOrders+GMT_Shift,24),      
           "\n---------------------------------------");
           
   return(0);
  }
  
// ===== Routine per effettuare il trailing degli ordini =====
void TrailingStop()
{  int cnt,err;
   int total = TotalOrders();
   for(cnt=0;cnt<total;cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
       if(OrderType()==OP_BUY)   // long position is opened
           {
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if(Bid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-Point*TrailingStop)
                    {
                     if (OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green) == false)
                     {
                      err=GetLastError();
                      Print("error(",err,"): ",ErrorDescription(err));
                     }
                     else return(0);
                    }
                 }
               }
          } // if(OrderType()==OP_BUY)  
         else // go to short position
           {
            // check for trailing stop
            if(TrailingStop>0)  
              {             
               if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     if (OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red) == false)
                     {
                      err=GetLastError();
                      Print("error(",err,"): ",ErrorDescription(err));
                     }
                     else return(0);                     
                    }
                 }
               } // if(TrailingStop>0)  
           }// if(OrderType()==OP_BUY) 
     }  // for 
}

// ===== Routine per gestire variabile globale MidnightOrderOpened ===== //
void GlobalVariable()
{
  // Set Global Variable MidnightOrderOpened 
  if (GlobalVariableCheck("MidnightOrderOpened_"+MagicNumber)==false) 
  {
   GlobalVariableSet("MidnightOrderOpened_"+MagicNumber,0);
  }
  // Set Global Variable TradeStatus 
  if (GlobalVariableCheck("TradeStatus_"+MagicNumber)==false) 
  {
   GlobalVariableSet("TradeStatus_"+MagicNumber,0);
  }
}

// ===== Routine per controllare se il TP è stato raggiunto e disabilitare i trades =====
int OrdersTakeProfit()
{
 int total,cnt;
 int TradeWin=0;
 
 int hstTotal=OrdersHistoryTotal();
   
 for(cnt=0;cnt<hstTotal;cnt++)
 {
   OrderSelect(cnt, SELECT_BY_POS, MODE_HISTORY);
   if (OrderMagicNumber()==MagicNumber)
   {
    if (NormalizeDouble(OrderClosePrice(),Digits)==NormalizeDouble(OrderTakeProfit(),Digits) && TimeDay(OrderCloseTime())==Day()) TradeWin++;
   }  // if (OrderMagicNumber()==MagicNumber)
 }  // for 
 if ( TradeWin == 1 )  GlobalVariableSet("TradeStatus_"+MagicNumber,0); // disable trades
 //Print("TradeLoss = ",TradeLoss);
}

// ===== Routine per contare gli ordini chiusi in perdita nello stesso giorno =====
int OrdersLossInDay()
{
 int total,cnt;
 int TradeLoss=0;
 
 int hstTotal=OrdersHistoryTotal();
   
 for(cnt=0;cnt<hstTotal;cnt++)
 {
   OrderSelect(cnt, SELECT_BY_POS, MODE_HISTORY);
   if (OrderMagicNumber()==MagicNumber)
   {
    if (NormalizeDouble(OrderClosePrice(),Digits)==NormalizeDouble(OrderStopLoss(),Digits) && TimeDay(OrderCloseTime())==Day()) TradeLoss++;
   }  // if (OrderMagicNumber()==MagicNumber)
 }  // for 
 if ( TradeLoss == MaxLossesTradesPerDay ) GlobalVariableSet("TradeStatus_"+MagicNumber,0); // disable trades
 //Print("TradeLoss = ",TradeLoss);
}
  
// ===== Routine per chiudere tutti gli ordini =====
void CloseAllOrders(int Ora)
{
 int total,cnt;
 
 total = TotalOrders();
 
 if ( Hour()>=MathMod(Ora+GMT_Shift,24) )
 {
  GlobalVariableSet("TradeStatus_"+MagicNumber,0); // azzera variabile globale per non aprire più trade
  //FirstOrderDone = false;
  GlobalVariableSet("MidnightOrderOpened_"+MagicNumber,0);  
  for(cnt=0;cnt<total;cnt++)
  {
   OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
   if (OrderMagicNumber()==MagicNumber)
   {
    if (OrderType() == OP_BUY)  OrderClose(OrderTicket(),OrderLots(), Bid, Slippage, LimeGreen);
    if (OrderType() == OP_SELL) OrderClose(OrderTicket(),OrderLots(), Ask, Slippage, Red);
   }  // if (OrderMagicNumber()==MagicNumber)
  }  // for 
 } // if
}

// ===== Routine per aprire il primo ordine alle 00:00 GMT =====
void OpenOrderMidnight(double Lot)
{  int Ticket,Errore; 
   double SL,TP;
   int ActualSpread;
   
   RefreshRates();
    
   int Total = TotalOrders();
   
   if ( Total < 1                                                                           && // there's no order opened
        (Hour()>=MathMod(24+GMT_Shift,24) && Hour()<(HourToCloseOrders+GMT_Shift))          && // Hour is more than 00 GMT and less than HourToCloseOrders GMT
        GlobalVariableGet("MidnightOrderOpened_"+MagicNumber) <= 1                                       && // First Midnight Order has still to be opened
        DayOfWeek()>=1 && DayOfWeek()<=5 )                                                     // Days of week is between Mon..Fri
   {
   GlobalVariableSet("TradeStatus_"+MagicNumber,0); // azzera variabile globale 
      
   // Controlla BUY Order
   if (CheckTrend()=="BUY")
    {   
      
      // Controlla SL 
      if (StopLoss < MarketInfo(Symbol(),MODE_STOPLEVEL)) StopLoss = MarketInfo(Symbol(),MODE_STOPLEVEL);
      if (StopLoss == 0) SL = 0;
      else {SL = Ask-StopLoss*Point;}
      if (TakeProfit == 0) TP = 0;
      else {TP = Ask+TakeProfit*Point;}
      // Piazza l'ordine BUY
      Ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,SL,TP,"BUY ORDER",MagicNumber,0,Blue);
          
      if(Ticket<0)
      {
       Errore=GetLastError();
       Print(
             "ERROR ON BUY ORDER (",Errore,") : ",ErrorDescription(Errore)+
             " Lots :",Lots,
             " Ask :",DoubleToStr(Ask,Digits),
             " TP :",DoubleToStr(TP,Digits),
             " SL :",DoubleToStr(SL,Digits)
            ) ;
      } 
      else 
      {
       GlobalVariableSet("MidnightOrderOpened_"+MagicNumber,2); // Mark first order as already opened
       GlobalVariableSet("TradeStatus_"+MagicNumber,2);         // Next trade is a sell
       //Print("BUY ORDER OPENED AT ",DoubleToStr(Ask,Digits),
       //      " TP AT ",DoubleToStr(TP,Digits),
       //      " SL AT ",DoubleToStr(SL,Digits));
      } 
     } 
   }
   
   // Rileva ordini relativi a questa EA (thanks to Vitalykk)
   Total = TotalOrders(); 
   
//   if ( Total < 1 && Hour()>=MathMod(24+GMT_Shift,24) && FirstOrderDone == false && DayOfWeek()>=1 && DayOfWeek()<=5 ) 
   if ( Total < 1                                                                           && // there's no order opened
        (Hour()>=MathMod(24+GMT_Shift,24) && Hour()<(HourToCloseOrders+GMT_Shift))          && // Hour is more than 00 GMT and less than HourToCloseOrders GMT
        GlobalVariableGet("MidnightOrderOpened_"+MagicNumber) <= 1                                       && // First Midnight Order has still to be opened
        DayOfWeek()>=1 && DayOfWeek()<=5 )                                                     // Days of week is between Mon..Fri
   {
   
     // Controlla SELL Order
     if (CheckTrend()=="SELL")
     {
 
      // Setta SL 
      if (StopLoss < MarketInfo(Symbol(),MODE_STOPLEVEL)) StopLoss = MarketInfo(Symbol(),MODE_STOPLEVEL);
      if (StopLoss == 0) SL = 0;
      else {SL = Bid+StopLoss*Point;}
      if (TakeProfit == 0) TP = 0;
      else {TP = Bid-TakeProfit*Point;}
      
      // Piazza Ordine SELL       
      Ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,SL,TP,"SELL ORDER",MagicNumber,0,Blue);
         
      if(Ticket<0)
      {
       Errore=GetLastError();
       Print("ERROR ON SELL ORDER (",Errore,") : ",ErrorDescription(Errore),
             " Lots :",Lots,
             " Bid :",DoubleToStr(Bid,Digits),
             " TP :",DoubleToStr(TP,Digits),
             " SL :",DoubleToStr(SL,Digits)
            ) ;

      } 
      else
      {
       GlobalVariableSet("MidnightOrderOpened_"+MagicNumber,2); // Mark first order as already opened
       GlobalVariableSet("TradeStatus_"+MagicNumber,1);         // Next trade is Buy
       //Print("SELL ORDER OPENED AT ",DoubleToStr(Bid,Digits),
       //      " TP AT ",DoubleToStr(TP,Digits),
       //      " SL AT ",DoubleToStr(SL,Digits));       
      }
     }    
   }
}

// ===== Routine per aprire ordini durante la giornata al raggiungimento dello SL o TP =====
void OpenNextOrders(double Lot)
{  int Ticket,Errore; 
   double SL,TP;
   int ActualSpread;
   
   RefreshRates();

   int Total = TotalOrders();
   
   if ( Total < 1 && 
        Hour()<=MathMod(HourToCloseOrders+GMT_Shift,24) &&
        DayOfWeek()>=1 && DayOfWeek()<=5 ) 
   {
   // Controlla BUY Order
   if ( GlobalVariableGet("TradeStatus_"+MagicNumber) == 1 )
    {         
      // Controlla SL 
      if (StopLoss < MarketInfo(Symbol(),MODE_STOPLEVEL)) StopLoss = MarketInfo(Symbol(),MODE_STOPLEVEL);
      if (StopLoss == 0) SL = 0;
      else {SL = Ask-StopLoss*Point;}
      if (TakeProfit == 0) TP = 0;
      else {TP = Ask+TakeProfit*Point;}
      
      // Piazza l'ordine BUY
      Ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,SL,TP,"BUY ORDER",MagicNumber,0,Blue);    
         
      if(Ticket<0)
      {
       Errore=GetLastError();
       Print(
             "ERROR ON BUY ORDER REVERSE (",Errore,") : ",ErrorDescription(Errore)+
             " Lots :",Lots,
             " Ask :",DoubleToStr(Ask,Digits),
             " TP :",DoubleToStr(TP,Digits),
             " SL :",DoubleToStr(SL,Digits)
            ) ;
      }  
      else
      {
       GlobalVariableSet("TradeStatus_"+MagicNumber,2); // Prossimo trade è Sell 
      }
     } 
   }
  
   Total = TotalOrders();
   if ( Total < 1 && 
        Hour()<=MathMod(HourToCloseOrders+GMT_Shift,24) &&
        DayOfWeek()>=1 && DayOfWeek()<=5 ) 
   {  
     // Controlla SELL Order
     if ( GlobalVariableGet("TradeStatus_"+MagicNumber) == 2 )
     {
 
      // Setta SL 
      if (StopLoss < MarketInfo(Symbol(),MODE_STOPLEVEL)) StopLoss = MarketInfo(Symbol(),MODE_STOPLEVEL);
      if (StopLoss == 0) SL = 0;
      SL = Bid+StopLoss*Point;
      if (TakeProfit == 0) TP = 0;
      else TP = Bid-TakeProfit*Point;
      
      // Piazza Ordine SELL       
      Ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,SL,TP,"SELL ORDER",MagicNumber,0,Blue);
          
      if(Ticket<0)
      {
       Errore=GetLastError();
       Print("ERROR ON SELL ORDER REVERSE (",Errore,") : ",ErrorDescription(Errore),
             " Lots :",Lots,
             " Bid :",DoubleToStr(Bid,Digits),
             " TP :",DoubleToStr(TP,Digits),
             " SL :",DoubleToStr(SL,Digits)
            ) ;
      } 
      else
      {
       GlobalVariableSet("TradeStatus_"+MagicNumber,1); // Prossimo trade è Buy
      }
     }    
   }
}

// ===== Routine per controllare il trend ===== 
string CheckTrend()
{

 // Check 1 day ago candle
 int DaysShift = 1;
 string C1="NONE",C2="NONE",C3="NONE";
 //if ( SundayCandleExists == true && DayOfWeek() == 1 ) DaysShift++; // if today is Monday then skip the Sunday candle
 if (SundayCandleExists == true && TimeDayOfWeek(iTime(NULL,PERIOD_D1,DaysShift)) == 0)  DaysShift++; // if candle is Monday then skip Sunday candle
 if (iOpen(NULL,PERIOD_D1,DaysShift)==iClose(NULL,PERIOD_D1,DaysShift)) DaysShift++;
 if (iOpen(NULL,PERIOD_D1,DaysShift)<iClose(NULL,PERIOD_D1,DaysShift)) C1 = "BULLISH";
 if (iOpen(NULL,PERIOD_D1,DaysShift)>iClose(NULL,PERIOD_D1,DaysShift)) C1 = "BEARISH";
 // Print("C1_DaysShift = ",DaysShift); // for debug purpouse

 // Check 2 days ago candle
 DaysShift++;
 if (SundayCandleExists == true && TimeDayOfWeek(iTime(NULL,PERIOD_D1,DaysShift)) == 0)  DaysShift++; // if candle is Monday then skip Sunday candle
 if (iOpen(NULL,PERIOD_D1,DaysShift)==iClose(NULL,PERIOD_D1,DaysShift)) DaysShift++;
 if (iOpen(NULL,PERIOD_D1,DaysShift)<iClose(NULL,PERIOD_D1,DaysShift)) C2 = "BULLISH";
 if (iOpen(NULL,PERIOD_D1,DaysShift)>iClose(NULL,PERIOD_D1,DaysShift)) C2 = "BEARISH";
 //Print("C2_DaysShift = ",DaysShift); // for debug purpouse

 // Check 3 days ago candle
 DaysShift++;
 if (SundayCandleExists == true && TimeDayOfWeek(iTime(NULL,PERIOD_D1,DaysShift)) == 0) DaysShift++; // if candle is Monday then skip Sunday candle
 if (iOpen(NULL,PERIOD_D1,DaysShift)==iClose(NULL,PERIOD_D1,DaysShift)) DaysShift++;
 if (iOpen(NULL,PERIOD_D1,DaysShift)<iClose(NULL,PERIOD_D1,DaysShift)) C3 = "BULLISH";
 if (iOpen(NULL,PERIOD_D1,DaysShift)>iClose(NULL,PERIOD_D1,DaysShift)) C3 = "BEARISH";
 // Print("C3_DaysShift = ",DaysShift);
 
 // Print("C1 = ",C1," C2 = ",C2," C3 = ",C3); // for debug purpouse
 
 // BULLISH Condition
 if (
    (C1=="BULLISH" && C2=="BEARISH" && C3=="BULLISH") ||
    (C1=="BULLISH" && C2=="BULLISH" && C3=="BEARISH") ||
    (C1=="BULLISH" && C2=="BEARISH" && C3=="BEARISH") ||     
    (C1=="BEARISH" && C2=="BEARISH" && C3=="BEARISH")
    )
 return("BUY"); 
 
 // BEARISH Condition
 if (
     (C1=="BEARISH" && C2=="BULLISH" && C3=="BEARISH") ||
     (C1=="BEARISH" && C2=="BEARISH" && C3=="BULLISH") ||
     (C1=="BEARISH" && C2=="BULLISH" && C3=="BULLISH") ||
     (C1=="BULLISH" && C2=="BULLISH" && C3=="BULLISH")
    )   
 return("SELL");   
}

// ===== Routine per il calcolo del Lot nel caso di Money Management =====
double CalcolaLot(int Rischio)
{
  double Lot=0;
  Lot=AccountEquity()* Rischio/100/1000;
  if( Lot>=0.1 )
  {
    Lot = NormalizeDouble(Lot,1); 
  }
  else Lot = NormalizeDouble(Lot,2);
  if (Lot > MarketInfo(Symbol(),MODE_MAXLOT)) { Lot = MarketInfo(Symbol(),MODE_MAXLOT); } // Avoid possible Lot value overflow if lot exceed maximum value allowed by broker
  if (Lot < MarketInfo(Symbol(),MODE_MINLOT)) { Lot = MarketInfo(Symbol(),MODE_MINLOT); } // Avoid possible Lot value overflow if lot exceed minimum value allowed by broker
  return(Lot);
}

// ===== Routine per calcolare MagicNumber diverso per ogni coppia e periodo =====
int MagicFromSymbol() 
{ // included by Renato 
   int MagicNumber=0;  
   for (int i=0; i<5; i++) 
   {  
     MagicNumber=MagicNumber*3+StringGetChar(Symbol(),i);  
   }  
   MagicNumber=MagicNumber*3+Period();  
   return(MagicNumber);  
}

//+------------------------------------------------------------------+

//START MODIFY********************************************************




bool selectOrder(int pos)
{
    if ( ! OrderSelect( pos, SELECT_BY_POS ) )
        return( false );
    if ( OrderMagicNumber() != MagicNumber )
        return( false );
    return( OrderSymbol() == Symbol() );
}
void manageOpened()
{
    for ( int i = OrdersTotal() - 1; i >= 0; i-- ) {
        if ( ! selectOrder( i ) ) {
            continue;
        }
        if ( TrailingStop > 0 ) {
            subTrailingStop();
        }
        if ( BreakEvenAfterPips > 0 ) {
            subBreakEvenAfterPips();
        }
    }
}



void subTrailingStop()
{
    setTrailingStop(
        trailingStopStart( TrailingStopType ),
        trailingStopGap( TrailingStopType )
    );
}

double trailingStopStart(int type)
{
    switch ( type ) {
    case 1: return ( TrailingStop * Point );
    case 2: return ( 0 );
    case 3: return ( 0 );
    default: return ( trailingStopStart( 1 ) );
    }
}

double trailingStopGap(int type)
{
    switch ( type ) {
    case 1: return ( TrailingStop * Point );
    case 2: return ( TrailingStop * Point );
    case 3:
        if ( TrailingStop <= 0 )
            return( 0 );
        if ( OrderType() == OP_BUY )
            return( Bid - Low[ TrailingStop ] );
        if ( OrderType() == OP_SELL )
            return( High[ TrailingStop ] - Ask );
        return( 0 );
    default:
        return ( trailingStopGap( 1 ) );
    }
}

void setTrailingStop(double start,double gap)
{
    double price;
    int type = OrderType();
    double stop = OrderStopLoss();
    if ( stop == 0 )
        stop = OrderOpenPrice();
    if ( type == OP_BUY ) {
        //Print( "Trail? " + Bid + "," + stop + "+" + gap + "," + ( OrderOpenPrice() + start ) );
        if ( Bid > MathMax( stop + gap, OrderOpenPrice() + start ) ) {
            price = NormalizeDouble( Bid - gap, Digits );
            OrderModify( OrderTicket(), OrderOpenPrice(), price, OrderTakeProfit(), 0, Green );
        }
    } else if ( type == OP_SELL ) {
        if ( Ask < MathMin( stop - gap, OrderOpenPrice() - start ) ) {
            price = NormalizeDouble( Ask + gap, Digits );
            OrderModify( OrderTicket(), OrderOpenPrice(), price, OrderTakeProfit(), 0, Red );
        }
    }
}

//---------------------- BREAK EVEN FUNCTION
// Uses interactive configurations:
//    BreakEvenAfterPips = price gap required

void subBreakEvenAfterPips()
{
    if ( OrderType() == OP_BUY ) {
        if ( OrderStopLoss() >= OrderOpenPrice() - Point )
            return;
        if ( Bid <= OrderOpenPrice() + Point * BreakEvenAfterPips )
            return;
        OrderModify( OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, Green );
    } else if ( OrderType() == OP_SELL ) {
        if ( OrderStopLoss() > 0 && OrderStopLoss() <= OrderOpenPrice() + Point )
            return;
        if ( Ask >= OrderOpenPrice() - Point * BreakEvenAfterPips )
            return;
        OrderModify( OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, Red );
    }
}

// ===== Routine per calcolare quanti ordini aperti ci sono per questa EA ===== 
int TotalOrders()
{  
   int cnt; 
   int Total = 0;
   for(cnt=0;cnt<OrdersTotal();cnt++)
   {
    OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
    if (OrderMagicNumber()==MagicNumber) Total ++;
   }
  return(Total); 
}



//+------------------------------------------------------------------+

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---