escape2reversed-2-maxorders_003

Profit factor:
4.60

This script is designed to automatically trade on the Forex market using the MetaTrader platform. Here's how it works:

Overall Goal: The script aims to make trades based on certain market conditions, and then manage those trades to maximize profit and minimize loss.

Key Components:

  1. Settings: The script starts by defining several settings that you, the user, can adjust. These settings control how the script behaves. Examples include:

    • iTakeProfitCloseValue: A base profit value that influences when a trade might be closed.
    • iTakeProfitMaxDecCount: The number of consecutive times the profit decreases on an open trade before considering closing the trade.
    • maxtrades: The maximum number of trades the script will allow to be open at the same time.
    • lTakeProfit/sTakeProfit: The desired profit target for buy ("long") and sell ("short") trades, respectively.
    • lTrailingStop/sTrailingStop: A mechanism to automatically adjust the stop-loss order (an order to limit potential losses) as the trade becomes more profitable for buy ("long") and sell ("short") trades, respectively.
    • Lots: The size of the trades it will make.
    • reverseLogic: A boolean to inverse the buying/selling signals from the moving averages.
  2. Trade Management (The Loop): The script constantly runs in a loop, checking several things:

    • Is it time to close a profitable trade?
      • It monitors the profit of each open trade.
      • If the profit starts to decrease after reaching a peak and this decrease happens a certain number of times in a row (determined by iTakeProfitMaxDecCount), it might close the trade to secure the profit it has already earned. It will only close if the profit is above a minimum value (influenced by iTakeProfitCloseValue). It also tries to close the trade several times if it fails initially.
    • Should the stop-loss be adjusted?
      • If a trade is profitable, the script can automatically move the stop-loss order to a better position (closer to the current price). This is called a "trailing stop." This helps to lock in profits and further limit potential losses.
  3. Making New Trades: The script looks at moving averages to determine whether to buy or sell.

    • Moving Averages: It calculates the average price over a specific period.
    • Buy/Sell Signals: The core logic of when to open a new buy or sell trade:
      • It compares current price to the moving averages.
      • If the current price is below moving averages it will open a sell trade, otherwise will open a buy trade.
      • The reverseLogic parameter inverses the signals.
    • Checks Before Trading: Before opening a new trade, the script checks:
      • Account Balance: Does the account have enough available funds to open the trade?
      • Maximum Trades: Has it already reached the maximum number of allowed open trades?
  4. Support Functions: The script also contains functions that perform specific tasks:

    • ExistPositions(): Checks if there are any open trades for the current currency pair.
    • TrailingPositionsBuy/Sell(): Implements the trailing stop logic.
    • OpenBuy/Sell(): Sends the order to open a new buy or sell trade.
    • GetSizeLot(): Gets the trade size (lot size) from the user-defined setting.

In Simple Terms:

Imagine a robot that trades for you. You give it some instructions (the settings). The robot constantly watches the market. If it sees a potential profit, it opens a trade. As the trade becomes profitable, it moves the "safety net" (stop-loss) to protect the profits. If the profit starts to decline, it closes the trade to make sure you don't lose what you've earned. It bases its decisions about when to buy or sell on basic trend indicators (moving averages).

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
Miscellaneous
It plays sound alerts
7 Views
0 Downloads
0 Favorites
escape2reversed-2-maxorders_003
//+------------------------------------------------------------------+
//|                                                      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 = 20;
extern double sTrailingStop = 10;
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 = true;

extern bool FractionalPips = true;
extern string NameFileSound = "Alert.wav";
extern double Lots = 0.05;

extern bool reverseLogic = true;
int magic_number = 013113324124;

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

    double SL = 100.0;
    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.59
Total Trades 1072
Won Trades 1062
Lost trades 10
Win Rate 99.07 %
Expected payoff -0.25
Gross Profit 383.59
Gross Loss -649.78
Total Net Profit -266.19
-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 -1.54
Gross Profit 95.65
Gross Loss -556.38
Total Net Profit -460.73
-100%
-50%
0%
50%
100%
EUR/USD Jul 2025 - Sep 2025
0.00
Total Trades 301
Won Trades 295
Lost trades 6
Win Rate 98.01 %
Expected payoff -1051.46
Gross Profit 147.50
Gross Loss -316636.55
Total Net Profit -316489.05
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.53
Total Trades 956
Won Trades 946
Lost trades 10
Win Rate 98.95 %
Expected payoff -0.43
Gross Profit 473.00
Gross Loss -884.70
Total Net Profit -411.70
-100%
-50%
0%
50%
100%
USD/JPY Jan 2025 - Jul 2025
2.13
Total Trades 10172
Won Trades 10162
Lost trades 10
Win Rate 99.90 %
Expected payoff 0.18
Gross Profit 3451.67
Gross Loss -1622.01
Total Net Profit 1829.66
-100%
-50%
0%
50%
100%
USD/CHF Jan 2025 - Jul 2025
4.43
Total Trades 3589
Won Trades 3579
Lost trades 10
Win Rate 99.72 %
Expected payoff 0.45
Gross Profit 2101.01
Gross Loss -474.35
Total Net Profit 1626.66
-100%
-50%
0%
50%
100%
NZD/USD Jan 2025 - Jul 2025
46.81
Total Trades 1770
Won Trades 1760
Lost trades 10
Win Rate 99.44 %
Expected payoff 0.49
Gross Profit 880.00
Gross Loss -18.80
Total Net Profit 861.20
-100%
-50%
0%
50%
100%
GBP/USD Jan 2025 - Jul 2025
0.72
Total Trades 2280
Won Trades 2270
Lost trades 10
Win Rate 99.56 %
Expected payoff -0.20
Gross Profit 1135.00
Gross Loss -1580.45
Total Net Profit -445.45
-100%
-50%
0%
50%
100%
GBP/AUD Jan 2025 - Jul 2025
0.08
Total Trades 1012
Won Trades 1002
Lost trades 10
Win Rate 99.01 %
Expected payoff -3.83
Gross Profit 333.98
Gross Loss -4208.00
Total Net Profit -3874.02
-100%
-50%
0%
50%
100%
EUR/USD Jan 2025 - Jul 2025
0.01
Total Trades 1016
Won Trades 1015
Lost trades 1
Win Rate 99.90 %
Expected payoff -46.49
Gross Profit 507.50
Gross Loss -47737.50
Total Net Profit -47230.00
-100%
-50%
0%
50%
100%

Comments