//+---------------------------------------------------------------------------------------------------------------------------------+
//|	ScalpMate.mq4
//|	Copyright © 2011, Fedorov Valeriy
//| Версия 0.3
//+---------------------------------------------------------------------------------------------------------------------------------+
#property copyright "Copyright © 2011, Fedorov Valeriy"
#property link      ""

extern int	StartSL_				=	7;
extern int	StartTP_				=	10;
extern int	StartSafe_			=	5;

extern int	StartLoke_			=	37;
extern int  PendingLevel_     =  2;  


extern bool SafeBreakEvent	= true;
extern bool SafeCloseHalf		= true;
extern double	SafePips_			= 0.5;

extern bool AutoLot					= false;
extern string AutoLotField	= "MasterMoneyBot";
extern double	BaseLot				=	1.0;

extern int	MagicNumber			= 88889999;
extern string	BotComments		=	"ScalpMate";

extern bool    UseSound       = True;   

extern int	Corner					=	1;
extern int	XShift					=	10;
extern int	YShift					=	70;
extern int	XInterval				=	100;
extern int	YInterval				=	25;

extern color	SLColor				=	Red;
extern color	TPColor				=	Green;
extern color	SafeColor			=	Blue;

//--------------------- Подключаемые библиотеки ---------------------+
#include       <stdlib.mqh>                       // Стандартная библиотека МТ4
#include       <WinUser32.mqh>

//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
int To[1000];							//Тикеты наших открытых ордеров
int Toc;						//Количество наших открытых ордеров
string         NameFileSound  = "news.wav";              // Наименование звукового файла
int            NumberOfTry    = 3;                       // Количество попыток выставить ордер
//int Tp[1000];							//Тикеты наших отложенных ордеров
//int Tpc;						//Количество наших отложенных ордеров
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//Константы
#define E_BUY			 	5
#define E_SELL		 	6
#define E_CLOSE_ALL	7
#define E_MOD_SL	 	8
#define E_MOD_TP	 	9
#define E_CLOSE_12	10

//Глобальные переменные
double OP, SL, TP, oldSL, oldTP;
double SFL;	//SafeLevel
double Lot;
double StartSL,StartTP,StartSafe,SafePips, StartLoke, PendingLevel, PendingPrice;
int MN; 		//MagicNumber
string CM;	//BotComments

//Объекты
//Линии
string 	LStop		 			= "LStop";
int			LStopStyle		=	STYLE_DASHDOT;
double	LStopLevel;
string 	LTake 				= "LTake";
int			LTakeStyle		=	STYLE_DASHDOT;
double	LTakeLevel, LLokeLevel ;
string 	LSafe 				= "LSafe";
int			LSafeStyle		=	STYLE_DASHDOT;
double	LSafeLevel;
bool		LSafeActive		= false;

//Поля данных
string 	FLot 			= "FLot";
color 	FLotColor	=	Blue;
int			FLotX,FLotY;

string 	FMagic 		= "FMagic";
color 	FMagicColor	=	Magenta;
int			FMagicX,FMagicY;

string 	FComment	= "FComment";
color 	FCommentColor	=	Purple;
int			FCommentX,FCommentY;

//Кнопки

string	BBuy		 				= "BBuy";
color 	BBuyColor				=	Red;
int			BBuyX,BBuyY;

string	BSell		 				= "BSell";
color 	BSellColor			=	Red;
int			BSellX,	BSellY;

string	BCloseAll				= "BCloseAll";
color 	BCloseAllColor	=	Magenta;
int			BCloseAllX,BCloseAllY;

string	BClose12				= "BClose1/2";
color 	BClose12Color		=	Blue;
int			BClose12X,BClose12Y;

//LN
 bool interrupt = true;
 int flags, answer, orders_type;
 string symbl, str_box, title_box;

