
// inpursuitofmargincall.ea by "rockit"; copyleft

input double Lots = 0.05;
input int TakeProfit = 30;
input int Slippage = 3;
input int Magic = 1234;
input double Multiplier = 1; // Lot Multiplier

int state = 0;
double multp = 1;
double sl_pts;
double tp_pts;
int history_last_ticket;
int last_ticket;
int last_side = -1;
double price1, price2, lot;
int OnInit()
{
	if(Digits == 3 || Digits == 5)
		multp = 10;
	tp_pts = NormalizeDouble(TakeProfit * multp * Point, Digits);
	lot = Lots;
	if(OrderSelect(OrdersHistoryTotal() - 1, SELECT_BY_POS, MODE_HISTORY)) {
		history_last_ticket = OrderTicket();
		return INIT_SUCCEEDED;
	}
	return INIT_FAILED;
}
void OnTick()
{
	check_tp_hit();
	if(state == 0) {
		last_side = cond_start();
		if(last_side == OP_BUY) {
			last_ticket = open(last_side, lot);
			if(last_ticket != -1) {
				price1 = OrderOpenPrice();
				state++;
			}
		}
	}
	else if(state == 1) {
		last_side = cond_cont();
		if(last_side == OP_SELL) {
			last_ticket = open(last_side, lot * Multiplier);
			if(last_ticket != -1) {
				price2 = OrderOpenPrice();
				lot *= Multiplier;
				state++;
			}
		}
	}
	else {
			if(last_side == OP_SELL && Bid >= price1) {
				last_ticket = open(OP_BUY, lot * Multiplier);
				if(last_ticket != -1) {
					last_side = OP_BUY;
					lot *= Multiplier;
				}
			}
			else if(last_side == OP_BUY && Ask <= price2) {
				last_ticket = open(OP_SELL, lot * Multiplier);
				if(last_ticket != -1) {
					last_side = OP_SELL;
					lot *= Multiplier;
				}
			}
	}
}
void check_tp_hit()
{
	for(int i = OrdersHistoryTotal() - 1; i >= 0; i--) {
		if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
			if(OrderTicket() == history_last_ticket) break;
			if(OrderMagicNumber() == Magic && StringFind(OrderComment(), "[tp]") != -1) {
				for(int j = OrdersTotal() - 1; j >= 0; j--)	{
					if(OrderSelect(j, SELECT_BY_POS) && OrderMagicNumber() == Magic)
							if(!OrderClose(OrderTicket(), OrderLots(), OrderType() == OP_BUY ? Bid : Ask, Slippage))
								Print("OrderClose failed with code: ", GetLastError());
				}
				state = 0; lot = Lots;
				break;
			}
		}
	}
	if(OrderSelect(OrdersHistoryTotal() - 1, SELECT_BY_POS, MODE_HISTORY))
		history_last_ticket = OrderTicket();
}
int open(uint side, double lot_multip)
{
	int ticket = OrderSend(_Symbol, side, lot_multip, side == OP_BUY ? Ask : Bid, Slippage,  0, 0, NULL, Magic, 0, side == OP_BUY ? Red : Blue); 
	if(OrderSelect(ticket, SELECT_BY_TICKET))
		if(!OrderModify(ticket, OrderOpenPrice(), 0, NormalizeDouble(side == OP_BUY ? OrderOpenPrice() + tp_pts : OrderOpenPrice() - tp_pts, Digits), 0))
			Print("OrderModify failed with code: ", GetLastError());
	return ticket;
}
int cond_start()
{
	if(Bid > iMA(NULL, 0, 10, 0, MODE_SMA, PRICE_CLOSE, 0)) return OP_BUY;
	return -1;
}
int cond_cont()
{
	if(Bid < iMA(NULL, 0, 10, 0, MODE_SMA, PRICE_CLOSE, 0)) return OP_SELL;
	return -1;
}
