Selasa, 20 Mei 2014

Moving Average.mq4

//+------------------------------------------------------------------+
//|                                               Moving Average.mq4 |
//|                   Copyright 2005-2014, MetaQuotes Software Corp. |
//|                                              http://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright   "2005-2014, MetaQuotes Software Corp."
#property link        "http://www.mql4.com"
#property description "Moving Average sample expert advisor"

#define MAGICMA  20131111
//--- Inputs
input double Lots          =0.1;
input double MaximumRisk   =0.02;
input double DecreaseFactor=3;
input int    MovingPeriod  =12;
input int    MovingShift   =6;
//+------------------------------------------------------------------+
//| 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()==MAGICMA)
        {
         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()
  {
   double ma;
   int    res;
//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//--- get Moving Average
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//--- sell conditions
   if(Open[1]>ma && Close[1]<ma)
     {
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      return;
     }
//--- buy conditions
   if(Open[1]<ma && Close[1]>ma)
     {
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      return;
     }
//---
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double ma;
//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//--- get Moving Average
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//---
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //--- check order type
      if(OrderType()==OP_BUY)
        {
         if(Open[1]>ma && Close[1]<ma)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(Open[1]<ma && Close[1]>ma)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
     }
//---
  }
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
//---
  }
//+------------------------------------------------------------------+
========

2 Moving Average Cross

//+------------------------------------------------------------------+
//|                                          2 Moving Average Cross |
//|                                  Copyright © 2009, EarnForex.com |
//|                                        http://www.earnforex.com/ |
//+------------------------------------------------------------------+

extern double Lots      = 0.1;
extern int StopLoss     = 35;
extern int TakeProfit   = 70;
extern int TrailingStop = 20;
extern int Slippage     = 3;

extern int Period_1  = 20;
extern int Period_2  = 40;
//0 - SMA, 1 - EMA, 2 - SMMA, 3 - LWMA
extern int MA_Method    = 0;
//The minimum difference between MAs for Cross to count
extern int MinDiff      = 5;

int Magic;
//Depend on broker's quotes
double Poin;
int Deviation;

int LastBars = 0;

//0 - undefined, 1 - bullish cross (fast MA above slow MA), -1 - bearish cross (fast MA below slow MA)
int PrevCross = 0;

int SlowMA;
int FastMA;

//+------------------------------------------------------------------+
//| Initialization                                                   |
//+------------------------------------------------------------------+
int init()
{
   FastMA = MathMin(Period_1, Period_2);
   SlowMA = MathMax(Period_1, Period_2);

    Poin = Point;
    Deviation = Slippage;
    //Checking for unconvetional Point digits number
   if ((Point == 0.00001) || (Point == 0.001))
   {
      Poin *= 10;
      Deviation *= 10;
   }

   Magic = Period()+19472394;
   return(0);
}

//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
{
   if (FastMA == SlowMA)
   {
      Print("MA periods should differ.");
      return;
   }

   if (TrailingStop > 0) DoTrailing();

   //Wait for the new Bar in a chart.
    if (LastBars == Bars) return;
    else LastBars = Bars;

   if ((Bars < SlowMA) || (IsTradeAllowed() == false)) return;
  
   CheckCross();
}

//+------------------------------------------------------------------+
//| Check for cross and open/close the positions respectively        |
//+------------------------------------------------------------------+
void CheckCross()
{
   double FMA_Current = iMA(NULL, 0, FastMA, 0, MA_Method, PRICE_CLOSE, 0);
   double SMA_Current = iMA(NULL, 0, SlowMA, 0, MA_Method, PRICE_CLOSE, 0);
  
   if (PrevCross == 0) //Was undefined
   {
      if ((FMA_Current - SMA_Current) >= MinDiff * Poin) PrevCross = 1; //Bullish state
      else if ((SMA_Current - FMA_Current) >= MinDiff * Poin) PrevCross = -1; //Bearish state
      return;
   }
   else if (PrevCross == 1) //Was bullish
   {
      if ((SMA_Current - FMA_Current) >= MinDiff * Poin) //Became bearish
      {
         ClosePrev();
         fSell();
         PrevCross = -1;
      }
   }
   else if (PrevCross == -1) //Was bearish
   {
      if ((FMA_Current - SMA_Current) >= MinDiff * Poin) //Became bullish
      {
         ClosePrev();
         fBuy();
         PrevCross = 1;
      }
   }
}

//+------------------------------------------------------------------+
//| Close previous position                                          |
//+------------------------------------------------------------------+
void ClosePrev()
{
   int total = OrdersTotal();
   for (int i = 0; i < total; i++)
   {
      if (OrderSelect(i, SELECT_BY_POS) == false) continue;
      if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic))
      {
         if (OrderType() == OP_BUY)
         {
            RefreshRates();
            OrderClose(OrderTicket(), OrderLots(), Bid, Deviation);
         }
         else if (OrderType() == OP_SELL)
         {
            RefreshRates();
            OrderClose(OrderTicket(), OrderLots(), Ask, Deviation);
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Sell                                                             |
//+------------------------------------------------------------------+
int fSell()
{
    double SL, TP;
    RefreshRates();
    if (StopLoss > 0) SL = Bid + StopLoss * Poin;
    else SL = 0;
   if (TakeProfit > 0) TP = Bid - TakeProfit * Poin;
    else TP = 0;   
    int result = OrderSend(Symbol(), OP_SELL, Lots, Bid, Deviation, SL, TP, "Adjustable MA", Magic);
    if (result == -1)
    {
        int e = GetLastError();
        Print(e);
    }
    else return(result);
}

//+------------------------------------------------------------------+
//| Buy                                                              |
//+------------------------------------------------------------------+
int fBuy()
{
    double SL, TP;
    RefreshRates();
    if (StopLoss > 0) SL = Ask - StopLoss * Poin;
    else SL = 0;
   if (TakeProfit > 0) TP = Ask + TakeProfit * Poin;
    else TP = 0;   
    int result = OrderSend(Symbol(), OP_BUY, Lots, Ask, Deviation, SL, TP, "Adjustable MA", Magic);
    if (result == -1)
    {
        int e = GetLastError();
        Print(e);
    }
    else return(result);
}

void DoTrailing()
{
   int total = OrdersTotal();
   for (int pos = 0; pos < total; pos++)
   {
      if (OrderSelect(pos, SELECT_BY_POS) == false) continue;
      if ((OrderMagicNumber() == Magic) && (OrderSymbol() == Symbol()))
      {
         if (OrderType() == OP_BUY)
         {
            RefreshRates();
            if (Bid - OrderOpenPrice() >= TrailingStop * Poin) //If profit is greater or equal to the desired Trailing Stop value
            {
               if (OrderStopLoss() < (Bid - TrailingStop * Poin)) //If the current stop-loss is below the desired trailing stop level
                  OrderModify(OrderTicket(), OrderOpenPrice(), Bid - TrailingStop * Poin, OrderTakeProfit(), 0);
            }
         }
         else if (OrderType() == OP_SELL)
         {
            RefreshRates();
            if (OrderOpenPrice() - Ask >= TrailingStop * Poin) //If profit is greater or equal to the desired Trailing Stop value
            {
               if (OrderStopLoss() > (Ask + TrailingStop * Poin)) //If the current stop-loss is below the desired trailing stop level
                  OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TrailingStop * Poin, OrderTakeProfit(), 0);
            }
         }
      }
   }  
}

//+------------------------------------------------------------------+

HedgeLot_EA.mq4

//+------------------------------------------------------------------+
//|                                                  HedgeLot_EA.mq4 |
//|                                     Copyright © 2009, metropolis |
//|                                           metropolisfx@yahoo.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, metropolis"
#property link      "metropolisfx@yahoo.com"

extern int  TP = 35;
extern int  SL = 10;
extern double InstantLot = 0.1;
extern double PendingLot = 0.3;

#define Slippage 2
#define id1 12345
#define id2 67890

//global variables
static datetime lastB = -1;
static datetime lastS = -1;
static datetime lastClose = -1;
static double nextLot;
static double levelBuy;
static double levelSell;
static bool firstRun;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
  
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
  
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
Comment("\n", "     Broker Time         : ",TimeToStr(TimeCurrent()),"\n",
        "\n", "     Stop Level           : ",MarketInfo(Symbol(),MODE_STOPLEVEL),
        "\n", "     Orders Total        : ",OrdersTotal(),"\n",
        "\n", "     Copyright © 2009, metropolis - metropolisfx@yahoo.com");
        
if(!IsTradeAllowed())
{
   Print("Server tidak mengizinkan trade");
   Sleep(5000);
   return(0);
}
if(IsTradeContextBusy())
{
   Print("Trade context is busy. Tunggu sebentar");
   Sleep(5000);
   return(0);
}
if(!IsConnected())
{
   Print("Nggak ada koneksi untuk order dari EA ke server");
   Sleep(5000);
   return(0);
}
if(MarketInfo(Symbol(),MODE_STOPLEVEL)>TP || MarketInfo(Symbol(),MODE_STOPLEVEL)>SL)
{
   Print("Stop Level lebih besar dari pada SL atau TP");
   return(0);


if(!firstRun)
{      
   for (int i=OrdersHistoryTotal()-1;i>=0;i--)
   {
      OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==id2 && OrderProfit()>0 )
      {
         if(OrderType()==OP_SELL && OrderOpenTime()==lastS)
         { 
            deleteAll(OP_BUYSTOP);
            lastS = -1;
            Sleep(5000);
         }
          
         if(OrderType()==OP_BUY && OrderOpenTime()==lastB)
         { 
            deleteAll(OP_SELLSTOP); 
            lastB = -1;
            Sleep(5000);
         }
      }
   }        
}

manageTrade();

if(OrdersTotal()==0) firstRun();

  
//----
   return(0);
  }
//+------------------------------------------------------------------+

double p()
{
   double p;
   if(Digits==5 || Digits==3) p = 10*(MarketInfo(Symbol(),MODE_POINT));
   else p = MarketInfo(Symbol(),MODE_POINT);
   return (p);


void openOrder(string simbol, int trade, double lotsize, double price, double sl, double tp,string pesan, int magic, color warna)
{                    
   int tiket=OrderSend(simbol,trade,lotsize,price,Slippage,sl,tp,pesan,magic,0,warna);                             
   if(tiket>0)
   { 
        if(OrderSelect(tiket,SELECT_BY_TICKET,MODE_TRADES)) OrderPrint();
   }
   else Print("Tidak bisa buka order karena : ",GetLastError());       
}

void firstRun()
{//

   RefreshRates();
   int spread = MarketInfo(Symbol(),MODE_SPREAD);

   //buy
   double buyTP = Ask+(TP-spread)*p();
   double buySL = Ask-SL*p();
   openOrder(Symbol(),OP_BUY,InstantLot,Ask,buySL,buyTP,"buy awal",id1,Blue);
   levelBuy = Ask;
  
   //sell
   double sellTP = Bid-(TP-spread)*p();
   double sellSL = Bid+SL*p();
   openOrder(Symbol(),OP_SELL,InstantLot,Bid,sellSL,sellTP,"sell awal",id1,Red);
   levelSell = Bid;
  
   //buystop
   openOrder(Symbol(),OP_BUYSTOP,PendingLot,buyTP+spread*p(),Bid,buyTP+TP*p(),"buy lanjut",id2,Blue);
  
   //sellstop
   openOrder(Symbol(),OP_SELLSTOP,PendingLot,sellTP-spread*p(),Ask,sellTP-TP*p(),"sell lanjut",id2,Red);
  
   nextLot = PendingLot*2;
   firstRun = true;
}

void manageTrade()
{
   int i;
   int spread = MarketInfo(Symbol(),MODE_SPREAD);
   bool NewBuyExist = false;
   bool NewSellExist = false;
  
   for (i=OrdersTotal()-1;i>=0;i--)// mencari  order terakhir buystop yang menjadi buy
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==id2 && OrderType()==OP_BUY)
         {
            if(lastB != OrderOpenTime())
            {
               lastB = OrderOpenTime();
               levelBuy = OrderOpenPrice();
               NewBuyExist = true;
               break;
            } 
         }
      }
   }
  
  
   for (i=OrdersTotal()-1;i>=0;i--)// mencari order terakhir sell stop yang menjadi sell
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==id2 && OrderType()==OP_SELL)
         {
            if(lastS != OrderOpenTime())
            {
               lastS = OrderOpenTime(); // order terakhir sell dicatet waktunya
               levelSell = OrderOpenPrice();
               NewSellExist = true;
               break;
            } 
         }
      }
   }
  
   if(NewBuyExist)
   {
      if(firstRun)
      {
         for(i=0;i<OrdersTotal();i++)
         {
            OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==id2 && OrderType()==OP_SELLSTOP)
            {
               OrderDelete(OrderTicket());
               firstRun = false;
            } 
         }
      }
     
      if(!firstRun)
      {
         double sellTP = levelSell-(TP-spread)*p();
         double sellSL = levelSell+SL*p();
         openOrder(Symbol(),OP_SELLSTOP,nextLot,levelSell,sellSL,sellTP,"sell lanjut",id2,Red);
         nextLot *= 2;
      }
  
   }
  
   if(NewSellExist)
   {
      if(firstRun)
      {
         for(i=0;i<OrdersTotal();i++)
         {
            OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==id2 && OrderType()==OP_BUYSTOP)
            {
               OrderDelete(OrderTicket());
               firstRun = false;
            } 
         }
      }
     
      if(!firstRun)
      {
         double buyTP = levelBuy+(TP-spread)*p();
         double buySL = levelBuy-SL*p();
         openOrder(Symbol(),OP_BUYSTOP,nextLot,levelBuy,buySL,buyTP,"buy lanjut",id2,Blue);
         nextLot *= 2;
      }
   }

//---

}//


void deleteAll( int trade)
{
   int i;
  
   for (i=0;i<OrdersTotal();i++)
   OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
   if(OrderSymbol()==Symbol())
   {
      if(OrderType()==trade) OrderDelete(OrderTicket());
   }
}