Trailing stop EAs/scripts

 

As many people are asking about EA to handle the stop loss for manual opened orders so we have the following threads/EAs/scripts in our forum:

- StepStopExpert EA from Igorad. I used this EA for the orders opened manually. It works. Ready to use and for everybody. It is very simple EA to move trailing stop. All the settings are changable.

- Tight Trailing Stops EA from Nicholishen.

- Kalenzo posted trailing stop code here which may be used in EAs (for programmers).

- some trailing stop codes (mostly usefull for programmers) are here.

- Trailing Stop EA posted long time ago.

- E-ASEClose Expert from KIMIV.

- many trailing files are here. I tried it some time ago.

 

The other EA for trailing stop is here.

 
newdigital:
As many people are asking about EA to handle the stop loss for manual opened orders so we have the following threads/EAs/scripts in our forum:

- StepStopExpert EA from Igorad. I used this EA for the orders opened manually. It works. Ready to use and for everybody. It is very simple EA to move trailing stop. All the settings are changable.

- Tight Trailing Stops EA from Nicholishen.

- Kalenzo posted trailing stop code here which may be used in EAs (for programmers).

- some trailing stop codes (mostly usefull for programmers) are here.

- Trailing Stop EA posted long time ago.

- E-ASEClose Expert from KIMIV.

- many trailing files are here. I tried it some time ago.

The other thread about tailing stop with some codes was started here.

 

wonderful, thanks ND.

 

Automatic breakeven code and Manually starting trailing stops

This code moves an open OP_BUY trade to breakeven after certain number of X pips profits is achieved. Many thanks for StepStopExpert_v1.mq4 by IgorAD.

Q: If this code is active on a chart, and I start a trailing stop manually how does that effect the EA auto stop code??? If it does effect it, how do I turn code off and let the manual trialing stop dominate. Is there a traling stop function or something ????

Q: I have used static variables to monitor if a breakeven order has been fired, is this ok ?

Q: Any comments on code welcome.

Note : Code is BUY side only at this stage.

Please help, thanks..

*******************************************************

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

//| ProtectCapital_v1.mq4 |

//| Copyright © 2006, Forex-TSD.com |

//| By XXXX@yahoo.co.nz |

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

/*

Many thanks to...

StepStopExpert_v1.mq4

by by IgorAD

XXXX@yahoo.co.uk

Forex-TSD.com

*/

#property copyright "Copyright © 2006, Forex-TSD.com"

#property link "By icm63@yahoo.co.nz"

#include

#include

#import "stdlib.ex4"

// -- USER INPUTS

extern int ProtectCapital_ONOFF = 1;

// If 1 then code is activated, if zero then code de activated.

extern int Email_ONOFF = 1;

// If email is 1 then emial is activated, if zero then de activated.

extern double Pip_Profit_Req = 40;

//Unrealised pip profit required to fire beakeven stop loss setting up.

//Must be greater then 10 pips

extern double Pip_SL_CutOff = 10;

//If a profit protecting Stop loss already set up it must be this close to open price.

//Between 0 and 10

extern double Pip_SL_Allowance = 3;

//Allowance added or subtracted from the to be installed protective stop. Spread or swap allowance.

//Between -10 and 10

//-- VARIABLES

int digit = 0; //Var for symbols number of digits or decimal places

static bool BE_BUY = false;// Used to monitor if a protective stop already fired for OP_BUY.

static bool BE_SELL = false;// Used to monitor if a protective stop already fired for OP_SELL.

bool OK = false; //OrderModify checker

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

//| expert initialization function |

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

int init()

{

return(0);

}

/* ---- Protect Capital Function

The idea is that when a level of unrealised pip profit is made set a stop loss order near or on

the trade entry level. But if a stop loss order already exsits that reduces the pip loss

by Pip_SL_CutOff or better do nothing. But if stop loss is required place a protective stoploss using

the trade order entry price plus or minus Pip_SL_Allowance, depending upon a + or - is loaded.

*/

void runProtectCapital()

{

double BuyStop, SellStop, ProfitLossPos ; //Var for new protective stop levels

int total = OrdersTotal(); // Var for count of market and pending orders in MT4 Order book.

for (int cnt=0;cnt<total;cnt++) //Loop thru all orders in MT4 order book

{

OrderSelect(cnt, SELECT_BY_POS); //Select orders so they can be studied by type

int mode = OrderType(); // Capture the order type for latter use

if ( OrderSymbol() == Symbol() ) // Only select orders that match the symbol in question

{

// OPEN BUY ORDERS, entered on ASK exit on BID

if ( mode == OP_BUY ) //Select buy orders that are executed for symbol in question.

{

BuyStop = OrderStopLoss(); // Get the current stop loss for open buy order

ProfitLossPos = Bid - OrderOpenPrice(); // Get current profit or loss position

if( BuyStop >= (OrderOpenPrice() - (Point * Pip_SL_CutOff)) )

//If a capital protective stop already in place close to order entry price then exit code

return(0);

if( BuyStop < (OrderOpenPrice() - (Point * Pip_SL_CutOff)) && BE_BUY == true )

// Capital protective stop already in place but under Pip_SL_CutOff threshold enusre BE_BUY is false.

BE_BUY = false;

if (ProfitLossPos < (Point * Pip_Profit_Req) || BE_BUY == true)

// If trade is under pip profit required or BE_BUY has already been actioned then exit code.

return(0);

if (ProfitLossPos >= (Point * Pip_Profit_Req) && BE_BUY == false)

// Trade is over pip profit required and BE_BUY not yet actioned then Ok protect capital.

{

BuyStop = OrderOpenPrice() + (Point * Pip_SL_Allowance);

//BuyStop is trade open price adjused for allowance for spread or swap pips - User determination.

BE_BUY = true;

// Breakeven action taken no need for further action set BE_BUY to true

OK = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(BuyStop,digit),OrderTakeProfit(),0,CLR_NONE);

// Post modified order.

if (OK == false)

{

int err = GetLastError();

Print("***************************************************************");

Print("* EA:ProtectCapital_v1");

Print("* Symbol:" + Symbol() + " Code: OP_BUY_1 Error Number: ", DoubleToStr(err,0));

Print("* Desc:",ErrorDescription(err));

Print("***************************************************************");

if(Email_ONOFF == 1)

SendMail("ProtectCapital_v1 ERROR", Symbol() +

" OP_BUY @ " + DoubleToStr(OrderOpenPrice(),4) +

" OP_BUY_1 Error: " + DoubleToStr(err,0) + ", " + ErrorDescription(err));

}

else

{

Print("***************************************************************");

Print("* EA:ProtectCapital_v1");

Print("* Symbol: " + Symbol() + " Code: OP_BUY_1 Order modified correctly.");

Print("* Desc: New stop loss @ ", DoubleToStr(NormalizeDouble(BuyStop,digit),4),

", OP_BUY @ ",DoubleToStr(OrderOpenPrice(),4));

Print("***************************************************************");

if(Email_ONOFF == 1)

SendMail("ProtectCapital_v1 Stop loss adjusted", Symbol() +

" OP_BUY @ " + DoubleToStr(OrderOpenPrice(),4) +

" New stop loss @ " + DoubleToStr(NormalizeDouble(BuyStop,digit),4));

}

return(0);

}

}

// OPEN SELL ORDERS, entered on BID exits on ASK

// To be done

}

}

}

// ---- Scan MT4 Order book for open orders for symbol in question

int ScanOrderBook()

{

int total = OrdersTotal(); // Counts number of market and pending orders.

int numords = 0;

for(int cnt=0; cnt< total; cnt++)

{

OrderSelect(cnt, SELECT_BY_POS);

if(OrderSymbol() == Symbol() && OrderType() <= OP_SELL)

numords++;

}

/*

Scans all orders for the Symbol in question to see if there are any orders

that qualify as either OP_SELL or OP_BUY. OP_SELL and OP_BUY are open or active buy and sell orders.

OrderSelect selects data by SELECT_BY_POS to allow determination of ordertype. As apposed to

OrderSelect by SELECT_BY_TICKET that returns an order ticket number

*/

return(numords);

}

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

//| expert deinitialization function |

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

int deinit()

{

return(0);

}

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

//| expert start function |

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

int start()

{

if (ProtectCapital_ONOFF == 0)

return(0);

// If code turned off exit

digit = MarketInfo(Symbol(),MODE_DIGITS);

// This gets the symbols number of decimal places for prices

// Symbol() = Returns the symbol in question. String format.

if (ScanOrderBook() < 1)

// This determines if there are any open BUY or SELL ( OP_BUY, OP_SELL) trades for the Symbol in market.

return(0);

else

if (Pip_Profit_Req >= 10 && Pip_SL_CutOff >= 0 && Pip_SL_CutOff <= 10

&& Pip_SL_Allowance >= -10 && Pip_SL_Allowance <= 10)

runProtectCapital();

/*

This runs ever time a new tick appears. It first determines if there are any open buy or sell

orders for the symbol in question. Once user inputs are ok, it fires the runProtectCapital() function.

*/

return(0);

}

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

 

May be some other people may reply but I do not know the function for manual orders selector for trailing stop. If it is EA so we may use magic number. But if orders opened manually so I don't know.

 

MT4 trailing stop from menu, how does code know its on ???

I am wrting some code to move my stop loss to breakeven after certain number of x pips profits has been secured.

BUT.. how can I turn my code off when and if I decide to start a trailing stop loss from the MT4 menu manually. Is there a function that recognises that a MT4 menu fired trailing stop is running for a particular order...???

Bear in mind I might have many open orders, but I decide to activate a menu trailing stop on one order alone, and leave the others to be managed by code.

What does this do, can it help me ???

bool IsTradeAllowed( )

Returns TRUE if the expert is allowed to trade and a thread for trading is not occupied, otherwise returns FALSE.

 

Script to modify the order by mouse.

Instruction for installation:

1. Open script in MetaEditor and set your desirable default settings.

Default settings in the script are started and finished

by this line //+--------------------------+

2. In Metarader: go to Tools, Options, Expert Advosirs

and select "Allow external experts import".

3. Move script to the chart by mouse just near the order

which you want to modify.

4. Move all the lines to the necessary levels:

- Open_Price_Line (white color by default) -

price to open the order (for pending orders only);

- Stop_Loss_Line (red color) - stop loss level;

- Take_Profit_Line (green color) - take profit level;

- Expiration_Line (yellow) - for pending orders only.

To remove stop loss, take profit, expiration date

so just delete the lines on the chart (by mouse).

Move the lines by mouse on the chart to modify the order.[/CODE]

Explanation of the settings inside the script:

Order_Find_Radius = 10;[/CODE]

It is distance between the price to open the order and where you drop this sctipt. Default is 10. If you are sniper so you may set to zero. It does not affecting on anything a lot because you should open the order manually before. So it is affecting on the following: will this script recognize the order to modify or not. I prefer 10 or more. 20 for example. Because I am not a sniper by mouse

Take_Profit = 50; int Stop_Loss = 50;

It is understandable: stop loss and take profit value. You may set it to 100 (both) to move easy after.

[CODE]Slippage = 5;

Understabdable.

[CODE]Expiration_Shift = 0;

It is for pending orders only. Value is in bas. For example, if you are attaching (moving) ther script to H4 chart and Expiration_Shift = 3 so it means that the order will be expired in 12 hours (3 bars x 4 H timeframe).

How to use this script:

1. Open the order.

2. Move this script by mouse to the place with order price on the chart. If you get the error so it means that you are not sniper and you moved the script far away from the order on the chart. Just increase Order_Find_Radius value in this case. I prefer 20 for example (20 pips target aroud the order open price on the chart).

3. Wait. Pop up window will be opened (see image attached). Ignore this pop-up window (do not click on "OK" or "Cancel", just ignore). If this pop-up window prevent you to see or move the lines on the chart so just move this window to somewhere by mouse.

4. You should see the lines. Just wait 2 or 3 seconds. To speed up this process, or if you do not see red/green stop loss and take profit lines so simple click on the chart by mouse in any place.

5. Move take profit line and stop loss line what ven distance you want (by mouse on the chart). How to move? Double mouse click on the line and move.

6. So, now only you may press "OK" in pop-up window. Afer that order will be modified.

7. If you want to modify once again so move this script to the "open order place" and repeat it.

It looks complicated but it is very simple. Just set your desirable Order_Find_Radius and use your mouse.

Files:
modifyorder.mq4  22 kb
screen2.gif  44 kb
Reason: