Help for sl

 

Hi guys,

I wanted to test Stop Loss Function, so i use this simple code. But nothing is happening. During the backtest no buy or  sell order

Can you help me please

Thank you for your time


#include <Trade\Trade.mqh>
CTrade trade;
  int a =0;

void OnTick()
  {

   double RsiArray[];
   int rsi = iRSI(_Symbol,PERIOD_CURRENT, 14, PRICE_CLOSE);
   ArraySetAsSeries(RsiArray,true);
   CopyBuffer(rsi,0,0,3, RsiArray);
   double rsivalue=NormalizeDouble(RsiArray[0],2);

double Ask=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
double Bid=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
if(rsivalue<40)
  {
a=5;
trade.Buy(0.10,NULL,(Ask-1000*_Point),(Ask+500*_Point),NULL);
CheckTrailingStop(Ask);
  }
  if(rsivalue>60)
  {
  a=10;
  trade.Sell(0.1,NULL,(Bid-1000*_Point),(Bid+500*_Point),NULL);
CheckTrailingStop1(Bid);
  } 
Comment(a);
  }

//+------------------------------------------------------------------+
void CheckTrailingStop(double Ask)
{
double SL=NormalizeDouble(Ask-150*_Point,_Digits);
for (int i=PositionsTotal()-1;i>=0;i--)
{
string symbol=PositionGetSymbol(i);

   if (Symbol()==symbol)
   {
   ulong PositionTicket=PositionGetInteger(POSITION_TICKET);
   double CurrentStopLoss=PositionGetDouble(POSITION_SL);

      if (CurrentStopLoss<SL)
      {
      trade.PositionModify(PositionTicket,(CurrentStopLoss+10*Point()),0);
      }
   }
}}

void CheckTrailingStop1(double Bib)
{
double SL=NormalizeDouble(Bib+150*Point(),Digits());
for (int i=PositionsTotal()-1;i>=0;i--)
{
string symbol=PositionGetSymbol(i);

   if (_Symbol==symbol)
   {
   ulong PositionTicket=PositionGetInteger(POSITION_TICKET);
   double CurrentStopLoss=PositionGetDouble(POSITION_SL);

      if (CurrentStopLoss<SL)
      {
      trade.PositionModify(PositionTicket,(CurrentStopLoss-10*_Point),0);
      } 
   }
}}
 
Kerkad :

Hi guys,

I wanted to test Stop Loss Function, so i use this simple code. But nothing is happening. During the backtest no buy or  sell order

Can you help me please

Thank you for your time


DO NOT create an indicator on each tick:

void OnTick()
  {

   double RsiArray[];
   int rsi = iRSI(_Symbol,PERIOD_CURRENT, 14, PRICE_CLOSE);

Indicator Handle NEEDS to get ONCE in OnInit ()! Correct your code.

 
  1. Check your return codes for errors, and report them including GLE/LE and your variable values. 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
  2. trade.Buy(0.10,NULL,(Ask-1000*_Point),(Ask+500*_Point),NULL);
    You buy at the Ask and sell at the Bid. So for buy orders you pay the spread on open. For sell orders you pay the spread on close.
    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid reaches it. Not the Ask. Your SL is shorter by the spread and your TP is longer. Don't you want the same/specified amount for either direction?
    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25
    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (Control-O) → charts → Show ask line.)
  3. Your test for moving stops is the same for a buy or a sell.
  4. Once the RSI goes below 40 or above you will be opening an order each tick.
 
Kerkad :

Look at an example - this script (not an adviser) opens a position with Stop Loss and Take Profit (This is a very simple example - without an RSI indicator.

But I can show an example with the RSI indicator.)


Simple script: it opens a BUY position. In this case, you can set Stop loss and Take profit.

Please note - Stop loss and Take profit must be normalized using the method CSymbolInfo::NormalizePrice

//+------------------------------------------------------------------+
//|                                         Open Positions SL TP.mq5 |
//|                              Copyright © 2019, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2019, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.00"
#property script_show_inputs
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//--- input parameters
input ushort   InpStopLoss          = 15;          // Stop Loss, in pips (1.00045-1.00055=1 pips)
input ushort   InpTakeProfit        = 46;          // Take Profit, in pips (1.00045-1.00055=1 pips)
input ulong    InpDeviation         = 10;          // Deviation, in points (1.00045-1.00055=10 points)
//---
input ulong    InpMagic             = 397752952;   // Magic number
//---
double   m_stop_loss                = 0.0;         // Stop Loss      -> double
double   m_take_profit              = 0.0;         // Take Profit    -> double
double   m_adjusted_point;                         // point value adjusted for 3 or 5 points
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return;
     }
   RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   m_adjusted_point=m_symbol.Point()*digits_adjust;

   m_stop_loss             = InpStopLoss              * m_adjusted_point;
   m_take_profit           = InpTakeProfit            * m_adjusted_point;
//--- open buy
   double sl=(m_stop_loss==0.0)?0.0:m_symbol.Ask()-m_stop_loss;
   double tp=(m_take_profit==0.0)?0.0:m_symbol.Ask()+m_take_profit;
   m_trade.Buy(m_symbol.LotsMin(),
               m_symbol.Name(),
               m_symbol.Ask(),
               m_symbol.NormalizePrice(sl),
               m_symbol.NormalizePrice(tp));
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
How to start with MQL5
How to start with MQL5
  • 2019.08.18
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
Files:
 
Hi guys
 thank's for your help i have correct my code with your help
But now il have an over question, 
How can i open 1 position when the condition are okay without "PositionsTotal()<1". Because with this code i open a position per tick.
So if it's the only technique, How can i open only 1 position per  market ? (like 1 position on EURUSD, and a other USDJPY)
 
Kerkad :
Hi guys
 thank's for your help i have correct my code with your help
But now il have an over question, 
How can i open 1 position when the condition are okay without "PositionsTotal()<1". Because with this code i open a position per tick.
So if it's the only technique, How can i open only 1 position per  market ? (like 1 position on EURUSD, and a other USDJPY)

The algorithm is this: send a trade order "Open Position" -> wait for the result in OnTradeTransaction -> get the result - you can move on.

In OnTradeTransaction it is necessary to catch the transaction TRADE_TRANSACTION_DEAL_ADD and the type of transaction.


The thing is that opening a position always takes time. And in this period of time several ticks may come. Therefore, you should always expect results in OnTradeTransaction.


Need an example?

Documentation on MQL5: Language Basics / Functions / Event Handling Functions
Documentation on MQL5: Language Basics / Functions / Event Handling Functions
  • www.mql5.com
The MQL5 language provides processing of some predefined events. Functions for handling these events must be defined in a MQL5 program; function name, return type, composition of parameters (if there are any) and their types must strictly conform to the description of the event handler function. The event handler of the client terminal...
 
Yes i need an exemple please
 
Kerkad :
Yes i need an exemple please

The example had to be simplified as much as possible: the EA works on the current symbol and always opens at most ONE BUY position with a minimum volume on this symbol.

 
Ok thank you i will going to study your code 
 
Kerkad :
Ok thank you i will going to study your code 

Be sure to ask questions. I will answer with pleasure.

Reason: