//+------------------------------------------------------------------+
//|                                                L5_OpenMarket.mq4 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property strict

#include <stdlib.mqh>

double efRealSLPt = 10;
double efSLPt = 15;
double efTPPt = 10;
double efRiskPct = 2;
int enMagic = 122;
double efMaxSpread = 2.2;

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
{
  double fPtScale = 1;
  double fMtr = 1;
  double fPrice=0;
  double fPipCost;
  double fSL;
  double fTP;
  int nCmd;
  color lClr;
  
  double fMoneyToTrade;
  double fSLCost;
  double fLot;

  if ((Digits==5) || (Digits==3))
    fPtScale=10;
  else
    fPtScale=1;
    
  if ((MarketInfo(Symbol(),MODE_SPREAD)/fPtScale)>efMaxSpread)
  {
    Alert("Spread to high");
    return;
  }
    
  fPipCost=MarketInfo(Symbol(),MODE_TICKVALUE)*fPtScale;
  fMoneyToTrade=AccountFreeMargin()/100*efRiskPct;
  fSLCost=efRealSLPt*fPipCost;
  fLot=NormalizeDouble(fMoneyToTrade/fSLCost,2);
  if (fLot<MarketInfo(Symbol(),MODE_MINLOT))
  {
    Alert("Lot to Small");
    return;
  }
    
  /*if ((Digits==3) || (Digits==2))
    fMtr=10;
  else
    fMtr=1000;*/

  if (WindowPriceOnDropped()>Bid)
  {
    fPrice=NormalizeDouble(Ask,Digits);
    fSL=NormalizeDouble(fPrice-efSLPt*Point*fPtScale,Digits);
    fTP=NormalizeDouble(fPrice+efTPPt*Point*fPtScale,Digits);
    nCmd=OP_BUY;
    lClr=clrBlue;
  }
  else
  {
    fPrice=NormalizeDouble(Bid,Digits);
    fSL=NormalizeDouble(fPrice+efSLPt*Point*fPtScale,Digits);
    fTP=NormalizeDouble(fPrice-efTPPt*Point*fPtScale,Digits);
    nCmd=OP_SELL;
    lClr=clrRed;
  }
  if (OrderSend(Symbol(),nCmd,fLot,fPrice,1,fSL,fTP,"",enMagic,0,lClr)<0)
    Alert(ErrorDescription(GetLastError()));
}
//+------------------------------------------------------------------+
