#Graal-CROSSmuvingi

Author: Rosh
Profit factor:
0.75

Okay, here's a breakdown of what this MetaTrader script does, explained in plain language:

Overall Purpose:

This script is designed to automatically trade on the Forex market. It aims to identify potential buying and selling opportunities based on a set of technical indicators, and then automatically open and manage trades. The script attempts to close the trades when trailing stop gets hit.

Key Components and How They Work:

  1. Setup (External Inputs): The script begins by allowing the user to define various settings or parameters. Think of these as knobs and dials that the trader can adjust to customize the script's behavior. These include:

    • FastPeriod and SlowPeriod: These control the sensitivity of two moving averages, which are lines that smooth out price data over a specified period.
    • MomPeriod and MomFilter: These relate to a "momentum" indicator, which measures the speed and strength of price movements. The MomFilter acts as a threshold.
    • PercentCapital: The percentage of the account balance to risk on each trade
    • Lots: The volume of currency to trade.
    • Slippage: The maximum acceptable difference between the requested trade price and the actual executed price.
    • StopLoss and TakeProfit: These determine how far the price needs to move in the wrong or right direction, respectively, before the trade is automatically closed to limit losses or secure profits.
    • Patr,Prange: Average True Range parameters.
    • Kstop,kts,Vts: parameters for stop loss and trailing stop.
    • MaximumRisk: Maximum percentage of account balance to risk on a single trade.
    • DecreaseFactor: How aggressively the script should reduce the trade size after losing trades.
  2. Calculating Existing Positions: The script first checks if there are any open trades for the specific currency pair it's watching. This helps it avoid opening multiple trades in the same direction and manage existing positions.

  3. Optimizing Trade Size (Lot Size): The script has a feature to adjust the size of each trade based on the account balance and the trader's risk tolerance. It calculates a "lot size" that represents the amount of currency to buy or sell in each trade. The lot size can be calculated in a aggressive or conservative way depending on the trader's parameters.

  4. Identifying Trading Opportunities (Opening Trades): The script uses a combination of moving averages and a momentum indicator to identify potential buy or sell signals.

    • It compares two moving averages (fast and slow) to see if they cross each other. A "crossover" can signal a change in the price trend.
    • It also looks at the momentum indicator to confirm the strength of the trend.
    • If both conditions are met (moving average crossover and strong momentum), the script sends a buy or sell order.
    • If there are trades in the opposite direction, the script attempts to close them before opening the new trade.
  5. Managing Open Trades (Closing Trades):

    • The script actively monitors open trades to protect profits and limit losses. It uses trailing stops to progressively adjust the stop loss level as the price moves in a favorable direction, locking in profits.
    • It calculates ATR(Average True Range) and other parameters to set the stop loss and trailing stop.
  6. The start() Function: This is the main function that runs repeatedly. It checks whether the minimum data is available, then decides whether to look for new opportunities (using CheckForOpen()) or manage existing trades (using CheckForClose()).

In Simpler Terms:

Imagine this script as a robot trader that follows a set of rules to buy and sell currencies. The trader gives the robot some initial instructions (the external inputs), and then the robot continuously watches the market, looking for signals that meet its criteria. When it finds a good opportunity, it places a trade, and then it monitors the trade, adjusting the stop loss as necessary, until it's time to close the trade.

Important Considerations:

  • No Guarantees: This script, like any automated trading system, doesn't guarantee profits. Trading Forex involves significant risk.
  • Customization is Key: The script's performance depends heavily on the chosen settings. The trader needs to understand how the different parameters affect the script's behavior and adjust them accordingly.
  • Testing is Essential: Before using this script with real money, it's crucial to test it thoroughly on a demo account to evaluate its performance and fine-tune the settings.
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategy
Indicators Used
Moving average indicatorMomentum indicator
Miscellaneous
It plays sound alerts
5 Views
0 Downloads
0 Favorites
#Graal-CROSSmuvingi
//+------------------------------------------------------------------+
//|                                            Graal-FxProg_team.mq4 |
//|               //+-                                              Rosh |
//|               http://www.investo.ru/forum/viewtopic.php?t=124777 |
//+------------------------------------------------------------------+
#property copyright "Rosh"

#define MAGIC  256
extern int       FastPeriod=13;
extern int       SlowPeriod=34;
extern int       MomPeriod=14;
extern double    MomFilter=0.1;
extern double    PercentCapital=10.0;
extern double    Lots=0.1;
extern int       Slippage=3;
extern int       StopLoss=20;
extern int       TakeProfit=200;
int myBars;
extern double Patr=9;
extern double Prange=5;
extern double Kstop=1.5;
extern double kts=2;
extern double Vts=2;
extern double MaximumRisk        = 0.05;
extern double DecreaseFactor     = 10;
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//---- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//---- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         //----
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//---- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
  int cnt;
  double curFastMA=iMA(NULL,0,FastPeriod,0,MODE_EMA,PRICE_CLOSE,1);
  double curSlowMA=iMA(NULL,0,SlowPeriod,0,MODE_EMA,PRICE_OPEN,1);
  double prevFastMA=iMA(NULL,0,FastPeriod,0,MODE_EMA,PRICE_CLOSE,2);
  double prevSlowMA=iMA(NULL,0,SlowPeriod,0,MODE_EMA,PRICE_OPEN,2);
  double curMom=iMomentum(NULL,0,MomPeriod,PRICE_CLOSE,1)-100.0;
  double prevMom=iMomentum(NULL,0,MomPeriod,PRICE_CLOSE,2)-100.0;
//----
   if (Bars!=myBars)
      {
      myBars=Bars;
      if (curFastMA>curSlowMA && prevFastMA<prevSlowMA && curMom>MomFilter && curMom>prevMom)
         {
         if (OrdersTotal()>0)
            {
            for (cnt=OrdersTotal()-1;cnt>=0;cnt--)
               {
               OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
               if (OrderType()==OP_SELL) {OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,White);Sleep(30000);}
               }
            }
         OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,Slippage,0,Ask+TakeProfit*Point,"buy",MAGIC,0,Blue);
         }
      if (curFastMA<curSlowMA && prevFastMA>prevSlowMA && curMom<-MomFilter && curMom<prevMom)
         {
         if (OrdersTotal()>0)
            {
            for (cnt=OrdersTotal()-1;cnt>=0;cnt--)
               {
               OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
               if (OrderType()==OP_BUY) {OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,White);Sleep(30000);}
               }
            }
         OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,Slippage,0,Bid-TakeProfit*Point,"sell",MAGIC,0,Red);
         }
      }
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
  int i,mode,ticket,total;
  double cnt=0,ValATR=0,hi=0,lo=0,SL=0,TS=0,prevBars=0;
  if (prevBars!=Bars) 
  {
    ValATR=0;
    for(i=1; i<=Patr; i++) { if(i<=Patr) { ValATR+=High[i]-Low[i]; } }
    ValATR=ValATR/Patr;
     
    hi=High[Highest(NULL,0,MODE_HIGH,Prange,Prange)]; 
    lo=Low[Lowest(NULL,0,MODE_LOW,Prange,Prange)]; 
 
    if (Vts==1)  {TS=kts*ValATR; SL=Kstop*ValATR;}
    if (Vts==2)  {TS=(hi-lo);    SL=Kstop*(hi-lo);}
    prevBars = Bars;
  }

  if (Vts<1 || Vts>2)  return(0);

//-------------------------------------------------------

  for (cnt=0; cnt<=OrdersTotal(); cnt++)
  {
    OrderSelect(cnt,SELECT_BY_POS);
    mode=OrderType();
    if(OrderSymbol()==Symbol())
    {
//First Stop---------------------------------
      if (mode==OP_BUY && OrderStopLoss()== 0)
      {
        OrderModify(OrderTicket(),OrderOpenPrice(),Low[0]-SL,OrderTakeProfit(),0,CLR_NONE);
        PlaySound("expert.wav");
        return(0);
      }

      if (mode==OP_SELL && OrderStopLoss()==0)
      {
        OrderModify(OrderTicket(),OrderOpenPrice(),High[0]+SL,OrderTakeProfit(),0,CLR_NONE);
        PlaySound("expert.wav");
        return(0);
      }
//Main Trailing-------------------------------
      if ((mode==OP_BUY && High[0]-OrderOpenPrice()>TS && OrderStopLoss()<High[0]-TS) || OrderStopLoss()==0)
      {
        OrderModify(OrderTicket(),OrderOpenPrice(),High[0]-TS,OrderTakeProfit(),0,CLR_NONE);
        PlaySound("expert.wav");
        return(0);
      }

      if ((mode==OP_SELL && OrderOpenPrice()-Low[0]>TS && OrderStopLoss()>Low[0]+TS) || OrderStopLoss()==0)
      {
        OrderModify(OrderTicket(),OrderOpenPrice(),Low[0]+TS,OrderTakeProfit(),0,CLR_NONE);
        PlaySound("expert.wav");
        return(0);
      }
    }
  }

  Comment("Versia: ",Vts,"\n",
          "Per_ATR: ",Patr,"\n",
          "Per_Range: ",Prange,"\n",
          "Range: ",(High[0]-Low[0]),"\n",
          "ATR: ",ValATR,"\n",
          "SL: ",SL,"\n",
          "TS: ",TS);

  return(0);
}

//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
  {
//---- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false) return;
//---- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
//----
  }
//+------------------------------------------------------------------+

Profitability Reports

GBP/AUD Jan 2025 - Jul 2025
1.01
Total Trades 52
Won Trades 43
Lost trades 9
Win Rate 82.69 %
Expected payoff 0.30
Gross Profit 2962.56
Gross Loss -2946.76
Total Net Profit 15.80
-100%
-50%
0%
50%
100%
AUD/USD Jan 2025 - Jul 2025
0.84
Total Trades 58
Won Trades 36
Lost trades 22
Win Rate 62.07 %
Expected payoff -10.37
Gross Profit 3269.00
Gross Loss -3870.20
Total Net Profit -601.20
-100%
-50%
0%
50%
100%
USD/CHF Oct 2024 - Jan 2025
0.00
Total Trades 0
Won Trades 0
Lost trades 0
Win Rate 0.0 %
Expected payoff 0.00
Gross Profit 0.00
Gross Loss 0.00
Total Net Profit 0.00
-100%
-50%
0%
50%
100%
USD/CAD Oct 2024 - Jan 2025
0.91
Total Trades 20
Won Trades 15
Lost trades 5
Win Rate 75.00 %
Expected payoff -4.49
Gross Profit 882.93
Gross Loss -972.77
Total Net Profit -89.84
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
1.05
Total Trades 21
Won Trades 16
Lost trades 5
Win Rate 76.19 %
Expected payoff 2.29
Gross Profit 1097.60
Gross Loss -1049.50
Total Net Profit 48.10
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
0.66
Total Trades 32
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -25.64
Gross Profit 1587.70
Gross Loss -2408.30
Total Net Profit -820.60
-100%
-50%
0%
50%
100%

Comments