Beispiel #1
0
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//--- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//--- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
           {
            Print("Error in history!");
            break;
           }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
            continue;
         //---
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1)
         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//--- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
{
   double ma_cur;
   double ma_prev1;
   double ma_prev2;
   
//---- go trading only for first tiks of new bar
   if(Volume[0] > 1){
     return;
   }
//---- get Moving Average 
   ma_cur = iMA(NULL, 0, MA_PERIOD, 0, MODE_SMA, PRICE_CLOSE, 0);
   ma_prev1 = iMA(NULL, 0, MA_PERIOD, 0, MODE_SMA, PRICE_CLOSE, 1);
   ma_prev2 = iMA(NULL, 0, MA_PERIOD, 0, MODE_SMA, PRICE_CLOSE, 2);
   
//---- buy conditions
   if(touch_bottom(ma_cur, ma_prev1, ma_prev2)) {
     OrderSend(Symbol(), OP_SELL, NormalizeDouble(AccountFreeMargin()*0.1/1000.0,1), Bid, 3, 0, 0, "", MAGICMA, 0, Blue);
     return;
   }
//---- sell conditions
   if(touch_top(ma_cur, ma_prev1, ma_prev2)) {
     OrderSend(Symbol(), OP_BUY, NormalizeDouble(AccountFreeMargin()*0.1/1000.0,1), Ask, 3, 0, 0, "", MAGICMA, 0, Red); 
     return;
   }

//----
}
Beispiel #3
0
int start()
{
    int err = 0;
    int total = 0;
    int prevticket = 0;
    int modespread = MarketInfo(Symbol(), MODE_SPREAD);
    
    //----
    if (IsTradeAllowed()) {
        RefreshRates();
        modespread = MarketInfo(Symbol(), MODE_SPREAD);
    } else {
        return (0);
    }
    
    ObjectSetText(WT_INFO_NAME,
        "Perceptron("+gOrderbar+"): " +
        "Spread("+modespread+") "+
        ""+DoubleToStr(perceptron(), 2)+"",
        7, "Arial", White);

    // check for opened position
    total = OrdersTotal();
    
    //----
    for (int i = 0; i < total; i++) {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        // check for symbol & magic number
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) {
            prevticket = OrderTicket();
            
            gOrderbar = iBarShift(Symbol(), 0, OrderOpenTime());
            
            // long position is opened
            if (OrderType() == OP_BUY) {
                // check profit 
                if (Bid > (OrderStopLoss() + (sl * 2 + modespread) * Point)) {
                    if (perceptron() < 0) { // reverse
                        gOrderTicket = OrderSend(Symbol(), OP_SELL, OrderLots(), Bid, 3,
                            Ask + sl * Point, 0, "AI Rev", MagicNumber, 0, Red);
                        Sleep(10000);
                        //----
                        if (gOrderTicket >= 0) {
                            OrderCloseBy(gOrderTicket, prevticket, Blue);
                        } else {
                            err=GetLastError();
                            Print("error[1](",err,"): ",ErrorDescription(err));
                            
                            if (OrderStopLoss() < OrderOpenPrice()) {
                                if (!OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), 0, 0, Blue)) {
                                    Sleep(1000);
                                }
                            }
                            
                        }
                    } else { // trailing stop
                        if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - sl * Point, 0, 0, Blue)) {
                            Sleep(1000);
                        }
                    }
                }
                // short position is opened
            } else {
                // check profit 
                if (Ask < (OrderStopLoss() - (sl * 2 + modespread) * Point)) {
                    if (perceptron() > 0) { // reverse
                        gOrderTicket = OrderSend(Symbol(), OP_BUY, OrderLots(), Ask, 3,
                            Bid - sl * Point, 0, "AI Rev", MagicNumber, 0, Blue);
                        Sleep(10000);
                        //----
                        if (gOrderTicket >= 0) {
                            OrderCloseBy(gOrderTicket, prevticket, Blue);
                        } else {
                            err=GetLastError();
                            Print("error[2](",err,"): ",ErrorDescription(err));
                            
                            if (OrderStopLoss() > OrderOpenPrice()) {
                                if (!OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), 0, 0, Blue)) {
                                    Sleep(1000);
                                }
                            }
                        }
                    } else { // trailing stop
                        if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + sl * Point,
                            0, 0, Blue)) {
                            Sleep(1000);
                        }
                    }
                }
            }
            // exit
            return (0);
        }
    }

    if (gOrderbar == iBarShift(Symbol(), 0, 0)) {
        return (0);
    }

    lots = NormalizeDouble(AccountBalance() * aiGetRisk(Period()) / (sl + modespread), 2);
    if (lots < 0.01) lots = 0.01;
    
    // check for long or short position possibility
    if (perceptron() > 0) { //long
        gOrderTicket = OrderSend(Symbol(), OP_BUY, lots, Ask, 3, Bid - sl * Point, 0, "AI",
            MagicNumber, 0, Blue);
        //----
        if (gOrderTicket < 0) {
            Sleep(10000);
            err=GetLastError();
            Print("error[3](",err,"): ",ErrorDescription(err));
        }
    } else { // short
        gOrderTicket = OrderSend(Symbol(), OP_SELL, lots, Bid, 3, Ask + sl * Point, 0, "AI",
            MagicNumber, 0, Red);
        if (gOrderTicket < 0) {
            Sleep(10000);
            err=GetLastError();
            Print("error[4](",err,"): ",ErrorDescription(err));
        }
    }
    //--- exit
    return (0);
}
Beispiel #4
0
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Do we have enough bars to work with
   if(Bars(_Symbol,_Period)<60) // if total bars is less than 60 bars
     {
      Alert("We have less than 60 bars, EA will now exit!!");
      return;
     }  

// We will use the static Old_Time variable to serve the bar time.
// At each OnTick execution we will check the current bar time with the saved one.
// If the bar time isn't equal to the saved time, it indicates that we have a new tick.

   static datetime Old_Time;
   datetime New_Time[1];
   bool IsNewBar=false;

// copying the last bar time to the element New_Time[0]
   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);
   if(copied>0) // ok, the data has been copied successfully
     {
      if(Old_Time!=New_Time[0]) // if old time isn't equal to new bar time
        {
         IsNewBar=true;   // if it isn't a first call, the new bar has appeared
         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print("We have new bar here ",New_Time[0]," old time was ",Old_Time);
         Old_Time=New_Time[0];            // saving bar time
        }
     }
   else
     {
      Alert("Error in copying historical times data, error =",GetLastError());
      ResetLastError();
      return;
     }

//--- EA should only check for new trade if we have a new bar
   if(IsNewBar==false)
     {
      return;
     }
 
//--- Do we have enough bars to work with
   int Mybars=Bars(_Symbol,_Period);
   if(Mybars<60) // if total bars is less than 60 bars
     {
      Alert("We have less than 60 bars, EA will now exit!!");
      return;
     }

//--- Define some MQL5 Structures we will use for our trade
   MqlTick latest_price;      // To be used for getting recent/latest price quotes
   MqlTradeRequest mrequest;  // To be used for sending our trade requests
   MqlTradeResult mresult;    // To be used to get our trade results
   MqlRates mrate[];          // To be used to store the prices, volumes and spread of each bar
   ZeroMemory(mrequest);      // Initialization of mrequest structure
/*
     Let's make sure our arrays values for the Rates, ADX Values and MA values 
     is store serially similar to the timeseries array
*/
// the rates arrays
   ArraySetAsSeries(mrate,true);
// the ADX DI+values array
   ArraySetAsSeries(plsDI,true);
// the ADX DI-values array
   ArraySetAsSeries(minDI,true);
// the ADX values arrays
   ArraySetAsSeries(adxVal,true);
// the MA-8 values arrays
   ArraySetAsSeries(maVal,true);


//--- Get the last price quote using the MQL5 MqlTick Structure
   if(!SymbolInfoTick(_Symbol,latest_price))
     {
      Alert("Error getting the latest price quote - error:",GetLastError(),"!!");
      return;
     }

//--- Get the details of the latest 3 bars
   if(CopyRates(_Symbol,_Period,0,3,mrate)<0)
     {
      Alert("Error copying rates/history data - error:",GetLastError(),"!!");
      ResetLastError();
      return;
     }

//--- Copy the new values of our indicators to buffers (arrays) using the handle
   if(CopyBuffer(adxHandle,0,0,3,adxVal)<0 || CopyBuffer(adxHandle,1,0,3,plsDI)<0
      || CopyBuffer(adxHandle,2,0,3,minDI)<0)
     {
      Alert("Error copying ADX indicator Buffers - error:",GetLastError(),"!!");
      ResetLastError();
      return;
     }
   if(CopyBuffer(maHandle,0,0,3,maVal)<0)
     {
      Alert("Error copying Moving Average indicator buffer - error:",GetLastError());
      ResetLastError();
      return;
     }
//--- we have no errors, so continue
//--- Do we have positions opened already?
   bool Buy_opened=false;  // variable to hold the result of Buy opened position
   bool Sell_opened=false; // variables to hold the result of Sell opened position

   if(PositionSelect(_Symbol)==true) // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         Buy_opened=true;  //It is a Buy
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
         Sell_opened=true; // It is a Sell
        }
     }

