Orders Execution
Checks for the total of open ordersIt can change open orders parameters, due to possible stepping strategyIt automatically opens orders when conditions are reached
Indicators Used
Moving average indicatorEnvelopes indicator
Miscellaneous
Uses files from the file systemIt writes information to fileIt reads information from a file
0 Views
0 Downloads
0 Favorites
LiveMALite
//+------------------------------------------------------------------+
//|                                                   LiveMALite.mq4 |
//|                      Copyright © 2011, MetaQuotes Software Corp. |
//|                             http://www.mql4.com/ru/users/rustein |
//-------------------------------------------------------------------+

// Trend Detection function
#define BULL 1
#define BEAR 2
// Input variables
//+------------------------------------------------------------------+
extern int    Slippage       = 5;
//-------------------------------------------------------------------+
extern int    Magic          = 55;
//-------------------------------------------------------------------+
extern bool   MoneyMangement = true;
extern double Lots           = 0.1;
extern double MaximumRisk    = 0.8;
//-------------------------------------------------------------------+
extern int    MAPeriod       = 19;
//-------------------------------------------------------------------+
extern int    MAMode         = 2; // 0=SMA,1=EMA,2=SSMA,3=LWMA
//+------------------------------------------------------------------+
extern bool   CheckChannel   = true;
extern int    ChannelDeviat  = 89;
//+------------------------------------------------------------------+
extern int    StopLoss       = 55;
//-------------------------------------------------------------------+
extern int    MinProfit      = 34;
extern int    TrailingStop   = 13;
extern int    TrailingStep   = 3;
//+------------------------------------------------------------------+
extern int    TotalOrders    = 8;
//-------------------------------------------------------------------+
string OrderComments = "LiveMALite";
//-----
color  BuyColor      = CLR_NONE;
color  SellColor     = CLR_NONE;
// Global variables
int Cnt = 0;              // counter variable, used in for() loops
bool InitVariables;       // init variable when program starts
datetime PreviousBar;     // record the candle/bar time
int LastTrendDirection;   // record the previous trends direction
int FileHandle;           // variable for file handling
//-------------------------------------------------------------------+
 
//+------------------------------------------------------------------+
//|            DO NOT MODIFY ANYTHING BELOW THIS LINE!!!             |
//+------------------------------------------------------------------+
 
//-------------------------------------------------------------------+
int init()
{
  if(IsTesting()==false)
  {
  InitVariables = true;  // Allows us to init variables in the start function because 
                         // we cannot do this in the init function because the variables 
                         // use values from the chart 
  //create data file if it does not exist and load variables if file does exist
  FileHandle=FileOpen("LiveMALite.dat",FILE_BIN | FILE_READ);
  if(FileHandle<1)
  {
    Print("LiveMALite.dat not found.");
    FileHandle=FileOpen("LiveMALite.dat",FILE_BIN | FILE_WRITE);
    if(FileHandle>0)
    {
      LastTrendDirection=0;
      FileWriteInteger(FileHandle,LastTrendDirection,SHORT_VALUE);
      FileClose(FileHandle);
      Print("LiveMALite.dat has been successfully created.");
    }
      else
      {
        FileClose(FileHandle);
        Print("Failed to create LiveMALite.dat file.");
      }  
    }
    else
    {
      LastTrendDirection=FileReadInteger(FileHandle,SHORT_VALUE);
      Print("LiveMALite variables loaded from file.");
      FileClose(FileHandle);
    }
  }      
  return(0);
}
//+------------------------------------------------------------------+
//|-----------------------//  Save Variables  //---------------------|
//+------------------------------------------------------------------+
int SaveVariables()
{
  if(IsTesting()==false)
  {
    //save variables to file
    FileHandle=FileOpen("LiveMALite.dat",FILE_BIN | FILE_WRITE);
    if(FileHandle<1)
    {
      Print("LiveMALite.dat not found.");
      FileHandle=FileOpen("LiveMALite.dat",FILE_BIN | FILE_WRITE);
      if(FileHandle>0)
      {
        FileWriteInteger(FileHandle,LastTrendDirection,SHORT_VALUE);
        FileClose(FileHandle);
        Print("LiveMALite.dat has been successfully created.");
      }  
      else
      {
      FileClose(FileHandle);
      Print("Failed to create LiveMALite.dat file.");
      }
    }
    else
    {
      FileWriteInteger(FileHandle,LastTrendDirection,SHORT_VALUE);
      FileClose(FileHandle);
      Print("LiveMALite Variables successfully saved to file.");
    }  
  }
return(0);
}
//+------------------------------------------------------------------+ 
int deinit()
{
  return(0);
} 
//+------------------------------------------------------------------+
int start()
{
//-----
  if(MoneyMangement == true)
  Lots = NormalizeDouble(AccountBalance()*MaximumRisk/100.00/100.00,1);
  else Lots = Lots;
//-----
  // init variables when the expert advisor first starts running
  if(InitVariables == true)
  {
    PreviousBar = Time[0];     // record the current canle/bar open time
                                 // place code here that you only wnat to run one time
    InitVariables = false;    // change to false so we only init variable once
  }
  // record trends direction
  if(LastTrendDirection==0)
  {
    if(TrendDetection()==BULL)
    {
      LastTrendDirection=BULL;
    }
    if(TrendDetection()==BEAR)
    {
      LastTrendDirection=BEAR;
    }
  }
//+------------------------------------------------------------------+
//|----------------------// Stops && Trailing //---------------------|
//+------------------------------------------------------------------+
  int Orders = OrdersTotal();
  for (int i=0; i<Orders; i++)
  {
    if(!(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))) continue;
    if(OrderSymbol() != Symbol()) continue;
    {
      if(OrderType() == OP_BUY && OrderStopLoss() == 0 && OrderMagicNumber()==Magic)
      {
      OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Bid,Digits)-StopLoss*Point,OrderTakeProfit(),0,CLR_NONE);            
      }   
      if(OrderType() == OP_BUY && OrderMagicNumber()==Magic) 
      {
        if(NormalizeDouble(Bid,Digits)-OrderOpenPrice() > MinProfit*Point) 
        {
          if(OrderStopLoss() < NormalizeDouble(Bid,Digits)-(TrailingStop+TrailingStep-1)*Point) 
          {
            OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Bid,Digits)-TrailingStop*Point,OrderTakeProfit(),0,CLR_NONE);        
          }
        }
      }
      if(OrderType() == OP_SELL && OrderStopLoss() == 0 && OrderMagicNumber()==Magic)
      {
      OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Ask,Digits)+StopLoss*Point,OrderTakeProfit(),0,CLR_NONE);
      }   
      if(OrderType() == OP_SELL && OrderMagicNumber()==Magic)
      {
        if(OrderOpenPrice()-NormalizeDouble(Ask,Digits) > MinProfit*Point) 
        {
          if(OrderStopLoss() > NormalizeDouble(Ask,Digits)+(TrailingStop+TrailingStep-1)*Point) 
          {
            OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Ask,Digits)+TrailingStop*Point,OrderTakeProfit(),0,CLR_NONE);          
          }
        }
      }   
    }   
  }
