Close Positions at New oppositte Signal. Signal triggered by MA cross.

 
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"

#include<Trade\Trade.mqh>

CTrade trade;

input int SMA1=12 ;
input int SMA2=144;



//Calculate the Ask Price.
double Ask=NormalizeDouble( SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);

//We Calculate Bid Price
double Bid=NormalizeDouble(SymbolInfoDouble (_Symbol,SYMBOL_BID),_Digits); 
//String 
string signal="";

void OnTick()
  {


//Create an Array for several Prices.

double SMA1Array[], SMA2Array[], SMA3Array[];

// Define the Properties of SMA1.
int SMA1Definiton = iMA (_Symbol,_Period,SMA1,0,MODE_EMA,PRICE_CLOSE);
int SMA2Definiton = iMA (_Symbol,_Period,SMA2,0,MODE_EMA,PRICE_CLOSE);


//Define .....
CopyBuffer (SMA1Definiton,0, 0, 3,SMA1Array);
CopyBuffer (SMA2Definiton,0, 0, 3,SMA2Array);
CopyBuffer (SMA3Definiton,0, 0, 3,SMA3Array);


// Sell Condition
if( SMA1Array [1]>SMA3Array[1]) 

if( SMA1Array  [2]<SMA3Array[2])

   {signal="sell";}
   
 
 //Buy Condition 
if (SMA1Array[1]<SMA3Array[1])
if (SMA1Array[2]>SMA3Array[2])
   
   {signal ="buy";}

//Open Sell trade 
   
 if (signal =="sell"  && PositionsTotal() <1)
  { 
  trade.Sell(0.10,NULL ,Bid,0,(Bid-1500 * _Point),NULL);
  }

//If a buy condition < Im trying to use it to close all sell positions>

if (signal=="buy")
CloseAllSellPositions();

Comment("The Signal is:",signal);
}

//Function to Close all SELL trades.
void CloseAllSellPositions ()
{
   for (int i=PositionsTotal()-1; i>0; i--) //go through all Positions
   {
   //Go through All Positions for Current Position
   int ticket=PositionGetTicket(i);
   
   //Get Position Direction
   int PositionDirection=PositionGetInteger(POSITION_TYPE);
   
   //If Position is A BUY
   if (PositionDirection==POSITION_TYPE_SELL)
   
   //Close the Current Position.
   trade.PositionClose(ticket);
   } //End of Loop
}

Hi guys. Please Correct Me.


I need the EA to open sell trades and Close them when Buy conditions are met.

Been at it for a month. Still cant figure it out.

 

Please read the help! The indicator handle must be received ONCE - in OnInit!

Example.

How to start with MQL5
How to start with MQL5
  • 2020.09.17
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
Reason: