After stoploss hit, next signal the opposite direction

 

Dear Trader,

I have a system based on a stochastic, but since I'm a newbie in programming MQL4 I need your help? After a stoploss is hit it will re enter the trade again, I dont want this. I want the system to wait for a signal in the opposite direction. For example, I got a sell signall but it went up and the stoploss was hit, the next signal I want is a buy signal and NOT a sell signal again. So that I prevent trading the stochastic when there is a strong trend.

Can anyone help me whit this??

THanks in advance!

 
Show code.
 

This is the difficulty with trading oscillators like the stochastic. You can pretty easily hit tops and bottoms spot on when you have decent volatility and a flat market. As soon as you are trending though your oscillator is pegged at overbought or oversold levels and you get the opposite signals from what you would want.

Things to try:

1) Create 2 bool variables, openlong and openshort. Set openshort when you enter a short position. Do not allow any other short positions to open when openshort is set. Do not reset openshort until the next time you open a long position. And vice versa.

2) Use Bollinger bands. Calculate the slope of the main line. Do not trade if the slope is above or below a certain threshold. When the slope is beyond this threshold, close losing positions that are outside of the bands.

3) Find a trend detection algorithm that you are comfortable with and use it to reverse the buy and sell signals you get from stochastics.

I know you are new to programming, consider these to be useful exercises. None of them is terribly difficult.

Hope this sets you in the right direction. Good luck!

 

Hello all,

Thanks for your quick replies!

This is the code:

#define SIGNAL_NONE 0
#define SIGNAL_BUY 1
#define SIGNAL_SELL 2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4

extern int MagicNumber = 0;
extern bool SignalMail = False;
extern bool EachTickMode = True;
extern double Lots = 1.0;
extern int Slippage = 3;
extern bool UseStopLoss = True;
extern int StopLoss = 300;
extern bool UseTakeProfit = True;
extern int TakeProfit = 300;
extern bool UseTrailingStop = False;
extern int TrailingStop = 30;

int BarCount;
int Current;
bool TickCheck = False;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init() {
BarCount = Bars;

if (EachTickMode) Current = 0; else Current = 1;

return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit() {
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start() {
int Order = SIGNAL_NONE;
int Total, Ticket;
double StopLossLevel, TakeProfitLevel;

if (EachTickMode && Bars != BarCount) TickCheck = False;
Total = OrdersTotal();
Order = SIGNAL_NONE;

//+------------------------------------------------------------------+
//| Variable Begin |
//+------------------------------------------------------------------+

double Var1 = iStochastic(NULL, 0, 25, 8, 5, MODE_SMA, 0, MODE_MAIN, Current + 0);

double Buy1_1 = iStochastic(NULL, 0, 25, 8, 5, MODE_SMA, 0, MODE_MAIN, Current + 0);
double Buy1_2 = 20;

double Sell1_1 = iStochastic(NULL, 0, 25, 8, 5, MODE_SMA, 0, MODE_MAIN, Current + 0);
double Sell1_2 = 80;


//+------------------------------------------------------------------+
//| Variable End |
//+------------------------------------------------------------------+

//Check position
bool IsTrade = False;

for (int i = 0; i < Total; i ++) {
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if(OrderType() <= OP_SELL && OrderSymbol() == Symbol()) {
IsTrade = True;
if(OrderType() == OP_BUY) {
//Close

//+------------------------------------------------------------------+
//| Signal Begin(Exit Buy) |
//+------------------------------------------------------------------+

if (False) Order = SIGNAL_CLOSEBUY;


//+------------------------------------------------------------------+
//| Signal End(Exit Buy) |
//+------------------------------------------------------------------+

if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen);
if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Close Buy");
if (!EachTickMode) BarCount = Bars;
IsTrade = False;
continue;
}
//Trailing stop
if(UseTrailingStop && TrailingStop > 0) {
if(Bid - OrderOpenPrice() > Point * TrailingStop) {
if(OrderStopLoss() < Bid - Point * TrailingStop) {
OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop, OrderTakeProfit(), 0, MediumSeaGreen);
if (!EachTickMode) BarCount = Bars;
continue;
}
}
}
} else {
//Close

//+------------------------------------------------------------------+
//| Signal Begin(Exit Sell) |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Signal End(Exit Sell) |
//+------------------------------------------------------------------+

if (Order == SIGNAL_CLOSESELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, DarkOrange);
if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Close Sell");
if (!EachTickMode) BarCount = Bars;
IsTrade = False;
continue;
}
//Trailing stop
if(UseTrailingStop && TrailingStop > 0) {
if((OrderOpenPrice() - Ask) > (Point * TrailingStop)) {
if((OrderStopLoss() > (Ask + Point * TrailingStop)) || (OrderStopLoss() == 0)) {
OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Point * TrailingStop, OrderTakeProfit(), 0, DarkOrange);
if (!EachTickMode) BarCount = Bars;
continue;
}
}
}
}
}
}

//+------------------------------------------------------------------+
//| Signal Begin(Entry) |
//+------------------------------------------------------------------+

if (Buy1_1 <= Buy1_2) Order = SIGNAL_BUY;

if (Sell1_1 >= Sell1_2) Order = SIGNAL_SELL;


//+------------------------------------------------------------------+
//| Signal End |
//+------------------------------------------------------------------+

//Buy
if (Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
if(!IsTrade) {
//Check free margin
if (AccountFreeMargin() < (1000 * Lots)) {
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);
}

if (UseStopLoss) StopLossLevel = Ask - StopLoss * Point; else StopLossLevel = 0.0;
if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; else TakeProfitLevel = 0.0;

Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, StopLossLevel, TakeProfitLevel, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);
if(Ticket > 0) {
if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
Print("BUY order opened : ", OrderOpenPrice());
if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Open Buy");
} else {
Print("Error opening BUY order : ", GetLastError());
}
}
if (EachTickMode) TickCheck = True;
if (!EachTickMode) BarCount = Bars;
return(0);
}
}

//Sell
if (Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
if(!IsTrade) {
//Check free margin
if (AccountFreeMargin() < (1000 * Lots)) {
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);
}

if (UseStopLoss) StopLossLevel = Bid + StopLoss * Point; else StopLossLevel = 0.0;
if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point; else TakeProfitLevel = 0.0;

Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
if(Ticket > 0) {
if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
Print("SELL order opened : ", OrderOpenPrice());
if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Open Sell");
} else {
Print("Error opening SELL order : ", GetLastError());
}
}
if (EachTickMode) TickCheck = True;
if (!EachTickMode) BarCount = Bars;
return(0);
}
}

if (!EachTickMode) BarCount = Bars;

return(0);
}

//+------------------------------------------------------------------+

 

HI Anomalous,

I like your first idea:

1) Create 2 bool variables, openlong and openshort. Set openshort when you enter a short position. Do not allow any other short positions to open when openshort is set. Do not reset openshort until the next time you open a long position. And vice versa.

I'm trying to build that in, but as a newbie a bit hard for me...Can you give me a direction how to work that out?

THanks!

 
 

In the code where you open a new short position:

//Sell
if (Order == SIGNAL_SELL && !openshort && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount))))
{
        if(!IsTrade)
        {
//Check free margin
                if (AccountFreeMargin() < (1000 * Lots)) {
                Print("We have no money. Free Margin = ", AccountFreeMargin());
                return(0);
        }

        if (UseStopLoss) StopLossLevel = Bid + StopLoss * Point; else StopLossLevel = 0.0;
        if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point; else TakeProfitLevel = 0.0;

        Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
        if(Ticket > 0)
        {
                if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES))
                {
                        openshort = true;
                        openlong = false;
                        Print("SELL order opened : ", OrderOpenPrice());
                        if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Open Sell");
                }
                else 
                        Print("Error opening SELL order : ", GetLastError());
        }
}

You would make the corresponding changes to the code where you open a long position.

And near the top of your code right after TickCheck is defined:

bool openshort = false;
bool openlong = false;

I honestly don't know how this will affect the performance of your EA. Like I say, good learning exercise.

 

Thank you very much, very helpfull. The only thing now is that I want the EA also to close not only if a stoploss or take profit is hit but also when a reverse signal appears? Could you also help me with that?

thanks again and have a good weekend!

 
Anomalous:

In the code where you open a new short position:

You would make the corresponding changes to the code where you open a long position.

And near the top of your code right after TickCheck is defined:

I honestly don't know how this will affect the performance of your EA. Like I say, good learning exercise.

Thank You, I was looking for this code for months. You are my god :)
 

Hi,

 I have a strategy just based on price. In my EA, whenever my long position hit its trailing stop, i would like to open a short order and vice verse. It is easy to do it once you fix your strategy to an indicator (rsi,srochastic, etc...) But how can i do it based on purely on price without any indicator? thanks.

 
Find the last trade in history. See if it was by trailing stop. Open the opposite. You haven't stated a problem, you stated a want. Show us your attempt (using the CODE button) and state the nature of your problem.
          No free help 2017.04.21

Or pay someone. Top of every page is the link Freelance.
          Hiring to write script - General - MQL5 programming forum 2018.05.12

We're not going to code it for you (although it could happen if you are lucky or the problem is interesting).
          No free help 2017.04.21

Reason: