Convert a Trading View Pine Script a MT5 Expert Adviser (EA)

MQL5 Experts

Specification

Hi,

I need to convert the Open Close Cross Strategy R5.1 from Tradingview Pine Script to Meta Trader5 EA, so that it can open and close orders on its own.

Here is the original code:

//@version=3
//
 
strategy(title = "Open Close Cross Strategy R5.1 revised by JustUncleL", shorttitle = "OCC Strategy R5.1", overlay = true, 
  pyramiding = 0, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, calc_on_every_tick=false)
 
//
// Revision:        5
// Original Author: @JayRogers
// Revision Author: JustUncleL revisions 3, 4, 5
//
// *** USE AT YOUR OWN RISK ***
//  - There are drawing/painting issues in pinescript when working across resolutions/timeframes that I simply
//    cannot fix here.. I will not be putting any further effort into developing this until such a time when
//    workarounds become available. 
//    NOTE: Re-painting has been observed infrequently with default settings and seems OK up to Alternate 
//          multiplier of 5.
//          Non-repainting mode is available by setting "Delay Open/Close MA" to 1 or more, but the reported
//          performance will drop dramatically.
//
// R5.1 Changes by JustUncleL
//  - Upgraded to Version 3 Pinescript.
//  - Added option to select Trade type (Long, Short, Both or None)
//  - Added bar colouring work around patch.
//  - Small code changes to improve efficiency.
//  - NOTE: To enable non-Repainting mode set "Delay Open/Close MA" to 1 or more.
//  9-Aug-2017
//  - Correction on SuperSmooth MA calculation.
//
// R5 Changes by JustUncleL
//  - Corrected cross over calculations, sometimes gave false signals.
//  - Corrected Alternate Time calculation to allow for Daily,Weekly and Monthly charts.
//  - Open Public release.
// R4 Changes By JustUncleL
//  - Change the way the Alternate resolution in selected, use a Multiplier of the base Time Frame instead,
//    this makes it easy to switch between base time frames.
//  - Added TMA and SSMA moving average options. But DEMA is still giving the best results.
//  - Using "calc_on_every_tick=false" ensures results between backtesting and real time are similar.
//  - Added Option to Disable the coloring of the bars.
//  - Updated default settings.
//
// R3 Changes by JustUncleL:
//  - Returned a simplified version of the open/close channel, it shows strength of current trend.
//  - Added Target Profit Option.
//  - Added option to reduce the number of historical bars, overcomes the too many trades limit error.
//  - Simplified the strategy code.
//  - Removed Trailing Stop option, not required and in my opion does not work well in Trading View,
//    it also gives false and unrealistic performance results in backtesting.
//
// R2 Changes:
//  - Simplified and cleaned up plotting, now just shows a Moving Average derived from the average of open/close.
//  - Tried very hard to alleviate painting issues caused by referencing alternate resolution..
//
// Description:
//  - Strategy based around Open-Close Crossovers.
// Setup:
//  - I have generally found that setting the strategy resolution to 3-4x that of the chart you are viewing
//    tends to yield the best results, regardless of which MA option you may choose (if any) BUT can cause
//    a lot of false positives - be aware of this
//  - Don't aim for perfection. Just aim to get a reasonably snug fit with the O-C band, with good runs of
//    green and red.
//  - Option to either use basic open and close series data, or pick your poison with a wide array of MA types.
//  - Optional trailing stop for damage mitigation if desired (can be toggled on/off)
//  - Positions get taken automagically following a crossover - which is why it's better to set the resolution
//    of the script greater than that of your chart, so that the trades get taken sooner rather than later.
//  - If you make use of the stops, be sure to take your time tweaking the values. Cutting it too fine
//    will cost you profits but keep you safer, while letting them loose could lead to more drawdown than you
//    can handle.
//  - To enable non-Repainting mode set "Delay Open/Close MA" to 1 or more.
//
 
// === INPUTS ===
useRes      = input(defval = true, title = "Use Alternate Resolution?")
intRes      = input(defval = 3,    title = "Multiplier for Alernate Resolution")
stratRes    = ismonthly? tostring(interval*intRes,"###M") : isweekly? tostring(interval*intRes,"###W") : isdaily?  tostring(interval*intRes,"###D") : isintraday ? tostring(interval*intRes,"####") : '60'
basisType   = input(defval = "SMMA", title = "MA Type: ", options=["SMA", "EMA", "DEMA", "TEMA", "WMA", "VWMA", "SMMA", "HullMA", "LSMA", "ALMA", "SSMA", "TMA"])
basisLen    = input(defval = 8, title = "MA Period", minval = 1)
offsetSigma = input(defval = 6, title = "Offset for LSMA / Sigma for ALMA", minval = 0)
offsetALMA  = input(defval = 0.85, title = "Offset for ALMA", minval = 0, step = 0.01)
scolor      = input(false, title="Show coloured Bars to indicate Trend?")
delayOffset = input(defval = 0, title = "Delay Open/Close MA (Forces Non-Repainting)", minval = 0, step = 1)
tradeType   = input("BOTH", title="What trades should be taken : ", options=["LONG", "SHORT", "BOTH", "NONE"])
// === /INPUTS ===
 
// Constants colours that include fully non-transparent option.
green100 = #008000FF
lime100  = #00FF00FF
red100   = #FF0000FF
blue100  = #0000FFFF
aqua100  = #00FFFFFF
darkred100 = #8B0000FF
gray100 = #808080FF
 
// === BASE FUNCTIONS ===
// Returns MA input selection variant, default to SMA if blank or typo.
variant(type, src, len, offSig, offALMA) =>
    v1 = sma(src, len)                                                  // Simple
    v2 = ema(src, len)                                                  // Exponential
    v3 = 2 * v2 - ema(v2, len)                                          // Double Exponential
    v4 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)               // Triple Exponential
    v5 = wma(src, len)                                                  // Weighted
    v6 = vwma(src, len)                                                 // Volume Weighted
    v7 = 0.0
    v7 := na(v7[1]) ? sma(src, len) : (v7[1] * (len - 1) + src) / len    // Smoothed
    v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))   // Hull
    v9 = linreg(src, len, offSig)                                       // Least Squares
    v10 = alma(src, len, offALMA, offSig)                               // Arnaud Legoux
    v11 = sma(v1,len)                                                   // Triangular (extreme smooth)
    // SuperSmoother filter
    // © 2013  John F. Ehlers
    a1 = exp(-1.414*3.14159 / len)
    b1 = 2*a1*cos(1.414*3.14159 / len)
    c2 = b1
    c3 = (-a1)*a1
    c1 = 1 - c2 - c3
    v12 = 0.0
    v12 := c1*(src + nz(src[1])) / 2 + c2*nz(v12[1]) + c3*nz(v12[2])
    type=="EMA"?v2 : type=="DEMA"?v3 : type=="TEMA"?v4 : type=="WMA"?v5 : type=="VWMA"?v6 : type=="SMMA"?v7 : type=="HullMA"?v8 : type=="LSMA"?v9 : type=="ALMA"?v10 : type=="TMA"?v11: type=="SSMA"?v12: v1
 
// security wrapper for repeat calls
reso(exp, use, res) => use ? security(tickerid, res, exp, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) : exp
 
// === /BASE FUNCTIONS ===
 
// === SERIES SETUP ===
closeSeries     = variant(basisType, close[delayOffset], basisLen, offsetSigma, offsetALMA)
openSeries      = variant(basisType, open[delayOffset], basisLen, offsetSigma, offsetALMA)
// === /SERIES ===
 
// === PLOTTING ===
 
// Get Alternate resolution Series if selected.
closeSeriesAlt = reso(closeSeries, useRes, stratRes)
openSeriesAlt = reso(openSeries, useRes, stratRes)
//
trendColour = (closeSeriesAlt > openSeriesAlt) ? green : red
bcolour     = (closeSeries > openSeriesAlt) ? lime100 : red100
barcolor(scolor?bcolour:na, title = "Bar Colours")
closeP=plot(closeSeriesAlt, title = "Close Series", color = trendColour, linewidth = 2, style = line, transp = 20)
openP=plot(openSeriesAlt, title = "Open Series", color = trendColour, linewidth = 2, style = line, transp = 20)
fill(closeP,openP,color=trendColour,transp=80)
 
// === /PLOTTING ===
//
 
//
// === ALERT conditions
xlong       = crossover(closeSeriesAlt, openSeriesAlt)
xshort      = crossunder(closeSeriesAlt, openSeriesAlt)
longCond    = xlong   // alternative: longCond[1]? false : (xlong or xlong[1]) and close>closeSeriesAlt and close>=open
shortCond   = xshort  // alternative: shortCond[1]? false : (xshort or xshort[1]) and close<closeSeriesAlt and close<=open
// === /ALERT conditions.
 
// === STRATEGY ===
// stop loss
slPoints    = input(defval = 0, title = "Initial Stop Loss Points (zero to disable)", minval = 0)
tpPoints    = input(defval = 0, title = "Initial Target Profit Points (zero for disable)", minval = 0)
// Include bar limiting algorithm
ebar            = input(defval = 10000, title="Number of Bars for Back Testing", minval=0)
dummy           = input(false,        title="- SET to ZERO for Daily or Longer Timeframes" )
//
// Calculate how many mars since last bar
tdays       = (timenow-time)/60000.0  // number of minutes since last bar
tdays       := ismonthly? tdays/1440.0/5.0/4.3/interval : isweekly? tdays/1440.0/5.0/interval : isdaily? tdays/1440.0/interval : tdays/interval // number of bars since last bar
//
//set up exit parameters
TP = tpPoints>0?tpPoints:na
SL = slPoints>0?slPoints:na
 
// Make sure we are within the bar range, Set up entries and exit conditions
if ((ebar==0 or tdays<=ebar) and tradeType!="NONE")
    strategy.entry("long", strategy.long, when=longCond==true and tradeType!="SHORT")
    strategy.entry("short", strategy.short, when=shortCond==true and tradeType!="LONG")
    strategy.close("long", when = shortCond==true and tradeType=="LONG")
    strategy.close("short", when = longCond==true and tradeType=="SHORT")
    strategy.exit("XL", from_entry = "long", profit = TP, loss = SL)
    strategy.exit("XS", from_entry = "short", profit = TP, loss = SL)
 
// === /STRATEGY ===
// eof


Responded

1
Developer 1
Rating
(412)
Projects
543
75%
Arbitration
9
44% / 0%
Overdue
24
4%
Free
2
Developer 2
Rating
(281)
Projects
454
39%
Arbitration
93
42% / 18%
Overdue
73
16%
Busy
Published: 2 codes
Similar orders
⚙ Renko EA Entry Logic (Simplified & Professional) 🔹 Buy Entry EA opens a Buy when Fast MA crosses above Slow MA , signaling an uptrend. 🔹 Sell Entry EA opens a Sell when Fast MA crosses below Slow MA , signaling a downtrend. 🔹 Close on Next Entry (if enabled) If CloseOnNextEntry = true : • Closes opposite trade before opening a new one • Ensures only one active trade at a time 🔹 Trend Filter (if enabled) EA
Hello All, I need a developer who can help me to modify my existing expert advisor with below requirements : 1. I have already a mql4 file and I want to modified it with some new certain filters or conditions 2. I will add more filters conditions which I will tell you later for the selected developer. 3. Once it’s done so you must share the modified mql4 to me and I will do back test many times to make sure whether
Buna tuturor developerilor romani de pe aici, Am un indicator care functioneaza destul de bine insa cum intotdeauna este loc de mai bine as avea nevoie de niste update uri pentru el. In principiu as vrea sa fie adaugat 2 indicatori noi in logica existenta, primul este CCI al doilea este Accelerator Oscillator. Primul ar trebui sa functioneze in TF current, iar al doilea in TF curent + un TF mai mare. Mai multe
En Yellowbit.co, una startup enfocada en el trading algorítmico, abrimos convocatoria para sumar al equipo a un desarrollador con experiencia en MQL5 y pasión por los mercados financieros. 🧠 ¿Qué buscamos? •⁠ ⁠Mínimo 3 años programando en MQL5 •⁠ ⁠Buen dominio de algoritmos y estructuras de datos •⁠ ⁠Nociones sólidas de trading y validación de estrategias •⁠ ⁠Comunicación clara y buena lógica para resolver problemas
Dear programmers, I am using a famous MT4 / MT5 copier called FX Blue. It supports external filters to control the copier / receiver. I need someone to program a external filter, so the receiver can be turned off or on, if there are trades or no trades. So for example. I run 3 different receivers with 3 different magic number (001,002,003). Receiver with magic number 002 received a trade. As long as this trade is
Hello All, I need News Filter For MT4. Input Parameters:- 1. News Filter ON/OFF 2. Stop Trade Before 3. Start Trade After 4. Low News ON/OFF 5.Medium News ON/OFF 6. High News ON/OFF 7. Number of News Show On Chart Example if user enter = 1 than only 1 Latest Upcoming News Show Get News Data From This Website Only : https://www.mql5.com/en/economic-calendar If News Filter is OFF than show NEWS FILTER IS OFF if
I Want a EA which take trade in my mention zone with TP, SL , BE & Trail Options for Example i will mention when gold reach Gold 3330 Price and its make a reversal candle then EA take trade regards
hello i have a problem i want toautomatize trading, i have a good indicator in tradingview and i want automatize with wundertrading. but for now the signal don't go and i want to solve the problem. I can make trade with binance or other exchange. we can solve by put a webhook that directly insert order in binance? or we can make a webhook that send order to wundertrading, that after, send order to binance. For me is
I want to a professional developer who is expert in creating the EA using Heikin Ashi candles. I am already having a simple trading view strategy, and just want to convert it to MT4 bot for auto execution of orders. Option for Changing SL and TP percentage in MT4 required. All other is mentioned in my simple strategy. [attached in txt file] Note: 1. The developer should back test the strategy on MT4 before accepting
Project Title** *"Develop a MetaTrader 5 Expert Advisor (EA) for XAUUSD with Trend/Momentum Filters"* #### **2. Core Requirements** - **Strategy Logic**: - **Trend-Following**: Ichimoku Cloud (Tenkan/Kijun crossover) + Moving Average (50/200 EMA filter). - **Momentum Confirmation**: RSI (oversold/overbought) + MACD histogram divergence. - **Volatility Adjustment**: Dynamic stop-loss/take-profit based on ATR

Project information

Budget
30+ USD
VAT (20%): 6 USD
Total: 36 USD
For the developer
27 USD
Deadline
to 7 day(s)