//+------------------------------------------------------------------+
//|                                    		   James_rat_adviser.mq4 |
//|                                               Schneider Anatoliy |
//|                                               fxnthint@gmail.com |
//+------------------------------------------------------------------+
#property copyright "Schneider Anatoliy"
#property link      "fxnthint@gmail.com"

//+------------------------------------------- external variables ---+ 

extern string sep_01 = "E N T R Y  S E T T I N G S";
extern bool red_rat = true;
extern bool green_rat = true;
extern double lot_size_01 = 0.1;
extern double lot_size_02 = 0.1;
extern bool enable_money_management = false;
extern double risk_percent_01 = 1.0;
extern double risk_percent_02 = 1.0;
extern int entry_buffer = 0;
extern bool enable_M5 = true;
extern int magic_M5 = 1001;
extern bool enable_M15 = true;
extern int magic_M15 = 1002;
extern bool enable_M30 = true;
extern int magic_M30 = 1003;
extern bool enable_H1 = true; 
extern int magic_H1 = 1004;
extern bool enable_H4 = true;
extern int magic_H4 = 1005;

extern string sep_02 = "S T R A T E G Y  S E T T I N G S";
extern int stop_buffer = 2;
extern int min_TP = 0;
extern double profit_multiplier = 0;

extern int expiration_TF = 1440;

extern string sep_03 = "M O M O";
extern bool enable_momo_filter = false;
extern int manual_momo_01 = 0;
extern int manual_momo_02 = 0;
extern int momo_TF_01 = 240;
extern int momo_TF_02 = 1440;
extern double momo_percentage = 200;
extern int momo_average_bars = 5;

extern string sep_04 = "B R E A K E V E N";
extern bool enable_breakeven = false;
extern int breakeven_after = 50;
extern int breakeven_value = 1;

extern string sep_05 = "T I M E  S E T T I N G S";
extern bool enable_orders_expiration = false;
extern string s_start_time_01 = "0:00";
extern string s_end_time_01 = "24:00";

extern string sep_labels = "L A B E L S";
extern bool enable_labels = false;
extern bool show_direction = true;
extern bool show_orders = true;
extern bool show_order_sizes = true;
extern bool show_profit_taking = true;
extern bool show_breakeven = true;
extern bool show_trend_bias = true;
extern bool show_time = true;
extern int X_shift = 100;
extern int Y_shift = 100;
extern int label_offset = 10;
extern int label_corner = 0;
extern color labels_color = White;  

extern string sep_06 = "O T H E R  S E T T I N G S";
extern bool enable_daily_lines = true;
extern color daily_high_color = DodgerBlue;
extern color daily_low_color = Red;
extern int daily_high_style = 0;
extern int daily_low_style = 0;
extern int magic = 2352;
int message_count = 0;

//+--------------------------------------------- global variables ---+ 

bool reverse_orders = false;

int orders[4][8];
double signals[12][6];
double price[2][2];
double buy_values[20], sell_values[20];
int max_orders = 1;
int time_period;
int slippage = 3;
int total_orders = 1;
datetime start_time, end_time;
bool allow_trading = true;
int last_sell_hour, last_buy_hour;
double previous_level, current_level;
datetime last_signal;
int bars_after_level = 2;

string high_names[100];
string low_names[100];

string prefix = "JRA_";

// information labels variables

int x_shift = 5, y_shift = 13;
int deviation = 1;
int font_size = 8;
int labels_corner = 1;

string debug_prefix = "James_rat_project_logs";
int debug_level = 3;
bool print_while_debug = true;
bool enable_debug = 1;
int  debug_index  = 3;

// 1 - entry bar
// 2 - momo
// 3 - early entry

//+----------------------------------------------- included files ---+ 

#include <inform.mqh> // v0.1
#include <debug.mqh> // v0.3
#include <openOrder.mqh> // v0.1

//+------------------------------------------------------------------+
//| normalizing variables for 5 digit broker                         |
//+------------------------------------------------------------------+
int fiveDigit()
{
	if (Digits == 5 || Digits == 3)
	{
		slippage = slippage*10;
		stop_buffer = stop_buffer*10;
		entry_buffer = entry_buffer*10;
		min_TP *= 10;
		
		breakeven_value *= 10;
		breakeven_after *= 10;
	}
}
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
	fiveDigit();	
	for (int i=0; i<ArrayRange(high_names, 0); i++)
	{
		high_names[i] = "";
		low_names[i] = "";
	}
	start();
}

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
{
	deleteObjects();
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{	 
	getPrice();
	expiration();
	checkSignals();
	breakeven();
    set_labels();
	if (!checkTime()) 
	{
		//Comment("Current time is disabled");
		return;
	}
	//else Comment("Trading allowed");	
    checkForOpen();
}
//+------------------------------------------------------------------+
//| getting current and previous prices                              |
//+------------------------------------------------------------------+
int getPrice()
{      
	price[1][0] = price[0][0];
	price[1][1] = price[0][1];
	price[0][0] = Bid;	
	price[0][1] = Ask;	
}
//+------------------------------------------------------------------+
//| check open conditions			                                 |
//+------------------------------------------------------------------+
int checkForOpen()
{      
    int i, ret;    
    double stop_loss,
           take_profit,
           open_price;  
    string message;
    
    for (i=0; i<ArrayRange(signals, 0); i++)
    {
    	if (i == 0) calculateOrders(Symbol(), "trades", magic_M5);
    	else
    	if (i == 1) calculateOrders(Symbol(), "trades", magic_M15);
    	else
    	if (i == 2) calculateOrders(Symbol(), "trades", magic_M30);
    	else
    	if (i == 3) calculateOrders(Symbol(), "trades", magic_H1);
    	
    	if (signals[i][0] == 1 &&
    		orders[1][1] == 0)
    	{
    		openOrder("buy", 
    				  signals[i][1], 
    				  signals[i][2],
    				  signals[i][3], 
    				  signals[i][4], 
    				  "", 
    				  signals[i][5]);
    	}
    	else
    	if (signals[i][0] == -1 &&
    		orders[1][2] == 0)
    	{
    		openOrder("sell", 
    				  signals[i][1], 
    				  signals[i][2],
    				  signals[i][3], 
    				  signals[i][4], 
    				  "", 
    				  signals[i][5]);
    	}
    }
} 
//+------------------------------------------------------------------+
//| check open conditions			                                 |
//+------------------------------------------------------------------+
void checkSignals()
{ 
	int i, s, shift, j, ret = 100, bars, start;
	int trend;
	bool down_trade, up_trade;
	static datetime last_signal_01, last_signal_02, last_signal_03, last_signal_04, last_signal_05;
		
	ArrayInitialize(signals, 0);	
	
	trend = checkTrend(1) + checkTrend(2); 
    		
//+---------------------------------------------------- signal M5 ---+
	
	shift = checkBar(5, 1);	
	if (shift > 0 && (trend >= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] > iHigh(0, 5, MathAbs(shift)) + entry_buffer*Point &&
		price[1][0] <= iHigh(0, 5, MathAbs(shift)) + entry_buffer*Point &&
		enable_M5 && iTime(0, 5, MathAbs(shift)) != last_signal_01)
	{
		s = 0;
		signals[s][0] = 1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 5);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_M5;
		last_signal_01 = iTime(0, 5, MathAbs(shift));
	}
	shift = checkBar(5, -1);
	debug(shift, 1);
	if (shift < 0 && (trend <= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] < iLow(0, 5, MathAbs(shift)) - entry_buffer*Point &&
		price[1][0] >= iLow(0, 5, MathAbs(shift)) - entry_buffer*Point &&
		enable_M5 && iTime(0, 5, MathAbs(shift)) != last_signal_01)
	{
		debug("entry m5 sell", 1);
		s = 0;
		signals[s][0] = -1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 5);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_M5;
		last_signal_01 = iTime(0, 5, MathAbs(shift));
	}
		
//+---------------------------------------------------- signal m15 ---+
	
	shift = checkBar(15, 1);
	if (shift > 0 && (trend >= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] > iHigh(0, 15, MathAbs(shift)) + entry_buffer*Point &&
		price[1][0] <= iHigh(0, 15, MathAbs(shift)) + entry_buffer*Point &&
		enable_M15 && iTime(0, 15, MathAbs(shift)) != last_signal_02)
	{
		s = 1;
		signals[s][0] = 1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 15);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_M15;
		last_signal_02 = iTime(0, 15, MathAbs(shift));
	}
	shift = checkBar(15, -1);
	if (shift < 0 && (trend <= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] < iLow(0, 15, MathAbs(shift)) - entry_buffer*Point &&
		price[1][0] >= iLow(0, 15, MathAbs(shift)) - entry_buffer*Point &&
		enable_M15 && iTime(0, 15, MathAbs(shift)) != last_signal_02)
	{
		s = 1;
		signals[s][0] = -1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 15);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_M15;
		last_signal_02 = iTime(0, 15, MathAbs(shift));
	}
		
//+---------------------------------------------------- signal m30 ---+
	
	shift = checkBar(30, 1);
	if (shift > 0 && (trend >= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] > iHigh(0, 30, MathAbs(shift)) + entry_buffer*Point &&
		price[1][0] <= iHigh(0, 30, MathAbs(shift)) + entry_buffer*Point &&
		enable_M30 && iTime(0, 30, MathAbs(shift)) != last_signal_03)
	{
		s = 2;
		signals[s][0] = 1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 30);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_M30;
		last_signal_03 = iTime(0, 30, MathAbs(shift));
	}
	shift = checkBar(30, -1);
	if (shift < 0 && (trend <= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] < iLow(0, 30, MathAbs(shift)) - entry_buffer*Point &&
		price[1][0] >= iLow(0, 30, MathAbs(shift)) - entry_buffer*Point &&
		enable_M30 && iTime(0, 30, MathAbs(shift)) != last_signal_03)
	{
		s = 2;
		signals[s][0] = -1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 30);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_M30;
		last_signal_03 = iTime(0, 30, MathAbs(shift));
	}
	
//+---------------------------------------------------- signal h1 ---+
	
	shift = checkBar(60, 1);	
	if (shift > 0 && (trend >= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] > iHigh(0, 60, MathAbs(shift)) + entry_buffer*Point &&
		price[1][0] <= iHigh(0, 60, MathAbs(shift)) + entry_buffer*Point &&
		enable_H1 && iTime(0, 60, MathAbs(shift)) != last_signal_04)
	{
		s = 3;
		signals[s][0] = 1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 60);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_H1;
		last_signal_04 = iTime(0, 60, MathAbs(shift));
	}
	shift = checkBar(60, -1);
	if (shift < 0 && (trend <= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] < iLow(0, 60, MathAbs(shift)) - entry_buffer*Point &&
		price[1][0] >= iLow(0, 60, MathAbs(shift)) - entry_buffer*Point &&
		enable_H1 && iTime(0, 60, MathAbs(shift)) != last_signal_04)
	{
		s = 3;
		signals[s][0] = -1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 60);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_H1;
		last_signal_04 = iTime(0, 60, MathAbs(shift));
	}	


