我如何编写mql5代码来平仓利润等于0并产生任何损失?

问题描述 投票:0回答:1

有人可以建议我编写当利润等于0时平仓的代码吗?我自己写的,但是没有成功。我想编写不会产生任何损失的代码,它的工作原理如下: 我想在某种条件下建仓,如果我的平仓条件被调用或者我的仓位利润为 0,则将其平仓,因为我不想产生任何损失,我不允许我的仓位遭受损失,并在仓位为 0 时迅速平仓.

我尝试了这个,但它只是不断产生损失。

#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));
         }
      }
   }
}
algorithmic-trading mql4 metatrader4 mql5 metatrader5
1个回答
0
投票

您的代码在盈利时平仓 <=0 .. so there will always be losses (spread, commission). Where is your takeprofit for an open position?

trade.Buy(0.01,_Symbol, 0, 0, ask + 20 * _Point)

并改变

for(int i = 0; i < PositionsTotal(); i--)

关于这个

for(int i = 0; i < PositionsTotal(); i++)
© www.soinside.com 2019 - 2024. All rights reserved.