//+---------------------------------------------------------------------------------------------------------------------------------+
int init()
{
	//Приведение к брокерскому количеству знаков после запятой
	double Digits4 = 4.0;	//В параметрах указываются значения для 4х знаков
	
	
	switch(Digits)
		{
		case 0: Digits4 = 0.0; break;
		case 1: Digits4 = 0.0; break;
		case 2: Digits4 = 2.0; break;
		case 3: Digits4 = 2.0; break;
		case 4: Digits4 = 4.0; break;
		case 5: Digits4 = 4.0; break;
		}
	
	StartSL=NormalizeDouble(StartSL_/MathPow(10,Digits4)*MathPow(10,Digits)*Point,Digits);
	StartTP=NormalizeDouble(StartTP_/MathPow(10,Digits4)*MathPow(10,Digits)*Point,Digits);
	StartSafe=NormalizeDouble(StartSafe_/MathPow(10,Digits4)*MathPow(10,Digits)*Point,Digits);
	SafePips=NormalizeDouble(SafePips_/MathPow(10,Digits4)*MathPow(10,Digits)*Point,Digits);
	
	StartLoke=NormalizeDouble(StartLoke_/MathPow(10,Digits4)*MathPow(10,Digits)*Point,Digits);
	
	PendingLevel = NormalizeDouble(PendingLevel_/MathPow(10,Digits4)*MathPow(10,Digits)*Point,Digits);
	
	Print("Digits4="+Digits4);

	int i=0;
	
	if(AutoLot)	Lot=StrToDouble(ObjectDescription(AutoLotField));
	else if(ObjectFind(FLot)==-1) Lot=BaseLot;

	if(ObjectFind(FMagic)==-1) MN=MagicNumber;
	if(ObjectFind(FComment)==-1) CM=BotComments;
	
	FLotX=XShift+XInterval;
	FLotY=YShift+i*YInterval;
	BBuyX=XShift;
	BBuyY=YShift+i*YInterval;
	i++;

	FMagicX=XShift+XInterval;
	FMagicY=YShift+i*YInterval;
	BSellX=XShift;
	BSellY=YShift+i*YInterval;
	i++;

	FCommentX=XShift+XInterval;
	FCommentY=YShift+i*YInterval;
	BCloseAllX=XShift;
	BCloseAllY=YShift+i*YInterval;
	
	i++;
	BClose12X=XShift;
	BClose12Y=YShift+i*YInterval;

	Toc=SearchOpenedOrders(To,MN);
	if(Toc>0)
		if(OrderSelect(To[0],SELECT_BY_POS,MODE_TRADES))
			{
			LStopLevel=OrderStopLoss();
			LTakeLevel=OrderTakeProfit();
			}
	
	return(0);
}
//+---------------------------------------------------------------------------------------------------------------------------------+
int deinit()
{
	DeleteObjects();
	return(0);
}
//+---------------------------------------------------------------------------------------------------------------------------------+
int LastEvent;