// Copy the bar close price for the previous bar prior to the current bar, that is Bar 1
   p_close=mrate[1].close;  // bar 1 close price

/*
    1. Check for a long/Buy Setup : MA-8 increasing upwards, 
    previous price close above it, ADX > 22, +DI > -DI
*/
//--- Declare bool type variables to hold our Buy Conditions
   bool Buy_Condition_1=(maVal[0]>maVal[1]) && (maVal[1]>maVal[2]); // MA-8 Increasing upwards
   bool Buy_Condition_2 = (p_close > maVal[1]);         // previuos price closed above MA-8
   bool Buy_Condition_3 = (adxVal[0]>Adx_Min);          // Current ADX value greater than minimum value (22)
   bool Buy_Condition_4 = (plsDI[0]>minDI[0]);          // +DI greater than -DI

//--- Putting all together   
   if(Buy_Condition_1 && Buy_Condition_2)
     {
      if(Buy_Condition_3 && Buy_Condition_4)
        {
         // any opened Buy position?
         if(Buy_opened)
           {
            Alert("We already have a Buy Position!!!");
            return;    // Don't open a new Buy Position
           }
         ZeroMemory(mrequest);
         mrequest.action = TRADE_ACTION_DEAL;                                  // immediate order execution
         mrequest.price = NormalizeDouble(latest_price.ask,_Digits);           // latest ask price
         mrequest.sl = NormalizeDouble(latest_price.ask - STP*_Point,_Digits); // Stop Loss
         mrequest.tp = NormalizeDouble(latest_price.ask + TKP*_Point,_Digits); // Take Profit
         mrequest.symbol = _Symbol;                                            // currency pair
         mrequest.volume = Lot;                                                 // number of lots to trade
         mrequest.magic = EA_Magic;                                             // Order Magic Number
         mrequest.type = ORDER_TYPE_BUY;                                        // Buy Order
         mrequest.type_filling = ORDER_FILLING_FOK;                             // Order execution type
         mrequest.deviation=100;                                                // Deviation from current price
         //--- send order
         OrderSend(mrequest,mresult);
         // get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
           }
         else
           {
            Alert("The Buy order request could not be completed -error:",GetLastError());
            ResetLastError();           
            return;
           }
        }
     }
/*
    2. Check for a Short/Sell Setup : MA-8 decreasing downwards, 
    previous price close below it, ADX > 22, -DI > +DI
*/
//--- Declare bool type variables to hold our Sell Conditions
   bool Sell_Condition_1 = (maVal[0]<maVal[1]) && (maVal[1]<maVal[2]);  // MA-8 decreasing downwards
   bool Sell_Condition_2 = (p_close <maVal[1]);                         // Previous price closed below MA-8
   bool Sell_Condition_3 = (adxVal[0]>Adx_Min);                         // Current ADX value greater than minimum (22)
   bool Sell_Condition_4 = (plsDI[0]<minDI[0]);                         // -DI greater than +DI

//--- Putting all together
   if(Sell_Condition_1 && Sell_Condition_2)
     {
      if(Sell_Condition_3 && Sell_Condition_4)
        {
         // any opened Sell position?
         if(Sell_opened)
           {
            Alert("We already have a Sell position!!!");
            return;    // Don't open a new Sell Position
           }
         ZeroMemory(mrequest);
         mrequest.action=TRADE_ACTION_DEAL;                                // immediate order execution
         mrequest.price = NormalizeDouble(latest_price.bid,_Digits);           // latest Bid price
         mrequest.sl = NormalizeDouble(latest_price.bid + STP*_Point,_Digits); // Stop Loss
         mrequest.tp = NormalizeDouble(latest_price.bid - TKP*_Point,_Digits); // Take Profit
         mrequest.symbol = _Symbol;                                          // currency pair
         mrequest.volume = Lot;                                              // number of lots to trade
         mrequest.magic = EA_Magic;                                          // Order Magic Number
         mrequest.type= ORDER_TYPE_SELL;                                     // Sell Order
         mrequest.type_filling = ORDER_FILLING_FOK;                          // Order execution type
         mrequest.deviation=100;                                             // Deviation from current price
         //--- send order
         OrderSend(mrequest,mresult);
         // get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Sell order has been successfully placed with Ticket#:",mresult.order,"!!");
           }
         else
           {
            Alert("The Sell order request could not be completed -error:",GetLastError());
            ResetLastError();
            return;
           }
        }
     }
   return;
  }