Porting · TradingView to MetaTrader
Pine Script to MQL5 porting
Your strategy runs in the TradingView chart and is supposed to trade automatically — independently of an open browser, testable in the strategy tester and with your broker. We port it to MQL5 or MQL4 and then prove that both sides produce the same entries and exits on the same price data.
Also for indicators, in the other direction, and for reworking AI-converted results.
Three ways from TradingView into the terminal
Which one is right depends on how independently the system should run and whether you want to test it reliably.
| Webhook bridge | The strategy stays in TradingView and sends alerts to a receiving program that executes the orders in MetaTrader. Quick to implement and inexpensive — but permanently dependent on TradingView, on the subscription and on the connection between both sides. A backtest of the entire chain is not possible. |
|---|---|
| Full port | The logic is rebuilt in MQL5. The system then runs independently in the terminal, can be checked in the strategy tester, works without an internet connection to third parties and can be extended as required. The standard case for production use. |
| Mixed operation | Signal generation stays in TradingView, all risk and position management moves into the terminal. Useful if you want to keep developing your strategy there but need reliable money management, break-even, trailing and emergency shutdown. |
Why porting is not translation
Pine Script and MQL5 look vaguely similar in syntax, and automatic converters and AI tools translate exactly that syntax, line by line. But the differences lie in the execution model — and that is exactly where the deviations arise that remain invisible in the chart. A converted script often compiles and still trades differently.
The most important difference: Pine recalculates the past, MQL5 doesn't
Pine Script runs over the entire visible history on every execution and recalculates all values. The current, not yet closed candle is evaluated continuously. MQL5 is event-driven: an Expert Advisor reacts to incoming ticks and does not know the future — not even that of the current candle.
Practical consequence: a Pine strategy whose condition was briefly met within a candle and no longer at the candle's close may show no signal in the chart, but would have traded live — or vice versa. Before porting, it must therefore be clarified whether decisions are made on closed or on running candles. That is a business decision, not a technical one.
Comparison of the most important constructs
| Task | Pine Script (TradingView) | MQL5 (MetaTrader 5) |
|---|---|---|
| Opening a position | strategy.entry() in a simplified simulation |
CTrade::Buy() with a real order that can be rejected or partially filled |
| Closing a position | strategy.close(), strategy.exit() |
PositionClose(), partial close via PositionClosePartial() |
| Price series | close[1], high[2] — the index counts backwards from the current candle |
CopyRates() into your own arrays; set the indexing direction with ArraySetAsSeries() |
| Moving average | ta.ema(close, 20) returns the value directly |
iMA() returns a handle; the values are fetched by CopyBuffer() |
| Higher timeframe | request.security() — with a risk of repainting if lookahead is set incorrectly |
Separate indicator handle on the target timeframe, value valid only after the candle closes |
| Candle state | barstate.isconfirmed, barstate.islast |
Comparing the candle's opening time to detect a new candle |
| Missing values | na as a separate state that propagates |
No counterpart — empty buffers must be checked explicitly |
| Position size | in strategy() as a percentage or number of units |
Lots, normalised to the broker's minimum size and step |
| Costs | Flat commission and slippage in the strategy settings | Real spreads, commission, swap and execution delay |
| Execution | Idealised strategy tester | Real orders with rejections, requotes, minimum distances and partial fills |
Add to this different default values of indicators with the same name, different price data from providers and different behaviour during trading breaks. Porting is therefore a technical translation followed by proof.
An example: the same strategy in Pine Script and MQL5
A simple TradingView strategy: enter when two moving averages cross from below, exit when they cross from above.
//@version=6
strategy("EMA cross", overlay = true)
fast = ta.ema(close, 10)
slow = ta.ema(close, 50)
if ta.crossover(fast, slow)
strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
strategy.close("Long")
The same strategy as an Expert Advisor, the way we implement it:
// MQL5: the same strategy as an Expert Advisor
#include <Trade/Trade.mqh>
CTrade trade;
int hFast, hSlow;
datetime lastBar = 0;
int OnInit()
{
hFast = iMA(_Symbol, _Period, 10, 0, MODE_EMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, 50, 0, MODE_EMA, PRICE_CLOSE);
if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE)
return(INIT_FAILED);
trade.SetExpertMagicNumber(4711);
trade.SetTypeFillingBySymbol(_Symbol);
return(INIT_SUCCEEDED);
}
void OnTick()
{
datetime bar = iTime(_Symbol, _Period, 0);
if(bar == lastBar) // decide once per bar, as Pine does
return;
double fast[], slow[];
ArraySetAsSeries(fast, true);
ArraySetAsSeries(slow, true);
if(CopyBuffer(hFast, 0, 1, 2, fast) != 2 || CopyBuffer(hSlow, 0, 1, 2, slow) != 2)
return; // try again on the next tick
lastBar = bar;
bool crossUp = fast[0] > slow[0] && fast[1] <= slow[1]; // ta.crossover
bool crossDown = fast[0] < slow[0] && fast[1] >= slow[1]; // ta.crossunder
bool isLong = PositionSelect(_Symbol)
&& PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY;
if(crossUp && !isLong && !trade.Buy(0.10)) // lots, not 1 contract
Print("Buy failed: ", trade.ResultRetcode());
if(crossDown && isLong && !trade.PositionClose(_Symbol))
Print("Close failed: ", trade.ResultRetcode());
}
What the extra lines are for:
- When the decision is made. By default, a Pine strategy calculates once at the close of each bar and fills the order at the open of the next one.
OnTick(), by contrast, runs on every tick. Without the once-per-bar lock, the Expert Advisor buys as soon as the lines cross briefly during the bar: different entries and more trades than in the TradingView test. - A precisely defined cross.
ta.crossover()requires the fast value to have been less than or equal to the slow one before. Drop the “or equal” and signals go missing when both values are identical on a bar. - Position size. Unless told otherwise, the Pine strategy trades one contract; in MetaTrader it is lots, with the broker's minimum size and step. This is agreed before porting.
- Starting values and price data. Moving averages with memory start from different values on the two platforms, and TradingView uses different price data from your broker. We therefore compare signals after a warm-up period and on comparable data.
Automatic converters often get the syntax of an example like this right, but rarely the moment of decision. If you already have a converted version, we check and correct it; that is often cheaper than porting from scratch. The review with effort estimate is free of charge.
How porting works
The fourth step is decisive. Without comparison against the original, a port is not complete, merely ended.
Review of the script
We look at your Pine Script and check which constructs are critical: higher timeframe access, repainting indicators, evaluation of running candles, built-in functions used without a direct equivalent. The result is an effort estimate with an upper limit.
Clarifying open points
Are decisions made on closed or running candles? Which position size applies? What happens with several simultaneous signals, at the weekend, during trading breaks? Pine Script answers these questions implicitly via its strategy tester — in the terminal they have to be decided explicitly.
Implementation in MQL5
Native structure instead of rebuilding the Pine way of thinking: indicator handles, position logic, handling of rejected orders. On request also MQL4 for MetaTrader 4.
Signal comparison against the original
Both sides run over the same period on comparable price data. The trade lists are then compared: time, direction, size, exit. Deviations are explained — for example by different price sources — or fixed.
Handover with log
Complete, commented .mq5 source code, brief documentation of the input parameters and a log recording every deliberate deviation from the original.
Effort and scope of delivery
Porting is billed by time because the scope depends entirely on the original script. The effort estimate after the review is free of charge and contains an upper limit that will not be exceeded.
| Low effort | Indicators without trading logic, simple strategies with one entry, one exit and standard indicators on one timeframe. |
|---|---|
| Medium effort | Several filters, higher timeframe access, money management, trailing logic, partial exits, custom helper functions. |
| High effort | Repainting constructs that first need to be cleaned up, strategies with several simultaneous positions, arrays and matrices, extensive drawing functions to be rebuilt in the terminal. |
| Rework | Checking and correcting a result that has already been converted by AI. Often considerably cheaper than porting from scratch. |
Included in delivery
- Complete, commented .mq5 source code
- On request, an additional MQL4 version
- Signal comparison against the Pine original
- Porting log with all deliberate deviations
- Brief documentation of the input parameters
- One round of corrections after the acceptance test
Not included
- Changes to the trading logic itself
- Optimising the parameters for MetaTrader
- Guarantee of identical trading results — price data and execution differ between the platforms
- Operation, server provisioning and monitoring
Frequently asked questions about porting
Can't TradingView trade directly?
Via connected brokers, TradingView can trigger orders, but the offering is limited and not intended for fully automated continuous operation. Pine Script is a scripting language for charts: it has no file system, no network access and no real order management. Alerts do keep running on TradingView's servers, but there is no independent order execution with error handling. If you want to trade unattended and independently of the broker, you need a program in the terminal.
What is the difference between a webhook bridge and a real port?
With the bridge, the strategy stays in TradingView and sends alerts via a webhook to a receiving program that executes the orders in MetaTrader. This is quick to implement but permanently depends on TradingView, on your subscription and on an internet connection between both sides. With a port, the logic itself is rebuilt in MQL5; the system then runs independently, can be backtested and is self-contained.
Why does the ported code generate different signals from the original?
Because Pine Script and MQL5 have different execution models. Pine recalculates the entire history on every execution and continuously evaluates the running candle. MQL5 is event-driven. On top of that come different bar indexing, different default values of indicators with the same name, a different treatment of missing values and a fundamentally different order model. Without deliberate alignment, deviations arise that don't stand out in the chart but cost money in live trading.
What does repainting mean and why does it matter when porting?
Repainting means that an indicator changes its values retrospectively as soon as new price data arrives. In TradingView this hardly stands out, because the chart is simply redrawn. A ported system would use these retrospectively improved values in the backtest and thus show results that are unattainable live. That is why, before porting, we check whether the original strategy repaints.
Can an AI tool convert my Pine strategy?
There are now several such tools, and they produce code that compiles without errors. But that is not the same as code that makes the same trading decisions. We are happy to build on an AI-generated result: checking it against the original, correcting the deviations, signal comparison as proof. This is often cheaper than a new development.
Do I keep my Pine source code?
Of course. Your Pine Script remains your property and continues to work unchanged. The port creates an additional version; many clients run both in parallel for a while and compare the signals in live trading.
Is the other direction possible too, i.e. MQL to Pine Script?
Yes. That is less common, but useful if you also want to see a proven trading system as an analysis tool in the TradingView chart. The scope is usually smaller, because only the signal display is needed and no order management.
How long does a port take?
A few days for simple strategies, one to two weeks for extensive ones with several indicators, filters and their own position management. The binding date is stated in the free effort estimate after the script review.
Why does my Expert Advisor trade more often than the strategy in TradingView?
Usually because it decides on every tick. By default, a Pine strategy only calculates at the close of each bar and fills at the open of the next. An Expert Advisor without a once-per-bar lock already reacts to crosses within the bar that have disappeared again by the close. Different price data and indicator starting values add to this. An example with both versions is shown above on this page.
Send us your Pine Script
After the review you receive an effort estimate with an upper limit — free of charge and without obligation. On request we sign a non-disclosure agreement before you send anything.
EA-Programmierung is a service of NordZentrum GmbH & Co. KG, Germany: Expert Advisors, indicators and trading systems for MetaTrader 5 and 4, cTrader, TradingView and ATAS, developed by André Liebetrau, Dipl.-Inf., a development service provider since 2009. Fixed price based on a written specification, complete source code included.
Still undecided whether a port is worth it at all? The comparison TradingView or MetaTrader sets order execution, strategy tester and custom indicators side by side.
Should your script stay on TradingView and be extended there? See TradingView indicator and Pine Script strategy development.