SimpleGrail1st

Author: Copyright � 2009, LEHayes

This script is designed to automatically trade in the Forex market. Here's how it works in plain language:

Overall Goal: The script aims to identify potential buying and selling opportunities based on recent price movements, and then automatically place and manage trades.

Key Components:

  1. Settings You Can Adjust (External Variables):

    • Trailing Stop: This sets how far behind the current price a "safety net" (stop loss) will follow as the price moves in a favorable direction. It's like saying, "If the price goes up, make sure to move my stop loss order up too, so I lock in some profit."
    • Stop Loss: An initial stop loss that can be set to protect your trade if price goes to the oposite direction.
    • Lots: This determines the trade volume.
    • Magic Number: A unique identifier for trades opened by this particular script. This helps the script manage only its own trades and not interfere with others.
    • Max Orders: This limits the number of trades the script can have open at the same time. A value of 1 means only one trade can be open at a time.
    • Percentage of Free Assets: percentage of your free margin to be used in the next trades.
  2. Initialization (init): This function runs once when the script is first loaded onto the chart, sets parameters for further use.

  3. Main Loop (start): This is the heart of the script. It runs repeatedly, checking market conditions and managing trades. Here's a breakdown of what it does in each cycle:

    • Determine Trade Volume (GetLots): Calculates the lot size (trade size) to use for new orders. It's based on the amount of free money available in your account and the percentage you want to risk per trade. It makes sure the trade isn't too small by comparing it to the minimum allowed trade size for that currency pair.

    • Trailing Stop Management: The script loops through all open trades. If a trade was opened by this script (identified by the "magic number"), it will try to adjust the stop loss order. The TrailingStairs function is responsible for this action. The key goal is to secure profits as the price moves in the desired direction,

    • Check for New Trade Opportunities:

      • It only considers opening new trades if the free margin is sufficient.
      • It looks at recent price data (the last few "bars" on the chart).
      • It checks if a Buy signal or a Sell signal has been generated
      • Buy Signal: If recent price bars shows a steady inclination, it considers opening a buy order
      • Sell Signal: If recent price bars shows a steady declination, it considers opening a sell order
      • Time Check: It avoid processing trades in the same price bar.
      • Trading Allowed: Checks if trading is allowed at the moment
      • Order Placement: If a buy or sell signal is detected and the maximum number of orders hasn't been reached, the script places a new order.
  4. Trailing Stop Adjustment (TrailingStairs): This function is called for each open trade managed by the script. It adjusts the stop loss order to "trail" behind the current price, locking in profits as the price moves favorably.

    • For Buy Orders: If the current price is far enough above the order's opening price, it moves the stop loss order up to a certain distance behind the current price. If the price keeps rising, the stop loss will continue to move up.
    • For Sell Orders: If the current price is far enough below the order's opening price, it moves the stop loss order down to a certain distance ahead of the current price. If the price keeps decreasing, the stop loss will continue to move down.
    • Partial Closing (PolLots): Optionally, if the price has moved favorably enough, the script can close half of the open trade. This allows you to secure some profit while still letting the remaining portion of the trade potentially earn more. If the partial closure is enabled, it verifies that the reduced amount is higher than the min lot size.

In Summary: This script is designed to automatically identify potential trends, open trades, and then manage those trades with a trailing stop mechanism to lock in profits. It also has the option to partially close trades to secure some earnings along the way.

Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategyIt Closes Orders by itself
4 Views
0 Downloads
0 Favorites

Profitability Reports

NZD/USD Oct 2024 - Jan 2025
1148.00 %
Total Trades 21
Won Trades 20
Lost trades 1
Win Rate 95.24 %
Expected payoff 447.69
Gross Profit 10298.50
Gross Loss -897.00
Total Net Profit 9401.50
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
367.00 %
Total Trades 26
Won Trades 25
Lost trades 1
Win Rate 96.15 %
Expected payoff 371.73
Gross Profit 13287.40
Gross Loss -3622.50
Total Net Profit 9664.90
-100%
-50%
0%
50%
100%
AUD/USD Oct 2024 - Jan 2025
809.00 %
Total Trades 21
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff 248.71
Gross Profit 5959.70
Gross Loss -736.80
Total Net Profit 5222.90
-100%
-50%
0%
50%
100%
SimpleGrail1st
//+------------------------------------------------------------------+
//|                                                  SimpleGrail.mq4 |
//|                                        Copyright © 2009, LEHayes |
//|                                   BlessingsFromEarth@hotmail.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, LEHayes"
#property link      "BlessingsFromEarth@hotmail.com"


extern int    TrailingStop   = 200;   // represents 20 lots with the extra digit
int    StopLoss       = 0;            // if using 4 digits, set to 20 on Trailing stop loss
double Lots           = 0.1;           // This is legacy, no switch at this time for progressive lots
extern int    magicnumber    = 143;
bool   PolLots        = false;         // This closes half the lots at some point, without it, more earnings.
extern int    MaxOrders      =  1;     // you can place multiple orders, but suffer equity risk
extern double Prots= 15;                                  // Percentage of free assets


double Lot;                         // global lot for calculating free assets
int prevtime;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----


  Lots = GetLots();


   int i=0;  
   int total = OrdersTotal();   
   for(i = 0; i <= total; i++) 
     {
      if(TrailingStop>0)  
       {                 
       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
       if(OrderMagicNumber() == magicnumber) 
         {
         TrailingStairs(OrderTicket(),TrailingStop);
         }
       }
      }

if(AccountFreeMargin() > (AccountBalance()/2))
{
bool BuyOp=false;
bool SellOp=false;


if (High[0]>High[1]&&High[1]>High[2]&&High[2]>High[3]&&Open[0]>Open[1]&&Open[1]>Open[2]&&Open[2]>Open[3]) BuyOp=true;
if (High[0]<High[1]&&High[1]<High[2]&&High[2]<High[3]&&Open[0]<Open[1]&&Open[1]<Open[2]&&Open[2]<Open[3]) SellOp=true;

   if(Time[0] == prevtime) 
       return(0);
   prevtime = Time[0];
   if(!IsTradeAllowed()) 
     {
       prevtime = Time[1];
       return(0);
     }


   if (total < MaxOrders || MaxOrders == 0)
     {   
       if(BuyOp)
        { 
         if (StopLoss!=0)
          {
           OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid-(StopLoss*Point),0,StringConcatenate("SimpleGrail_", Symbol(), "_Buy"),magicnumber,0,Green);
          }
         else
          {
           OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,0,StringConcatenate("SimpleGrail_",Symbol(), "_Buy"),magicnumber,0,Green);
          }
        }
       if(SellOp)
        { 
         if (StopLoss!=0)
          {
           OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Ask+(StopLoss*Point),0,StringConcatenate("SimpleGrail_", Symbol(), "_Sell"),magicnumber,0,Red);
          } 
         else 
          {
           OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,0,StringConcatenate("SimpleGrail_", Symbol(), "_Sell"),magicnumber,0,Red);
          }
        }
      }
}   
//----
   return(0);
  } 
  
//+------------------------------------------------------------------+
double GetLots()
   {
   
   Lot = NormalizeDouble( (AccountFreeMargin()/MaxOrders)*Prots/100/1000, 1);// Calculate the amount of lots 
   Print("Lot calculation is: ", Lot); 
   if (Lot < MarketInfo(Symbol(),MODE_MINLOT))
      {
         Lot = MarketInfo(Symbol(),MODE_MINLOT);       // For testing on const. min. lots
         Print("Lot is too small, setting to minlot of: ", Lot);
      }
   return(Lot);
   }  
  
//+------------------------------------------------------------------+
void TrailingStairs(int ticket,int trldistance)
   {
    bool result;
    int error;
    int Spred=Ask - Bid;
    int spread;
    
    if (OrderType()==OP_BUY)
      {
       if((Bid-OrderOpenPrice())>(Point*trldistance))
         {
          if(OrderStopLoss()<Bid-Point*trldistance || (OrderStopLoss()==0))
            {
             result=OrderModify(ticket,OrderOpenPrice(),Bid-Point*trldistance,OrderTakeProfit(),0,Green);
             while(result!=True)
               {
                  error=GetLastError();
                  Print("LastError closing first try =",error);
                  if(error==138)
                  {
                     Sleep(10000);
                     RefreshRates();
                     result=OrderModify(ticket,OrderOpenPrice(),Bid-Point*trldistance,OrderTakeProfit(),0,Green);
                  }
                  if(error==0)
                   {
                      result=true;
                   }
               }
           
            
             if (PolLots)
                if (NormalizeDouble(OrderLots()/2,2)>MarketInfo(Symbol(), MODE_MINLOT))
                  {
                     spread=MarketInfo(Symbol(),MODE_SPREAD); 
                     result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Ask,spread,Green);
                     while(result!=True)
                     {
                        error=GetLastError();
                        Print("1 LastError closing first try =",error);
                        if(error==138)
                          {
                              Sleep(10000);
                              RefreshRates();
                              spread=MarketInfo(Symbol(),MODE_SPREAD);
                              result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Ask,spread,Green);
                           }
                        if(error==0)
                           {
                              result=true;
                           }
                     }
                     
                  }
                else
                  {
                     spread=MarketInfo(Symbol(),MODE_SPREAD);
                     result = OrderClose(ticket,OrderLots(),Ask,spread,Green);
                     while(result!=True)
                     {
                        error=GetLastError();
                        Print("2 LastError closing first try =",error);
                        if(error==138)
                           {
                              Sleep(10000);
                              RefreshRates();
                              spread=MarketInfo(Symbol(),MODE_SPREAD);
                              result = OrderClose(ticket,OrderLots(),Ask,spread,Green);
                           }
                        if(error==0)
                           {
                              result=true;
                           }
                     }
                  }
            }
         }
       }
     else
       {
        if((OrderOpenPrice()-Ask)>(Point*trldistance))
          {
           if((OrderStopLoss()>(Ask+Point*trldistance)) || (OrderStopLoss()==0))
             {
               result=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*trldistance,OrderTakeProfit(),0,Red);
               while(result!=True)
                  {
                     error=GetLastError();
                     Print("LastError closing first try =",error);
                     if(error==138)
                        {
                           Sleep(10000);
                           RefreshRates();
                           result=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*trldistance,OrderTakeProfit(),0,Red);
                        }
                        if(error==0)
                           {
                              result=true;
                           }
                  }
             if (PolLots)
             if (NormalizeDouble(OrderLots()/2,2)>MarketInfo(Symbol(), MODE_MINLOT))
               {
                  spread=MarketInfo(Symbol(),MODE_SPREAD);
                  result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Bid,spread,Green);
                  while(result!=True)
                  {
                     error=GetLastError();
                     Print("3 LastError closing first try =",error);
                     if(error==138)
                        {
                           Sleep(10000);
                           RefreshRates();
                           spread=MarketInfo(Symbol(),MODE_SPREAD);
                           result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Bid,spread,Green);
                        }
                        if(error==0)
                           {
                              result=true;
                           }
                  }
                  
               }
             else
               {
                  spread=MarketInfo(Symbol(),MODE_SPREAD);
                  result = OrderClose(ticket,OrderLots(),Bid,spread,Green);
                  while(result!=true)
                  {
                     error=GetLastError();
                     Print("4 LastError closing first try =",error);
                     if(error==138)
                        {
                           Sleep(10000);
                           RefreshRates();
                           spread=MarketInfo(Symbol(),MODE_SPREAD);
                           result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Bid,spread,Green);
                        }
                        if(error==0)
                           {
                              result=true;
                           }
                  }

               }
             }
          }
        }
    }

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 ---