//+---------------------------------------------------- signal h4 ---+
	
	shift = checkBar(240, 1);	
	if (shift > 0 && (trend >= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] > iHigh(0, 240, MathAbs(shift)) + entry_buffer*Point &&
		price[1][0] <= iHigh(0, 240, MathAbs(shift)) + entry_buffer*Point &&
		enable_H4 && iTime(0, 240, MathAbs(shift)) != last_signal_05)
	{
		s = 4;
		signals[s][0] = 1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 240);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_H4;
		last_signal_05 = iTime(0, 240, MathAbs(shift));
	}
	shift = checkBar(240, -1);
	if (shift < 0 && (trend <= 0 || !enable_momo_filter) && 
		MathAbs(shift) < bars_after_level &&
		price[0][0] < iLow(0, 240, MathAbs(shift)) - entry_buffer*Point &&
		price[1][0] >= iLow(0, 240, MathAbs(shift)) - entry_buffer*Point &&
		enable_H4 && iTime(0, 240, MathAbs(shift)) != last_signal_05)
	{
		s = 4;
		signals[s][0] = -1;
		signals[s][2] = getOpenPrice(signals[s][0]);
		signals[s][3] = getStopLoss(signals[s][0], signals[s][2], shift, 240);
		signals[s][4] = getTakeProfit(signals[s][0], signals[s][2], signals[s][3], shift);
		signals[s][1] = getLotSize(signals[s][0], signals[s][2], signals[s][3], trend);
		signals[s][5] = magic_H4;
		last_signal_05 = iTime(0, 240, MathAbs(shift));
	}	
}
//+------------------------------------------------------------------+
//| check open conditions			                                 |
//+------------------------------------------------------------------+
int checkBar(int TF, int type)
{
	int shift, i;
	double low = 10000, high = 0;
    double daily_high;
    double daily_low;
    bool low_found, high_found;
    
    daily_high = flatBorder("high");
    daily_low = flatBorder("low");    
     
    for (i=bars_after_level; i>0; i--)
    {
    	// Green rat 
    	if (NormalizeDouble(iLow(0, TF, i), Digits) == 
    		NormalizeDouble(daily_low, Digits) &&
    		type == 1 &&
    		green_rat)
    	{
    		low_found = true;
    		Print("green found");
    	}
    	if (low_found && iClose(0, TF, i) > iOpen(0, TF, i) &&
    		type == 1 && green_rat)
    	{
    		return(i);
    	}
    	// Red rat 
    	if (NormalizeDouble(iHigh(0, TF, i), Digits) == 
    		NormalizeDouble(daily_high, Digits) &&
    		type == -1 &&
    		red_rat)
    	{
    		high_found = true;
    	}
    	if (high_found && iClose(0, TF, i) < iOpen(0, TF, i) &&
    		type == -1 && red_rat)
    	{
    		return(-i);
    	}
    }
    return(0);	
}
//+------------------------------------------------------------------+
//| Calculate flat borders                                           |
//+------------------------------------------------------------------+
double flatBorder(string type)
{
    double low = 100000, high = 0;
    int hours, minutes, start_shift, i;
    string name;
    
    
	hours = StrToInteger(StringSubstr(s_start_time_01, 0, 2));
	minutes = StrToInteger(StringSubstr(s_start_time_01, 3, 2));
	start_time = iTime(0, 1440, 0) + (hours*60+minutes)*60;
	
	hours = StrToInteger(StringSubstr(s_end_time_01, 0, 2));
	minutes = StrToInteger(StringSubstr(s_end_time_01, 3, 2));
	end_time = iTime(0, 1440, 0) + (hours*60+minutes)*60;	
	
	start_shift = iBarShift(0, 0, start_time);
	
	for (i=1; i<=start_shift; i++)
	{
		if (iLow(0, 0, i) < low) low = iLow(0, 0, i);
		if (iHigh(0, 0, i) > high) high = iHigh(0, 0, i);
	}
	
	if (enable_daily_lines && TimeCurrent() >= start_time)
	{
		name = prefix + "day_high_" + iTime(0, 1440, 0);
		if (ObjectFind(name) == -1)
			ObjectCreate(name, OBJ_TREND, 0, 
					 	start_time,
					 	high,
					 	end_time,
					 	high);
		ObjectSet(name, OBJPROP_PRICE1, high);
		ObjectSet(name, OBJPROP_PRICE2, high);
		ObjectSet(name, OBJPROP_COLOR, daily_high_color);
		ObjectSet(name, OBJPROP_STYLE, daily_high_style);
		ObjectSet(name, OBJPROP_RAY, false);
	
		name = prefix + "day_low_" + iTime(0, 1440, 0);
		if (ObjectFind(name) == -1)
			ObjectCreate(name, OBJ_TREND, 0, 
					 	start_time,
					 	low,
					 	end_time,
					 	low);
		ObjectSet(name, OBJPROP_PRICE1, low);
		ObjectSet(name, OBJPROP_PRICE2, low);
		ObjectSet(name, OBJPROP_COLOR, daily_low_color);
		ObjectSet(name, OBJPROP_STYLE, daily_low_style);
		ObjectSet(name, OBJPROP_RAY, false);
	}
		
    if (type == "high")
    {
        return(high);
	}
    else
    if (type == "low")
    {
        return(low);
    }
}
//+------------------------------------------------------------------+
//| checking current trend	                                         |			                                                 |
//+------------------------------------------------------------------+
int checkTrend(int t)
{
	int i, j, trend_02, trend_01;
	double momo_01, momo_02, average_candle;	

	if (t == 1 && momo_TF_01 == -1) return(0);
	if (t == 1 && manual_momo_01 != 0) return(manual_momo_01);
	if (t == 2 && manual_momo_02 != 0) return(manual_momo_02);
	for (i=1; i<1000 && t == 1; i++)
	{
		momo_01 = iClose(0, momo_TF_01, i) - iOpen(0, momo_TF_01, i);
		momo_02 = iClose(0, momo_TF_01, i+1) - iOpen(0, momo_TF_01, i+1);
		if (MathAbs(momo_01) < MathAbs(momo_02)*momo_percentage/100) continue;
		
		average_candle = 0;
		for (j=i+1; j<=i+momo_average_bars; j++)
		{
			average_candle += MathAbs(iClose(0, momo_TF_01, j) - iOpen(0, momo_TF_01, j));
		}
		average_candle /= momo_average_bars;
		
		if (MathAbs(momo_01) > MathAbs(average_candle))
		{
			if (momo_01 > 0) 
			{
				return(1);
				break;
			}
			if (momo_01 < 0)
			{
				return(-1);
				break;
			}
		}			
	}
	if (t == 2 && momo_TF_02 == -1) return(0);
	for (i=1; i<1000 && t == 2; i++)
	{
		momo_01 = iClose(0, momo_TF_01, i) - iOpen(0, momo_TF_01, i);
		momo_02 = iClose(0, momo_TF_01, i+1) - iOpen(0, momo_TF_01, i+1);
		if (MathAbs(momo_01) < MathAbs(momo_02)*momo_percentage/100) continue;
		
		average_candle = 0;
		for (j=i+1; j<=i+momo_average_bars; j++)
		{
			average_candle += MathAbs(iClose(0, momo_TF_01, j) - iOpen(0, momo_TF_01, j));
		}
		average_candle /= momo_average_bars;
		
		if (MathAbs(momo_01) > MathAbs(average_candle))
		{
			if (momo_01 > 0) 
			{
				return(1);
				break;
			}
			if (momo_01 < 0)
			{
				return(-1);
				break;
			}
		}			
	}
}
//+------------------------------------------------------------------+
//| set labels function                                              |
//+------------------------------------------------------------------+
void set_labels()
{
	double ratio, spread, loss, profit;
 	int label_count, profit_pips, magic, ticket;
 	string name;
 	string main_font = "Lucida Console";
 	string text;
 	color col = labels_color;
 	
 	if (!enable_labels) return;
 
 	label_count = 0;
 	
//+------------------------------------------------- ticket label ---+

	if (show_direction)
	{
  	name = prefix + "red_rat";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  	if (red_rat)
  		text = "Red Rat: ON";		
  	if (!red_rat)
  		text = "Red Rat: OFF";
  	ObjectSetText(name, text, 12, main_font, col);   	
  	label_count++;
  	
  	name = prefix + "green_rat";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
   if (green_rat)
  		text = "Green Rat: ON";		
  	if (!green_rat)
  		text = "Green Rat: OFF";	
  	ObjectSetText(name, text, 12, main_font, col);   	
  	label_count++;
  	}
  	
  	name = prefix + "space_01";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  		text = "";		
  	ObjectSetText(name, text, 12, main_font, col);   	
  	label_count++;
  	
//+------------------------------------------------- ticket label ---+

/*	if (show_orders)
	{
	name = prefix + "buy_M5";
	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
	ObjectSet(name, OBJPROP_YDISTANCE, 
			  Y_shift + font_size * label_count + label_offset * label_count);
	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
	text = "Buy M5: #" + findTicket("buy", "M5");	
	ObjectSetText(name, text, font_size, main_font, col);   	
	label_count++;
  	
	name = prefix + "buy_M15";
 	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
 	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
 	ObjectSet(name, OBJPROP_YDISTANCE, 
 			  Y_shift + font_size * label_count + label_offset * label_count);
 	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
 	text = "Buy M15: #" + findTicket("buy", "M15");	
 	ObjectSetText(name, text, font_size, main_font, col);   	
 	label_count++;
  	
 	name = prefix + "buy_M30";
 	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
 	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
 	ObjectSet(name, OBJPROP_YDISTANCE, 
 			  Y_shift + font_size * label_count + label_offset * label_count);
 	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
 	text = "Buy M30: #" + findTicket("buy", "M30");	
 	ObjectSetText(name, text, font_size, main_font, col);   	
 	label_count++;
  	
 	name = prefix + "buy_H1";
 	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
 	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
 	ObjectSet(name, OBJPROP_YDISTANCE, 
 			  Y_shift + font_size * label_count + label_offset * label_count);
 	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
 	text = "Buy H1: #" + findTicket("buy", "H1");	
	ObjectSetText(name, text, font_size, main_font, col);   	
	label_count++;
  	
  	
  	
 	name = prefix + "sell_M5";
 	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
 	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
 	ObjectSet(name, OBJPROP_YDISTANCE, 
 			  Y_shift + font_size * label_count + label_offset * label_count);
 	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
 	text = "Sell M5: #" + findTicket("sell", "M5");	
 	ObjectSetText(name, text, font_size, main_font, col);   	
 	label_count++;
  	
 	name = prefix + "sell_M15";
 	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
 	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
 	ObjectSet(name, OBJPROP_YDISTANCE, 
 			  Y_shift + font_size * label_count + label_offset * label_count);
 	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
 	text = "Sell M15: #" + findTicket("sell", "M15");	
 	ObjectSetText(name, text, font_size, main_font, col);   	
 	label_count++;
  	
 	name = prefix + "sell_M30";
 	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
 	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
 	ObjectSet(name, OBJPROP_YDISTANCE, 
 			  Y_shift + font_size * label_count + label_offset * label_count);
 	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
 	text = "Sell M30: #" + findTicket("sell", "M30");	
 	ObjectSetText(name, text, font_size, main_font, col);   	
 	label_count++;
  	
 	name = prefix + "sell_H1";
 	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
 	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
 	ObjectSet(name, OBJPROP_YDISTANCE, 
 			  Y_shift + font_size * label_count + label_offset * label_count);
 	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
 	text = "Sell H1: #" + findTicket("sell", "H1");	
 	ObjectSetText(name, text, font_size, main_font, col);   	
 	label_count++;
 	}  	
 	*/
  	
//+------------------------------------------------- ticket label ---+
  	
	if (show_order_sizes)   		
	{
  	name = prefix + "Title_Money";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);    	
  	
  	text = "Money Management";
  	
  	ObjectSetText(name, text, 11, main_font, col);   	
  	label_count++;  
  	
  	name = prefix + "space_02";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  		text = "";		
  	ObjectSetText(name, text, 12, main_font, col);   	
  	label_count++;
  	
  	name = prefix + "order_size";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  	
  	if (enable_money_management)
  		text = "Money Management: ON";		
  	if (!enable_money_management)
  		text = "Money Management: OFF";	
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;
  		}
  	
