TradingView Stop and Reverse strategies don't work correctly

Hi,

I have a MT5 Hedge demo account.
Here is a very simple TradingView SAR (stop and reverse strategy) :


//@version=6
strategy("test", "tst", true, pyramiding=1, default_qty_value= 1, close_entries_rule="ANY")

if buySignal
    strategy.entry("buy", strategy.long)
else
    if sellSignal
        strategy.entry("sell", strategy.short)

How does TradingView executes this strategy ? Simple :

Buy 1 (+1 long) then Sell 2 (-1 short), then Buy 2 (+1 long)…

Why ? Here is what TradingView Reference Manual says about “strategy.entry” :

“By default, when a strategy executes an order from this command in the opposite direction of the
current market position, it reverses that position.
For example, if there is an open long position of five shares, an order from this command with
a qty of 5 and a direction of strategy.short triggers the sale of 10 shares to close the long position
and open a new five-share short position”.

Instead, “TradingViewToMT5.ex5” version 4.001 does this :

Buy 1 (+1 long - OK) then Sell 2 (-2 short - NO!), then Buy 2 (0 flat - NO!), then Sell 2 (-2 short - NO!)

{{strategy.order.action}} EURUSD Q={{strategy.order.contracts}}
Position mode : Close - Exit on Reverse

Please fix this bug.

Thank you

Hi @p51

Sorry for the delay. Some updates were made on the site.
Here is my confirmation for you.

Your goal is to automate tradingview strategy so when any order comes in, the existing trades are closed and a new trade is opened with the specified Quantity.

To achieve this goal, Use the setting called FLIP which closes all your existing trades and opens a new one on the opposite direction.

image

This will achieve the functionality similar to tradingview close all existing positions and enter a new trade on the other side.


Commands Example

  1. buy EURUSD q=0.1 will open a buy of 0.1
  2. sell EURUSD q=0.02 will close existing buy trades and open a sell of 0.02

Enjoy!

I have just downloaded the new “TradingViewToMT5.ex5” version 4.001 from your website (size 133592).

Nice try but “Flip - Exit and Enter” *** STILL *** doesn’t solve the SAR strategy problem.

Here is what TradingViewToMT5.ex5 does, whatever the account, hedging or netting :

Buy 1 (+1 long - OK) then Sell 2 (-2 short - NO!), then Buy 2 (2 long - NO!), then Sell 2 (-2 short - NO!)

Instead, here is *** how TradingView works *** :

Buy 1 (+1 long) then Sell 2 (-1 short), then Buy 2 (+1 long)… then Sell 2 (-1 short),

Please fix this bug and use the original data coming from TradingView, no quantity modification :

//@version=6
strategy("stop and reverse", "sar", true, pyramiding=1, default_qty_value= 1, close_entries_rule="ANY")

if barstate.islast and barstate.isconfirmed

    buySignal=  minute(time) % 2 == 0
    sellSignal= not buySignal

    if strategy.position_size <= 0 and buySignal
        strategy.entry("buy", strategy.long)
    else
        if strategy.position_size >= 0 and sellSignal
            strategy.entry("sell", strategy.short)

{{strategy.order.action}} {{ticker}} Q={{strategy.order.contracts}}

Thank you.

The MQL5 solution to solve this problem is the following :

Example of the TRADE_ACTION_CLOSE_BY trade operation for closing positions by opposite positions:

#define EXPERT_MAGIC 123456  // MagicNumber of the expert
//+------------------------------------------------------------------+
//| Close all positions by opposite positions                        |
//+------------------------------------------------------------------+
void OnStart()
  {
//--- declare and initialize the trade request and result of trade request
   MqlTradeRequest request;
   MqlTradeResult  result;
   int total=PositionsTotal(); // number of open positions   
//--- iterate over all open positions
   for(int i=total-1; i>=0; i--)
     {
      //--- parameters of the order
      ulong  position_ticket=PositionGetTicket(i);                                    // ticket of the position
      string position_symbol=PositionGetString(POSITION_SYMBOL);                      // symbol 
      int    digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS);            // ticket of the position
      ulong  magic=PositionGetInteger(POSITION_MAGIC);                                // MagicNumber of the position
      double volume=PositionGetDouble(POSITION_VOLUME);                               // volume of the position
      double sl=PositionGetDouble(POSITION_SL);                                       // Stop Loss of the position
      double tp=PositionGetDouble(POSITION_TP);                                       // Take Profit of the position
      ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);  // type of the position
      //--- output information about the position
      PrintFormat("#%I64u %s  %s  %.2f  %s  sl: %s  tp: %s  [%I64d]",
                  position_ticket,
                  position_symbol,
                  EnumToString(type),
                  volume,
                  DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
                  DoubleToString(sl,digits),
                  DoubleToString(tp,digits),
                  magic);
      //--- if the MagicNumber matches
      if(magic==EXPERT_MAGIC)
        {
         for(int j=0; j<i; j++)
           {
            string symbol=PositionGetSymbol(j); // symbol of the opposite position
            //--- if the symbols of the opposite and initial positions match
            if(symbol==position_symbol && PositionGetInteger(POSITION_MAGIC)==EXPERT_MAGIC)
              {
               //--- set the type of the opposite position
               ENUM_POSITION_TYPE type_by=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
               //--- leave, if the types of the initial and opposite positions match
               if(type==type_by)
                  continue;
               //--- zeroing the request and result values
               ZeroMemory(request);
               ZeroMemory(result);
               //--- setting the operation parameters
               request.action=TRADE_ACTION_CLOSE_BY;                         // type of trade operation
               request.position=position_ticket;                             // ticket of the position
               request.position_by=PositionGetInteger(POSITION_TICKET);      // ticket of the opposite position
               //request.symbol     =position_symbol;
               request.magic=EXPERT_MAGIC;                                   // MagicNumber of the position
               //--- output information about the closure by opposite position
               PrintFormat("Close #%I64d %s %s by #%I64d",position_ticket,position_symbol,EnumToString(type),request.position_by);
               //--- send the request
               if(!OrderSend(request,result))
                  PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, output the error code
 
               //--- information about the operation   
               PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);
              }
           }
        }
     }
  }

Hello @p51

Could you please mention your strategy on Tradingview or something similar to your strategy? I will be glad to test it on hedging and netting accounts to see if I obtain similar results.

Thank you.

Tash.

??? Please read again my previous message, I have included the TradingView strategy in it, just copy and paste into TradingView.

Here are the options that you can take when automating.
image

1. Hedge - Enter all Trades

This allows you to open any trade that you want buy or sell without restricting your positions. Your must have an account that supports this. This is the default setting in your EA.

2. Close Netting - Similar to your example

This option allows you to close the reverse side the equivalent positions that you want to enter. Lets say you have 10 long and you enter 20 short, the result would be 10 short.

3. Flip Side - Switches overall direction

This option allows you to switch to long when a long position comes in. This means that all the opposite side trades are closed and a new position is opened. Similar to my demo.


These are the only options available. Does this work for you?

@p51 I now understand the bug you are referring to. So you were able to trade like tradingview when reducing the position but the problem came when the new quantity was greater than the existing one. This would result to a behavior similar to close and exit instead of performing the netting.

A fix has been made for all relevant EAs

Direct Connection EAs

MT4
MT5

Telegram Connection EAs

MT4
MT5

These downloads are also available on your account page under your webhook information

Congratulations Lucem ! 4.003 now works correctly.

Your EA is fast to react to TradingView signals, the only drawbacks I now see are the following :

Your EA feeds the comment field with the string “TradingViewToMT5” of the MQL5 MqlTradeRequest structure + the ulong magic number “884” and you send this information with each order to the broker without customer agreement.

The magic number can be removed with “m=0” but the comment “TradingViewToMT5” can’t.

These days, unfortunately, some brokers are dishonest.
I regularly advise profitable traders NOT to give the broker any clues about the strategy they use, the tool they use, whether or not they trade manually, when… or about the tool they use, whether or not they trade manually, when…

If the strategy is highly profitable, even banks are capable of putting money on the table to bribe people to get the strategy’s source code.

In addition, telling the broker what tool his client uses can help him anticipate his orders to trigger his stop losses, as many brokers trade against their clients’ positions because 90% of them lose money.

It would be an improvement if this comment be optional or a customized string field…

Thanks

struct MqlTradeRequest 
  { 
   ENUM_TRADE_REQUEST_ACTIONS    action;           // Trade operation type 
   ulong                         magic;            // Expert Advisor ID (magic number) 
   ulong                         order;            // Order ticket 
   string                        symbol;           // Trade symbol 
   double                        volume;           // Requested volume for a deal in lots 
   double                        price;            // Price 
   double                        stoplimit;        // StopLimit level of the order 
   double                        sl;               // Stop Loss level of the order 
   double                        tp;               // Take Profit level of the order 
   ulong                         deviation;        // Maximal possible deviation from the requested price 
   ENUM_ORDER_TYPE               type;             // Order type 
   ENUM_ORDER_TYPE_FILLING       type_filling;     // Order execution type 
   ENUM_ORDER_TYPE_TIME          type_time;        // Order expiration type 
   datetime                      expiration;       // Order expiration time (for the orders of ORDER_TIME_SPECIFIED type) 
   string                        comment;          // Order comment 
   ulong                         position;         // Position ticket 
   ulong                         position_by;      // The ticket of an opposite position 
  };
1 Like

Hi @p51. I am glad that worked out for you.

Unfortunately you cannot hide from the broker when using EAs. Manual trading is different from automatic even if you were to hide EAs magic and order comment. The order comment exists for our branding.

Enjoy

IMHO, the order comment should be optional or customizable, like the magic number.
None of your competitors force their user to tell to their brokers that they are using a trading system ready to be investigated if very profitable. No clue.

Keep tuned for new features coming soon. Also note that many people are using this software for automation purposes; it only works when you tell it to so there no advantage to the broker knowing or not what you use.