Help in coding Trading View strategy in Metaeditor

 

Hi everyone,

I am new to Metaeditor. I have programmed one strategy (quite simple) for TradingView, and now I would like to make it automatic.

I have been fighting with Metaeditor, but so far no luck in programming it. Could any of you help me in coding it? or at least give me some help so I can do it?

Please find the strategy attached, coded for TradingView.

Thanks for all your help.

Gonzalo

Files:
 
Hello please visit codebase for examples https://www.mql5.com/en/code 
MQL5 Code Base
MQL5 Code Base
  • www.mql5.com
Pivotal points as described in the March 2009 SFO magazine article "Trading FX Like Jesse Livermore Traded Stocks" by Jamie Saettele. Compared to the CCI Squeeze indicator, this version is a standalone multi timeframe version (no other indicator is needed for its work). Combination of two very well known indicators (CCI and Moving Average...
 
Marco vd Heijden:
Hello please visit codebase for examples https://www.mql5.com/en/code 

Thanks for your reply marco. I have been checking it, but I am afraid it is too complex for my knowledge. Would it be possible for you/someone to translate it to Mql5? I know I am asking too much, but honestly, I don't know what to do.

Thanks

 

Well you would first have to start by explaining the strategy.

strategy("4 Semanas opening, 4 closing_Close")
a = max(close[1],max(close[2],max(close[3],max(close[4],max(close[5],max(close[6],max(close[7],max(close[8],max(close[9],max(close[10],max(close[11],max(close[12],max(close[13],max(close[14],max(close[15],max(close[16],max(close[17],max(close[18],max(close[19],close[20])))))))))))))))))))
b = min(close[1],min(close[2],min(close[3],min(close[4],min(close[5],min(close[6],min(close[7],min(close[8],min(close[9],min(close[10],min(close[11],min(close[12],min(close[13],min(close[14],min(close[15],min(close[16],min(close[17],min(close[18],min(close[19],close[20])))))))))))))))))))

longCondition = close > a
shortCondition = close < b   

strategy.entry ("long", strategy.long, when = longCondition)
strategy.entry ("short", strategy.short, when = shortCondition)
strategy.close ("long", when=shortCondition)
strategy.close ("short", when=longCondition)


A flow chart would be handy.

 
Marco vd Heijden:

Well you would first have to start by explaining the strategy.


A flow chart would be handy.

Thanks for your reply again Marco, I thought it was clear with the code, my bad. The strategy consists on:

- a variable has the maximum value of the close of the past 20 days (4 weeks)

- b variable has the minimum value of the close of the past 20 days (4 weeks)

- When daily close is above a, short trade is closed and long trade is opened

- When daily close is below b, long trade is closed and short trade is opened

As you can see, this is a continuous strategy, meaning that we always have a trade opened for each symbol, either short or long. I am applying this for several currency pairs and comodities:


- Currency pairs: lot size is always 0.01

- Comodities: lot size varies from 0.01 to 0.1, depending on each one


I would like to set protective stop loss just in case it goes too heavily against me, setting it around 400 pips away.

Please let me know if you need further information.

Thanks for all your help!

 

I forgot to add:


- If a long trade is ongoing, and daily close is above "a", nothing is done, I only have one trade opened per symbol at the same time

- Same applies to short, if a short trade is ongoing, and daily close is below "b", nothing is done.

 
ok hang on.
 
//+------------------------------------------------------------------+
//|                                                   GonzalonV2.mq5 |
//|      Copyright 2018, Marco vd Heijden, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, Marco vd Heijden, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "2.00"
#define EXPERT_MAGIC 9876548
double close[],a,b,c;
bool direction;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {

   int count=CopyClose(Symbol(),PERIOD_D1,1,21,close);
//for(int i=count-1;i>0;i--){Print("Bar: "+IntegerToString(i)+" Close: "+DoubleToString(close[i]));}

//--- a variable has the maximum value of the close of the past 20 days (4 weeks)
   a=close[ArrayMaximum(close,0,WHOLE_ARRAY)];
   //Print("a: "+DoubleToString(a));
//--- b variable has the minimum value of the close of the past 20 days (4 weeks)
   b=close[ArrayMinimum(close,0,WHOLE_ARRAY)];
   //Print("b: "+DoubleToString(b));
//--- c variable is daily close
   c=iClose(Symbol(),PERIOD_D1,0);
   //Print("c: "+DoubleToString(c));
//--- When daily close is above a, short trade is closed and long trade is opened 
   if(c>a)
     {
      if(direction==0)
        {
         CloseAll();
         Long();
         direction=1;
        }
     }
//--- When daily close is below b, long trade is closed and short trade is opened
   if(c<b)
     {
      if(direction==1)
        {
         CloseAll();
         Short();
         direction=0;
        }
     }
  }
//+------------------------------------------------------------------+
//| Opening Buy position                                             |
//+------------------------------------------------------------------+
void Long()
  {
//--- declare and initialize the trade request and result of trade request
   MqlTradeRequest request={0};
   MqlTradeResult  result={0};
//--- parameters of request
   request.action   =TRADE_ACTION_DEAL;                     // type of trade operation
   request.symbol   =Symbol();                              // symbol
   request.volume   =0.01;                                  // volume  
   request.type     =ORDER_TYPE_BUY;                        // order type
   request.price    =SymbolInfoDouble(Symbol(),SYMBOL_ASK); // price for opening
   request.deviation=5;                                     // allowed deviation from the price
   request.magic    =EXPERT_MAGIC;                          // MagicNumber of the order
//--- 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);
  }
//+------------------------------------------------------------------+
//| Opening Sell position                                            |
//+------------------------------------------------------------------+
void Short()
  {
//--- declare and initialize the trade request and result of trade request
   MqlTradeRequest request={0};
   MqlTradeResult  result={0};
//--- parameters of request
   request.action   =TRADE_ACTION_DEAL;                     // type of trade operation
   request.symbol   =Symbol();                              // symbol
   request.volume   =0.01;                                  // volume  
   request.type     =ORDER_TYPE_SELL;                       // order type
   request.price    =SymbolInfoDouble(Symbol(),SYMBOL_BID); // price for opening
   request.deviation=5;                                     // allowed deviation from the price
   request.magic    =EXPERT_MAGIC;                          // MagicNumber of the order
//--- 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);
  }
//+------------------------------------------------------------------+
//| Closing all positions                                            |
//+------------------------------------------------------------------+
void CloseAll()
  {
//--- 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);              // number of decimal places
      ulong  magic=PositionGetInteger(POSITION_MAGIC);                                  // MagicNumber of the position
      double volume=PositionGetDouble(POSITION_VOLUME);                                 // volume 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 [%I64d]",
                  position_ticket,
                  position_symbol,
                  EnumToString(type),
                  volume,
                  DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
                  magic);
      //--- if the MagicNumber matches
      if(magic==EXPERT_MAGIC)
        {
         //--- zeroing the request and result values
         ZeroMemory(request);
         ZeroMemory(result);
         //--- setting the operation parameters
         request.action   =TRADE_ACTION_DEAL;        // type of trade operation
         request.position =position_ticket;          // ticket of the position
         request.symbol   =position_symbol;          // symbol 
         request.volume   =volume;                   // volume of the position
         request.deviation=5;                        // allowed deviation from the price
         request.magic    =EXPERT_MAGIC;             // MagicNumber of the position
         //--- set the price and order type depending on the position type
         if(type==POSITION_TYPE_BUY)
           {
            request.price=SymbolInfoDouble(position_symbol,SYMBOL_BID);
            request.type =ORDER_TYPE_SELL;
           }
         else
           {
            request.price=SymbolInfoDouble(position_symbol,SYMBOL_ASK);
            request.type =ORDER_TYPE_BUY;
           }
         //--- output information about the closure
         PrintFormat("Close #%I64d %s %s",position_ticket,position_symbol,EnumToString(type));
         //--- 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);
         //---
        }
     }
  }
//+------------------------------------------------------------------+

It needs tweaking so you have to specify where and what.

I have to go walk the dog.

Edit to V2.
 
Marco vd Heijden:

It needs tweaking so you have to specify where and what.

I have to go walk the dog.

Edit to V2.

Wow! Incredible work Marco, thank you so much. I can see how much more complex Metaeditor is compared to Tradingview...

I created a new Expert Advisor template, copy/pasted your code, and then saved it as "MQL5 source file". Then I clicked on "Compile", and it returned me an error " 'iClose' - Function not defined". I tried adding it to line 10 (double close[],a,b,c;) but it didn't work. Could you please tell me if I am doing something wrong?

Also, you mentioned that I have to specify where and what, would it be possible for you to explain that more in detail? As you can see, I am a bit too new for this...


Thanks for your great help! I hope you enjoyed that walk with your dog, I miss walking mine (she passed away a few years ago)

 
Gonzalon77: it returned me an error " 'iClose' - Function not defined".
Old version - iTime, iOpen, iHigh, iLow, iClose, iVolume, iBars, iBarShift, iLowest, iHighest, iRealVolume, iTickVolume, iSpread
          New MetaTrader 5 Platform beta build 1845: MQL5 functions for operations with bars and Strategy Tester improvements - Options Trading Strategies - General - MQL5 programming forum 2018.06.08 13:02
 

Please open a demo account on MetaQuotes-Demo server.

After this your terminal will update to the newest version that allows the use of these functions.

Reason: