Modify and existing EA and to create a addwinner function that increase the position size when position is positive.

MQL4 지표 전문가

작업 종료됨

실행 시간 3 일
고객의 피드백
Simply one of the best programmers that I encountered so far here. He managed to debug my existing EA and added some new features in it.
피고용인의 피드백
Best job. Happy working with him.

명시

I only accept only programmer whose rating is good and also did more than 50 jobs.

I need the source code and also the programmer should allow me to test the code for 2 more days and to make reasonable adjustment if there is any problem with the code.

I need someone to make modification to an existing MQL4 EA

Attached is the EA, this EA is solely use on Dow Jones Industrial Average, NASDAQ and SPX.

//+------------------------------------------------------------------+
//|                                               Moving Average.mq4 |
//|                                                          Zhiming |
//|                         https://www.offshorecapitalsolutions.com |
//+------------------------------------------------------------------+
#property copyright "Zhiming"
#property link      "https://www.offshorecapitalsolutions.com"

//--- Trade Setup Module Inputs

extern string           Note0="Period for Moving Average";
extern int FastMA=5;
extern int FastMaShift=0;
extern ENUM_MA_METHOD      FastMaMethod=0;
extern ENUM_APPLIED_PRICE  FastMaAppliedTo=0;
extern int SlowMA=21;
extern int SlowMaShift=0;
extern ENUM_MA_METHOD      SlowMaMethod=0;
extern ENUM_APPLIED_PRICE  SlowMaAppliedTo=0;

extern string           Note1="ATR period for risk management";
extern int              ATRPeriod=20;
extern int              Number_Of_ATR=4;

//---Risk Reward Stop
extern string           Note2="Percentage at Risk and the Reward Ratio";
extern double           RiskPercent=2;
extern double           Reward_ratio=4;

//--- This part has to go with the Breakeven Module
extern string           Note3="If UseMoveToBreakeven=true, this will activate the Breakeven Stop";
extern bool             UseMoveToBreakeven=TRUE;
extern int              ATRToBreakeven=1;
extern double           ATRToLockIn=0.5;

//--- Trailing Stop Module
extern string           Note4="Trailing stop, UseTrailingStop = true will activate trailing stop";
extern bool             UseTrailingStop=TRUE;
extern double           KTATR=2;


//---Day and Date Filter
extern string           Note5="Day and Date Filter";
extern bool             Sunday = true;
extern bool             Monday = true;
extern bool             Tuesday = true;
extern bool             Wednesday = true;
extern bool             Thursday = true;
extern bool             Friday = true;
extern bool             NFP_Friday = true;
extern bool             NFP_ThursdayBefore = true;
extern bool             ChristmasHolidays = true;
extern double           XMAS_DayBeginBreak = 15;
extern bool             NewYearsHolidays = true;
extern double           NewYears_DayEndBreak = 3;

//---Time Filter Module
extern string           Note6="Time Filter";
extern bool             UseTimeFilter=false;
extern int              start_time_hour=22;
extern int              start_time_minute=0;
extern int              end_time_hour=18;
extern int              end_time_minute=0;
extern int              gmt=0;

//--- Syncronize the Tick Size and Lot Size Inputs
extern string           Note7="Magic Number";
extern int              MagicNumber=21013;

double pips;
bool  OrderModifyResult=false;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//---
   double ticksize = MarketInfo(Symbol(),MODE_TICKSIZE); //For FX
   if(ticksize == 0.00001 || Point==0.001)
   pips = ticksize*10;
   else pips = ticksize;
//---
   }
   
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//---Delete all objects on chart------------------------------------------------------------------------------  

//------------------------------------------------------------------------------------------------------------
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
int start()
  {
//---
if(OpenOrdersThisPair(Symbol())>=1) //Start scanning opportunity to move up breakeven and trailing stop
      {
         if(UseMoveToBreakeven)MoveToBreakeven(); 
         if(UseTrailingStop)AdjustTrail();
      }
   if(UseTimeFilter==1)
      {
         bool time_in_range=is_time_in_range(TimeCurrent(),start_time_hour,start_time_minute,end_time_hour,end_time_minute,gmt);
         if(time_in_range==1)
            {
               if(IsNewCandle())CheckForKTSRTrade();
               return(0);
            }
      } 
else
   
   if(UseTimeFilter==0)
      {
         if(IsNewCandle())CheckForKTSRTrade();
         return(0);
      }        
  } 
  
//+------------------------------------------------------------------+

int OpenOrdersThisPair(string pair) // This has to be include in part of the Order Entry and Modification Modules.
{
   int total=0;
      for(int i=OrdersTotal()-1;i>=0;i--)
      {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()==pair) total++;
      }
      return(total);
}   

bool IsNewCandle() //This is to reduce the computer burden
{
   static int BarsOnChart=0;
   if(BarsOnChart == Bars)
   return(false);
   BarsOnChart = Bars;
   return(true);
}

void CheckForKTSRTrade() //Trade Setup Mudule
{
   double PreviousFast = iMA(NULL,0,FastMA,FastMaShift,FastMaMethod,FastMaAppliedTo,2);
   double CurrentFast = iMA(NULL,0,FastMA,FastMaShift,FastMaMethod,FastMaAppliedTo,1);
   double PreviousSlow = iMA(NULL,0,SlowMA,SlowMaShift,SlowMaMethod,SlowMaAppliedTo,2);
   double CurrentSlow = iMA(NULL,0,SlowMA,SlowMaShift,SlowMaMethod,SlowMaAppliedTo,1);   
   if(PreviousFast < PreviousSlow && CurrentFast > CurrentSlow)OrderEntry(0);
   if(PreviousFast > PreviousSlow && CurrentFast < CurrentSlow)OrderEntry(1);
}


void OrderEntry(int direction) // Order Entry and Modification Modules.
{
   double tickvalue=MarketInfo(Symbol(),MODE_TICKVALUE);
   double LotSize=0;
   double Equity=AccountEquity();
   double RiskAmount=(Equity*RiskPercent*0.01)/tickvalue;
   double ATR_Risk=iATR(Symbol(),0,ATRPeriod,1);
   double ATR_Risk_Range=ATR_Risk*Number_Of_ATR;
   double buy_stop_price=Ask-ATR_Risk_Range;
   double pips_to_bsl=Ask-buy_stop_price;
   double buy_takeprofit_price=Ask+pips_to_bsl * Reward_ratio;
   double sell_stop_price=Bid+ATR_Risk_Range;
   double pips_to_ssl=sell_stop_price-Bid;
   double sell_takeprofit_price=Bid-pips_to_ssl* Reward_ratio;
   
if(direction==0)
   {
      double bsl=buy_stop_price;
      double btp=buy_takeprofit_price;
      LotSize = (RiskAmount/ (pips_to_bsl/pips) ) ;
      if(OpenOrdersThisPair(Symbol())==0)int buyticket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,3,bsl,btp,NULL,MagicNumber,0,Green);
         if(buyticket>0)OrderModifyResult=OrderModify(buyticket,OrderOpenPrice(),bsl,btp,0,Green);
   }      
         
if(direction==1)
   {  
      double ssl=sell_stop_price;
      double stp=sell_takeprofit_price;
      LotSize = (RiskAmount/ (pips_to_ssl/pips) ) ; 
      if(OpenOrdersThisPair(Symbol())==0)int sellticket=OrderSend(Symbol(),OP_SELL,LotSize,Bid,3,ssl,stp,NULL,MagicNumber,0,Red);       
         if(sellticket>0)OrderModifyResult=OrderModify(sellticket,OrderOpenPrice(),ssl,stp,0,Red);
   }
}

//--- Trailing Stop Module Function
void AdjustTrail()
{
   int bar=0, i=0;
   double KTBTrailingStop=0.0, KTSTrailingStop=0.0;
   bool ans=false;

//buy order section
   for(int b=OrdersTotal()-1;b>=0;b--)
      {
      if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==MagicNumber)
            if(OrderSymbol()==Symbol())
               if(OrderType()==OP_BUY)
                  {
                                        bar=iBarShift(Symbol(),0,OrderOpenTime());
                     KTBTrailingStop=iHigh(Symbol(),0, iHighest(Symbol(),0,MODE_HIGH,bar+1,0)) - KTATR * iATR(Symbol(),0,ATRPeriod,iHighest(Symbol(),0,MODE_HIGH,bar,1));
                        if(Bid - KTBTrailingStop > OrderStopLoss())
                        {
                           i=0;ans=false;
                           while(!ans&&i<3)
                           { 
                            if(i>0)Sleep(1000);
                            ans=OrderModify(OrderTicket(),OrderOpenPrice(),KTBTrailingStop,OrderTakeProfit(),0,clrOrange);
                            i++;
                           }//while(!ans&&i<3)
                        }
                   }
                }
  
//sell order section
   for(int s=OrdersTotal()-1;s>=0;s--)
      {
      if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==MagicNumber)
            if(OrderSymbol()==Symbol())
               if(OrderType()==OP_SELL)
                                        {
                                        bar=iBarShift(Symbol(),0,OrderOpenTime());
                              KTSTrailingStop=iLow(Symbol(),0, iLowest(Symbol(),0,MODE_LOW,bar+1,0) ) + KTATR * iATR(Symbol(),0,ATRPeriod,iLowest(Symbol(),0,MODE_LOW,bar,1));
                              if(OrderStopLoss()> KTSTrailingStop - Ask)
                              {
                                 i=0;ans=false;
                                 while(!ans&&i<3)
                                 { 
                                  if(i>0)Sleep(1000);
                                  ans=OrderModify(OrderTicket(),OrderOpenPrice(),KTSTrailingStop,OrderTakeProfit(),0,clrOrange);
                                  i++;
                                 }
                              }
 
                                        }               
       }                 
}

void MoveToBreakeven() //Breakeven Stop Module
{
   double BEATR=iATR(NULL,0,ATRPeriod,1)*ATRToBreakeven;
   double LockInATR=iATR(NULL,0,ATRPeriod,1) * ATRToLockIn;
   for(int b=OrdersTotal()-1; b >= 0; b--)
      {
      if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==MagicNumber) //If this is not true, it will not move down further
            if(OrderSymbol()==Symbol())   
               if(OrderType()==OP_BUY)
                  if(Bid-OrderOpenPrice()>BEATR) //This need to add the pips definition from ini init
                     if(OrderOpenPrice()>OrderStopLoss())
                        OrderModifyResult=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(LockInATR),OrderTakeProfit(),0,Lime);                  
      }
   for(int s=OrdersTotal()-1; s >= 0; s--)
      {
      if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==MagicNumber) //If this is not true, it will not move down further
            if(OrderSymbol()==Symbol())   
               if(OrderType()==OP_SELL)
                  if(OrderOpenPrice()-Ask>BEATR) //This need to add the pips definition from ini init
                     if(OrderOpenPrice()<OrderStopLoss())
                        OrderModifyResult=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-(LockInATR),OrderTakeProfit(),0,Lime);                  
      }  
}

//Day and Date Filter-----------------------------------------------------------------------------------------
bool DaytoTrade(){
bool daytotrade = false;

if(DayOfWeek() == 0 && Sunday) daytotrade = true;
if(DayOfWeek() == 1 && Monday) daytotrade = true;
if(DayOfWeek() == 2 && Tuesday) daytotrade = true;
if(DayOfWeek() == 3 && Wednesday) daytotrade = true;
if(DayOfWeek() == 4 && Thursday) daytotrade = true;
if(DayOfWeek() == 5 && Friday) daytotrade = true;
if(DayOfWeek() == 5 && Day() < 8 && !NFP_Friday ) daytotrade = false;
if(DayOfWeek() == 4 && Day() < 8 && !NFP_ThursdayBefore ) daytotrade = false;
if(Month() == 12 && Day() > XMAS_DayBeginBreak && !ChristmasHolidays ) daytotrade = false;
if(Month() == 1 && Day() < NewYears_DayEndBreak && !NewYearsHolidays ) daytotrade = false;

return(daytotrade);}

//------------------------------------------------------------------------------------------------------------

//Time Filter-------------------------------------------------------------------------------------------------
bool is_time_in_range(datetime time,int start_hour,int start_min,int end_hour,int end_min,int gmt_offset=0)
  {
   if(gmt_offset!=0)
     {
      start_hour+=gmt_offset;
      end_hour+=gmt_offset;
     }
   if(start_hour>23) start_hour=(start_hour-23)-1;
   else if(start_hour<0) start_hour=23+start_hour+1;
   if(end_hour>23) end_hour=(end_hour-23)-1;
   else if(end_hour<0) end_hour=23+end_hour+1;
   int hour=TimeHour(time);
   int minute=TimeMinute(time);
   int t = (hour*3600)+(minute*60);
   int s = (start_hour*3600)+(start_min*60);
   int e = (end_hour*3600)+(end_min*60);
   if(s==e)
      return true;
   else if(s<e)
     {
      if(t>=s && t<e)
         return true;
     }
   else if(s>e)
     {
      if(t>=s || t<e)
         return true;
     }
   return false;
  }
  
//------------------------------------------------------------------------------------------------------------

In this EA, the trailing stop is suppose to:

For buy trade, it will look at the highest high bar after the buy trade is initiated. Based on the high of the highest bar and minus off ATR(s) of the previous bar and come out with KTBTrailingStop. If the existing stoploss and the order entry price is below the KTBTrailingStop, then modify the existing stop to KTBTrailingStop. If the KTBTrailingStop is below the order entry price and the existing stop loss price, do not make any changes.

For sell trade, it will look at the lowest low bar after the sell trade is initiated. Based on the low of the lowest bar and plus ATR(s) of the previous bar and come out with KTSTrailingStop. If the existing stoploss and the order entry price is above the KTSTrailingStop, then modify the existing stop to KTSTrailingStop. If the KTSTrailingStop is above the order entry price and the existing stop loss price, do not make any changes.

For the trailing stop, I noticed the existing code did not trigger after the conditions are met. Please see if there are any changes need to be made.

The existing breakeven stop works perfectly but I am not sure if the int start() is correctly written. What I want is:

1.      if the UseMoveToBreakeven=FALSE and the UseTrailingStop=TRUE, the EA should be able to use TrailingStop only and should not be using the BreakevenStop.

2.      if the UseMoveToBreakeven=FALSE and the UseTrailingStop=FALSE, the EA should not be able to use TrailingStop and should not be using the BreakevenStop.

3.      if the UseMoveToBreakeven=TRUE and the UseTrailingStop=FALSE, the EA should not be able to use TrailingStop only and should be using the BreakevenStop.

4.      if the UseMoveToBreakeven=TRUE and the UseTrailingStop=TRUE, the EA should be able to use TrailingStop and the BreakevenStop.

So upon initiate a position, if the price moves to its favour and trigger the breakeven loss function, the stoploss will move toward the level determined by the breakeven function.

If the price did not move in favour and did not trigger the breakeven loss function, the stop loss should stay at the risk level.

After the price triggered the breakeven function, it will depend on the trailing stop function without changing the price target.

For the OrderSend part, I need the EA to do resend the order if there is any error. The resend of order should look something like:

for(int i=OrderTotal()-1; i >=0;i--)
{       
        if(OrderSelect(i,SELECT_BY_POS, MODE_TRADES))
        {
                if(OrderType()==OP-BUY && OrderMagicNumber()==Magic Number)
                {
                        while(true)
                        {
                                bool result = OrderClose(OrderTicket(),OrderLots(),Bid, 3, Red);
                                if(result!= true)
                                {
                                        int err = GetLastError(); Print("LastError = ",err);
                                }
                                else err = 0;
                                switch(err)
                                {
                                        case 135://ERR_PRICE_CHANGED
                                        case 136://ERR_OFF_QUOTES
                                        case 137://ERR_BROKER_BUSY
                                        case 138://ERR_REQUOTE
                                        case 146:sleep(1000);RefreshRates();i++;break;//ERR_TRADE_CONTEXT_BUSY
                                }
                        }
                }
        }
}

Also need to create a function for the EA to add on more position when the existing position is making profit.  This add more winning position function should only be activated when the price moves in favour of the position by 3 ATRs and when a new high is formed after a long position is initiated or a new low is formed after a short position is initiated.

There should be an input to key in the factor (1-10) and for the ATR that moves in the favour of the position as well.  

Since this function is similar with the trailing stop function, it should come in before the trailing stop function. It should add on more position before the EA moves higher for the long trailing stop and before the EA moves lower for the short tailing stop.

The input should have a bool UseAddWinner=TRUE to activate this function and the function should start with AddWinner() just like the way I do it for AdjustTrail()

The example is below.

Long Position

Current long Position 5 contract and average cost is 24,600

Highest high after initiate long position 24,900

Offer price now is 24,871 and the bid price is 24,870.9

Stop loss price is 24,720

Factor = 3

Average price after buy more contract = ((Stop Loss Price – Average Price) * (1/Factor)) + Average Price

((24,720 - 24,600) * (1/3)) + 24,600 = 24,640

Calculation to buy number of contract = Current Long Position / ((Offer Price - Average price after buy more contract) / (Average price after buy more contract - Current Average Price))

5 / ((24,871 - 24,640) / (24,640 - 24,600))

= 0.866

Round down to the nearest 2 decimal place = 0.86

 

Short Position

Current short Position 3.5 contract and average cost is 24,700

Lowest low after initiate long position 24200

Offer price now is 24,351 and the bid price is 24,350.9

Stop loss price is 24,500

Factor = 3

Average price after short more contract = ((Stop Loss Price – Current Average Price) * (1/Factor)) + Current Average Price

((24,500 - 24,700) * (1/3)) + 24,700 = 24,633.33

Calculation to short number of contract = Current Short Position / ((Bid Price - Average price after short more contract)/(Average price after short more contract – Current Average Price))

3.5 / ((24,350.9 - 24,633.33) / (24,633.33 - 24,700))

= 0.826

Round down to the nearest 2 decimal place = 0.82









응답함

1
개발자 1
등급
(277)
프로젝트
334
55%
중재
14
36% / 29%
기한 초과
1
0%
무료
비슷한 주문
My expert already has the rest of the required features implemented . Bring in your support and resistance expert to save time . My expert already has money management , session filter etc . Trailing is threshold based . Please send a picture as well to show your expert on a live chart . Most specific is the 5m tf , to 1m execution
Ai bot 100 - 300 USD
I’m looking for one person who is both a Forex trader and a programmer . I don’t want a coder who only writes code without understanding the market, and I don’t want a trader who can’t program. I want someone who actively trades and understands market behavior, liquidity, volatility, and risk management. Most importantly, the bot must be built using real artificial intelligence that learns and adapts , not just
Platform: - MetaTrader 4 (MT4) Type: - Expert Advisor (EA) Strategy rules: - Buy when fast EMA crosses above slow EMA - Sell when fast EMA crosses below slow EMA - EMA periods must be input parameters Trade settings: - Lot size: fixed (input parameter) - Stop Loss: fixed pips (input parameter) - Take Profit: fixed pips (input parameter) - One trade at a time only Risk & filters: - No trading during high spread -
can anyone help me with building a complete automated pine code strategy and indicator that work for both FXs & CFDs and have a high winning rate proved through back testing. I have a very complex current code that developed mostly using AI but lots of gaps are there although it translate exactly what I have in my mind. So, you are free to decide whether wo build a complete new code or fix my current working code ( i
Hello, I’m looking for an experienced MT4 (MQL4) developer to convert the Lucky Reversal indicator from indicatorspot.com into a fully functional Expert Advisor (EA). Project Scope Code an MT4 EA that replicates the exact logic and signals of the Lucky Reversal indicator Trades should open and close automatically based on the indicator’s rules Must match indicator behavior 1:1 (no approximations) EA Requirements MT4
This is a request for a formal price quote only. No work should begin until the quote is accepted. I am requesting a quantitative audit of an existing trading strategy. Scope (strict): 10-year historical backtest Full performance metrics (expectancy, win rate, profit factor, max drawdown, trade distribution) Identification of logical flaws, bias, and overfitting Rule-based corrections only if justified by data
I am looking for a senior MQL5 developer to build a custom MT5 Expert Advisor using a dual-engine grid structure (BUY + SELL operating independently). The EA will be used in a real operating business with live clients, so the implementation must be clean, deterministic and reliable. I already have a complete specification describing all the required logic (entry rules, grid logic, basket TP, break-even behavior
I would like to request the development of an Expert Advisor (EA) for MetaTrader 5 with the following specifications: 1. Instruments: NASDAQ (US100) Dow Jones (US30) DAX (DE40) 2. Opening Range Selection: The EA should allow me to manually select a specific time range on the chart. Example: US100 opening range from 14:30 UTC to 14:45 UTC (15-minute opening range for the US market). The EA should automatically
Hello, I have the code for an indicator file that works with binary options. I want to make a simple modification to it that won't take much effort for professionals. In short, the modification I want is that if the strategy's conditions are met, a buy or sell signal should appear at 17:55. The strategy works exclusively on the 5-minute timeframe, and I want to delay the signal by 7 minutes so that it appears and
描述(项目概述): 我需要为 MetaTrader 5 平台开发一个功能完整的智能交易系统( 专家顾问 ),用于交易 XAUUSD (伦敦金)。该 艺电 的核心是基于一份详细的技术规格书,实现一个多指标共振、多层条件过滤的短线反转策略。 1. 核心策略逻辑简述: 交易品种与周期:主交易周期为 M30 ,需在代码内部动态读取 H4 周期进行趋势过滤,并监控 M5 周期以执行复杂的出场逻辑。 入场机制:采用 “ 价格触发 -> 成交量确认 -> 多指标渐进式达标 ” 的严格流程。入场信号需在特定时间窗口内,同时满足布林带突破及 5 个动量指标( CCI、RSI、MFI, 威廉指标, 随机指标)的超买 / 超卖条件,并受 H4 级别趋势过滤器约束。 出场机制:采用三层递进逻辑,包括动态保本移动、 M5 周期指标集体反转信号以及基于 K 线形态的趋势反转终极止损。

프로젝트 정보

예산
30+ USD