//+------------------------------------------------------------------+
//|------------------------//  Open Orders  //-----------------------|
//+------------------------------------------------------------------+
  // perform analysis and open orders on new candle/bar 
  if(NewBar() == true)
  {
    // only perform analysis and open new order if we have not reached our TotalOpenOrders max
    if(TotalOpenOrders() < TotalOrders)
    {
//----- // Open BUY
      if(TrendDetection() == BULL && LastTrendDirection == BEAR)
      {
        OrderSend(Symbol(),OP_BUY,Lots,NormalizeDouble(Ask,Digits),Slippage,0,0,OrderComments,Magic,0,BuyColor);
        LastTrendDirection=BULL;
        // save variables to file
        SaveVariables();
      }     
//----- // Open SELL
      if(TrendDetection() == BEAR && LastTrendDirection == BULL)
      {
        OrderSend(Symbol(),OP_SELL,Lots,NormalizeDouble(Bid,Digits),Slippage,0,0,OrderComments,Magic,0,SellColor);
        LastTrendDirection=BEAR;
        // save variables to file
        SaveVariables();
      }
    }
  }
  return(0);
}
//+------------------------------------------------------------------+
//|-----------------------//  Orders Count  //-----------------------|
//+------------------------------------------------------------------+
// This function returns the total amount of orders the expert advisor has open  
int TotalOpenOrders()
{
  Cnt=OrdersTotal();
  int TotalOpenOrders = 0;
  if(Cnt==0)
  {
    return(0);
  }
    else
    {
    for(;Cnt>=0;Cnt--)
    {
      RefreshRates();
      OrderSelect(Cnt,SELECT_BY_POS);
      if(OrderMagicNumber()==Magic)
      {
      TotalOpenOrders++;
      }
    }
  }
  return(TotalOpenOrders);
}
//+------------------------------------------------------------------+
//|--------------------------//  New Bar  //-------------------------|
//+------------------------------------------------------------------+
// This function return the value true if the current bar/candle was just formed
bool NewBar()
{
  if(PreviousBar<Time[0])
  {
    PreviousBar = Time[0];
    return(true);
  }
  else
  {
    return(false);
  }
  return(false);    // in case if - else statement is not executed
}
//+------------------------------------------------------------------+
//|---------------------//  Trend Detection  //----------------------|
//+------------------------------------------------------------------+
int TrendDetection()
{
//-------------------------------------------------------------------+
  double MA1=iMA(NULL,0,MAPeriod,0,MAMode,PRICE_CLOSE,0);
  double MA2=iMA(NULL,0,MAPeriod,0,MAMode,PRICE_WEIGHTED,0);
  double MA3=iMA(NULL,0,MAPeriod,0,MAMode,PRICE_TYPICAL,0);
  double MA4=iMA(NULL,0,MAPeriod,0,MAMode,PRICE_MEDIAN,0);
  double MA5=iMA(NULL,0,MAPeriod,0,MAMode,PRICE_OPEN,0);
//-----
  double ChannelUP = iEnvelopes(NULL,0,MAPeriod,MAMode,0,PRICE_OPEN,ChannelDeviat/100,MODE_UPPER,0);
  double ChannelDN = iEnvelopes(NULL,0,MAPeriod,MAMode,0,PRICE_OPEN,ChannelDeviat/100,MODE_LOWER,0);
//-----
  double Signal = iMA(NULL,0,1,0,0,PRICE_OPEN,0);
//-------------------------------------------------------------------+
//BULL trend
  if(MA1 > MA2 && MA2 > MA3 && MA3 > MA4 && MA4 > MA5)
  {
    if(!CheckChannel || Signal > ChannelUP)
    {
      return(BULL);
    }
  }
//BEAR trend
  if(MA1 < MA2 && MA2 < MA3 && MA3 < MA4 && MA4 < MA5)
  {
    if(!CheckChannel || Signal < ChannelDN)
    {
      return(BEAR);
    }
  }
//-----
  return(0);
}
//+------------------------------------------------------------------+
//|---------------------------// END //------------------------------|
//+------------------------------------------------------------------+

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