what is wrong with my code?

 
So I have this Median indicator

Here is the code ....


#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Black
#property indicator_width1 2

extern int Length = 14;
extern int ApplyTo = PRICE_CLOSE;

double median[];
double array[];
int midlea;
int midleb;

//+------------------------------------------------------------------+
int init()
{
ArrayResize(array,Length);
SetIndexBuffer(0,median);
IndicatorShortName("median ("+Length+")");

Length = MathMax(Length,2);
if ((Length%2) == 0)
{
midlea = (Length/2)-1;
midleb = (Length/2);
}
else
{
midlea = MathFloor(Length/2);
midleb = midlea;
}
return(0);
}

//+------------------------------------------------------------------+
int deinit()

{
return(0);
}

//+------------------------------------------------------------------+
int start()
{
int i,limit;
int counted_bars=IndicatorCounted();
if (counted_bars>0) counted_bars--;
limit=Bars-counted_bars;

for(i=limit; i>=0; i--)
{
for (int k=0; k<Length; k++)
array[k] = iMA(NULL,0,1,0,MODE_SMA,ApplyTo,i+k);
ArraySort(array);
median[i] = (array[midlea]+array[midleb])/2.0;
}
return(0);
}

And so I want to code a simple median/moving average cross.

Have a look at my code....





// External variables
extern double LotSize = 0.1;
extern double StopLoss = 50;
extern double TakeProfit = 100;

extern int Slippage = 5;
extern int MagicNumber = 123;

extern int FastMAPeriod = 10;

// Median Variables

extern int MedianLength = 3;
extern int MedianApplyTo = PRICE_CLOSE;
extern int SlowMAPeriod = 20;


// Global variables
int BuyTicket;
int SellTicket;
double UsePoint;
int UseSlippage;


// Init function
int init()
{
UsePoint = PipPoint(Symbol());
UseSlippage = GetSlippage(Symbol(),Slippage);
}


// Start function
int start()
{
// Moving averages
double FastMA = iMA(NULL,0,FastMAPeriod,0,0,0,0);

// Add the Median indicator
double MedianIndi = iCustom(NULL, 0, "Median", MedianLength,MedianApplyTo, 0, 3);


// Buy order
if(MedianIndi > FastMA && BuyTicket == 0)
{
OrderSelect(SellTicket,SELECT_BY_TICKET);

// Close order
if(OrderCloseTime() == 0 && SellTicket > 0)
{
double CloseLots = OrderLots();
double ClosePrice = Ask;

bool Closed = OrderClose(SellTicket,CloseLots,ClosePrice,UseSlippage,Red);
}

double OpenPrice = Ask;

// Calculate stop loss and take profit
if(StopLoss > 0) double BuyStopLoss = OpenPrice - (StopLoss * UsePoint);
if(TakeProfit > 0) double BuyTakeProfit = OpenPrice + (TakeProfit * UsePoint);

// Open buy order
BuyTicket = OrderSend(Symbol(),OP_BUY,LotSize,OpenPrice,UseSlippage,BuyStopLoss,BuyTakeProfit,"Buy Order",MagicNumber,0,Green);

SellTicket = 0;
}


// Sell Order
if(FastMA < MedianIndi && SellTicket == 0)
{
OrderSelect(BuyTicket,SELECT_BY_TICKET);

if(OrderCloseTime() == 0 && BuyTicket > 0)
{
CloseLots = OrderLots();
ClosePrice = Bid;

Closed = OrderClose(BuyTicket,CloseLots,ClosePrice,UseSlippage,Red);
}

OpenPrice = Bid;

if(StopLoss > 0) double SellStopLoss = OpenPrice + (StopLoss * UsePoint);
if(TakeProfit > 0) double SellTakeProfit = OpenPrice - (TakeProfit * UsePoint);

SellTicket = OrderSend(Symbol(),OP_SELL,LotSize,OpenPrice,UseSlippage,SellStopLoss,SellTakeProfit,"Sell Order",MagicNumber,0,Red);

BuyTicket = 0;
}

return(0);
}


// Pip Point Function
double PipPoint(string Currency)
{
int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
if(CalcDigits == 2 || CalcDigits == 3) double CalcPoint = 0.01;
else if(CalcDigits == 4 || CalcDigits == 5) CalcPoint = 0.0001;
return(CalcPoint);
}


// Get Slippage Function
int GetSlippage(string Currency, int SlippagePips)
{
int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
if(CalcDigits == 2 || CalcDigits == 4) double CalcSlippage = SlippagePips;
else if(CalcDigits == 3 || CalcDigits == 5) CalcSlippage = SlippagePips * 10;
return(CalcSlippage);
}


But it opens and closes trades like crazy.

Here is a screenshot.....




Plainly something is amiss.

Can anybody give me a few pointers?

Thanks a lot folks.
 

What is this an indicator or ea? Whats exactly are you trying to do? Have you tried going through some comprehensive material for learning how to code mql4? Example The Book.

 

i would suggest that we rewrite a couple of things that appear to be a bit redundant in my opinion.

int start()
{
// Moving averages
double FastMA = iMA(NULL,0,FastMAPeriod,0,0,0,0);

// Add the Median indicator
double MedianIndi = iCustom(NULL, 0, "Median", MedianLength,MedianApplyTo, 0, 3);

int myoptype=-1;

if(MedianIndi > FastMA && BuyTicket == 0) myoptype=OP_BUY;
if(FastMA < MedianIndi && SellTicket == 0) myoptype=OP_SELL;

if(myoptype==-1) return(0); //??


//CLOSE OPEN TRADES HERE?
double desiredprofitamount=AccountBalance()*0.01; //i am just guessing here..
double price;
int total=OrdersTotal();
for(int pos=0;pos<total;pos++)
{
if(OrderSelect(pos,SELECT_BY_POS)==false) continue;
if(OrderType()!=myordertype) continue;
if(OrderType()==OP_BUY) price=MarketInfo(OrderSymbol(),MODE_BID);
if(OrderType()==OP_SELL) price=MarketInfo(OrderSymbol(),MODE_ASK);
if(orderProfit()<desiredprofitamount) continue;


//close it here..
int rc=OrderClose(OrderTicket(),OrderLots(),price,0,CLR_NONE);
if(rc<0)
{
Comment("ordersend failed with error #",GetLastError());
}//if

}/*end of for loop*/


/*
AND HERE IS YOUR PROBLEM...

YOU ARE JUST SIMPLY OPENING TRADES, ONE AFTER THE NEXT...

THERE IS NO LOGIC THAT TELLS IT TO OPEN A TRADE IF WHATEVER CONDIITION IS MET..

anyways, you were writing all of this code twice, and you dont need to..

*/

//what you need is some kind of logic that does something like this:

if(blah blah blah)
{
int ticket =
OrderSend(Symbol(),myoptype,LotSize,OpenPrice,UseSlippage,BuyStopLoss,BuyTakeProfit,"Buy Order",MagicNumber,0,Green);
}//end of if

else

{

//do not open a trade, and just fall thru..


}//else


return(0);
}/*end of start function*/



 

there are a lot of general errors in my above code, but if you can just pick up on the general gist of what i am trying to do above, fine..

should you have any questions, feel free to ask, i enjoy writing code.

above is a very obvious kind of error:

i wrote:

if(OrderType()!=myordertype) continue;

but it should have said:

if(OrderType()!=myoptype) continue;

stuff like that.

 

if you will only describe for me, in plain text, tell me what it is that you are trying to accomplish, i will be most pleased to take a shot at getting you there.

i am an old hand at coding.

 
sarauharrison:

if you will only describe for me, in plain text, tell me what it is that you are trying to accomplish, i will be most pleased to take a shot at getting you there.

i am an old hand at coding.



What is this an indicator or ea? Whats exactly are you trying to do? Have you tried going through some comprehensive material for learning how to code mql4? Example The Book.

Did you read this if so then why you don't use it?? If you write a new message then you have several options

You already know how to place a picture . How to show your code is with that SRC button makes it more easier to read.....

 

Thanks so far so far.


I'm off to work now, I'll add more when I get back.

 

OK here goes.


I'm looking to code an EA.

It'll use a moving average and a median indicator.

Take a look at this screenshot. The red line is the Median, the yellow a SMA.



I want it to buy/sell whenever there is a median/ma cross.


Onto the code.


Here is the code for the median indicator.

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Black
#property indicator_width1 2

extern int Length = 14;
extern int ApplyTo = PRICE_CLOSE;

double median[];
double array[];
int midlea;
int midleb;

//+------------------------------------------------------------------+
int init()
{
ArrayResize(array,Length);
SetIndexBuffer(0,median);
IndicatorShortName("median ("+Length+")");

Length = MathMax(Length,2);
if ((Length%2) == 0)
{
midlea = (Length/2)-1;
midleb = (Length/2);
}
else
{
midlea = MathFloor(Length/2);
midleb = midlea;
}
return(0);
}

//+------------------------------------------------------------------+
int deinit()

{
return(0);
}

//+------------------------------------------------------------------+
int start()
{
int i,limit;
int counted_bars=IndicatorCounted();
if (counted_bars>0) counted_bars--;
limit=Bars-counted_bars;

for(i=limit; i>=0; i--)
{
for (int k=0; k<Length; k++)
array[k] = iMA(NULL,0,1,0,MODE_SMA,ApplyTo,i+k);
ArraySort(array);
median[i] = (array[midlea]+array[midleb])/2.0;
}
return(0);
}


And here is my EA code.


// External variables
extern double LotSize = 0.1;
extern double StopLoss = 50;
extern double TakeProfit = 100;

extern int Slippage = 5;
extern int MagicNumber = 123;

extern int FastMAPeriod = 10;

// Median Variables

extern int MedianLength = 3;
extern int MedianApplyTo = PRICE_CLOSE;
extern int SlowMAPeriod = 20;


// Global variables
int BuyTicket;
int SellTicket;
double UsePoint;
int UseSlippage;


// Init function
int init()
{
UsePoint = PipPoint(Symbol());
UseSlippage = GetSlippage(Symbol(),Slippage);
}


// Start function
int start()
{
// Moving averages
double FastMA = iMA(NULL,0,FastMAPeriod,0,0,0,0);

// Add the Median indicator
double MedianIndi = iCustom(NULL, 0, "Median", MedianLength,MedianApplyTo, 0, 3);


// Buy order
if(MedianIndi > FastMA && BuyTicket == 0)
{
OrderSelect(SellTicket,SELECT_BY_TICKET);

// Close order
if(OrderCloseTime() == 0 && SellTicket > 0)
{
double CloseLots = OrderLots();
double ClosePrice = Ask;

bool Closed = OrderClose(SellTicket,CloseLots,ClosePrice,UseSlippage,Red);
}

double OpenPrice = Ask;

// Calculate stop loss and take profit
if(StopLoss > 0) double BuyStopLoss = OpenPrice - (StopLoss * UsePoint);
if(TakeProfit > 0) double BuyTakeProfit = OpenPrice + (TakeProfit * UsePoint);

// Open buy order
BuyTicket = OrderSend(Symbol(),OP_BUY,LotSize,OpenPrice,UseSlippage,BuyStopLoss,BuyTakeProfit,"Buy Order",MagicNumber,0,Green);

SellTicket = 0;
}


// Sell Order
if(FastMA < MedianIndi && SellTicket == 0)
{
OrderSelect(BuyTicket,SELECT_BY_TICKET);

if(OrderCloseTime() == 0 && BuyTicket > 0)
{
CloseLots = OrderLots();
ClosePrice = Bid;

Closed = OrderClose(BuyTicket,CloseLots,ClosePrice,UseSlippage,Red);
}

OpenPrice = Bid;

if(StopLoss > 0) double SellStopLoss = OpenPrice + (StopLoss * UsePoint);
if(TakeProfit > 0) double SellTakeProfit = OpenPrice - (TakeProfit * UsePoint);

SellTicket = OrderSend(Symbol(),OP_SELL,LotSize,OpenPrice,UseSlippage,SellStopLoss,SellTakeProfit,"Sell Order",MagicNumber,0,Red);

BuyTicket = 0;
}

return(0);
}


// Pip Point Function
double PipPoint(string Currency)
{
int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
if(CalcDigits == 2 || CalcDigits == 3) double CalcPoint = 0.01;
else if(CalcDigits == 4 || CalcDigits == 5) CalcPoint = 0.0001;
return(CalcPoint);
}


// Get Slippage Function
int GetSlippage(string Currency, int SlippagePips)
{
int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
if(CalcDigits == 2 || CalcDigits == 4) double CalcSlippage = SlippagePips;
else if(CalcDigits == 3 || CalcDigits == 5) CalcSlippage = SlippagePips * 10;
return(CalcSlippage);
}


But like I said, it is continually opening trades like crazy.


Help

 

Hi monkeybus,

Click here maybe.

:D

 
// Buy order
if(MedianIndi > FastMA && BuyTicket == 0)

// Sell Order
if(FastMA < MedianIndi && SellTicket == 0)

What is the difference for doing buy or sell ??

your buytrade is closed everytime directly your selltrade keeps going on .... check what happens

 

OK, but here's the thing, If I use the same code with a simple MA cross to trigger trades everything works fine.


// External variables
extern double LotSize = 0.1;
extern double StopLoss = 50;
extern double TakeProfit = 100;

extern int Slippage = 5;
extern int MagicNumber = 123;

extern int FastMAPeriod = 10;
extern int SlowMAPeriod = 20;


// Global variables
int BuyTicket;
int SellTicket;
double UsePoint;
int UseSlippage;


// Init function
int init()
        {
      UsePoint = PipPoint(Symbol());
      UseSlippage = GetSlippage(Symbol(),Slippage);
        }


// Start function
int start()
        {
                // Moving averages
                double FastMA = iMA(NULL,0,FastMAPeriod,0,0,0,0);
                double SlowMA = iMA(NULL,0,SlowMAPeriod,0,0,0,0);
                
                
                // Buy order 
                if(FastMA > SlowMA && BuyTicket == 0)
                        {
                                OrderSelect(SellTicket,SELECT_BY_TICKET);
                
                                // Close order
                                if(OrderCloseTime() == 0 && SellTicket > 0)
                                        {
                                                double CloseLots = OrderLots();
                                                double ClosePrice = Ask;

                                                bool Closed = OrderClose(SellTicket,CloseLots,ClosePrice,UseSlippage,Red);
                                        }                               

                                double OpenPrice = Ask;
                                
                                // Calculate stop loss and take profit
                                if(StopLoss > 0) double BuyStopLoss = OpenPrice - (StopLoss * UsePoint);
                                if(TakeProfit > 0) double BuyTakeProfit = OpenPrice + (TakeProfit * UsePoint);
                                
                                // Open buy order
                                BuyTicket = OrderSend(Symbol(),OP_BUY,LotSize,OpenPrice,UseSlippage,BuyStopLoss,BuyTakeProfit,"Buy Order",MagicNumber,0,Green);
                                
                                SellTicket = 0;
                        }
                
                
                // Sell Order 
                if(FastMA < SlowMA && SellTicket == 0)
                        {
                                OrderSelect(BuyTicket,SELECT_BY_TICKET);
                
                                if(OrderCloseTime() == 0 && BuyTicket > 0)
                                        {
                                                CloseLots = OrderLots();
                                                ClosePrice = Bid;

                                                Closed = OrderClose(BuyTicket,CloseLots,ClosePrice,UseSlippage,Red);
                                        }               
                                
                                OpenPrice = Bid;
                                
                                if(StopLoss > 0) double SellStopLoss = OpenPrice + (StopLoss * UsePoint);
                                if(TakeProfit > 0) double SellTakeProfit = OpenPrice - (TakeProfit *    UsePoint);
                                
                                SellTicket = OrderSend(Symbol(),OP_SELL,LotSize,OpenPrice,UseSlippage,SellStopLoss,SellTakeProfit,"Sell Order",MagicNumber,0,Red);
                                
                                BuyTicket = 0;
                        }
                        
                return(0);
        }


// Pip Point Function
double PipPoint(string Currency)
        {
                int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
                if(CalcDigits == 2 || CalcDigits == 3) double CalcPoint = 0.01;
                else if(CalcDigits == 4 || CalcDigits == 5) CalcPoint = 0.0001;
                return(CalcPoint);
        }


// Get Slippage Function
int GetSlippage(string Currency, int SlippagePips)
        {
                int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
                if(CalcDigits == 2 || CalcDigits == 4) double CalcSlippage = SlippagePips;
                else if(CalcDigits == 3 || CalcDigits == 5) CalcSlippage = SlippagePips * 10;
                return(CalcSlippage);
        }



This code will buy or sell on a fastMA/slowMA cross.



if(FastMA > SlowMA && BuyTicket == 0)
The above condition is OK. But this one causes all kinds of mayhem
if(MedianIndi > FastMA && BuyTicket == 0)
I really don't understand why.
Reason: