You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
Sorry, I don't have time to examine the entire code, but let us just examine this snippet.
if(OrderSymbol()==Symbol() && OrderType()==OP_SELL && Bid+Profit>OrderOpenPrice())
Let us say that the OrderOpenPrice = 1.2100
and the profit is 0.0010
So, you want to close the short trade if the bid is less than or equal to 1.2100-0.0010 = 1.2090.
Let us assume that there was a gap down and the prices skipped 1.2090 and the bid price now is 1.2088. According to your formula,
Bid + Profit = 1.2088 + 0.0010 = 1.2098. It is NOT greater than OrderOpenPrice even though your system has exceeded the profit threshold. Thus, the order will not be closed. The logic of the closing condition need to be reevaulated and rescripted, in my opinion. Also, you should deal with Ask prices when dealing with short trades as you can only close the trade at the ask price.
Another bit of advice,
The count loop of for (int cnt = 0 ; cnt = 0; cnt--) or something similar.
Good luck.I appreciate learning this, thanks Maji! This isn't the closing logic I wanted on this anyway... the logic I wanted was to have it close IF it hadn't triggered the trailing stop loss. Since I don't understand exactly how to detect if that is triggered or not I can't use this time-to-close closing strategy until I learn how to program it to do what I intended.
New closing Criteria...help me place the code right please...
I'm needing some assistance putting another closing criteria in this which is that the longEMA goes below the minortrendsetter (if long) and visa versa if short. I'm not sure exactly how to isolate the long and short open positions to close them with this new criteria.
//+--------- settings may vary use at your own risk-----------------+
//+--------------user inputs--------------------+
extern double Trendsetter = 250;
extern double Minortrendsetter = 150;
extern double LongEMA = 20;
extern double ShortEMA = 5;
extern double TrailingStop = 15;
extern double TrailingStopTrigger = 1;
extern double StopLoss = 186;
extern double TakeProfit = 250;
extern double Lots = 0.1;
extern double EquityStop = 9;
//---- Custom "Channel-1" Indicator and Filter Parameters
extern int Hours=36;
extern color col=SkyBlue;
extern double TF = 60; //--which bar period for the custom indicator to use
extern double upperproximity = 30; //---disallows long orders within this proximity to resistance line
extern double lowerproximity = 30; //---disallows short orders within this proximity to the support line
//+-----------close based on not triggering trailing stop in allotted time----------------+
extern int MonitorInMinutes = 60; // minutes after open to check state of trade
extern int ThresholdMove = 11; // if after that time we don't have +'x' pips we will exit
extern int MinsMultiplier = 600; // multiplies the MonitorInMinutes to make minutes (if 'x'=60) into hours
//+----------------------end of allotted time user inputs-----------------------------+
//+-----------------------------end of user inputs----------------------------------+
//+------------------------------------------------------------------+
//| expert start function
//+------------------------------------------------------------------+
int start(){
CloseOrder();
int cnt, ticket;
if(Bars<100){
Print("bars less than 100");
return(0);
}
//+----------------------Get Moving Average(s) Data----------------------------------------+
double currentlong=iMA(NULL,0,LongEMA,0,MODE_EMA,PRICE_CLOSE,0);//--current period longEMA
double currentshort=iMA(NULL,0,ShortEMA,0,MODE_EMA,PRICE_CLOSE,0);//--current period shortEMA
double trendsetter=iMA(NULL,0,Trendsetter,0,MODE_EMA,PRICE_CLOSE,0);//--current period TrendsetterEMA
double minorts=iMA(NULL,0,Minortrendsetter,0,MODE_EMA,PRICE_CLOSE,0);//--current period MinortrendsetterEMA
double prevlong=iMA(NULL,0,LongEMA,0,MODE_EMA,PRICE_CLOSE,1);//--previous period longEMA
double prevshort=iMA(NULL,0,ShortEMA,0,MODE_EMA,PRICE_CLOSE,1);//--previous period shortEMA
double prevtrendsetter=iMA(NULL,0,Trendsetter,0,MODE_EMA,PRICE_CLOSE,1);//--previous period TrendsetterEMA
double prevminorts=iMA(NULL,0,Minortrendsetter,0,MODE_EMA,PRICE_CLOSE,1);//--previous period MinortrendsetterEMA
//+----------------------------end of Get Moving Average(s) Data-----------------------------+
//+--------------------channel filter---------------------------+
double resistance = iCustom(NULL,TF,"Channel-1",Hours,col,0,0);
double support = iCustom(NULL,TF,"Channel-1",Hours,col,2,0);
//+------------------- end channel filter------------------------+
//+---------Obnoxious money management code needs revision----------------+
int total=OrdersTotal();
if(total<1){
if(AccountFreeMargin()<(1000*Lots)){
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);
}
//+---------end of Obnoxious money management code-----------------+
//+---------------------------------------Order Entry--------------------------------------------+
//+---------enter long positions----------+
if (prevshortcurrentlong && currentshort>currentlong>Trendsetter && Ask > resistance - upperproximity*Point){ //---conditions to open long positions change as desired
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point, NULL,16384,0,Green);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES )) Print("BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());
return(0);
}
//+---------enter short positions----------+
if (prevshort>prevlong && currentshort<currentlong && currentshort<currentlong<Trendsetter && Ask < support + lowerproximity*Point){ //---conditions to open short positions change as desired
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point, NULL,16384,0,Red);
if(ticket>0) {
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES )) Print("SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());
return(0);
}
}
//+---------end of order entry-------------------------+
//+-------------------------Trailing Stop Code------------------------------------+
for(cnt=0;cnt<total;cnt++) {
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) {
if(OrderType()==OP_BUY){
if(TrailingStop>0) {if(Bid-OrderOpenPrice()>Point*TrailingStopTrigger) {
if(OrderStopLoss()<Bid-Point*TrailingStop) {
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}else{
if(TrailingStop>0) {if((OrderOpenPrice()-Ask)>(Point*TrailingStopTrigger)) {
if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) {
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
return(0);
}
}
}
}
//+-------------------------End of Trailing Stop Code----------------------------+
//+---------------------Equity Stop Code---------------------------+
if((AccountEquity()+ EquityStop)<AccountBalance()) {
{
int ttotal = OrdersTotal();
for(int i=ttotal-1;i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
int type = OrderType();
bool result = false;
switch(type)
{
//Close opened long positions
case OP_BUY : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
break;
//Close opened short positions
case OP_SELL : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
}
if(result == false)
{
Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
Sleep(3000);
}
}
return(0);
}
}
}
}
}
//+---------------------End of Equity Stop Code---------------------------+
//|
//+---------------------Close Based on Time-------------------------------+
//+--------------needs revision, not working as desired---------------------+
//+------------I want it to close IF and ONLY IF trailing stop is NOT triggered-------------+
void CloseOrder()
{
double Profit=ThresholdMove*Point;
int total = OrdersTotal();
for (int cnt = 0 ; cnt < total ; cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if ((CurTime()-OrderOpenTime())>MonitorInMinutes*60*MinsMultiplier)
{
if(OrderSymbol()==Symbol() && OrderType()==OP_BUY && Bid-Profit<OrderOpenPrice() )
{
OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet);
}
if(OrderSymbol()==Symbol() && OrderType()==OP_SELL && Bid+Profit>OrderOpenPrice())
{
OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet);
}
}
}
}
//+---------------------------end of close on time code---------------+ok I need to understand this part of the code now....
first line counts
second line selects counted orders
third line..this tricks me..I THINK it wants to know if the order selected is a sell..but what is up with the "0? I mean there are FIVE 'if' lines here...
I guess if any one of them are true then it will modify the order otherwise...I guess it goes to the ..'else' and ...well this somehow must manage to deal with both long and short positions but I don't understand it yet.
Since i want to add criteria to close long or short based on the cross of the longEMA with the minortrendsetterEMA...I'm not sure where in all this to do it.
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) {
if(OrderType()==OP_BUY){
if(TrailingStop>0) {if(Bid-OrderOpenPrice()>Point*TrailingStopTrigger) {
if(OrderStopLoss()<Bid-Point*TrailingStop) {
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}else{
if(TrailingStop>0) {if((OrderOpenPrice()-Ask)>(Point*TrailingStopTrigger)) {
if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) {
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
return(0);
}
}
}
}ok i understand that all the if's and elses lead to thess lines. these are the ones I need to understand..
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
I need to learn more about how these order modify lines are constructed..are these the ones that are closing as well as changing the orders? or do they just change orders and something else closes the orders??
Look at the help in MetaEditor
OP_BUY 0 Buying position.
OP_SELL 1 Selling position.
OP_BUYLIMIT 2 Buy limit pending position.
OP_SELLLIMIT 3 Sell limit pending position.
OP_BUYSTOP 4 Buy stop pending position.
OP_SELLSTOP 5 Sell stop pending position.
[/PHP]
so, <= OP_SELL is OP_BUY or OP_SELL. Just instead of using
[PHP]if((OrderType()==OP_SELL) || (OrderType()==OP_BUY) ...Just less typing
Here u go
void CloseOrders(int op)
{
int tik[30], t = 0;
for(int i =0;i<OrdersTotal();i++){
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
if(OrderSymbol()==Symbol() && MagicNum==OrderMagicNumber() && OrderType() == op){
tik[t] = OrderTicket(); t++;
}
}
}
for (i = 0; i<t; i++)
{
if(OrderSelect(tik,SELECT_BY_TICKET)){
double prc = Bid;
if (op == OP_SELL) prc = Ask;
CloseOrder(tik, OrderLots(), prc);
}
}
}Call it : CloseOrder(OP_BUY); // Close all buy orders
or
CloseOrder(OP_SELL); // Close all sell orders
The reason that I am keeping all the orders tickets in an array and then delete is because when I close order in position # 1 then the next one become 1 again and we have a problem.
I forget this one
{
int CloseCnt, err;
// try to close 3 Times
CloseCnt = 0;
color clr = Violet;
if (OrderType() == OP_SELL)
clr = Orange;
while (CloseCnt < 3)
{
if (OrderClose(ticket,numLots,close_price,Slippage,clr))
{
CloseCnt = 3;
}
else
{
err=GetLastError();
Print(CloseCnt," Error closing order : (", err , ") " + ErrorDescription(err));
if (err > 0) CloseCnt++;
}
}
}
[/PHP]
and dont forget to add this line after #property link
[PHP]#property link "http://www.elihayun.com"
#include
I'm still confused...
Understand that I didn't create this code originally. I'm working to understand what someone else did and modify it. I put my name on the property line only now that I have modified it so much that it bears little resemblance anymore to the original. I have modified more of it now than I have left untouched. There are still some aspects of it that I don't understand and therefore havn't been able to modify.
What I am looking for is the code that closes orders...it seems that all of this is just modifying to update the trailing stop.
this is more than one way to close.
right now this EA has the ability to close with a stop loss.
to close with a trailing stop.
to close with a take profit target.
or to close based on the passage of some defined time after opening.
what it doesn't have that I want it to have is the ability to close if the longEMA goes back on the minortrendsetterEMA. it could do this crossing up to close a short position or crossing down to close a long position. How do I make it do that? I mean with all of these other closing options where do I put the new code to superceed all of these other closing options?
In my expirementation when I don't want to use some aspect of this I simply make the criteria of that parameter so extreme that it's never going to trigger it which is like turning that criteria basically off. Doing that allows the other criteria's play out to show what they would return.
I forget this one
{
int CloseCnt, err;
// try to close 3 Times
CloseCnt = 0;
color clr = Violet;
if (OrderType() == OP_SELL)
clr = Orange;
while (CloseCnt < 3)
{
if (OrderClose(ticket,numLots,close_price,Slippage,clr))
{
CloseCnt = 3;
}
else
{
err=GetLastError();
Print(CloseCnt," Error closing order : (", err , ") " + ErrorDescription(err));
if (err > 0) CloseCnt++;
}
}
}
[/PHP]
and dont forget to add this line after #property link
[PHP]#property link "http://www.elihayun.com"
#include
ok great thankyou!
so this is basically only a closing code?
Will this close both open long and short positions?
How would I use this to close if the longema crossed back on the minortrendsetterema? crossing up if it had opened short and crossing down if it had opened long?
p.s. I will not be back to the computer until later this afternoon. I'll check back then.
one more question...
what does 'swap' mean?
Everytime u decide to open a LONG position call : CloseOrders(OP_SELL);
and vise versa.
Look at your code where u are openning the orders.
You don't have to check if there is an order to close. The routine will do that for u
BTW, I post a code to convert 2006.07.02 kinda cell to date in excel. Look at your post there