How to plot Higher time frame indicator using end-of-day value of Lower time frame indicator ? [Pine Script] /[Tradingview] - trading

I have written a script (Pine script / Tradingview) like this :
//#version=5
indicator("Normalized (ATR - wise) Relative strength of a stock compared to an index (daily close comparison)", "Normalized (ATR - wise) Relative strength of a stock",precision = 2)
//Input
comparativeTickerId = input.symbol("VNINDEX",title = "Comparative Symbol" )
smoothing = input.string(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
lengthFastMA = input.int(5,minval=1, title="Fast MA")
lengthSlowMA = input.int(25,minval=1, title="Slow MA")
//Calculation
baseSymbol = request.security(syminfo.tickerid, "60", close)
fixSymbolBar = request.security(syminfo.tickerid, "D", close[1],barmerge.gaps_off, barmerge.lookahead_on)
atr_baseSymbol = request.security(syminfo.tickerid, "60", ta.atr(25))
normalizeSymbolBar = (baseSymbol-fixSymbolBar)/atr_baseSymbol
comparativeSymbol = request.security(comparativeTickerId, "60", close)
fixComparativeSymbolbar = request.security(comparativeTickerId, "D", close[1],barmerge.gaps_off, barmerge.lookahead_on) // correct
atrComparativeSymbol = request.security(comparativeTickerId,"60",ta.atr(25))
normalizeComparativeSymbol = (comparativeSymbol - fixComparativeSymbolbar)/atrComparativeSymbol
ma_function(source, length) =>
switch smoothing
"RMA" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
=> ta.wma(source, length)
res = (normalizeSymbolBar - normalizeComparativeSymbol)*100
//plot
plot(res,style = plot.style_columns, color = res > 0 ? color.blue : color.orange)
plot(ma_function(res,lengthFastMA), color = ma_function(res,lengthFastMA) > 0 ? #0c5847 : color.red, title = "Fast MA", linewidth = 2)
plot(ma_function(res,lengthSlowMA), style = plot.style_area, title = 'Slow MA', color = color.gray)
In short, this indicator calculate the different between the normalized return of a stock compared to that of an index.
Now i want to write an indicator on daily time frame using the end-of-day value of ta.ema(res,lengthFastMA) on 60 mins time frame to plot. For example, lets say the value of ta.ema(res,lengthFastMA) of 23 pm June 30th 2022 bar on 60 mins timeframe is 50, that makes the value of the indicator on daily time frame for June 30th 2022 is 50 too.
Anyone can help on this issue pls?. Thank you so much

my_timeframe = input.timeframe(title="Custom Timeframe", defval="1", group="Strategy parameters")
changed_data = request.security(syminfo.tickerid, my_timeframe, graph_data, gaps=barmerge.gaps_on)
plot(changed_data , title = "Your custom graph", color=color.orange)
For version 5: define timeframe input to allow customize from settings section, request security update with your timeframe that is different than deafult for your view, show graph.

Related

Rounding a Duration to the nearest second based on desired precision

I recently started working with Dart, and was trying to format a countdown clock with numbers in a per-second precision.
When counting down time, there's often a precise-yet-imperfect way of representing the time - so if I started a Duration at 2 minutes, and asked to show the current time after one second has elapsed, it is almost guaranteed that the precision of the timer will report at 1:58:999999 (example), and if use Duration.inSeconds() to emit the value, it will be 118 (seconds) which is due to how the ~/ operator works, since it's rounding down to integers based on the Duration's microseconds.
If I render the value as a clock, I'll see the clock go from "2:00" to "1:58" after one second, and will end up displaying "0:00" twice, until the countdown is truly at 0:00:00.
As a human, this appears like the clock is skipping, so I figured since the delta is so small, I should round up to the nearest second, and that would be accurate enough for a countdown timer, and handle the slight imprecision measured in micro/milli-seconds to better serve the viewer.
I came up with this secondRounder approach:
Duration secondRounder(Duration duration) {
int roundedDuration;
if (duration.inMilliseconds > (duration.inSeconds * 1000)) {
roundedDuration = duration.inSeconds + 1;
} else {
roundedDuration = duration.inSeconds;
}
return new Duration(seconds: roundedDuration);
}
This can also be run in this DartPad: https://dartpad.dartlang.org/2a08161c5f889e018938316237c0e810
As I'm yet unfamiliar with all of the methods, I've read through a lot of the docs, and this is the best I've come up with so far. I think I was looking for a method that might looks like:
roundedDuration = duration.ceil(nearest: millisecond)
Is there a better way to go about solving this that I haven't figured out yet?
You can "add" your own method to Duration as an extension method:
extension RoundDurationExtension on Duration {
/// Rounds the time of this duration up to the nearest multiple of [to].
Duration ceil(Duration to) {
int us = this.inMicroseconds;
int toUs = to.inMicroseconds.abs(); // Ignore if [to] is negative.
int mod = us % toUs;
if (mod != 0) {
return Duration(microseconds: us - mod + toUs);
}
return this;
}
}
That should allow you to write myDuration = myDuration.ceil(Duration(seconds: 1)); and round the myDuration up to the nearest second.
The best solution according to the documentation is to use .toStringAsFixed() function
https://api.dart.dev/stable/2.4.0/dart-core/num/toStringAsFixed.html
Examples from the Documentation
1.toStringAsFixed(3); // 1.000
(4321.12345678).toStringAsFixed(3); // 4321.123
(4321.12345678).toStringAsFixed(5); // 4321.12346
123456789012345678901.toStringAsFixed(3); // 123456789012345683968.000
1000000000000000000000.toStringAsFixed(3); // 1e+21
5.25.toStringAsFixed(0); // 5
Another more flexible option can be...
You can use this function to roundup the time.
DateTime alignDateTime(DateTime dt, Duration alignment,
[bool roundUp = false]) {
assert(alignment >= Duration.zero);
if (alignment == Duration.zero) return dt;
final correction = Duration(
days: 0,
hours: alignment.inDays > 0
? dt.hour
: alignment.inHours > 0
? dt.hour % alignment.inHours
: 0,
minutes: alignment.inHours > 0
? dt.minute
: alignment.inMinutes > 0
? dt.minute % alignment.inMinutes
: 0,
seconds: alignment.inMinutes > 0
? dt.second
: alignment.inSeconds > 0
? dt.second % alignment.inSeconds
: 0,
milliseconds: alignment.inSeconds > 0
? dt.millisecond
: alignment.inMilliseconds > 0
? dt.millisecond % alignment.inMilliseconds
: 0,
microseconds: alignment.inMilliseconds > 0 ? dt.microsecond : 0);
if (correction == Duration.zero) return dt;
final corrected = dt.subtract(correction);
final result = roundUp ? corrected.add(alignment) : corrected;
return result;
}
and then use it the following way
void main() {
DateTime dt = DateTime.now();
var newDate = alignDateTime(dt,Duration(minutes:30));
print(dt); // prints 2022-01-07 15:35:56.288
print(newDate); // prints 2022-01-07 15:30:00.000
}

Qlikview Format textbox expression as percentage to 3 decimal places

I am trying to show percentage increase / decrease based on week number for 2018 v 2019 with an expression in a textbox in Qlikview: Here is my expression:
= num(Sum({<Year = {$(=Max(Year))},
Week = {"$(=Week(Today()))"}>}Retail) - Sum({<Year = {$(=Max(Year)-1)},
Week = {"$(=Week(Today()))"}>}Retail)) / num(Sum({<Year = {$(=Max(Year)-1)},
Week = {"$(=Week(Today()))"}>}Retail),'##0 %')
No matter what i try i end up with -0.38877082 etc.
What am i doing wrong?
Please fix parenthesis and formatting:
= num(Sum({}Retail) - Sum({}Retail) / Sum({}Retail),'##,#0.00 %')

Action Script 3.0 from 2.0 Falling Randomly Placed Objects and a countdown timer

Looking for some help on a lesson I teach to my pupils in Flash Animation.
Not overly familiar with the code, I can essentially do this one thing
I have four layers on my animation. Background, snow, timer and action script.
I have the following code on my snow layer (which has a simple oval in white on it)
onClipEvent (load) {
movieWidth=550;
movieHeight=400;
i=1+Math.random()*2;
k = -Math.PI+Math.random()*Math.PI;
this._xscale = this._yscale=50+Math.random()*100;
this._alpha = 60+Math.random()*100;
this._x = -10+Math.random()*movieWidth;
this._y = -10+Math.random()*movieHeight;
}
onClipEvent (enterFrame){
rad += (k/180)*Math.PI;
this._x -= Math.cos(rad);
this._y += i;
if(this._y>=movieHeight){
this._y = -5;
}
if((this._x>=movieWidth) || (this._x<=0)){
this._x = -10+Math.random()*movieWidth;
this._y = -5;
}
}
and this on my action script layer
this.onEnterFrame = function()
{
var today:Date = new Date();
var currentYear = today.getFullYear();
var currentTime = today.getTime();
var targetDate:Date = new Date(currentYear, 11, 25);
var targetTime = targetDate.getTime();
var timeLeft = targetTime - currentTime();
var sec = Math.floor(timeLeft/1000);
var min = Math.floor(sec/60);
var hours = Math.floor(min/60);
var days = Math.floor(hours/24);
sec = String(sec % 60);
if(sec.length < 2){
sec = "0" + sec;
}
min = String(min % 60);
if(min.length < 2){
min = "0" + min;
}
hours = String(hours % 24);
if(hours.length < 2){
hours = "0" + hours;
}
days = String(days)
var counter:String = days + " Days\n" + hours + ":" + min + ":" + sec;
time_txt.text = counter;
}
for (k=0; k<100; k++){
duplicateMovieClip(this.snow, "snow"+k, k);
}
I know this worked previously in AS2, but I have trouble getting it to work.
Currently getting a syntax error which wasn't there when I used an older version
Any help is much appreciated
Thanks
You are using flash player 6 syntax with flash player 5 elements (onClipEvent() handlers assignable to movieclips on the timeline). I don't think one could possibly expect to see something like that now... As it started getting outdated by late 2001, when FP 6 with (almost) fully ECMA262-compliant ActionScript 1.0 emerged.
Anyway, you can compile it after setting File -> Publish Settings... -> Script option to ActionScript 1.0 or ActionScript 2.0. Your code does work this way, I copied and pasted it to make sure. Be carefull to place the onClipEvent() code on the snow clip and not on the timeline frame. This is the FP5 way of handling events. And the rest of the code goes to timeline frame (I guess this is what you did).
You may also need to change target Flash Player version in case your IDE doesn't allow you to set script version to 1.0 without that (with Flash Pro CS6 this is not the case).
Working example (open in CS5 or newer): snowCS5.fla

rCharts - highcharts speed

General question on the speed of (rCharts) highcharts rendering.
Given the following code
rm(list = ls())
require(rCharts)
set.seed(2)
time_stamp<-seq(from=as.POSIXct("2014-05-20 01:00",tz=""),to=as.POSIXct("2014-05-22 20:00",tz=""),by="1 min")
Data1<-abs(rnorm(length(time_stamp))*50)
Data2<-rnorm(length(time_stamp))
time<-as.numeric(time_stamp)*1000
CombData=data.frame(time,Data1,Data2)
CombData$Data1=round(CombData$Data1,2);CombData$Data2=round(CombData$Data2,2);
HCGraph <- Highcharts$new()
HCGraph$yAxis(list(list(title = list(text = 'Data1')),
list(title = list(text = 'Data2'),
opposite =TRUE)))
HCGraph$series(data = toJSONArray2(CombData[,c('time','Data1')], json = F, names = F),enableMouseTracking=FALSE,shadow=FALSE,name = "Data1",type = "line")
HCGraph$series(data = toJSONArray2(CombData[,c('time','Data2')], json = F, names = F),enableMouseTracking=FALSE,shadow=FALSE,name = "Data2",type = "line",yAxis=1)
HCGraph$xAxis(type = "datetime"); HCGraph$chart(zoomType = "x")
HCGraph$plotOptions(column=list(animation=FALSE),shadow=FALSE,line=list(marker=list(enabled=FALSE)));
HCGraph
Produces a highcharts graph of 2 series each 4021 points in length and renders immediately.
However, if I increase the timespan to say 10 days (8341 points) the resulting plot can take several minutes to generate.
I'm aware there are several modifications that can be made to highcharts for better performance,
Highcharts Performance Enhancement Method?,
however, are there any changes I can make from an R / rCharts perspective to speed up performance?
Cheers

Highcharts - Keep Zero Centered on Y-Axis with Negative Values

I have an area chart with negative values. Nothing insanely different from the example they give, but there's one twist: I'd like to keep zero centered on the Y axis.
I know this can be achieved by setting the yAxis.max to some value n and yAxis.min to −n, with n representing the absolute value of either the peak of the chart or the trough, whichever is larger (as in this fiddle). However, my data is dynamic, so I don't know ahead of time what n needs to be.
I'm relatively new to Highcharts, so it's possible I'm missing a way to do this through configuration and let Highcharts take care of it for me, but it's looking like I'll need to use Javascript to manually adjust the y axis myself when the page loads, and as new data comes in.
Is there an easy, configuration-driven way to keep zero centered on the Y axis?
I ended up finding a way to do this through configuration after digging even further into the Highcharts API. Each axis has a configuration option called tickPositioner for which you provide a function which returns an array. This array contains the exact values where you want ticks to appear on the axis. Here is my new tickPositioner configuration, which places five ticks on my Y axis, with zero neatly in the middle and the max at both extremes :
yAxis: {
tickPositioner: function () {
var maxDeviation = Math.ceil(Math.max(Math.abs(this.dataMax), Math.abs(this.dataMin)));
var halfMaxDeviation = Math.ceil(maxDeviation / 2);
return [-maxDeviation, -halfMaxDeviation, 0, halfMaxDeviation, maxDeviation];
},
...
}
I know this is an old post, but thought I would post my solution anyway (which is inspired from the one macserv suggested above in the accepted answer) as it may help others who are looking for a similar solution:
tickPositioner: function (min, max) {
var maxDeviation = Math.ceil(Math.max(Math.abs(this.dataMax), Math.abs(this.dataMin)));
return this.getLinearTickPositions(this.tickInterval, -maxDeviation, maxDeviation);
}
You can do this with the getExtremes and setExtremes methods
http://api.highcharts.com/highcharts#Axis.getExtremes%28%29
http://api.highcharts.com/highcharts#Axis.setExtremes%28%29
example:
http://jsfiddle.net/jlbriggs/j3NTM/1/
var ext = chart.yAxis[0].getExtremes();
Here is my solution. The nice thing about this is that you can maintain the tickInterval.
tickPositioner(min, max) {
let { tickPositions, tickInterval } = this;
tickPositions = _.map(tickPositions, (tickPos) => Math.abs(tickPos));
tickPositions = tickPositions.sort((a, b) => (b - a));
const maxTickPosition = _.first(tickPositions);
let minTickPosition = maxTickPosition * -1;
let newTickPositions = [];
while (minTickPosition <= maxTickPosition) {
newTickPositions.push(minTickPosition);
minTickPosition += tickInterval;
}
return newTickPositions;
}
Just in case someone is searching,
One option more. I ended up in a similar situation. Follows my solution:
tickPositioner: function () {
var dataMin,
dataMax = this.dataMax;
var positivePositions = [], negativePositions = [];
if(this.dataMin<0) dataMin = this.dataMin*-1;
if(this.dataMax<0) dataMax = this.dataMax*-1;
for (var i = 0; i <= (dataMin)+10; i+=10) {
negativePositions.push(i*-1)
}
negativePositions.reverse().pop();
for (var i = 0; i <= (dataMax)+10; i+=10) {
positivePositions.push(i)
}
return negativePositions.concat(positivePositions);
},
http://jsfiddle.net/j3NTM/21/
It is an old question but recently I have had the same problem, and here is my solution which might be generalized:
const TICK_PRECISION = 2;
const AXIS_MAX_EXPAND_RATE = 1.2;
function setAxisTicks(axis, tickCount) {
// first you calc the max from the data, then multiply with 1.1 or 1.2
// which can expand the max a little, in order to leave some space from the bottom/top to the max value.
// toPrecision decide the significant number.
let maxDeviation = (Math.max(Math.abs(axis.dataMax), Math.abs(axis.dataMin)) * AXIS_MAX_EXPAND_RATE).toPrecision(TICK_PRECISION);
// in case it is not a whole number
let wholeMaxDeviation = maxDeviation * 10 ** TICK_PRECISION;
// halfCount will be the tick counts on each side of 0
let halfCount = Math.floor(tickCount / 2);
// look for the nearest larger number which can mod the halfCount
while (wholeMaxDeviation % halfCount != 0) {
wholeMaxDeviation++;
}
// calc the unit tick amount, remember to divide by the precision
let unitTick = (wholeMaxDeviation / halfCount) / 10 ** TICK_PRECISION;
// finally get all ticks
let tickPositions = [];
for (let i = -halfCount; i <= halfCount; i++) {
// there are problems with the precision when multiply a float, make sure no anything like 1.6666666667 in your result
let tick = parseFloat((unitTick * i).toFixed(TICK_PRECISION));
tickPositions.push(tick);
}
return tickPositions;
}
So in your chart axis tickPositioner you may add :
tickPositioner: function () {
return setAxisTicks(this, 7);
},

Resources