//+------------------------------------------------- ticket label ---+

 	
  	if (!enable_money_management)
	{
  	name = prefix + "lot_size_01";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
   	   text = "Lot 01: " + DoubleToStr(lot_size_01, 2) +  "   "  +  "Lot 02: " + DoubleToStr(lot_size_02, 2); 	
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;
  	
  	}
//+------------------------------------------------- ticket label ---+
  	


  	
  	if (enable_money_management)
	{
  	name = prefix + "risk_percent_01";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  	if (enable_money_management)
  		text = "Risk% 01: " + DoubleToStr(risk_percent_01, 2) + "   " + "Risk% 02: " + DoubleToStr(risk_percent_02, 2);	
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;

  	}
//+------------------------------------------------- ticket label ---+

	if (show_profit_taking)
	{
  	name = prefix + "expiration";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  	
  	switch (expiration_TF)
  	{
  		case 1440: text = "Take Profit: Daily";
  		case 10080: text = "Take Profit: Weekly";
  		case 43200: text = "Take Profit: Monthly";
  	}	
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;
  	
  	name = prefix + "min_tp";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  	text = "Minimum TP: " + min_TP;	
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;
	
//  	name = prefix + "profit_mult";
//  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
//  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
//  	ObjectSet(name, OBJPROP_YDISTANCE, 
//  			  Y_shift + font_size * label_count + label_offset * label_count);
//  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
//  	text = "Profit Multiplier: " + DoubleToStr(profit_multiplier, 2);	
//  	ObjectSetText(name, text, font_size, main_font, col);   	
//  	label_count++;
  	}
  	 
//+------------------------------------------------- ticket label ---+

	if (show_breakeven)
	{
  	name = prefix + "breakeven";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  	if (enable_breakeven)
  		text = "Breakeven: on";		
  	if (!enable_breakeven)
  		text = "Breakeven: off";		
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;
  	}
  	

//+------------------------------------------------- ticket label ---+

	if (show_trend_bias)
	
	{
	name = prefix + "space_03";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  		text = "";		
  	ObjectSetText(name, text, 12, main_font, col);   	
  	label_count++;
  	
  	name = prefix + "Title_Bias";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);    	
  	  	text = "Trending Bias";
  	ObjectSetText(name, text, 12, main_font, col);   	
  	label_count++;  
  	
  	name = prefix + "space_04";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  		text = "";		
  	ObjectSetText(name, text, 12, main_font, col);   	
  	label_count++;
  	
  	name = prefix + "trend_bias_01";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  	
  	switch (momo_TF_01)
  	{
  		case 240: text = "Trend Bias 1: 4 hours";
  		case 1440: text = "Trend Bias 1: Daily";
  		case 10080: text = "Trend Bias 1: Weekly";
  		case 43200: text = "Trend Bias 1: Monthly";
  	}		
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;	
  	
 	name = prefix + "trend_bias_type_01";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);    	
  	
  	if (manual_momo_01 == 0 && checkTrend(1) > 0) text = "Automated: Bullish";
  	if (manual_momo_01 == 0 && checkTrend(1) < 0) text = "Automated: Bearish";
  	if (manual_momo_01 != 0 && checkTrend(1) > 0) text = "Manual: Bullish";
  	if (manual_momo_01 != 0 && checkTrend(1) < 0) text = "Manual: Bearish";
  	
  	ObjectSetText(name, text, 11, main_font, col);   	
  	label_count++;
  	
  	name = prefix + "trend_bias_02";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  	
  	switch (momo_TF_02)
  	{
  		case 240: text = "Trend Bias 2: 4 hours";
  		case 1440: text = "Trend Bias 2: Daily";
  		case 10080: text = "Trend Bias 2: Weekly";
  		case 43200: text = "Trend Bias 2: Monthly";
  	}		
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;
  	
  	name = prefix + "trend_bias_type_02";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);    	
  	if (manual_momo_02 == 0 && checkTrend(2) > 0) text = "Automated: Bullish";
  	if (manual_momo_02 == 0 && checkTrend(2) < 0) text = "Automated: Bearish";
  	if (manual_momo_02 != 0 && checkTrend(2) > 0) text = "Manual: Bullish";
  	if (manual_momo_02 != 0 && checkTrend(2) < 0) text = "Manual: Bearish";
  	ObjectSetText(name, text, 11, main_font, col);   	
  	label_count++;
  	  	
  	}
  	
 
//+------------------------------------------------- ticket label ---+
	
	if (show_time)
	{
	
	name = prefix + "space_05";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  		text = "";		
  	ObjectSetText(name, text, 12, main_font, col);   	
  	label_count++;
  	
  	name = prefix + "Title_Other";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);    	
  	
  	text = "Other Settings";
  	
  	ObjectSetText(name, text, 11, main_font, col);   	
  	label_count++;  
  		
  	name = prefix + "space_06";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);  
  		text = "";		
  	ObjectSetText(name, text, 12, main_font, col);   	
  	label_count++;
  	
  	name = prefix + "start_time";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);    	
  	
  	text = "Trading Start Time: " + s_start_time_01;
  	
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;  	
  	
  	name = prefix + "end_time";
  	if (ObjectFind(name) == -1) ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
  	ObjectSet(name, OBJPROP_XDISTANCE, X_shift);
  	ObjectSet(name, OBJPROP_YDISTANCE, 
  			  Y_shift + font_size * label_count + label_offset * label_count);
  	ObjectSet(name, OBJPROP_CORNER, label_corner);    	
  	
  	text = "Trading End Time: " + s_end_time_01;
  	
  	ObjectSetText(name, text, font_size, main_font, col);   	
  	label_count++;
  	}
  	
  	WindowRedraw();
}
//+------------------------------------------------------------------+
//| calculating open price	                                         |			                                                 |
//+------------------------------------------------------------------+
int findTicket(string type, string tf)
{
	int i;
	
	for (i=OrdersTotal()-1; i>=0; i--)
    {
    	if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) break;  
    	if (OrderSymbol() != Symbol()) continue;
    	
    	if (type == "buy" && OrderType() == OP_BUY &&
    		tf == "M5" && OrderMagicNumber() == magic_M5)
    	{
    		return(OrderTicket());
    	}
    	else
    	if (type == "buy" && OrderType() == OP_BUY &&
    		tf == "M15" && OrderMagicNumber() == magic_M15)
    	{
    		return(OrderTicket());
    	}
    	else
    	if (type == "buy" && OrderType() == OP_BUY &&
    		tf == "M30" && OrderMagicNumber() == magic_M30)
    	{
    		return(OrderTicket());
    	}
    	else
    	if (type == "buy" && OrderType() == OP_BUY &&
    		tf == "H1" && OrderMagicNumber() == magic_H1)
    	{
    		return(OrderTicket());
    	}
    	else
    	if (type == "buy" && OrderType() == OP_BUY &&
    		tf == "H4" && OrderMagicNumber() == magic_H4)
    	{
    		return(OrderTicket());
    	}
    	else
    	// ========
    	if (type == "sell" && OrderType() == OP_SELL &&
    		tf == "M5" && OrderMagicNumber() == magic_M5)
    	{
    		return(OrderTicket());
    	}
    	else    	
    	if (type == "sell" && OrderType() == OP_SELL &&
    		tf == "M15" && OrderMagicNumber() == magic_M15)
    	{
    		return(OrderTicket());
    	}
    	else    	
    	if (type == "sell" && OrderType() == OP_SELL &&
    		tf == "M30" && OrderMagicNumber() == magic_M30)
    	{
    		return(OrderTicket());
    	}
    	else    	
    	if (type == "sell" && OrderType() == OP_SELL &&
    		tf == "H1" && OrderMagicNumber() == magic_H1)
    	{
    		return(OrderTicket());
      }
    	else    	
    	if (type == "sell" && OrderType() == OP_SELL &&
    		tf == "H4" && OrderMagicNumber() == magic_H4)
    	{
    		return(OrderTicket());
    	}
    }
}
//+------------------------------------------------------------------+
//| calculating open price	                                         |			                                                 |
//+------------------------------------------------------------------+
double getOpenPrice(int type)
{
	if (type == 1)
	{
		return(Ask);
	}
	else
	if (type == -1)
	{
		return(Bid);	
	}
}
//+------------------------------------------------------------------+
//| calculating stop value	                                         |			                                                 |
//+------------------------------------------------------------------+
double getStopLoss(int type, double open_price = 0, int shift = 0, int TF = 0)
{
	double stop_loss;
	
	if (type == 1)
	{
		stop_loss = flatBorder("low") - stop_buffer*Point;
		if (stop_buffer == 0) stop_loss = 0;
		return(stop_loss);
	}
	else
	if (type == -1)
	{
		stop_loss = flatBorder("high") + stop_buffer*Point;
		if (stop_buffer == 0) stop_loss = 0;
		return(stop_loss);	
	}
}
//+------------------------------------------------------------------+
//| calculating profit value	                                     |			                                                 |
//+------------------------------------------------------------------+
double getTakeProfit(int type, double open_price = 0, double stop_loss = 0, int shift = 0)
{
	double take_profit;
	
	if (type == 1)
	{
		take_profit = open_price + 
					  MathMax(min_TP*Point, (open_price-stop_loss)*profit_multiplier);
		if (profit_multiplier == 0) take_profit = 0;
		return(take_profit);
	}
	else
	if (type == -1)
	{
		take_profit = open_price - 
					  MathMax(min_TP*Point, (stop_loss-open_price)*profit_multiplier);
		if (profit_multiplier == 0) take_profit = 0;
		return(take_profit);
	}
}
//+------------------------------------------------------------------+
//| calculating lot size	                                         |			                                                 |
//+------------------------------------------------------------------+
double getLotSize(int type, double open_price = 0, double stop_loss = 0, int trend = 0)
{      
	int i;
    double lot_size, 
           max_risk, 
           stop_size, 
           min_tick_value;
    double balance = AccountBalance();  
    double tick_value = MarketInfo(Symbol(), MODE_TICKVALUE); 
    double min_lot = MarketInfo(Symbol(), MODE_MINLOT);        
    double lot_step = MarketInfo(Symbol(), MODE_LOTSTEP);    
    double prev_lot = lot_step;
    double order_risk, count;
    
    if (!enable_money_management)
	{
		if (trend == 0) return(lot_size_02);
		else return(lot_size_01);
	}	
    
    if (enable_M5) count++;
    if (enable_M15) count++;
    if (enable_M30) count++;
    if (enable_H1) count++;
    
    if (trend == 0) order_risk = risk_percent_02/count;
	else order_risk = risk_percent_01/count;
    
    if (type == 1)
    {  
        max_risk = balance * (order_risk/100);        
        stop_size = (open_price - stop_loss ) / Point;        
        min_tick_value = tick_value * min_lot;
        lot_size = MathAbs((max_risk / (stop_size * min_tick_value)) * min_lot);
                  
        for (i=0; i<1000; i++)
        {
        	if (prev_lot < lot_size && prev_lot + lot_step > lot_size) 
        	{	
        		lot_size = prev_lot;
        		break;
        	}
        	else prev_lot = prev_lot + lot_step;
        }        
        return(lot_size);
    }
    else
    if (type == -1)
    {  
        max_risk = balance * (order_risk/100);
        stop_size = (stop_loss - open_price ) / Point;
        min_tick_value = tick_value * MarketInfo(Symbol(), MODE_MINLOT);
        lot_size = MathAbs((max_risk / (stop_size * min_tick_value)) * min_lot);

        for (i=0; i<1000; i++)
        {
        	if (prev_lot < lot_size && prev_lot + lot_step > lot_size)
        	{	
        		lot_size = prev_lot;
        		break;
        	}
        	else prev_lot = prev_lot + lot_step;
        }        
        return(lot_size);
    }  
}
//+------------------------------------------------------------------+
//| orders expiration						                         |
//+------------------------------------------------------------------+
int expiration()
{
	int i;
	
	if (!enable_orders_expiration) return;
		
	for(i=0;i<OrdersTotal();i++)
    {
        if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;      
        if ((OrderMagicNumber() != magic_M5 &&
        	 OrderMagicNumber() != magic_M15 &&
        	 OrderMagicNumber() != magic_M30 &&
        	 OrderMagicNumber() != magic_H1 && 
        	 OrderMagicNumber() != magic_H4) || 
             OrderSymbol() != Symbol()) continue;
                 
        if (OrderType() == OP_BUYSTOP || 
        	OrderType() == OP_BUYLIMIT || 
        	OrderType() == OP_SELLSTOP || 
        	OrderType() == OP_SELLLIMIT)
        {
        	if (OrderOpenTime() < iTime(0, expiration_TF, 0))
        	{
        		OrderDelete(OrderTicket());
        	}
        }
        else
        {
        	if (OrderOpenTime() < iTime(0, expiration_TF, 0) &&
        		OrderType() == OP_BUY)
        	{
        		OrderClose(OrderTicket(), OrderLots(), 
        				   NormalizeDouble(Bid, Digits), slippage, Blue);
        	}
        	else
        	if (OrderOpenTime() < iTime(0, expiration_TF, 0) &&
        		OrderType() == OP_SELL)
        	{
        		OrderClose(OrderTicket(), OrderLots(), 
        				   NormalizeDouble(Ask, Digits), slippage, Red);
        	}
        }
	}
}
//+------------------------------------------------------------------+
//| check time						                                 |
//+------------------------------------------------------------------+
bool checkTime()
{
	int hours, minutes;
	
	// first period
	hours = StrToInteger(StringSubstr(s_start_time_01, 0, 2));
	minutes = StrToInteger(StringSubstr(s_start_time_01, 3, 2));
	start_time = iTime(0, 1440, 0) + (hours*60+minutes)*60;
	
	hours = StrToInteger(StringSubstr(s_end_time_01, 0, 2));
	minutes = StrToInteger(StringSubstr(s_end_time_01, 3, 2));
	end_time = iTime(0, 1440, 0) + (hours*60+minutes)*60;	
	
	if (start_time > end_time) start_time -= 1440*60;
	
	if (TimeCurrent() >= start_time && TimeCurrent() <= end_time) return(true);
	
	return(false);
}
//+------------------------------------------------------------------+
//| Check for break even                                             |
//+------------------------------------------------------------------+
void breakeven()
{     
    double stop_loss;
    int i, filter;
    
    if (!enable_breakeven) return;
   
    for(i=0;i<OrdersTotal();i++)
    {
        if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES) == false) break;      
        if ((OrderMagicNumber() != magic) || 
             OrderSymbol() != Symbol()) continue;
       
		filter = breakeven_after;
        
        if (OrderType()==OP_BUY)                   
        { 
            if (Ask > OrderOpenPrice() + filter*Point)                                               
            {
                stop_loss = OrderOpenPrice() + breakeven_value*Point;
                if (OrderStopLoss() >= NormalizeDouble(stop_loss, Digits) ||
                	stop_loss > Ask) continue;
                             
                	OrderModify(OrderTicket(),
                            	OrderOpenPrice(),
                            	NormalizeDouble(stop_loss, Digits),
                            	OrderTakeProfit(),
                            	0,
                            	Green);
            }
        }
        else
        if(OrderType()==OP_SELL)                
        {
            if (Bid < OrderOpenPrice() - filter*Point)   
            {
                stop_loss = OrderOpenPrice() - breakeven_value*Point;
                if (OrderStopLoss() <= NormalizeDouble(stop_loss, Digits) ||
                	stop_loss < Bid) continue;
                
                	OrderModify(OrderTicket(),
                            	OrderOpenPrice(),
                            	NormalizeDouble(stop_loss, Digits),
                            	OrderTakeProfit(),
                            	0,
                            	Red);
            }         
        }
    }
}
//+------------------------------------------------------------------+
//| Calculating the orders	                                         |
//| Version 0.2 (only 1 magic support, types: all, buy, sell)        |
//| 						                                         |
//+------------------------------------------------------------------+
void calculateOrders(string symbol, string mode, int magic_01 = 0,  int magic_02 = 0, int magic_03 = 0)
{
	int i, o;
	ArrayInitialize(orders, 0);	
	orders[0][0] = OrdersTotal();
	
	for(i=0;i<OrdersTotal();i++)
	{
		if (mode == "trades")
		{
			if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) break;
		}
		else
		if (mode == "history")
		{
			if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY) == false) break;
		}
		if (OrderOpenTime() < iTime(0, 1440, 0)) continue;
        
        o = 0;
        orders[o][0]++;
        if (OrderType() == OP_BUY) orders[o][1]++;
        if (OrderType() == OP_SELL) orders[o][2]++;        
        if (OrderType() != OP_BUY &&
        	OrderType() != OP_SELL) orders[o][3]++;
        if (OrderType() == OP_BUYLIMIT) orders[o][4]++;
        if (OrderType() == OP_SELLLIMIT) orders[o][5]++;
        if (OrderType() == OP_BUYSTOP) orders[o][6]++;
        if (OrderType() == OP_SELLSTOP) orders[o][7]++;
        
		if (OrderSymbol() == symbol)
		{
			if (magic_01 == 0)
			{
				o = 1;
        		orders[o][0]++;
        		if (OrderType() == OP_BUY) orders[o][1]++;
        		if (OrderType() == OP_SELL) orders[o][2]++;        
        		if (OrderType() != OP_BUY &&
        			OrderType() != OP_SELL) orders[o][3]++;
        		if (OrderType() == OP_BUYLIMIT) orders[o][4]++;
        		if (OrderType() == OP_SELLLIMIT) orders[o][5]++;
        		if (OrderType() == OP_BUYSTOP) orders[o][6]++;
        		if (OrderType() == OP_SELLSTOP) orders[o][7]++;
			}
			else
			if (OrderMagicNumber() == magic_01)
			{
				o = 1;
        		orders[o][0]++;
        		if (OrderType() == OP_BUY) orders[o][1]++;
        		if (OrderType() == OP_SELL) orders[o][2]++;        
        		if (OrderType() != OP_BUY &&
        			OrderType() != OP_SELL) orders[o][3]++;
        		if (OrderType() == OP_BUYLIMIT) orders[o][4]++;
        		if (OrderType() == OP_SELLLIMIT) orders[o][5]++;
        		if (OrderType() == OP_BUYSTOP) orders[o][6]++;
        		if (OrderType() == OP_SELLSTOP) orders[o][7]++;
			}
			if (magic_02 != 0 &&
				OrderMagicNumber() == magic_02)
			{
				o = 2;
        		orders[o][0]++;
        		if (OrderType() == OP_BUY) orders[o][1]++;
        		if (OrderType() == OP_SELL) orders[o][2]++;        
        		if (OrderType() != OP_BUY &&
        			OrderType() != OP_SELL) orders[o][3]++;
        		if (OrderType() == OP_BUYLIMIT) orders[o][4]++;
        		if (OrderType() == OP_SELLLIMIT) orders[o][5]++;
        		if (OrderType() == OP_BUYSTOP) orders[o][6]++;
        		if (OrderType() == OP_SELLSTOP) orders[o][7]++;
			}
			if (magic_03 != 0 &&
				OrderMagicNumber() == magic_03)
			{
				o = 3;
        		orders[o][0]++;
        		if (OrderType() == OP_BUY) orders[o][1]++;
        		if (OrderType() == OP_SELL) orders[o][2]++;        
        		if (OrderType() != OP_BUY &&
        			OrderType() != OP_SELL) orders[o][3]++;
        		if (OrderType() == OP_BUYLIMIT) orders[o][4]++;
        		if (OrderType() == OP_SELLLIMIT) orders[o][5]++;
        		if (OrderType() == OP_BUYSTOP) orders[o][6]++;
        		if (OrderType() == OP_SELLSTOP) orders[o][7]++;	
			}
		}
	}
}
//+------------------------------------------------------------------+
//| delete all objects, created by the EA				             |
//+------------------------------------------------------------------+
void deleteObjects()
{
    string name;
    int i = 0;  
    
    while (i < ObjectsTotal())
    {
       	name = ObjectName(i);    
       	if ( (StringSubstr(name, 0, StringLen(prefix)) == prefix) )   
       	{     
           	ObjectDelete(name);
       	}
       	else i++;
    } 
}
//+------------------------------------------------------------------+

