Can anyone advice me on writing code that when the profit is equal to 0 close the position? I wrote it by myself but it didn't work. I want to write code that generates no losses and it is how it works: i want to enter a position in a condition and close it if my close condition is called or my positions profits are 0 because i want to generate no loss at all i don't allow my positions getting loss and rapidly close them when they are 0.
i try this but it just generates continuously generates loss.
#include <Trade\Trade.mqh>
CTrade trade;
void OnTick()
{
// Check if there is an open buy position
bool hasOpenBuyPosition = CheckOpenBuyPosition();
double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits);
// Get the current symbol price
double currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
// Get the open price of the buy position
MqlRates PriceInformation[];
ArraySetAsSeries(PriceInformation, true);
double Data=CopyRates(Symbol(), Period(), 0, Bars(Symbol(), Period()), PriceInformation);
if (PriceInformation[1].close < Ask) {
trade.Buy(0.1);
}
CloseZeroProfit();
}
void CloseZeroProfit()
{
// Iterate through all open positions
for (int i = 0; i < PositionsTotal(); i--)
{
// Select the position by its index
if (PositionSelectByTicket(PositionGetTicket(i)))
{
// Check the position's profitability
double profit = PositionGetDouble(POSITION_PROFIT);
if (profit <= 0 || profit == 0)
{
// Close the position
trade.PositionClose(PositionGetTicket(i));
}
}
}
}
Your code closes positions when profit <=0 .. so there will always be losses (spread, commission). Where is your takeprofit for an open position?
and change
on this