int start()
{
	oldSL=SL;
	oldTP=TP;
	
	CreateObjects();
	GetInfo();
	SafeLineVerify();
	VerifyOrders();
	FieldsPosition();
	LastEvent=GetEvent();
	
	//open order from the market
	if(LastEvent==E_BUY)	{ 
		//LN
		str_box = "Type of order. \n YES - Market / NOT - Pendig / Cancel";
      title_box = " Choose Type of order.";
      flags = MB_YESNOCANCEL|MB_ICONEXCLAMATION;
      answer = MessageBox(str_box, title_box, flags);
      if(answer == IDCANCEL)interrupt = false;
      else {
         if(answer == IDYES){
             orders_type = OP_BUY;
             
		  	    OpenOrder(OP_BUY, Lot, 0, 0, MN, CM);
		       LStopLevel=Ask-StartSL;
		       LTakeLevel=Ask+StartTP;
		       LSafeLevel=Ask+StartSafe;
		       if(StartSafe_>0) LSafeActive=true;
		
		       LLokeLevel=Ask-StartLoke;
          }
          else {
             orders_type = OP_BUYSTOP;
             PendingPrice=Ask + PendingLevel;
             Print("PendingPrice="+PendingPrice); //+"; price="+price+"; LLokeLevel="+LLokeLevel+"; price- LLokeLevel="+ (price-LLokeLevel));         
             SetOrder("", orders_type, Lot, PendingPrice, 0,0, MN, 0);
             //SetOrder("", orders_type, Lot, open_pr, order_sl, order_tp, MN, 0);
             
             LStopLevel=PendingPrice-StartSL;
		       LTakeLevel=PendingPrice+StartTP;
		       LSafeLevel=PendingPrice+StartSafe;
		       if(StartSafe_>0) LSafeActive=true;
		  	 
         }          
     }	
	}
	if(LastEvent==E_SELL) {
	
		OpenOrder(OP_SELL, Lot, 0, 0, MN, CM);
		LStopLevel=Bid+StartSL;
		LTakeLevel=Bid-StartTP;
		LSafeLevel=Bid-StartSafe;
		if(StartSafe_>0) LSafeActive=true;
		
		LLokeLevel=Bid+StartLoke;
		
		}
	//
	if(LastEvent==E_CLOSE_ALL) 
		CloseAll(-1, MN, 1);

	//
	if(LastEvent==E_CLOSE_12) 
		CloseAll(-1, MN, 0.5);
		
	//Перестановка стопов
	Toc=SearchOpenedOrders(To,MN);
	if(Toc>0)
		{
		if(oldSL!=SL) 
			{
			ModStops(SL,-1);
			}
		if(oldTP!=TP) 
			{
			ModStops(-1, TP);
			}
		
		}
	
	return(0);
}
//+---------------------------------------------------------------------------------------------------------------------------------+
void SetOrder(string sy, int op, double ll, double pp, double sl=0, double tp=0, int mn=0, datetime ex=0) 
{
   int err, dg, ticket=0;
   
//---------------
   if (sy=="" || sy=="0") sy=Symbol();
   
   for (int it=1; it<=NumberOfTry; it++) {

      while (!IsTradeAllowed()) Sleep(5000);
      
      dg=MarketInfo(sy, MODE_DIGITS);
      pp=NormalizeDouble(pp, dg);
      
      ticket=OrderSend(sy, op, ll, pp, 0, sl, tp, NULL, mn, 0, CLR_NONE);
      
      if (ticket>0) {
         if (UseSound) PlaySound(NameFileSound); break;
      } 
      else {
         err=GetLastError();
         // Вывод сообщения об ошибке
         Print("Error(",err,") opening position: ",ErrorDescription(err),", try ",it);

         if (err==4 || err==131 || err==132) Sleep(1000*300); break;
         if (err==128 || err==142 || err==143) Sleep(1000*66.666);
         if (err==140 || err==148 || err==4110 || err==4111) break;
         if (err==141) Sleep(1000*100);
         if (err==145) Sleep(1000*17);
         if (err==146) while (IsTradeContextBusy()) Sleep(1000*11);
         if (err!=135) Sleep(1000*7.7);
      }
   }
  return(ticket);
}

//+---------------------------------------------------------------------------------------------------------------------------------+

//+---------------------------------------------------------------------------------------------------------------------------------+
//open pozy
/*
params:
	OType  - type of signal. value: OP_BUY (or  0) - signal BUY, OP_SELL (or 1) - signal SELL
	vol - lot
	sl - stop loss
	tp - take profit
	nm - magic
	cm - comments
	
return values: 
	-1 - pozy did not open
	>0 - ticket open pozy
*/
int OpenOrder(int OType, double vol, double sl, double tp, int mn, string cm)
{
	//check if  alreafy have open order that do not open new one
	Toc=SearchOpenedOrders(To,mn);
//LN 	if (Toc>0) return(-1);

	int j;
	int T=0;
	double pr;
  int tries=10;				//numbers of attemps to open/close/modify order
  color clr;
	
	if(OType==OP_BUY)
		{
		pr=Ask;
		clr=Blue;
		}
	if(OType==OP_SELL)
		{
		pr=Bid;
		clr=Red;
		}

	pr=NormalizeDouble(pr,Digits);
	sl=NormalizeDouble(sl,Digits);
	tp=NormalizeDouble(tp,Digits);

	for(j=1; j<=tries; j++)
		{
		T=OrderSend(Symbol(), OType, vol, pr, 3, sl, tp, cm, mn, 0, clr);
		if(T>0) break;
		Sleep(500);
		RefreshRates();
		}
	if(j>tries)
		Print("error # ", GetLastError() ," when try to open ", OType, " Lot=", vol , " Ask=", Ask, " Bid=", Bid, " SL=", sl, " TP=", tp);
	
	return(T);
}
//+---------------------------------------------------------------------------------------------------------------------------------+
//Удаление объектов
void DeleteObjects()
{
	/*
	ObjectDelete(FLot);
	ObjectDelete(FMagic);
	ObjectDelete(FComment);
	*/
	ObjectDelete(BBuy);
	ObjectDelete(BSell);
	ObjectDelete(BCloseAll);
	ObjectDelete(LStop);
	ObjectDelete(LTake);
	ObjectDelete(LSafe);
	ObjectDelete(BClose12);
	
}

//
int CreateObjects()
{
	//field
	if(ObjectFind(FLot)==-1) 
		{
		ObjectCreate(FLot,OBJ_LABEL,0,FLotX,FLotY);
		ObjectSetText(FLot,DoubleToStr(Lot,2));
		ObjectSet(FLot,OBJPROP_COLOR,FLotColor);
		ObjectSet(FLot,OBJPROP_CORNER,Corner);
		ObjectSet(FLot,OBJPROP_XDISTANCE,FLotX);
		ObjectSet(FLot,OBJPROP_YDISTANCE,FLotY);
		}

	if(ObjectFind(FMagic)==-1) 
		{
		ObjectCreate(FMagic,OBJ_LABEL,0,FMagicX,FMagicY);
		ObjectSetText(FMagic,DoubleToStr(MN,0));
		ObjectSet(FMagic,OBJPROP_COLOR,FMagicColor);
		ObjectSet(FMagic,OBJPROP_CORNER,Corner);
		ObjectSet(FMagic,OBJPROP_XDISTANCE,FMagicX);
		ObjectSet(FMagic,OBJPROP_YDISTANCE,FMagicY);
		}
	if(ObjectFind(FComment)==-1) 
		{
		ObjectCreate(FComment,OBJ_LABEL,0,FCommentX,FCommentY);
		ObjectSetText(FComment,CM);
		ObjectSet(FComment,OBJPROP_COLOR,FCommentColor);
		ObjectSet(FComment,OBJPROP_CORNER,Corner);
		ObjectSet(FComment,OBJPROP_XDISTANCE,FCommentX);
		ObjectSet(FComment,OBJPROP_YDISTANCE,FCommentY);
		}

	//line
	if(!LSafeActive) ObjectDelete(LSafe);
	double pos, npos;
	Toc=SearchOpenedOrders(To,MN);
	if(Toc==0)
		{
		ObjectDelete(LStop);
		ObjectDelete(LTake);
		}
	if(Toc>0)
		{
		if(StartSL_>0)
			{
			if(ObjectFind(LStop)==-1) 
				{
				ObjectCreate(LStop,OBJ_HLINE,0,0,LStopLevel);
				ObjectSet(LStop,OBJPROP_COLOR,SLColor);
				ObjectSet(LStop,OBJPROP_STYLE,LStopStyle);
				}
			else
				{
				pos=ObjectGet(LStop, OBJPROP_PRICE1);
				npos=NormalizeDouble(pos,Digits);
				if(pos!=npos) ObjectSet(LStop,OBJPROP_PRICE1,npos);
				LStopLevel=npos;
				}
			}
		if(StartTP_>0)
			{
			if(ObjectFind(LTake)==-1) 
				{
				ObjectCreate(LTake,OBJ_HLINE,0,0,LTakeLevel);
				ObjectSet(LTake,OBJPROP_COLOR,TPColor);
				ObjectSet(LTake,OBJPROP_STYLE,LTakeStyle);
				}
			else
				{
				pos=ObjectGet(LTake, OBJPROP_PRICE1);
				npos=NormalizeDouble(pos,Digits);
				if(pos!=npos) ObjectSet(LTake,OBJPROP_PRICE1,npos);
				LTakeLevel=npos;
				}
			}
			
		if(LSafeActive)
			{
			if(ObjectFind(LSafe)==-1) 
				{
				ObjectCreate(LSafe,OBJ_HLINE,0,0,LSafeLevel);
				ObjectSet(LSafe,OBJPROP_COLOR,SafeColor);
				ObjectSet(LSafe,OBJPROP_STYLE,LSafeStyle);
				}
			else
				{
				pos=ObjectGet(LSafe, OBJPROP_PRICE1);
				npos=NormalizeDouble(pos,Digits);
				if(pos!=npos) ObjectSet(LSafe,OBJPROP_PRICE1,npos);
				LSafeLevel=npos;
				}
			}
		
		}
	
	//button
	if(ObjectFind(BBuy)==-1) 
		{
		ObjectCreate(BBuy,OBJ_LABEL,0,BBuyX,BBuyY);
		ObjectSetText(BBuy,"BUY");
		ObjectSet(BBuy,OBJPROP_COLOR,BBuyColor);
		ObjectSet(BBuy,OBJPROP_CORNER,Corner);
		ObjectSet(BBuy,OBJPROP_XDISTANCE,BBuyX);
		ObjectSet(BBuy,OBJPROP_YDISTANCE,BBuyY);
		}

	if(ObjectFind(BSell)==-1) 
		{
		ObjectCreate(BSell,OBJ_LABEL,0,BSellX,BSellY);
		ObjectSetText(BSell,"SELL");
		ObjectSet(BSell,OBJPROP_COLOR,BSellColor);
		ObjectSet(BSell,OBJPROP_CORNER,Corner);
		ObjectSet(BSell,OBJPROP_XDISTANCE,BSellX);
		ObjectSet(BSell,OBJPROP_YDISTANCE,BSellY);
		}

	if(ObjectFind(BCloseAll)==-1) 
		{
		ObjectCreate(BCloseAll,OBJ_LABEL,0,BCloseAllX,BCloseAllY);
		ObjectSetText(BCloseAll,"Close ALL");
		ObjectSet(BCloseAll,OBJPROP_COLOR,BCloseAllColor);
		ObjectSet(BCloseAll,OBJPROP_CORNER,Corner);
		ObjectSet(BCloseAll,OBJPROP_XDISTANCE,BCloseAllX);
		ObjectSet(BCloseAll,OBJPROP_YDISTANCE,BCloseAllY);
		}

	if(ObjectFind(BClose12)==-1) 
		{
		ObjectCreate(BClose12,OBJ_LABEL,0,BClose12X,BClose12Y);
		ObjectSetText(BClose12,"Close 1/2");
		ObjectSet(BClose12,OBJPROP_COLOR,BClose12Color);
		ObjectSet(BClose12,OBJPROP_CORNER,Corner);
		ObjectSet(BClose12,OBJPROP_XDISTANCE,BClose12X);
		ObjectSet(BClose12,OBJPROP_YDISTANCE,BClose12Y);
		}

}

//+---------------------------------------------------------------------------------------------------------------------------------+
//Сбор информации с объектов
int GetInfo()
{
	SL=ObjectGet(LStop, OBJPROP_PRICE1);
	TP=ObjectGet(LTake, OBJPROP_PRICE1);
	SFL=ObjectGet(LSafe, OBJPROP_PRICE1);
	if(AutoLot)	Lot=StrToDouble(ObjectDescription(AutoLotField));
	else Lot=StrToDouble(ObjectDescription(FLot));
	MN=StrToDouble(ObjectDescription(FMagic));
	CM=ObjectDescription(FComment);
}
//+---------------------------------------------------------------------------------------------------------------------------------+
//Проверка событий
/*
Параметры:
	nm 	- magic

Возвращаемые значения:
	E_PEND_STOP	=	1	-	нажата кнопка PEND_STOP
	E_PEND_LIM	=	2	-	нажата кнопка PEND_LIM
	E_DEL_STOP	= 3	-	нажата кнопка DEL_STOP
	E_DEL_LIM	 	= 4	-	нажата кнопка DEL_LIM
	E_BUY			 	= 5	-	нажата кнопка BUY
	E_SELL		 	= 6	-	нажата кнопка SELL
	E_CLOSE_ALL	= 7	-	нажата кнопка CLOSE_ALL
	E_MOD_SL	 	= 8	-	нажата кнопка MOD_SL
	E_MOD_TP	 	= 9	-	нажата кнопка MOD_TP
	

*/
int LastDrag=0;

int GetEvent()
{
	int res=0;
	int x, y;
	
	//BUY
	x=ObjectGet(BBuy, OBJPROP_XDISTANCE);
	y=ObjectGet(BBuy, OBJPROP_YDISTANCE);
	if(x!=BBuyX || y!=BBuyY) 
		{
		ObjectSet(BBuy,OBJPROP_XDISTANCE,BBuyX);
		ObjectSet(BBuy,OBJPROP_YDISTANCE,BBuyY);
		LastDrag=E_BUY;
		}
	if(x==BBuyX && y==BBuyY && LastDrag==E_BUY) 
		{
		res=E_BUY;
		LastDrag=0;
		}

	//SELL
	x=ObjectGet(BSell, OBJPROP_XDISTANCE);
	y=ObjectGet(BSell, OBJPROP_YDISTANCE);
	if(x!=BSellX || y!=BSellY) 
		{
		ObjectSet(BSell,OBJPROP_XDISTANCE,BSellX);
		ObjectSet(BSell,OBJPROP_YDISTANCE,BSellY);
		LastDrag=E_SELL;
		}
	if(x==BSellX && y==BSellY && LastDrag==E_SELL) 
		{
		res=E_SELL;
		LastDrag=0;
		}
		
	//CLOSE_ALL
	x=ObjectGet(BCloseAll, OBJPROP_XDISTANCE);
	y=ObjectGet(BCloseAll, OBJPROP_YDISTANCE);
	if(x!=BCloseAllX || y!=BCloseAllY) 
		{
		ObjectSet(BCloseAll,OBJPROP_XDISTANCE,BCloseAllX);
		ObjectSet(BCloseAll,OBJPROP_YDISTANCE,BCloseAllY);
		LastDrag=E_CLOSE_ALL;
		}
	if(x==BCloseAllX && y==BCloseAllY && LastDrag==E_CLOSE_ALL) 
		{
		res=E_CLOSE_ALL;
		LastDrag=0;
		}
	

	//CLOSE 1/2
	x=ObjectGet(BClose12, OBJPROP_XDISTANCE);
	y=ObjectGet(BClose12, OBJPROP_YDISTANCE);
	if(x!=BClose12X || y!=BClose12Y) 
		{
		ObjectSet(BClose12,OBJPROP_XDISTANCE,BClose12X);
		ObjectSet(BClose12,OBJPROP_YDISTANCE,BClose12Y);
		LastDrag=E_CLOSE_12;
		}
	if(x==BClose12X && y==BClose12Y && LastDrag==E_CLOSE_12) 
		{
		res=E_CLOSE_12;
		LastDrag=0;
		}
		
			
	//MOD_SL
/*
	double p;
	
	p=ObjectGet(LStop, OBJPROP_PRICE1);
	Toc=SearchOpenedOrders(To,mn);
	//x=ObjectGet(BModSL, OBJPROP_XDISTANCE);
	//y=ObjectGet(BModSL, OBJPROP_YDISTANCE);
	if(p!=BModSLX || y!=BModSLY) 
		{
		ObjectSet(BModSL,OBJPROP_XDISTANCE,BModSLX);
		ObjectSet(BModSL,OBJPROP_YDISTANCE,BModSLY);
		LastDrag=E_MOD_SL;
		}
	if(x==BModSLX && y==BModSLY && LastDrag==E_MOD_SL) 
		{
		res=E_MOD_SL;
		LastDrag=0;
		}

	//MOD_TP
	x=ObjectGet(BModTP, OBJPROP_XDISTANCE);
	y=ObjectGet(BModTP, OBJPROP_YDISTANCE);
	if(x!=BModTPX || y!=BModTPY) 
		{
		ObjectSet(BModTP,OBJPROP_XDISTANCE,BModTPX);
		ObjectSet(BModTP,OBJPROP_YDISTANCE,BModTPY);
		LastDrag=E_MOD_TP;
		}
	if(x==BModTPX && y==BModTPY && LastDrag==E_MOD_TP) 
		{
		res=E_MOD_TP;
		LastDrag=0;
		}
*/
	return(res);
}
//+---------------------------------------------------------------------------------------------------------------------------------+
//Проверка стопов
int VerifyOrders()
{
	/*
	if(SearchOpenedOrders(To, MagicNumber)>0) 
		{
		CloseAll(OP_BUYSTOP, MN);
		CloseAll(OP_SELLSTOP, MN);
		CloseAll(OP_BUYLIMIT, MN);
		CloseAll(OP_SELLLIMIT, MN);
		}
	*/
}
//+---------------------------------------------------------------------------------------------------------------------------------+
//Проверка положения полей
void FieldsPosition()
{
	ObjectSet(FLot,OBJPROP_XDISTANCE,FLotX);
	ObjectSet(FLot,OBJPROP_YDISTANCE,FLotY);

	ObjectSet(FMagic,OBJPROP_XDISTANCE,FMagicX);
	ObjectSet(FMagic,OBJPROP_YDISTANCE,FMagicY);
	
	ObjectSet(FComment,OBJPROP_XDISTANCE,FCommentX);
	ObjectSet(FComment,OBJPROP_YDISTANCE,FCommentY);
}

//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
////searh for open ordes
//params:
//	to[]	- array for tickets
/*
	nm 	- magic
	
return values: 
	numbers of open orders
*/
int SearchOpenedOrders(int &to[], int mn)
{
	int i, count=0;
	
	for (i=0; i<OrdersTotal(); i++)
		if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
			if (mn==OrderMagicNumber() && OrderSymbol()==Symbol())
				if (OrderType()==OP_BUY || OrderType()==OP_SELL  ) 
					{
					to[count]=OrderTicket();
					count++;
					}
	return(count);
}
//+---------------------------------------------------------------------------------------------------------------------------------+

//+---------------------------------------------------------------------------------------------------------------------------------+
//close pozy
/*
params:
	ticket - tiket #. if -1, that apply to all open orders
	OType  - type of order . Close only that type of order if  ticket=-1
						if: -1 	close all orders 
											OP_BUY (if 0) 		- close  BUY, 
											OP_SELL (if 1) 	- close SELL
	nm - magic
	
	klot -  what part of pozy close  (>0, <=1).
					if : 1 - close all 
										0,5 - half pozy
										
return values: -
*/
int CloseAll(int OType, int mn, double klot)
{
	int i;
	int To[1000], Toc;
	Toc=SearchOpenedOrders(To,mn);

	for(i=0; i<Toc; i++)
		if(OrderSelect(To[i],SELECT_BY_TICKET,MODE_TRADES))
			if(OrderType()==OType || OType==-1)
				CloseOrder(To[i],klot);

	return(0);
}
//+---------------------------------------------------------------------------------------------------------------------------------+
//close order
/*
params:
	ticket - order number. if -1, that apply to all open orders
	nm - magic number
	klot - what part of pozy close  (>0, <=1).
					if : 1 - close all 
										0,5 - half pozy
	
return values:
 true		- ok
 false	- not ok
*/
bool CloseOrder(int ticket,double klot)
{
	bool res=false;

	if(klot<=0 || klot >1) return(res);
	
	int j;
	double price;
  int tries=10;				//numbera to attemps close/modify/open ordera
  double lot, minlot, lotstep, lt;
  int minlotdigits;
  
  lotstep=MarketInfo(Symbol(),MODE_LOTSTEP);
  minlot=MarketInfo(Symbol(),MODE_MINLOT);
  lt=MathMin(minlot,lotstep);
  
  minlotdigits=0;
  while(lt<1)
  	{
  	lt*=10;
  	minlotdigits++;
  	}

	// close particular order
	if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
		{
		if(OrderType()==OP_BUY) price=Bid;
		if(OrderType()==OP_SELL) price=Ask;
		for(j=1; j<=tries; j++)
			{
			lot=NormalizeDouble(OrderLots()*klot,minlotdigits);
			if(OrderClose(OrderTicket(),lot,price,3,Chocolate)) break;
			Sleep(500);
			RefreshRates();
			}
		if(j>tries)
			Print("error ", GetLastError() ," when try to close ",ticket, " ", OrderType(), " Ask=", Ask, " Bid=", Bid);
		else
			res=true;
		}
	return(res);
}

