//-------------------------------------------------------------
//  Etasoft Inc. Forex EA and Script Generator version 4.4   EA
//-------------------------------------------------------------
// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "GVC"
#property link      "http://www.forexgenerator.com/"

#include <stdlib.mqh>
#include <WinUser32.mqh>

// exported variables
extern string BOXSIZE   = "BoxSize";
extern int    BoxSize   = 150;   
extern int TrailingStop6 = 0;
extern int NewTakeProfit6 = 0;
extern int TrailingGap6 = 0;
extern double BuyLots8 = 0.1;
extern int BuyStoploss8 = 0;
extern int BuyTakeprofit8 = 0;
extern double SellLots12 = 0.1;
extern int SellStoploss12 = 0;
extern int SellTakeprofit12 = 0;


// local variables
double PipValue=1;    // this variable is here to support 5-digit brokers
bool Terminated = false;
string LF = "\n";  // use this in custom or utility blocks where you need line feeds
int NDigits = 4;   // used mostly for NormalizeDouble in Flex type blocks
int ObjCount = 0;  // count of all objects created on the chart, allows creation of objects with unique names
int current = 0;

int Count2 = 0;


int init()
{
    NDigits = Digits;
    
    if (false) ObjectsDeleteAll();      // clear the chart
    
    
    Comment("");    // clear the chart
}

// Expert start
int start()
{
    if (Bars < 10)
    {
        Comment("Not enough bars");
        return (0);
    }
    if (Terminated == true)
    {
        Comment("EA Terminated.");
        return (0);
    }
    
    OnEveryTick1();
    
}

void OnEveryTick1()
{
    if (true == false && false) PipValue = 10;
    if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10;
    
    TrailingStop6();
    PrintInfoToChart2();    
    TechnicalAnalysis4();
    TechnicalAnalysis9();
    
}

void TrailingStop6()
{
    for (int i=OrdersTotal()-1; i >= 0; i--)
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == 1)
        {
            double takeprofit = OrderTakeProfit();
            
            if (OrderType() == OP_BUY && Ask - OrderOpenPrice() > TrailingStop6*PipValue*Point)
            {
                if (OrderStopLoss() < Ask-(TrailingStop6+TrailingGap6)*PipValue*Point)
                {
                    if (NewTakeProfit6 != 0) takeprofit = Ask+(NewTakeProfit6 + TrailingStop6)*PipValue*Point;
                    bool ret1 = OrderModify(OrderTicket(), OrderOpenPrice(), Ask-TrailingStop6*PipValue*Point, takeprofit, OrderExpiration(), White);
                    if (ret1 == false)
                    Print("OrderModify() error - ", ErrorDescription(GetLastError()));
                }
            }
            if (OrderType() == OP_SELL && OrderOpenPrice() - Bid > TrailingStop6*PipValue*Point)
            {
                if (OrderStopLoss() > Bid+(TrailingStop6+TrailingGap6)*PipValue*Point)
                {
                    if (NewTakeProfit6 != 0) takeprofit = Bid-(NewTakeProfit6 + TrailingStop6)*PipValue*Point;
                    bool ret2 = OrderModify(OrderTicket(), OrderOpenPrice(), Bid+TrailingStop6*PipValue*Point, takeprofit, OrderExpiration(), White);
                    if (ret2 == false)
                    Print("OrderModify() error - ", ErrorDescription(GetLastError()));
                }
            }
        }
    }
    else
    Print("OrderSelect() error - ", ErrorDescription(GetLastError()));
    
}

void PrintInfoToChart2()
{
    string temp = "\nExecuted : " + Count2 + "\n"
    + "Spread: " + DoubleToStr(MarketInfo(Symbol(), MODE_SPREAD)/PipValue, 2)+ "\n"
    + "------------------------------------------------\n"
    + "ACCOUNT INFORMATION:\n"
    + "\n"
    + "Account Name:     " + AccountName()+ "\n"
    + "Account Leverage:     " + DoubleToStr(AccountLeverage(), 0)+ "\n"
    + "Account Balance:     " + DoubleToStr(AccountBalance(), 2)+ "\n"
    + "Account Equity:     " + DoubleToStr(AccountEquity(), 2)+ "\n"
    + "Free Margin:     " + DoubleToStr(AccountFreeMargin(), 2)+ "\n"
    + "Used Margin:     " + DoubleToStr(AccountMargin(), 2)+ "\n"      
    + "------------------------------------------------\n"
    
    + " BUY >= 1 / SELL = 0 " + DoubleToStr(iCustom(NULL, NULL, "I_XO_A_H",BoxSize,0,0), 5) + "\n";
    Comment(temp);
    Count2++;
    
}



void TechnicalAnalysis4()
{
    if (iCustom(NULL, NULL, "I_XO_A_H",BoxSize,0,1) >= 1)
    {
        IfOrderDoesNotExist5();
        
    }
}

void IfOrderDoesNotExist5()
{
    bool exists = false;
    for (int i=OrdersTotal()-1; i >= 0; i--)
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
        if (OrderType() == OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)
        {
            exists = true;
        }
    }
    else
    {
        Print("OrderSelect() error - ", ErrorDescription(GetLastError()));
    }
    
    if (exists == false)
    {
        CloseOrder7();
        
    }
}

void CloseOrder7()
{
    int orderstotal = OrdersTotal();
    int orders = 0;
    int ordticket[30][2];
    for (int i = 0; i < orderstotal; i++)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if (OrderType() != OP_SELL || OrderSymbol() != Symbol() || OrderMagicNumber() != 1)
        {
            continue;
        }
        ordticket[orders][0] = OrderOpenTime();
        ordticket[orders][1] = OrderTicket();
        orders++;
    }
    if (orders > 1)
    {
        ArrayResize(ordticket,orders);
        ArraySort(ordticket);
    }
    for (i = 0; i < orders; i++)
    {
        if (OrderSelect(ordticket[i][1], SELECT_BY_TICKET) == true)
        {
            bool ret = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 4, Red);
            if (ret == false)
            Print("OrderClose() error - ", ErrorDescription(GetLastError()));
        }
    }
    BuyOrder8();
    
}

void BuyOrder8()
{
    double SL = Ask - BuyStoploss8*PipValue*Point;
    if (BuyStoploss8 == 0) SL = 0;
    double TP = Ask + BuyTakeprofit8*PipValue*Point;
    if (BuyTakeprofit8 == 0) TP = 0;
    int ticket = -1;
    if (true)
    ticket = OrderSend(Symbol(), OP_BUY, BuyLots8, Ask, 4, 0, 0, "", 1, 0, Blue);
    else
    ticket = OrderSend(Symbol(), OP_BUY, BuyLots8, Ask, 4, SL, TP, "", 1, 0, Blue);
    if (ticket > -1)
    {
        if (true)
        {
            OrderSelect(ticket, SELECT_BY_TICKET);
            bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Blue);
            if (ret == false)
            Print("OrderModify() error - ", ErrorDescription(GetLastError()));
        }
            
    }
    else
    {
        Print("OrderSend() error - ", ErrorDescription(GetLastError()));
    }
}

void TechnicalAnalysis9()
{
    if (iCustom(NULL, NULL, "I_XO_A_H",BoxSize,0,1) == 0)
    {
        IfOrderDoesNotExist10();
        
    }
}

void IfOrderDoesNotExist10()
{
    bool exists = false;
    for (int i=OrdersTotal()-1; i >= 0; i--)
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
        if (OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)
        {
            exists = true;
        }
    }
    else
    {
        Print("OrderSelect() error - ", ErrorDescription(GetLastError()));
    }
    
    if (exists == false)
    {
        CloseOrder11();
        
    }
}

void CloseOrder11()
{
    int orderstotal = OrdersTotal();
    int orders = 0;
    int ordticket[30][2];
    for (int i = 0; i < orderstotal; i++)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if (OrderType() != OP_BUY || OrderSymbol() != Symbol() || OrderMagicNumber() != 1)
        {
            continue;
        }
        ordticket[orders][0] = OrderOpenTime();
        ordticket[orders][1] = OrderTicket();
        orders++;
    }
    if (orders > 1)
    {
        ArrayResize(ordticket,orders);
        ArraySort(ordticket);
    }
    for (i = 0; i < orders; i++)
    {
        if (OrderSelect(ordticket[i][1], SELECT_BY_TICKET) == true)
        {
            bool ret = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 4, Red);
            if (ret == false)
            Print("OrderClose() error - ", ErrorDescription(GetLastError()));
        }
    }
    SellOrder12();
    
}

void SellOrder12()
{
    double SL = Bid + SellStoploss12*PipValue*Point;
    if (SellStoploss12 == 0) SL = 0;
    double TP = Bid - SellTakeprofit12*PipValue*Point;
    if (SellTakeprofit12 == 0) TP = 0;
    int ticket = -1;
    if (true)
    ticket = OrderSend(Symbol(), OP_SELL, SellLots12, Bid, 4, 0, 0, "My Expert", 1, 0, Red);
    else
    ticket = OrderSend(Symbol(), OP_SELL, SellLots12, Bid, 4, SL, TP, "My Expert", 1, 0, Red);
    if (ticket > -1)
    {
        if (true)
        {
            OrderSelect(ticket, SELECT_BY_TICKET);
            bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Red);
            if (ret == false)
            Print("OrderModify() error - ", ErrorDescription(GetLastError()));
        }
            
    }
    else
    {
        Print("OrderSend() error - ", ErrorDescription(GetLastError()));
    }
}



int deinit()
{
    if (false) ObjectsDeleteAll();
    
    
}


