达到利润后关闭所有订单的代码

时间:2019-09-07 15:12:40

标签: mql4

我是MQL4 EA编程的新手。我正在尝试对达到一定利润水平的自动关闭所有订单进行编码。

假设我设置了USD_Profit = 1 $

EA将在卖出和买入中开仓。我想在ORDERPROFIT + ORDERCOMMISSION + ORDERSWAP> 1 $

时将其全部关闭

我正在尝试上面的代码,但是并没有按照我的意愿完成交易

input double USD_Profit=1;
double Profit_By_USD(int type=-1) 
{
double pts;
for(int i=0;i<OrdersTotal();i++)
{

 bool s=OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
string sy=OrderSymbol();
int    mn=OrderMagicNumber(),
     ot=OrderType();
double pt=OrderProfit(),
     sw=OrderSwap(),
     cm=OrderCommission();  
if(sy==Symbol()&&mn==MagicNo)
{
if(ot==type||type==-1)
{
 pts+=pt+sw+cm;
 }
 }
 }  
 return(pts);
 }



 double Money()

 {

 double sum_profits = 0;

  int i, iOrders = OrdersTotal() - 1;        //
  for(i = iOrders; i >= 0; i--)
{

if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)

{    

  if( Symbol() == OrderSymbol())  sum_profits += 
OrderProfit()+OrderSwap()+OrderCommission();

}

} 

return( sum_profits );

} 



 if(USD_Profit!=0&&Money()>=USD_Profit){CloseOrdersClaudio();} 

 void CloseOrdersClaudio(){

 //Update the exchange rates before closing the orders
 RefreshRates();
  //Log in the terminal the total of orders, current and past
  Print(OrdersTotal());

  //Start a loop to scan all the orders
  //The loop starts from the last otherwise it would miss orders
  for(int i=(OrdersTotal()-1);i>=0;i--){

  //If the order cannot be selected throw and log an error
  if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false){
     Print("ERROR - Unable to select the order - ",GetLastError());
     break;
  } 

  //Create the required variables
  //Result variable, to check if the operation is successful or not
  bool res=false;

  //Allowed Slippage, which is the difference between current price and close price
  int Slippage=0;

  //Bid and Ask Price for the Instrument of the order
  double BidPrice=MarketInfo(OrderSymbol(),MODE_BID);
  double AskPrice=MarketInfo(OrderSymbol(),MODE_ASK);

  //Closing the order using the correct price depending on the type of order
  if(OrderType()==OP_BUY){
     res=OrderClose(OrderTicket(),OrderLots(),BidPrice,Slippage);
  }
  if(OrderType()==OP_SELL){
     res=OrderClose(OrderTicket(),OrderLots(),AskPrice,Slippage);
  }

  //If there was an error log it
  if(res==false) Print("ERROR - Unable to close the order - ",OrderTicket()," - ",GetLastError());
 }
  }

0 个答案:

没有答案