Close order by sequence

MQL5 Göstergeler Uzmanlar

İş tamamlandı

Tamamlanma süresi: 3 gün
Müşteri tarafından geri bildirim
Super genius and super fast
Geliştirici tarafından geri bildirim
5 star client! Happy to have worked with Naresh.

Şartname

I need to modify my script to create a loop to check the buy and sell orders profit separately. close when 1st buy order and last buy order's average is profit. 

Currently, my code closes all the buy/sell order's  average is in profit. I would like to modify that for buy and sell orders. 

//+------------------------------------------------------------------+
//|                                               CloseOnAverage.mq4 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern int Choose_stragegy=1; // 1-hedging 2-trend
input int             InpMaxTrades = 10;         // Max number of trades
input double          InpTradeGap = 0.005;       // Distance between trades
//input ENUM_ORDER_TYPE InpType = ORDER_TYPE_BUY;  // Order type;//
input double          InpMinProfit = 1.00;       // Profit point
input int             InpMagicNumber = 1111;     // Magic number
input double          Multiplier = 2;       
input string          InpTradeComment = __FILE__; // Trade comment
input double          InpVolume = 0.01;          // Volume per order
double pips;

//double multi= (InpVolume*Multiplier);

struct STradeSum {
   int buycount;
   int sellcount;
   double buyprofit;
   double sellprofit;
   double buytrailPrice;
   double selltrailPrice;
};

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+

void OnTick() 
{
 
   STradeSum  sum;
   GetSum(sum);
    
   if (sum.buyprofit>InpMinProfit) 
   { // target reached
      CloseAll(ORDER_TYPE_BUY);
   } 
   if (OrdersTotal()>=3)
   {
      drawdownreduction();
   }
   
   else if (sum.sellprofit>InpMinProfit) 
   { // target reached
      CloseAll(ORDER_TYPE_SELL);
   }
   
   else if (sum.buycount==0) 
   {  // no buy trades
      OpenTrade(ORDER_TYPE_BUY);
   } 
   
   else if (sum.sellcount==0)
   {  // no sell trades
      OpenTrade(ORDER_TYPE_SELL);
   } 
   
   else if ((sum.buycount<InpMaxTrades))
   {
      
      if ( OrderType()==ORDER_TYPE_BUY && SymbolInfoDouble(Symbol(), SYMBOL_ASK)<=(sum.buytrailPrice-InpTradeGap)) 
      {   // Far enough below
         OpenmultiTrade(ORDER_TYPE_BUY);
      } 
      else if ((sum.sellcount<InpMaxTrades))
      {
         if ( OrderType() ==ORDER_TYPE_SELL && SymbolInfoDouble(Symbol(), SYMBOL_BID)>=(sum.selltrailPrice+InpTradeGap)) 
            {   // Far enough above
              OpenmultiTrade(ORDER_TYPE_SELL);
             }
      }
    }
    
   //else  if (sum.sellcount<InpMaxTrades)     
}

//+------------------------------------------------------------------+

void  OpenTrade(ENUM_ORDER_TYPE InpType) {
 
   double   price =  (InpType==ORDER_TYPE_BUY) ?
                        SymbolInfoDouble(Symbol(), SYMBOL_ASK) :
                        SymbolInfoDouble(Symbol(), SYMBOL_BID);
   OrderSend(Symbol(), InpType, InpVolume, price, 0, 0, 0, InpTradeComment, InpMagicNumber);
    
}

//+------------------------------------------------------------------+

void  OpenmultiTrade(ENUM_ORDER_TYPE InppType) {
 
   double   price =  (InppType==ORDER_TYPE_BUY) ?
                        SymbolInfoDouble(Symbol(), SYMBOL_ASK) :
                        SymbolInfoDouble(Symbol(), SYMBOL_BID);
   double multi = (InpVolume*Multiplier);
   OrderSend(Symbol(), InppType, multi, price, 0, 0, 0, InpTradeComment, InpMagicNumber);
}

//+------------------------------------------------------------------+

void  CloseAll(ENUM_ORDER_TYPE orderType) {
 
   int   count    =  OrdersTotal();
 
   for (int i = count-1; i>=0; i--) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
         if (  OrderSymbol()==Symbol()
               && OrderMagicNumber()==InpMagicNumber
               && OrderType()==orderType
               ) {
            OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0);
         }
      }
   }
 
}
//+------------------------------------------------------------------+

void  GetSum(STradeSum &sum) {
 
   sum.buycount      =  0;
   sum.buyprofit     =  0.0;
   sum.buytrailPrice =  0.0;
   sum.sellcount      =  0;
   sum.sellprofit     =  0.0;
   sum.selltrailPrice =  0.0;
    
   int   count    =  OrdersTotal();
 
   for (int i = count-1; i>=0; i--) 
   {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) 
      {
      //Buy orders
         if (OrderSymbol()==Symbol() && OrderMagicNumber()==InpMagicNumber && OrderType()== ORDER_TYPE_BUY)
                {
                  sum.buycount++;
                  sum.buyprofit  += OrderProfit()+OrderSwap()+OrderCommission();
                  if (sum.buytrailPrice==0 || OrderOpenPrice()<sum.buytrailPrice)
                     {
                        sum.buytrailPrice =  OrderOpenPrice();
                     }
                 }
          //sellorders
          if (OrderSymbol()==Symbol()&& OrderMagicNumber()==InpMagicNumber && OrderType()==ORDER_TYPE_SELL)
                { 
                  sum.sellcount++;
                  sum.sellprofit  += OrderProfit()+OrderSwap()+OrderCommission();
                  if (sum.selltrailPrice==0 || OrderOpenPrice()>sum.selltrailPrice)
                     {
                        sum.selltrailPrice =  OrderOpenPrice();
                     }
                }
            
        } 
     }
          
   return;
    
}

//+------------------------------------------------------------------+
//found this code online. The below code compares and closes the last two orders
void drawdownreduction()
{
  int slippage=10;
  double minimum_profit=InpMinProfit;
  int x;
  double trades[][4];
  int total=OrdersTotal();
  if(total>1)
  {
  ArrayResize(trades,total);
  for(x=total-1;x>=0;x--)
     {
     if(OrderSelect(x,SELECT_BY_POS,MODE_TRADES))
        {
        trades[x][0]=OrderTicket();
        trades[x][1]=OrderProfit()+OrderCommission()+OrderSwap();
        trades[x][2]=OrderLots();
        trades[x][3]=OrderType();
        }
     }
  
  ArraySort(trades,WHOLE_ARRAY,0,MODE_ASCEND);
  x=0;
  
  while(x<total-1)
     {
     double profit=trades[x][1]+trades[total-1][1];
     if(profit>=minimum_profit)
        {
        RefreshRates();
        double close_price=Ask;
        if(trades[x][3]==OP_BUY)
           close_price=Bid;
        if(!OrderClose((int)trades[x][0],trades[x][2],close_price,slippage,clrNONE))
           Print("Error closing #",DoubleToStr(trades[x][0],0)," Error code ",GetLastError());
        RefreshRates();
        close_price=Ask;
        if(trades[x+1][3]==OP_BUY)
           close_price=Bid;
        if(!OrderClose((int)trades[x+1][0],trades[x+1][2],close_price,slippage,clrNONE))
           Print("Error closing #",DoubleToStr(trades[x][0],0)," Error code ",GetLastError());
        }
        x+=2;
     }
     }
 }   
  


Yanıtlandı

1
Geliştirici 1
Derecelendirme
(21)
Projeler
23
0%
Arabuluculuk
6
17% / 83%
Süresi dolmuş
2
9%
Serbest
2
Geliştirici 2
Derecelendirme
(52)
Projeler
66
41%
Arabuluculuk
1
0% / 100%
Süresi dolmuş
7
11%
Serbest
3
Geliştirici 3
Derecelendirme
(213)
Projeler
286
47%
Arabuluculuk
27
59% / 37%
Süresi dolmuş
36
13%
Serbest
4
Geliştirici 4
Derecelendirme
(139)
Projeler
181
24%
Arabuluculuk
23
22% / 39%
Süresi dolmuş
13
7%
Serbest
5
Geliştirici 5
Derecelendirme
(93)
Projeler
133
35%
Arabuluculuk
13
38% / 31%
Süresi dolmuş
32
24%
Serbest
6
Geliştirici 6
Derecelendirme
(1)
Projeler
1
0%
Arabuluculuk
2
0% / 100%
Süresi dolmuş
0
Serbest
Yayınlandı: 7 kod
7
Geliştirici 7
Derecelendirme
(645)
Projeler
873
48%
Arabuluculuk
29
38% / 17%
Süresi dolmuş
63
7%
Serbest
8
Geliştirici 8
Derecelendirme
(24)
Projeler
28
32%
Arabuluculuk
1
0% / 0%
Süresi dolmuş
0
Serbest
Yayınlandı: 1 kod
9
Geliştirici 9
Derecelendirme
(155)
Projeler
239
70%
Arabuluculuk
3
67% / 33%
Süresi dolmuş
20
8%
Serbest
Benzer siparişler
Create a bot that can trade and read indicators easy to read for first time users. Bot that can be used on a phone and connect to MT5. It should be easy to install or use on any device especially phone and laptop, preferably the bot that can run over night and controllable when needed
These are orderflow footprint indicator I would like to know if you can algorithmisie and build a stacked imbalance bot from them .. Kindlt let me know if you can do it and check the file before replying me
I have 2 trading view indicators by GainzAlgo that I want code to mt5 , could u advise? I need you to give me response if you can convert This
I DO NOT need any programming or strategy development. I already have a working NinjaTrader 8 automated strategy based on a 3/5 EMA crossover. I need you to run my existing strategy through NinjaTrader Strategy Analyzer/Optimizer, test the existing adjustable parameters, and find robust settings with the best profit factor and lowest reasonable drawdown. I will provide the existing NinjaScript ZIP. I do not want the
Platform: TradingView Programming Language: Pine Script v6 Type: Custom Indicator Project Name: Scalping Reaction Zones + Valid Order Blocks MAIN GOAL I need a custom TradingView indicator for scalping. The indicator must detect: 1. Reaction / Explosion Zones 2. Valid Order Blocks 3. Combined Reaction Zone + Order Block zones The indicator should NOT generate: Buy signals Sell signals TP SL Entry signals Trading
Project Description I am looking for an experienced MQL5/MT5 Expert Advisor developer to develop an automated trading EA for XAUUSD on the M3 timeframe , running on an Exness account . The EA will automate a manual strategy based on SNR/GAP zones , using two setup types: Price Rejection Price Correction The EA should identify valid BUY/SELL setups around predefined SNR/GAP areas, apply configurable RSI, SMA, EMA and
Indicador Maximas e Minimas + Super Trend O Indicador MAX/MIN é um indicador de análise técnica para o MetaTrader 5 , desenvolvido para ajudar você a identificar regiões importantes de preço e possíveis oportunidades de compra e venda. O que ele faz MAX/MIN: identifica máximas e mínimas relevantes do mercado e mostra os preços no gráfico. HH / HL / LH / LL: ajuda a visualizar a estrutura do mercado, mostrando quando
Hello Traders, Have a trading strategy or idea you want to automate? I specialize exclusively in MQL5 development, helping traders turn their concepts into professional trading solutions. Custom Expert Advisors — automate your strategy and reduce manual execution Custom Indicators — transform your market ideas into powerful trading tools Fix & Debug — identify errors and get your existing code working properly
I DO NOT need any programming or strategy development. I already have a working NinjaTrader 8 automated strategy based on a 3/5 EMA crossover. I need you to run my existing strategy through NinjaTrader Strategy Analyzer/Optimizer, test the existing adjustable parameters, and find robust settings with the best profit factor and lowest reasonable drawdown. I will provide the existing NinjaScript ZIP. I do not want the
I'm looking for an experienced developer to create an automated gold trading bot. The bot should be compatible with MetaTrader 4/5 and TradingView. Key Requirements: - Automated trading bot - Compatible with MetaTrader 4/5 and TradingView - Implement scalping and swing trading strategies Ideal Skills and Experience: - Proficiency in trading algorithms - Experience with gold trading - Familiarity with MetaTrader and

Proje bilgisi

Bütçe
30+ USD
Son teslim tarihi
to 2 gün