escape2reversed-2-maxorders

Profit factor:
4.32

This script is designed to automatically trade currencies in the Forex market. Here's the breakdown of its logic:

1. Initial Setup (the "extern" part):

  • It starts by defining a set of customizable settings, like how much profit it should aim for ("TakeProfit"), how much loss it's willing to risk ("StopLoss"), the size of trades it should make ("Lots"), and whether it should reverse its trading logic ("reverseLogic"). These are the "knobs and dials" the user can adjust to tweak the robot's behavior.
  • It also sets up visual elements, like colors for buy and sell signals, and optional alerts like sounds.
  • A "magic number" is a unique identifier, like a license plate for the script, to help it manage its own trades and avoid interfering with trades placed manually or by other scripts.

2. Ongoing Monitoring and Action (the "start" part):

  • Trade Management: The script continuously checks all open trades on the currency pair it's attached to.
  • Profit Protection: If a trade is in profit, the script has a mechanism to potentially close it if the profit starts to decline significantly after reaching a high point. It does this by tracking how many times the profit decreases consecutively. If the profit dips too many times in a row, it assumes the trend is reversing and closes the trade to secure the existing profit.
  • Stop Loss Adjustment (Trailing Stop): The script can also automatically adjust the "StopLoss" order to protect profits as the price moves in a favorable direction. This is called a "trailing stop." As the price goes up for a buy trade (or down for a sell trade), the StopLoss is moved along with it, ensuring that if the price suddenly reverses, the trade will still close with a profit.
  • Checking Conditions to open a trade: It uses a moving average and its relation to the latest price to identify potential buying or selling opportunities. Moving averages smooth out price fluctuations and can indicate the overall trend.
  • Opening New Trades: If the conditions are met and there are no existing trades, the script opens a buy or sell trade based on the moving average analysis. The direction of the trade is determined by whether the "reverseLogic" setting is enabled.

3. Decision Making:

  • Buy or Sell?: The decision to buy or sell is based on the relationship between the current price and its moving averages, potentially inverted by a "reverseLogic" setting.
  • When to Close?: Trades are closed either when the stop loss is hit, or the profit retracement mechanism triggers a close to preserve gains.

4. Auxiliary functions:

  • ExistPositions(): It scans open trades to determine if the EA has already opened positions in the current symbol
  • TrailingPositionsBuy/Sell(): Manages trailing stops. It determines if the stop loss needs to be adjusted to lock in profits as the price moves in a favorable direction.
  • ModifyStopLoss(): Modifies the stop loss for an existing order.
  • OpenBuy/OpenSell(): Opens new buy or sell orders based on the determined parameters such as lot size, stop loss and take profit levels.
  • GetCommentForOrder/GetSizeLot/GetTakeProfitBuy/GetTakeProfitSell(): Used to retrieve the values that will be used when a new trade is opened, such as the comment, lot size, take profit level etc.

In essence, this script is a simple automated trading system that aims to identify trends using moving averages, open trades in the direction of those trends (or against them if reversed logic is set), protect profits with a trailing stop, and close trades if profit drops significantly. All based on user-defined parameters.

Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It can change open orders parameters, due to possible stepping strategyIt automatically opens orders when conditions are reached
7 Views
1 Downloads
0 Favorites
escape2reversed-2-maxorders
//+------------------------------------------------------------------+
//|                                                      robotic.mq4 |
//|                                    Copyright © 2008, OGUZ BAYRAM |
//|                                            es_cape77@hotmail.com |
//+------------------------------------------------------------------+
extern int       iTakeProfitCloseValue=30;
extern int       iTakeProfitMaxDecCount=30; 
extern int       maxtrades=10;

static bool      bTakeProfitPrevious=-1;
static int       iTakeProfitDecraeseCount=0;
static int       iTakeProfitMaxValue=-1;
extern double lTakeProfit = 10;
extern double sTakeProfit = 10;
extern double lTrailingStop = 15;
extern double sTrailingStop = 15;
extern color clOpenBuy = Blue;
extern color clCloseBuy = Aqua;
extern color clOpenSell = Red;
extern color clCloseSell = Violet;
extern color clModiBuy = Blue;
extern color clModiSell = Red;
extern string Name_Expert = "Robotic";
extern int Slippage = 1;
extern bool UseSound = false;

extern bool FractionalPips = true;
extern string NameFileSound = "Alert.wav";
extern double Lots = 0.1;
extern double StopLoss=100.0;

extern bool reverseLogic = true;
int magic_number = 013113324124;

void deinit() {
    Comment("");
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start(){

    double SL = StopLoss;
    int totalOrderCount=OrdersTotal();
    for(int pos=0;pos<totalOrderCount;pos++)
    {
        if( OrderSelect(pos,SELECT_BY_POS)==false ) continue;
        //orderý seçtik þu an
        if (OrderSymbol() == Symbol()) //bu satýr sadece ea'yý attýðýnýz grafiðin sembolündeki para ile açýlan emirleriniz üzerinde iþlem yapmak için konuldu
        { 
            if ( OrderProfit() > 0 )
            {


                //TAKE PROFÝT DÜÞMEYE BAÞLARSA KAPAT
                //eðer kârdaysak ve peþpeþe iTakeProfitMaxDecCount sayýsýndan daha çok düþüþ yaþamýþsak, (TP: 100, 90, 80, 70 gibi, burada 4 kez düþüþ oldu demektir) pozisyonu hiç gözünün yaþýna bakmadan kapatýr
                //fakat kapatabilmek için birde istenilen minimum deðeri geçmiþmi bakýyorum hesabý þöyle (Profit > iTakeProfitCloseValue * 7.0) isterseniz bu kýsýtý kaldýrýn if'den 
                
                if (OrderProfit()> iTakeProfitMaxValue)
                iTakeProfitMaxValue = OrderProfit();

                if (bTakeProfitPrevious > OrderProfit())
                iTakeProfitDecraeseCount = iTakeProfitDecraeseCount + 1;
                else if (bTakeProfitPrevious < OrderProfit())
                {
                    iTakeProfitDecraeseCount = iTakeProfitDecraeseCount - 1;
                    if (iTakeProfitDecraeseCount<0)
                    iTakeProfitDecraeseCount = 0;
                }
                //Print(Symbol()," TPCount: ",iTakeProfitDecraeseCount);
                bTakeProfitPrevious = OrderProfit();         
                
                if (( iTakeProfitMaxDecCount <= iTakeProfitDecraeseCount) && (OrderProfit() >= (iTakeProfitCloseValue * 7.0))  )
                {
                    bool cticket;
                    Print(Symbol()," P:",Period()," take profit ",iTakeProfitDecraeseCount," kez düþtü kapattýk. Fiyat:",Ask);
                    /*if ( OrderType() == OP_BUY )
            {  
                    Print(Symbol()," P:",Period()," take profit ",iTakeProfitDecraeseCount," kez düþtü kapattýk. Fiyat:",Ask);
                    cticket = OrderClose(OrderTicket(),OrderLots(),Ask,3,Yellow);                    
            }
            if ( OrderType() == OP_SELL )
            {  
                    Print(Symbol()," P:",Period()," take profit ",iTakeProfitDecraeseCount," kez düþtü kapattýk. Fiyat:",Bid);
                    cticket = OrderClose(OrderTicket(),OrderLots(),Bid,3,Yellow);                    
            }*/

                    //yeni close iþlemi
                    double Price=OrderOpenPrice();       
                    int Ticket=OrderTicket();         
                    double Lot=OrderLots();           

                    //artýk pozisyonu kapatmayý kafaya koyduk hemen kapatýyoruz ama bazen broker kapatmýyor istediðimiz yerden, 
                    //onun için 7 kez peþ peþe deniyoruz
                    int AttemptCount=0;
                    while(true)                                 
                    {
                        switch(OrderType())                       
                        {
                        case 0: double Price_Cls=Bid;
                            string Text="Buy ";       
                            break;                    
                        case 1: Price_Cls=Ask;       
                            Text="Sell ";             
                        }
                        //Print("Kapatmaya çalýþýyoruz ",Text," ",Ticket);
                        bool Ans=OrderClose(Ticket,Lot,Price_Cls,2);

                        if (Ans==true)                            // kapantý
                        {
                            Print("Kapattýk :) ",Text," ",Ticket," Attemp: ",AttemptCount);
                            break;                                 //while'ý kýrýyoruz
                        }

                        //hata var tekrar deneyelim
                        Sleep(300);                
                        RefreshRates();   
                        AttemptCount++;  
                        if (AttemptCount > 7) break;       
                        continue;                  
                    }//while
                }//kapatma if'inin sonu







                //BURALAR STOP LOSS AYAR ÝÞLEMLERÝ 
                //SL YOKSA KOYARMI BÝLMÝYORUM DENEMEDÝM :)), 
                //BURASI SL'yi eðer kârda ise pozisyon daha iyi yere taþýr sürekli olarak, böylece sert dönüþlerde daha az zarar görmemize yarar
                int temp = -1;
                if (OrderType() == OP_BUY)
                {
                    double ftemp = SL;               
                    if (Digits > 4)
                    {  
                        ftemp = ftemp*MathPow(100,(Digits-4));//  
                    } else {
                        ftemp = ftemp*MathPow(100,(4-Digits));//                    
                    }
                    
                    if ( OrderStopLoss() < (Bid-ftemp*Point) )
                    {
                        OrderModify(OrderTicket(),OrderOpenPrice(),Bid-ftemp*Point,OrderTakeProfit(),0,Blue);
                    }
                    
                    temp = GetLastError();
                    if (temp>0)
                    {
                        Print(Symbol()," P: ",Period(),", ORDER DEÐÝÞTÝ HATA - SL: ", Bid-ftemp*Point," Err: ",temp);
                    }            
                } else {
                    double ftemp2 = SL;
                    if (Digits > 4)
                    {  
                        ftemp2 = ftemp2*MathPow(100,(Digits-4));//  
                    } else {
                        ftemp2 = ftemp2*MathPow(100,(4-Digits));//                    
                    }
                    
                    
                    if (OrderStopLoss() > ( Ask+ftemp2*Point ))
                    OrderModify(OrderTicket(),OrderOpenPrice(),Ask+ftemp2*Point,OrderTakeProfit(),0,Blue);
                    
                    temp = GetLastError();
                    if (temp>0)
                    {
                        Print(Symbol()," P: ",Period(),", ORDER DEÐÝÞTÝ HATA - SL:", Ask+ftemp2*Point," Err: ",temp);
                    }
                }//if orderType
                
            }//if orderprofit
        }//if ordersymbol
    }//for
    if(Bars<100){
        Print("bars less than 100");
        return(0);
    }
    if (Digits==3 || Digits==5)

    if(lTakeProfit<1){
        Print("TakeProfit less than 1");
        return(0);
    }
    if(sTakeProfit<1){
        Print("TakeProfit less than 1");
        return(0);
    }

    double diClose0=iClose(NULL,5,0);
    double diMA1=iMA(NULL,5,5,0,MODE_SMA,PRICE_OPEN,1);
    double diClose2=iClose(NULL,5,0);
    double diMA3=iMA(NULL,5,4,0,MODE_SMA,PRICE_OPEN,1);

    if(AccountFreeMargin()<(1000*Lots)){
        Print("We have no money. Free Margin = ", AccountFreeMargin());
        return(0);
    }
    if (!ExistPositions()){

        if ((diClose0<diMA1)){
            if (reverseLogic) OpenSell();
            else OpenBuy();
        }

        if ((diClose2>diMA3)){
            if (reverseLogic) OpenBuy();
            else OpenSell();
        }
    }
    TrailingPositionsBuy(lTrailingStop);
    TrailingPositionsSell(sTrailingStop);
    return (0);
}

bool ExistPositions() {
    for (int i=maxtrades-1; i<OrdersTotal(); i++) {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
            if (OrderSymbol()==Symbol()) {
                return(True);
            }
        } 
    } 
    return(false);
}
void TrailingPositionsBuy(int trailingStop) { 
    for (int i=maxtrades-1; i<OrdersTotal(); i++) { 
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { 
            if (OrderSymbol()==Symbol()) { 
                if (OrderType()==OP_BUY) { 
                    if (Bid-OrderOpenPrice()>trailingStop*Point) { 
                        if (OrderStopLoss()<Bid-trailingStop*Point) 
                        ModifyStopLoss(Bid-trailingStop*Point); 
                    } 
                } 
            } 
        } 
    } 
} 
void TrailingPositionsSell(int trailingStop) { 
    for (int i=maxtrades-1; i<OrdersTotal(); i++) { 
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { 
            if (OrderSymbol()==Symbol()) { 
                if (OrderType()==OP_SELL) { 
                    if (OrderOpenPrice()-Ask>trailingStop*Point) { 
                        if (OrderStopLoss()>Ask+trailingStop*Point || 
                                OrderStopLoss()==0)  
                        ModifyStopLoss(Ask+trailingStop*Point); 
                    } 
                } 
            } 
        } 
    } 
} 
void ModifyStopLoss(double ldStopLoss) { 
    bool fm;
    fm = OrderModify(OrderTicket(),OrderOpenPrice
    (),ldStopLoss,OrderTakeProfit(),0,CLR_NONE); 
    //if (fm && UseSound) PlaySound(NameFileSound); 
} 

void OpenBuy() { 
    double ldLot, ldStop, ldTake; 
    string lsComm; 
    ldLot = GetSizeLot(); 
    ldStop = 0; 
    ldTake = GetTakeProfitBuy(); 
    lsComm = GetCommentForOrder(); 
    OrderSend(Symbol(),OP_BUY,ldLot,Ask,Slippage,ldStop,ldTake,lsComm,magic_number,0,clOpenBuy); 
    //if (UseSound) PlaySound(NameFileSound); 
} 
void OpenSell() { 
    double ldLot, ldStop, ldTake; 
    string lsComm; 

    ldLot = GetSizeLot(); 
    ldStop = 0; 
    ldTake = GetTakeProfitSell(); 
    lsComm = GetCommentForOrder(); 
    OrderSend(Symbol(),OP_SELL,ldLot,Bid,Slippage,ldStop,ldTake,lsComm,magic_number,0,clOpenSell); 
    //if (UseSound) PlaySound(NameFileSound); 
} 
string GetCommentForOrder() { return(Name_Expert); } 
double GetSizeLot() { return(Lots); } 
double GetTakeProfitBuy() { return(Ask+lTakeProfit*Point); } 
double GetTakeProfitSell() { return(Bid-sTakeProfit*Point); } 

Profitability Reports

