Pine Script V5 plotting daily timeframe open price on 5 min chart - timezone

I would like to plot the open price from daily timeframe on my 5 minute timeframe chart with the below codes. Turned out the open rice from previous day is plotted.
//#version=5
indicator("My script", overlay=true)
o = request.security(syminfo.ticker, "D", open)
plot(o)

You don't need security for that. You can simply use the time() to see if it is a new day and store the open price in a var variable. This way, your script will be more efficient.
var float daily_open = na
is_new_day = ta.change(time("D"))
daily_open := is_new_day ? open : daily_open // Update the price when it is a new day, keep its value otherwise
plot(daily_open)
If you really want to use the security(), you should add barmerge.lookahead_on.
o = request.security(syminfo.ticker, "D", open, lookahead=barmerge.lookahead_on)

Related

How to convert time format to a number format (Google Sheets/Data Studio)

I want to convert the numbers in ColA to normal numbers, like the ones I have in ColB. The one in ColA currently are in this format: 00:56:00.000. I initially started out with a time length, that I then converted to seconds (what's currently in ColA). I need to convert them back into a single number to import into Data Studio so it can read it as time. If I try to change the formatting to a number it comes up as a decimal, how can I change the format to a number? Or can I do it in Data Studio?
https://docs.google.com/spreadsheets/d/1xaAfc6hcFJJ1JsPfrx9Ly3usfljuzELT80UsgSxcNM8/edit#gid=0
Try this on col B3 on Google Sheets while A3:A is converted into number format (in decimals):
=Arrayformula((A3:A*3600)*24)
Output:
Explanation:
This is just an observation, but it seems that Google Data Studio strictly follows the formatting of the cell values. If you want to read the seconds as integers, a few arithmetic operations was performed to convert the number formatting of duration as such presented above.
Apps Script (use this if removing helper column B):
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data = ss.getRange('A3:A').getValues();
Logger.log(data);
var second = 3600;
var hour = 24;
var output = data.map(x => [x[0] * second * hour]);
ss.getActiveSheet().getRange(3, 1, output.length, output[0].length).setValues(output);
}
Output:
Change format to seconds only.

iMA not displaying correctly in backtesting

I developed and started testing an EA in MQL4 that uses iMA function. Basically the program compares the iMA value of the current candle with the iMA value of the previous candle. When I test the EA using the Strategy Tester (Every Tick) my EA is not opening and closing trades correctly. What I mean is the trade does not open on the correct candle. Upon further investigating I noticed, on the current candle the value for iMA in the data window and chart are the same, but they difer from the 'Print' value. The value for the previous candle is correct. When I did a Google search I found that someone in 2008 reported this exact same issue. In 2008 there didn't appear to be a solution.
Now that we are in a new decade, I'm wondering if there is a solution?
Does anyone know if iMA works in MQL5 Strategy Tester?
double MAEMACurrent = iMA(NULL,0,3,0,MODE_EMA,PRICE_CLOSE,0);
double MAEMAPrevious = iMA(NULL,0,3,0,MODE_EMA,PRICE_CLOSE,1);
double MASlowEMACurrent = iMA(NULL,0,10,0,MODE_EMA,PRICE_CLOSE,0);
double MASlowEMAPrevious = iMA(NULL,0,10,0,MODE_EMA,PRICE_CLOSE,1);
Print("MAEMACurrent " + MAEMACurrent + " MAEMAPrevious " + MAEMAPrevious + " MASlowEMACurrent " + MASlowEMACurrent + " MASlowEMAPrevious " + MASlowEMAPrevious);
Chart & Data Window:
MAEMACurrent: 1.95552
MAEMAPrevious: 1.95572
MASlowEMACurrent: 1.95201
MASlowEMAPrevious: 1.95097
Print Value:
MAEMACurrent: 1.95538
MAEMAPrevious: 1.95572
MASlowEMACurrent: 1.951086
MASlowEMAPrevious: 1.950972
As you can see from the above example the 'Chart & Data Window' values for MAEMACurrent and the MASlowEMACurrent do not match 'Print Value'.
This is the first time that I'm asking a question, so if I've missed something or I am not following the correct protocol for asking a question please let me know.
First, always use the "NormalizeDouble" function to round the values to a proper number of fractions. In your case, if there are just 5 digits after fraction, use the following code to round the values of "MASlowEMACurrent" and "MASlowEMAPrevious" to 5 digits:
double dNormalizedValue = NormalizeDouble(MASlowEMACurrent, 5);
In addition, never compare the value of the in-progress candle on the chart with the values which are returned by the indicator or price functions like (iMA, iClose, etc). Please note that even a very slight time difference could cause differences in the two values. For other candles (in your case the previous candle), since they all have been closed and there are no changes in progress so you can compare the values on the chart with the values returned by the functions. So, iMA is working as expected.

How to calculate 5 minute rolling mean of ATR with Pine script (TradingView)?

In TradingView Pine script, I want to calculate:
ATR taking high, low, close data with a timeperiod of 30 minutes
5 minute rolling mean of ATR
In Python, I do this:
# Calculate the Average True Range(ATR)
df_indicator['ATR'] = talib.ATR(df_indicator['high'], df_indicator['low'], df_indicator['close'], timeperiod=30)
# Calculate the rolling mean of ATR
df_indicator['ATR_MA_5'] = df_indicator['ATR'].rolling(5).mean()
How can I do this in TradingView Pine script?
Pine has a built-in function atr().
To get the value atr for the current symbol on the current timeframe with a length of 30, use atr(30).
To get the value atr for the current symbol on the timeframe 5 minute with a length of 30, use security(syminfo.ticker, "5", atr(30)).