//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//move all stops for all open orders
/*
params :
double sl, tp - SL and TP. if value =(-1), that do not change
*/
int ModStops(double sl, double tp)
{
	int i,j, count=0;
	int tries=1;
	double pr, ssl, ttp;
	
	Toc=SearchOpenedOrders(To, MN);
	for(i=0;i<Toc;i++)
		{
		if(OrderSelect(To[i],SELECT_BY_TICKET,MODE_TRADES))
			{
			pr=OrderOpenPrice();
		
			if(tp<0) ttp=OrderTakeProfit();
			else ttp=NormalizeDouble(tp,Digits);

			if(sl<0) ssl=OrderStopLoss();
			else ssl=NormalizeDouble(sl,Digits);
		
			for(j=1; j<=tries; j++)
				{
				if(OrderModify(To[i], pr, ssl, ttp, 0, DodgerBlue)) break;
				Sleep(500);
				RefreshRates();
				}

			if(j>tries)
				Print("error #", GetLastError() ," when try to modify order ", To[i], " Ask=", Ask, " Bid=", Bid, " SL=", ssl, " TP=", ttp);
			}
		}
	return(0);
}

//+---------------------------------------------------------------------------------------------------------------------------------+
//+---------------------------------------------------------------------------------------------------------------------------------+
//check condition of  SafeLine
void SafeLineVerify()
{
	Toc=SearchOpenedOrders(To,MN);
	if(Toc==0) LSafeActive=false;
	
	if(!LSafeActive) return(0);
	
	int i,j, count=0,oty;
	double pr, price;
	
	for(i=0;i<Toc;i++)
		{
		if(OrderSelect(To[i],SELECT_BY_TICKET,MODE_TRADES))
			{
			pr=OrderOpenPrice();
			oty=OrderType();
			
			//move stop v bezubitok i kroem half pozi
			if((oty==OP_BUY) && (Close[0]>=SFL))
				{
				if(SafeBreakEvent) 
					{
					LStopLevel=pr+SafePips;
					ObjectDelete(LStop);
					}
				if(SafeCloseHalf) CloseAll(-1, MN, 0.5);
				LSafeActive=false;
				}
			
			if((oty==OP_SELL) && (Close[0]<=SFL))
				{
				if(SafeBreakEvent) 
					{
					LStopLevel=pr-SafePips;
					ObjectDelete(LStop);
					}
					//ModStops(pr-SafePips, -1);
				if(SafeCloseHalf) CloseAll(-1, MN, 0.5);
				LSafeActive=false;
				}
				
					// LN my modification; check if price move more then StartLoke  7.25.2012
						if(OrderType()==OP_BUY) price=Bid;
		            if(OrderType()==OP_SELL) price=Ask;
			   //	Print("open pr="+pr+"; price="+price+"; LLokeLevel="+LLokeLevel+"; price- LLokeLevel="+ (price-LLokeLevel));
			   if( ((oty==OP_BUY) && (price - LLokeLevel) < 0  )  || ((oty==OP_SELL) && (price - LLokeLevel) > 0) )
			   {
					ObjectDelete(LStop);
							
		         ModStops(0, 0); 
		         LSafeActive=false;
		         
		         ObjectDelete(LSafe);
		         
		         if(OrderType()==OP_BUY) {
		          OpenOrder(OP_SELL, Lot, 0, 0, MN, CM);
		         }
		         if(OrderType()==OP_SELL) {
		          OpenOrder(OP_BUY, Lot, 0, 0, MN, CM);
		         }
		         ObjectDelete(LTake);
	
		
		       }  
					
		         
   		}  // if  
	}  // for
	
	return(0);
}