GBP/CAD Jul 2025 - Sep 2025
0.54
Total Trades 1131
Won Trades 1121
Lost trades 10
Win Rate 99.12 %
Expected payoff -0.61
Gross Profit 809.66
Gross Loss -1505.02
Total Net Profit -695.36
-100%
-50%
0%
50%
100%
GBP/AUD Jul 2025 - Sep 2025
0.17
Total Trades 300
Won Trades 290
Lost trades 10
Win Rate 96.67 %
Expected payoff -3.07
Gross Profit 191.38
Gross Loss -1112.87
Total Net Profit -921.49
-100%
-50%
0%
50%
100%
EUR/USD Jul 2025 - Sep 2025
0.00
Total Trades 326
Won Trades 320
Lost trades 6
Win Rate 98.16 %
Expected payoff -1941.57
Gross Profit 320.00
Gross Loss -633271.00
Total Net Profit -632951.00
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.51
Total Trades 912
Won Trades 902
Lost trades 10
Win Rate 98.90 %
Expected payoff -0.95
Gross Profit 902.00
Gross Loss -1772.50
Total Net Profit -870.50
-100%
-50%
0%
50%
100%
USD/JPY Jan 2025 - Jul 2025
2.04
Total Trades 9774
Won Trades 9764
Lost trades 10
Win Rate 99.90 %
Expected payoff 0.35
Gross Profit 6630.49
Gross Loss -3245.75
Total Net Profit 3384.74
-100%
-50%
0%
50%
100%
USD/CHF Jan 2025 - Jul 2025
4.48
Total Trades 3486
Won Trades 3476
Lost trades 10
Win Rate 99.71 %
Expected payoff 0.91
Gross Profit 4083.38
Gross Loss -912.11
Total Net Profit 3171.27
-100%
-50%
0%
50%
100%
USD/CAD Jan 2025 - Jul 2025
0.78
Total Trades 2474
Won Trades 2464
Lost trades 10
Win Rate 99.60 %
Expected payoff -0.20
Gross Profit 1756.79
Gross Loss -2256.84
Total Net Profit -500.05
-100%
-50%
0%
50%
100%
NZD/USD Jan 2025 - Jul 2025
50.33
Total Trades 1837
Won Trades 1827
Lost trades 10
Win Rate 99.46 %
Expected payoff 0.97
Gross Profit 1827.00
Gross Loss -36.30
Total Net Profit 1790.70
-100%
-50%
0%
50%
100%
GBP/USD Jan 2025 - Jul 2025
0.70
Total Trades 2230
Won Trades 2220
Lost trades 10
Win Rate 99.55 %
Expected payoff -0.42
Gross Profit 2220.00
Gross Loss -3165.20
Total Net Profit -945.20
-100%
-50%
0%
50%
100%
GBP/CAD Jan 2025 - Jul 2025
0.45
Total Trades 728
Won Trades 718
Lost trades 10
Win Rate 98.63 %
Expected payoff -0.87
Gross Profit 518.59
Gross Loss -1153.12
Total Net Profit -634.53
-100%
-50%
0%
50%
100%

Comments