Code for trailing stop

 

I am using following code to set buy/sell order and than set trailing stop/loss order.

It uses SMA for setting order and than set trailing stop loss on stock


The issue I am seeing is the last order is not setting stop loss porperly.

I have just started on MT4. It took me 2 weeks to understand pick the code


Can someone please help me what I am doing wrong


//+------------------------------------------------------------------+
//|                                               Moving Average.mq4 |
//|                   Copyright 2005-2014, MetaQuotes Software Corp. |
//|                                              http://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright   "2005-2014, MetaQuotes Software Corp."
#property link        "http://www.mql4.com"
#property description "Moving Average sample expert advisor"

#define MAGICMA  20131111
//--- Inputs
input double Lots          =0.1;
input double MaximumRisk   =0.02;
input double DecreaseFactor=3;
input int    MovingPeriod  =12;
input int    MovingShift   =6;
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//---
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//--- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//--- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//--- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
           {
            Print("Error in history!");
            break;
           }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
            continue;
         //---
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1)
         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//--- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double ma;
   int    res;
//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//--- get Moving Average 
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//--- sell conditions
   if(Open[1]>ma && Close[1]<ma)
     {
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      return;
     }
//--- buy conditions
   if(Open[1]<ma && Close[1]>ma)
     {
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      return;
     }
//---
  }



//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
//---
  }
//+------------------------------------------------------------------+





extern bool   AllPositions  =False;       
extern bool   ProfitTrailing=True;          
extern int    TrailingStop  =50;            
extern int    TrailingStep  =2;             
extern bool   UseSound      =True;         
extern string NameFileSound ="expert.wav";  
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
  void CheckForClose() 
  {
     for(int i=0; i<OrdersTotal(); i++) 
     {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) 
        {
           if (AllPositions || OrderSymbol()==Symbol()) 
           {
            TrailingPositions();
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|              |
//+------------------------------------------------------------------+
  void TrailingPositions() 
  {
   double pBid, pAsk, pp;
   

   //----
   pp=MarketInfo(OrderSymbol(), MODE_POINT);
     if (OrderType()==OP_BUY) 
     {
      pBid=MarketInfo(OrderSymbol(), MODE_BID);
        if (!ProfitTrailing || (pBid-OrderOpenPrice())>TrailingStop*pp) 
        {
           if (OrderStopLoss()<pBid-(TrailingStop+TrailingStep-1)*pp) 
           {
            ModifyStopLoss(pBid-TrailingStop*pp);
            return;
           }
        }
     }
     if (OrderType()==OP_SELL) 
     {
      pAsk=MarketInfo(OrderSymbol(), MODE_ASK);
        if (!ProfitTrailing || OrderOpenPrice()-pAsk>TrailingStop*pp) 
        {
           if (OrderStopLoss()>pAsk+(TrailingStop+TrailingStep-1)*pp || OrderStopLoss()==0) 
           {
            ModifyStopLoss(pAsk+TrailingStop*pp);
            return;
           }
        }
     }
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
  void ModifyStopLoss(double ldStopLoss) 
  {
   bool fm;
   fm=OrderModify(OrderTicket(),OrderOpenPrice(),ldStopLoss,OrderTakeProfit(),0,CLR_NONE);
   if (fm && UseSound) PlaySound(NameFileSound);
  }
//+------------------------------------------------------------------+
MQL4: automated forex trading, strategy tester and custom indicators with MetaTrader
MQL4: automated forex trading, strategy tester and custom indicators with MetaTrader
  • www.mql4.com
MQL4: automated forex trading, strategy tester and custom indicators with MetaTrader
 
I will move this topic to the MQL4 and MT4 section. In future please post in the correct section. 
 
thank you
 
  1. Proper place
  2. Iamidiot ass: The issue I am seeing is the last order is not setting stop loss porperly.
    "Doesn't work" is meaningless — just like saying the car doesn't work. Doesn't start, won't go in gear, no electrical, missing the key, flat tires — meaningless.
    Do you really expect an answer with the information you've provided? There are no mind readers here and our crystal balls are cracked. Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?

  3. lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
    ⋮
          res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
    Is your broker's minlot actual 0.1?
  4. Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

    Risk depends on your initial stop loss, lot size, and the value of the pair. It does not depend on margin and leverage. No SL means you have infinite risk.

    1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce the stop goes below the support.
    2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/pip but it takes account of the exchange rates of the pair vs. your account currency.)
    3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
                MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum 2017.10.10
                Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum 2018.02.11
                Lot value calculation off by a factor of 100 - MQL5 programming forum 2019.07.19
    4. You must normalize lots properly and check against min and max.
    5. You must also check FreeMargin to avoid stop out

    Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

  5.       res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
    ⋮
       fm=OrderModify(OrderTicket(),OrderOpenPrice(),ldStopLoss,OrderTakeProfit(),0,CLR_NONE);
    
    Check your return codes for errors, and report them including GLE/LE, your variable values, and the market. That way we would know that at least you are calling your code.

    Don't look at GLE/LE unless you have an error. Don't just silence the compiler, it is trying to help you.
              What are Function return values ? How do I use them ? - MQL4 programming forum
              Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles

  6.    if(Volume[0]>1) return;

    For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart,) volume is unreliable (miss ticks,) Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.

    I disagree with making a new bar function, because it can only be called once per tick. A variable can be tested multiple times.
              New candle - MQL4 programming forum

 

the first part of code is just a pickup from demo script given by MT4

Second part is the trailing functionality added


You give me few give me few points which will help in trading but I still dont know a lot about Mt4

Probably someone can look at code and understand it easily as it not complicated and comes with me MT4

 
Iamidiot ass: Probably someone can look at code and understand it easily as it not complicated and comes with me MT4
MT4: Learn to code it.
  1. If you don't learn MQL4/5, there is no common language for us to communicate. If we tell you what you need, you can't code it. If we give you the code, you don't know how to integrate it into yours.
  2. or pay (Freelance) someone to code it.
              Hiring to write script - General - MQL5 programming forum
We're not going to code it for you (although it could happen if you are lucky or the problem is interesting.) We are willing to help you when you post your attempt (using CODE button) and state the nature of your problem.
          No free help
 

sorry I come from python background

will hire someone than


thanks

Reason: