Why Buy order is not placed when calculated Stoploss and Take profit are used - mql4

I have a simple BUY order that, when the Take Profit and Stoploss are in points (ie: Ask+10*_Point), operates correctly. But when I change the take profit and stop loss from points to my own calculated values (CL_OP), the BUY order is not placing trades. How can I solve the issue:
input int _Hour =16;
input int _Minute =30;
bool NewBar()
{
static datetime OldTime = 0;
if(OldTime < Time[0])
{
OldTime = Time[0];
return(true);
}
else
{
return(false);
}
}
void OnTick()
{
int Hour_Int = Hour();
int Minute_Int = Minute();
double CL_OP = (Close[1] - Open[1]);
bool LastBearHiLoEngulf = (Close[1] < Open[1] && High[1] > High[2] && Low[1] < Low[2] );
if(NewBar())
if(OrdersTotal()==0)
// Apply signals on Buy opportunities
if( Hour_Int == _Hour && Minute_Int == _Minute && LastBearHiLoEngulf == TRUE)
{
int buyticket = OrderSend
(
Symbol(), // all symbols
OP_BUY, // Buy without delay
1, // 1 Microlots
Ask, // for market price
3, // 3 pips slippage
Ask - CL_OP, // Stop Loss - 1000*_Point
Ask + CL_OP , // Take profitworks with 100*_Point
"Buy LastBearHiLoEngulf Target: ", // comment
144, // Magic number
0, // no experiation day
Green // draw green arrow
);
}
}

double CL_OP = (Close[1] - Open[1]);
CL_OP is not a normal price to open trade. Actually, it is the Size of the Candle 1!
It should be something like this:
double CL_OP = Close[1] + (Close[1] - Open[1]);

Related

how to track take profit and stoploss in mql4

I have the following code in mql4 and it is partially working but having an issue with order tracking.
int ticket;
void OnTick(){
... not included code, setting variables, etc ...
if(tenkan_sen < kijun_sen){
comment += "\nSHORT!";
if(OrderSelect(ticket,SELECT_BY_TICKET) && OrderType() == OP_BUY){
if(OrderClose(OrderTicket(),OrderLots(),Bid,1000,clrCrimson)){
ticket = 0;
}
}
if(ticket <= 0){
// need to set stoploss and takeprofit prices
double short_tp = current_close - (atr*6);
double short_sl = current_close + (atr*2);
ticket = OrderSend(_Symbol,OP_SELL,0.01,Bid,1000,short_sl,short_tp,"This is a sell",1,0,clrPink);
}
} else if(tenkan_sen > kijun_sen){
comment += "\nLONG!";
if(OrderSelect(ticket,SELECT_BY_TICKET) && OrderType() == OP_SELL){
if(OrderClose(OrderTicket(),OrderLots(),Ask,1000,clrPink)){
ticket = 0;
}
}
if(ticket <= 0){
// need to set stoploss and take profit prices
double long_tp = current_close + (atr*6);
double long_sl = current_close - (atr*2);
ticket = OrderSend(_Symbol,OP_BUY,0.01,Ask,1000,long_sl,long_tp,"This is a buy",1,0,clrCrimson);
}
}
}
This was previously based on the logic of closing the previous position upon opening the last position, it was working as expected before I added the sl and tp values. I am not sure how I should reset the ticket variable to 0 in the event of a sl or tp, or if there is a different way I should be handling this.

Why is it that when the second arrow indicator shows up the EA doesn't execute anything?

