Gandalf_PRO_v1

Author: budimir

This script is designed to automatically place buy and sell orders in the Forex market based on certain calculations and conditions. Here's a breakdown of how it works:

Overall Goal:

The script aims to identify potential trading opportunities and execute trades on your behalf, following pre-defined rules and risk parameters.

Key Components:

  1. Initialization (init function):

    • When the script starts, it checks the number of decimal places used for pricing in the current currency pair. This value (Digits) dictates the precision of calculations later.
  2. Deinitialization (deinit function):

    • This function is empty, meaning it doesn't perform any specific actions when the script is stopped or removed from the chart.
  3. Main Execution (start function):

    • Time Check: The script first checks if the current time is the same as the last time it ran. If it is, it does nothing and exits, preventing it from executing multiple times within the same minute.
    • Trading Allowed Check: It verifies if trading is currently allowed by your broker. If not, it pauses for a while, then checks again later.
    • Buy/Sell Execution: The script then uses two functions Trade_BUY and Trade_SELL functions which contain the main logic. The Trade_BUY function is called if In_BUY is enabled and the Trade_SELL function is called if In_SELL is enabled. The In_BUY and In_SELL parameters is a simple boolean to turn on and off buy and sell orders.
  4. Buy Order Logic (Trade_BUY function):

    • Existing Order Check: Before placing a buy order, the script checks if there's already an open buy order for the same currency pair and with a specific identifier (Magic_BUY). If there is, it assumes a buy order is already active and stops.
    • Target Price Calculation: It calls a function named Out, which uses moving averages (iMA function which calculates moving averages) and other calculations (weighted price and trend that are factored into calculations) to determine a target price where a buy order should be placed.
    • Order Placement:
      • If the calculated target price is significantly higher than the current asking price, the script places a buy order.
      • The size of the trade (lot size) is determined by another function called lot.
      • A stop-loss is set to limit potential losses, calculated from current bid price using the SL_buy parameter.
      • A target profit level is set based on the target value.
  5. Sell Order Logic (Trade_SELL function):

    • This function works similarly to the Trade_BUY function, but for placing sell orders. It checks for existing sell orders, calculates a target price (using the same Out function), and places a sell order if the target price is significantly lower than the current bid price. It also sets a stop-loss level (SL_sell).
  6. Target Price Calculation (Out function):

    • This function is crucial. It calculates the predicted future price using weighted moving averages.
    • It calculates two types of moving averages (LWMA and SMA) of the closing prices.
    • It then uses those moving averages to calculate a trend and smooth the price forecast using the input n, l1, and l2 parameters.
  7. Lot Size Calculation (lot function):

    • This function determines the appropriate trade size (lot size) based on your account's available margin and the risk percentage you've set (Risk_buy and Risk_sell).
    • It ensures that the lot size is within the minimum and maximum limits allowed by your broker.

In simple terms:

The script acts like a Forex robot that monitors the market. It uses moving averages to guess where the price might go. If it thinks the price will go up, it places a buy order; if it thinks the price will go down, it places a sell order. It also includes safety measures like stop-loss orders to limit potential losses. The amount of money it risks on each trade is determined by the available money in your trading account and the percentage set in Risk_buy and Risk_sell parameters.

Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reached
Indicators Used
Moving average indicator
2 Views
0 Downloads
0 Favorites
Gandalf_PRO_v1

//+------------------------------------------------------------------+
//|                                                  Gandalf_PRO.mq4 |
//|                                                          budimir |
//|                                              tartar27@bigmir.net |
//+------------------------------------------------------------------+
#property copyright "budimir"
#property link      "tartar27@bigmir.net"
 
//---- input parameters
//ooooooooooooooooooooooooooooooooooooooooooooooooo
extern bool      In_BUY=true;
extern int       Count_buy=24;
extern double    w_price=0.18;
extern double    w_trend=0.18;
extern int       SL_buy=62;
extern int       Risk_buy=0;
//ooooooooooooooooooooooooooooooooooooooooooooooooo
extern bool      In_SELL=true;
extern int       Count_sell=24;
extern double    m_price=0.18;
extern double    m_trend=0.18;
extern int       SL_sell=62;
extern int       Risk_sell=0;
//ooooooooooooooooooooooooooooooooooooooooooooooooo
//extern int       Risk=0;
//ooooooooooooooooooooooooooooooooooooooooooooooooo
//---- other parameters
   static int  prevtime=0;
          int    ticket=0;
          int Magic_BUY  =123;
          int Magic_SELL =321;
          int x=1;
 
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
      if(Digits == 5) x=10;
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//oooooooooooooooooooooooooooooooooooooooooooooooooooo
    if (Time[0] == prevtime) return(0); 
                             prevtime = Time[0];
    if (!IsTradeAllowed()) {
     prevtime=Time[1]; MathSrand(TimeCurrent());Sleep(30000 + MathRand());
                           }
//oooooooooooooooooooooooooooooooooooooooooooooooooooo
   if( In_BUY)Trade_BUY ( Magic_BUY, Count_buy,w_price,w_trend, SL_buy);
   if(In_SELL)Trade_SELL(Magic_SELL,Count_sell,m_price,m_trend,SL_sell);
//oooooooooooooooooooooooooooooooooooooooooooooooooooo
   return(0);
  }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
void Trade_BUY(int mn,int num,double factor1,double factor2,int sl) { 
 
         int total=OrdersTotal();
         
    for (int i = 0; i < total; i++) {   OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    
                if (OrderSymbol() == Symbol() && OrderMagicNumber() == mn) { return(0);
                                                                           } 
                                    }
 //ooooooooooooooooooooooooooooooooooooooooooooooooooo
      ticket = -1;  
      
      double target=Out(num,factor1,factor2);  
 
  if (target>(Bid+15*x*Point)  && IsTradeAllowed()) { 
  
    ticket= OrderSend(Symbol(), OP_BUY,lot(Risk_buy),Ask,5,Bid-x*sl*Point,target,DoubleToStr(mn,0),mn,0,Blue);
        
   
                 RefreshRates();   
      
              if ( ticket < 0) { Sleep(30000);   prevtime = Time[1]; } 
                                           
                                           } //-- Exit ---
 
       return(0); } 
       
       
 //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 void Trade_SELL(int mn,int num,double factor1,double factor2,int sl) { 
 
         int total=OrdersTotal();
         
    for (int i = 0; i < total; i++) {   OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    
                if (OrderSymbol() == Symbol() && OrderMagicNumber() == mn) { return(0);
                                                                           } 
                                    }
 //ooooooooooooooooooooooooooooooooooooooooooooooooooo
      ticket = -1; 
       
      double target=Out(num,factor1,factor2);  
 
     if (target<(Ask-15*x*Point)  && IsTradeAllowed()) { 
     
     ticket= OrderSend(Symbol(),OP_SELL,lot(Risk_sell),Bid,5,Ask+x*sl*Point,target,DoubleToStr(mn,0),mn,0, Red);
  
   
                 RefreshRates();   
      
              if ( ticket < 0) { Sleep(30000);   prevtime = Time[1]; } 
                                           
                                           } //-- Exit ---
 
       return(0); } 
       
       
 //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 double Out(int n,double l1,double l2) {    double t[120],
                                                   s[120],
                                        lm=iMA(NULL,0,n,0,MODE_LWMA,PRICE_CLOSE,1),
                                        sm=iMA(NULL,0,n,0, MODE_SMA,PRICE_CLOSE,1); 
 //ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo  
        t[n]=(6*lm-6*sm)/(n-1);s[n]=4*sm-3*lm-t[n]; 
              for (int k = n-1; k>0; k--) {    
           s[k]=l1*Close[k]+(1-l1)*(s[k+1]+t[k+1]);
           t[k]=l2*(s[k]-s[k+1])+(1-l2)*t[k+1];
                                          }//--end--for-
   return  (NormalizeDouble(s[1]+t[1],MarketInfo(Symbol(),MODE_DIGITS)));}
 
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
double lot(int R) { double minlot = MarketInfo(Symbol(), MODE_MINLOT);
                       int o = MathAbs(MathLog(minlot) *0.4343) + 0.5;  
                  double lot = minlot;
//ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
   lot = NormalizeDouble(AccountFreeMargin() * 0.00001*R, o);//---
   if (AccountFreeMargin() < lot * MarketInfo(Symbol(), MODE_MARGINREQUIRED)) {
   lot = NormalizeDouble(AccountFreeMargin() / MarketInfo(Symbol(), MODE_MARGINREQUIRED), o);
                                                                               }
//ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
   if(lot < minlot) lot = minlot;
   double maxlot =MarketInfo(Symbol(), MODE_MAXLOT);
   if(lot > maxlot) lot = maxlot;
   return(lot);    } 
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_end_film_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


   

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