Plotting time series + offset not working

I want to plot two time series that are in different formats in the
same format, but one of those two doesn't work for me.
So here's the thing:
I have a time series in seconds with a given starting time t0.
So the series looks like this:
Starting time: t0
0 -21.0028
5 -21.0067
10 -21.007
...
17875 -20.9943
I want to plot this time series with the time (e.g. 9:03) instead
of seconds and I want to show another time series where the
data is given in standard time in the same plot.
I can plot the second series just fine.
But when I try to plot the first series, the measured points
start jumping from x=100 back to 0 and then back and forth.
Additionally I can't add the offset t0 to the series.
Here's what I tried (t0 = 32615s) to get at least the first time series plotted:
gnuplot> set xdata time
gnuplot> set timefmt "%S"
gnuplot> set format x "%H:%M"
gnuplot> plot 'measurement.dat' u (timecolumn(1)+32615):2 w l, 'measurement2.dat" u 1:2 w l
Does anyone know how I can plot these time series?
Thanks in advance!
My understanding of your problem is that you have two data sets with different timedata. One in seconds and the other what you call "standard", I assume, e.g. 09:03:00.
And you want to shift the one with seconds by some value.
Internally, dates and times are stored as seconds from January 1st 1970 00:00:00.
Since the first dataset is already in seconds just add your shift-value.
You need to convert ´$Data2´ into seconds via timecolumn(1,"%H:%M:%S").
And the way you display the xtic labels is set via set format x "%H:%M" time. Also check help timecolumn. It also depends if you want to display a time of the day, i.e. 00:00 to 23:59 or if you want to display hours >24h. Then you might want to use "%tH:%tM:%tS"as format. Check help time_specifiers.
Code:
### shifted time data
reset session
# create some test data
set print $Data1
do for [i=1:20000:200] {
print sprintf("%d %.3f",i,sin(i/2000.))
}
set print
set print $Data2
do for [i=30000:50000:200] {
print sprintf("%s %.3f",strftime("%H:%M:%S",i),2*sin(i/2000.-2.5))
}
set print
set format x "%H:%M" time
set key top center
set multiplot layout 2,1
plot $Data1 u 1:2 w lp ti "Data1", \
$Data2 u (timecolumn(1,"%H:%M:%S")):2 w lp ti "Data2"
t0 = 30000
plot $Data1 u ($1+t0):2 w lp ti "shifted Data1", \
$Data2 u (timecolumn(1,"%H:%M:%S")):2 w lp title "Data2"
unset multiplot
### end of code
Result:

How to get OHLC prices for a historic bar in MQL4?

I'm getting a bit stuck with a piece of mql4 code. Esentially, I need to access and store the OHLC prices of a historic bar back in time maximum 30 days back from current date. This is how I am currently doing it.
input int referenceDay=1;
static double reference;
if ( Day() == referenceDay ) reference = Open[0];
This is working fine until the point I either add to the code which, it then resets the reference back to 0. I am looking for a way to be able to access the history on each new candle and store the price for the referenceDay.
The objective is that whenever the EA is loaded to the chart, it automatically goes into the history and updates the reference price to be used on this trading day without having to wait for the entire month's iteration in real time.
The objective is that whenever the EA is loaded to the chart, it automatically goes into the history and updates the reference price
So far so good.
Once EA gets loaded,
the definition of static double reference; sets the initial value of reference == 0.;
next, the call to Day() sets the rules:
int Day(); returns the current day of the month, which is not the "today"'s-day, but the day of month of the so called last known server time. Given the EA was loaded on Sunday afternoon, or Monday morning, before the Market was opened, the "last known server time" is still Friday ... remember, the Server-side datetime rules ( so, if trading on APAC or Australia / New Zealand TimeZone servers, additional gymnastics are in place ).
So, as the code continues - in all such cases, when the input int referenceDay value will accidentally != the last known server time Day(), your ( just ) initialised variable reference will remain == 0.
Surprised?
May test it:
static double reference = EMPTY; // .SET EXPLICIT INITIALISER
if ( Day() == referenceDay )
{ reference = Open[0];
print( reference,
"AFTER Day() MATCHED referenceDay" // THIS NEED NOT HAPPEN
);
}
else
{ print( reference,
"ON( ",Day(), " ) ",
"AFTER Day() DID NOT MATCH referenceDay = ",
referenceDay
}
May redefine the assignment strategy, using:
input int referenceDAYinput = 1;
int referenceDAYnDaysBACK = max( 0, // FUSED
Day() - referenceDAYinput
);
static double referenceLEVEL = iOpen( _Symbol,
PERIOD_D1,
referenceDAYnDaysBACK
);
This code snippet certainly does not strive to be the complete solution, but shows the mechanics for achieving the desired objective.
Your actual code will have to solve how many Trading days - which is needed to address the TimeSeries-indexing logic of MetaTrader Terminal 4 platofrm -- ( not just the Calendar days ) -- there were in between the referenceDAYinput and the "last known server time"-Day(), but your are this close to have this done.

Resources