I've written some code on an Expert Advisor to trade on the Fiji-trend-indicator. The EA recognises the first arrow indicator and executes a trade accordingly, however, when the second arrow is supposed to show up on a back test, the rest of the code doesn't do anything.
I see that the custom price box in the indicator that follows the bid price on the chart stops moving up or down in value when the EA executes the first trade, maybe that's where thing go wrong?
double CloseAllTradesThisPair()
{
for (int i=OrdersTotal();i>=0;i--)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if (OrderSymbol()==Symbol())
{
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),10,Red);
}
}
}
extern bool bought = false;
extern bool sold = false;
double Lotsize = AccountBalance()/5000;
double Lots = NormalizeDouble(Lotsize,2);
void OnTick()
{
for(int i=0;i<OrdersTotal();i++)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
return(0);
}
double uparrow = iCustom(Symbol(),PERIOD_CURRENT,"fiji-trend-indicator",2,0);
double dnarrow = iCustom(Symbol(),PERIOD_CURRENT,"fiji-trend-indicator",3,0);
if(uparrow < 1000 && i==0)
{
double buyticket = OrderSend(Symbol(),OP_BUY,0.01,Ask,10,0,0,NULL,0,0,Green);
bought = true;
}
if(dnarrow < 1000 && i==0)
{
double sellticket = OrderSend(Symbol(),OP_SELL,0.01,Bid,10,0,0,NULL,0,0,Red);
sold = true;
}
if(bought != true && dnarrow < 1000 )
{
CloseAllTradesThisPair();
double sticket = OrderSend(Symbol(),OP_SELL,0.01,Bid,10,0,0,NULL,0,0,Red);
}
if(sold != true && uparrow < 1000)
{
CloseAllTradesThisPair();
double bticket = OrderSend(Symbol(),OP_BUY,0.01,Ask,10,0,0,NULL,0,0,Green);
}
}
Q : "when the EA executes the first trade, maybe that's where thing go wrong?"
Oh sure it is.
Given the code, the EA does exactly what it is instructed to in the void OnTick(){...}-code:
...
for ( int i = 0; i < OrdersTotal(); i++ )
{
OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
return( 0 ); // _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _THE_TERMINATOR_ >>> FINITO...
}
...
This fragment does nothing, until a 1st order was placed (as then the i stopped to meet the condition < OrdersTotal().
The rest is obvious: return( 0 ); ...besides a flaw to return a value from void... terminates under no exceptions any and all next code-passes through the OnTick()-code, so effectively avoiding any trading at all:

How do i calculate all the profit for a certain day?

double CheckProfitSofar()
{
datetime today = iTime(_Symbol,PERIOD_D1,0);
int dDay=TimeDay(today);
int dMonth = TimeMonth(today);
int dYear = TimeYear(today);
int todayYear, todayMonth, todayDay;
datetime opnOrdTime = 0;
double opnOrdProfit =0;
double addLoss = 0;
for(int s=0 ; s<OrdersHistoryTotal(); s++)
{
if ( OrderSelect( s, SELECT_BY_POS, MODE_HISTORY ) == true )
opnOrdTime = OrderCloseTime();
todayYear=TimeYear(opnOrdTime);
todayMonth =TimeMonth(opnOrdTime);
todayDay=TimeDay(opnOrdTime);
if ( dYear==todayYear && dMonth==todayMonth && dDay==todayDay )
totalLoss_Profit += (OrderProfit() + OrderSwap() + OrderCommission());
}
Comment(dYear," ",dMonth," ",dDay," ",todayYear," ",todayMonth," ",todayDay);
return totalLoss_Profit;
}
What i want to is that i want to calculate the profit (whether +ve or -ve) for a particular day. e.g today. i used the "datetime today" to get the opening time of the first candle of today, then follows. It is not returning the accurate value. Please help out. Thanks in advance.
You just need start of that particular day received by datetime timeStart = iTime(_Symbol,PERIOD_D1,i) and end of that day datetime timeEnd=timeStart+PeriodSeconds(PERIOD_D1);. Then loop over closed deals and filter them out if OrderClosePrice() is not in range.
double getClosedPnlOfDay(const int indexDay)
{
const datetime timeStart=iTime(_Symbol,PERIOD_D1,i),
timeEnd = timeStart+PeriodSeconds(PERIOD_D1);
double result=0.;
for(int i=OrdersHistoryTotal()-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))continue;
//filter by OrderSymbol() and OrderMagicNumber() here
if(OrderCloseTime()<timeStart || OrderCloseTime()>=timeEnd) continue;
result+=OrderProfit() + OrderCommission() + OrderSwap();
}
}

How to create a MQL4 function that returns the largest losing trade? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create an Expert Adviser (EA) in MQL4 language.
How to code a function that returns the largest losing trade, (and not the total losing trades)?
The following function will return the ticket of the largest loss trade.
With a default of loss = DBL_MAX, this can still return profitable trades with the lowest profit.With a loss = 0, it will only return a trade with the most negative profit or zero.
Will return a ticket of such trade and EMPTY, if no trades found.
int LargestLoss( int magic, double loss = DBL_MAX )
{
int ticket=EMPTY;
for(int i=0; i < Orderstotal(); i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderProfit()+OrderSwap()+OrderCommision()<loss)
{
loss=OrderProfit()+OrderSwap()+OrderCommision();
ticket=OrderTicket();
}
}
}
return ticket;
}
An actual Net Profit of any order has 3 components to add:
for a fair comparison, one ought add all [A] + [B] + [C] to compare one against the others:
double aNetLOSS = OrderProfit() // [A]
+ OrderCommission() // [B]
+ OrderSwap(); // [C]
A robust calling-interface ought provide
For a serious MQL4 automation, the returned value ought be always avoding any unwanted side-effects:
bool GetTheTicketWithLargestLOSS( int &aTicket2SEARCH,
double &aValueOfLOSS,
const string aSymbol2SEARCH, // <= _Symbol
const int aMagNUM = 0,
const int aSearchMODE = MODE_TRADES // | MODE_HISTORY
)
{
double aLocalMaxLOSS = 0.;
aTicket2SEARCH = EMPTY; // BLOCK ANY BLIND OrderSelent() USE
for ( int i = 0; i < OrdersTotal(); i++ )
{ // TRY:
if ( OrderSelect( i, SELECT_BY_POS, aSearchMODE ) )
{
if ( OrderSymbol() == aSymbol2SEARCH // MATCH?
&& OrderMagicNumber() == aMagNUM // MATCH?
)
{ double aNetLOSS = OrderProfit() // [A]
+ OrderCommission() // [B]
+ OrderSwap(); // [C]
if ( aNetLOSS < aLocalMaxLOSS )
{
aLocalMaxLOSS = aNetLOSS; // UPDATE
aLocalTkt2FIND = OrderTicket();
}
continue; // ----------------------------^ LOOP NEXT
}
continue; // ----------------------------------^ LOOP NEXT
}
else
{ // ON EXC:
// LOG:
// REPORT:
// HANDLE:
// RET/SIG:
return( False ); // SIG TERM EXIT
}
}
aTicket2SEARCH = aLocalTkt2FIND; // ON FAIR EXIT: FINAL ASSIGNMENTS
aValueOfLOSS = aLocalMaxLOSS;
return( True ); // SIG FAIR EXIT ( &DATA SET )
}

Why wont my MQL4 EA code change my open positions to breakeven?

Trying to add a StopLoss to my open market positions which also takes into account my brokers stoplevel. I have set this to add a breakeven stop loss when my trade gets to 100 points in profit.
This is the code - but its completely ignoring any order modification during my back testing.
OK this is now what I have so far, one for loop for the buy, one for the sell. I;ve also declared the "BuyMod" & "SellMod" to true as was suggested in pervious answers, as well as Normalzing prices in the OrderModify signature.
/*Breakeven Order Modification*/
bool BuyMod = true;
bool SellMod = true;
for(int b = OrdersTotal()-1;b>=0;b--)
{
if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
{
double aBidPrice = MarketInfo(Symbol(),MODE_BID);
double anOpenPrice = OrderOpenPrice();
double aNewTpPrice = OrderTakeProfit();
double aCurrentSL = OrderStopLoss();
double aNewSLPrice = anOpenPrice;
double pnlPoints = (aBidPrice - anOpenPrice)/_Point;
double stopPoints = (aBidPrice - aNewSLPrice)/_Point;
int stopLevel = int(MarketInfo(Symbol(),MODE_STOPLEVEL));
int aTicket = OrderTicket();
if(OrderType() == OP_BUY)
if(stopPoints >= stopLevel)
if(aTicket > 0)
if(pnlPoints >= breakeven)
if(aNewSLPrice != aCurrentSL)
{
BuyMod = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(aNewSLPrice,Digits),NormalizeDouble(aNewTpPrice,Digits),0,buycolor);
SendMail("Notification of Order Modification for Ticket#"+IntegerToString(OrderTicket(),10),"Good news! Order Ticket#"+IntegerToString(OrderTicket(),10)+"has been changed to breakeven");
}
}
}
for(int s = OrdersTotal()-1; s>=0; s--)
{
if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
{
double anAskPrice = MarketInfo(Symbol(),MODE_ASK);
double anOpenPrice = OrderOpenPrice();
double aNewTpPrice = OrderTakeProfit();
double aCurrentSL = OrderStopLoss();
double aNewSLPrice = anOpenPrice;
double pnlPoints = (anOpenPrice - anAskPrice)/_Point;
double stopPoints = (aNewSLPrice - anAskPrice)/_Point;
int stopLevel = int(MarketInfo(Symbol(),MODE_STOPLEVEL));
int aTicket = OrderTicket();
if(OrderType()== OP_SELL)
if(stopPoints >= stopLevel)
if(pnlPoints >= breakeven)
if(aNewSLPrice != aCurrentSL)
if(aTicket > 0)
{
SellMod = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(aNewSLPrice,Digits),NormalizeDouble(aNewTpPrice,Digits),0,sellcolor);
SendMail("Notification of Order Modification for Ticket#"+IntegerToString(OrderTicket(),10),"Good news! Order Ticket#"+IntegerToString(OrderTicket(),10)+"has been changed to breakeven");
}
}
}
This code will not work due to several reasons:
First:The function-call signature of OrderModify() is wrong.
You might want to know, that OrderModify() call-signature requires as per MQL4 documentation to include also an OrderExpiration value in the call, even though the Order is currently not a pending order any more.
Check the documentation and the IDE tooltip, which helps one remind the order of the function call parameters.
Second:The other, less-visible reasons could be reported by GetLastError() after the OrderModify() function call returns a False as an indication of failure.

Resources