How to make global variable in pinescript(Tradingview) - variables

I am working on creating a trend indicator in tradingview to track which way the trend is going. Specifically, I want a variable that will stay the same over days, but when a certain condition is met it will change. It seems like it should be simple to do, but everytime I try I get thrown into a never ending loop and I can't seem to wrap my head around it. Variable "Trend"
///Condition
pos = close > open
neg = close < open
pos_cond = pos and pos[1]
neg_cond = neg and neg[1]
///Variables to keep track of trend
Trend = iff(***pos_cond or neg_cond not met***, Trend[1], Trend + real_trend)
trend_change_neg = iff(pos_cond, 1, 0)
trend_change_pos = iff(neg_cond, -1, 0)
real_trend = trend_change_neg + trend_change_pos
Trend = iff(Trend > 2, 2, iff(Trend < -2, -2, Trend))
/////////plots
plotshape(Trend > 0, color = color.green, location = location.top, style = shape.square, title="TrendLong")
plotshape( Trend == 0, color = color.yellow, location = location.top, style = shape.square, title = "TrendNeutral")
plotshape( Trend < 0, color = color.red, location = location.top, style = shape.square, title = "TrendShort")
So basically what I want to do is keep a running total for Trend where each time there are 2 consecutive candles against the trend it will switch to neutral, but as the trend continues to move in 1 direction it can build back up to +-2 (This was we are never more than 2 "pullbacks" away from neutral. I've racked my brain over this for days now, but if anyone has any ideas any help would be appreciated.

You need to use var.
Example:
var a = 0
a:=close>open?1:0
https://www.tradingview.com/pine-script-docs/en/v4/language/Expressions_declarations_and_statements.html

Related

mplcursors on multiaxis graph

In my program, im using mplcursors on a matplotlib graph so I can identify certain points precisely.
mplcursors.cursor(multiple=True).connect("add", lambda sel: sel.annotation.draggable(False))
Now I made a complex graph with multiple axis:
first = 1
offset = 60
for x in range(len(cat_list)):
if "Time" not in cat_list[x]:
if first and not cat_list[x].startswith("EngineSpeed"):
parasites[x] = ParasiteAxes(host, sharex = host)
host.parasites.append(parasites[x])
parasites[x].axis["right"].set_visible(True)
parasites[x].set_ylabel(cat_list[x])
parasites[x].axis["right"].major_ticklabels.set_visible(True)
parasites[x].axis["right"].label.set_visible(True)
p_plot, = parasites[x].plot(t, t_num_list[x], label = cat_list[x])
#parasites[x].axis["right"+str(x+1)].label.set_color(p_plot.get_color())
parasites[x].axis["right"].label.set_color(p_plot.get_color())
first = 0
elif not cat_list[x].startswith("EngineSpeed"):
parasites[x] = ParasiteAxes(host, sharex = host)
host.parasites.append(parasites[x])
parasites[x].set_ylabel(cat_list[x])
new_axisline = parasites[x].get_grid_helper().new_fixed_axis
parasites[x].axis["right"+str(x+1)] = new_axisline(loc = "right",
axes = parasites[x],
offset = (offset, 0))
p_plot, = parasites[x].plot(t, t_num_list[x])
parasites[x].axis["right"+str(x+1)].label.set_color(p_plot.get_color())
offset = offset + 60
host.legend()
fig.add_axes(host)
plt.show()
This code results in the following graph:
https://i.stack.imgur.com/Wl7yC.png
Now I have to somehow be able to select certain points by selecting which axis im using. How do I make a selection menu for choosing an active axis and how do I then use mplcursors to select my points?
Thanks,
Ziga

Confidence Interval for large dataset

I would like to get a confidence interval for very large datasets. It is composed by around 700,000 points for x and y. I also tried to use less data, like 200 points, and with that it is possible to plot. But, when it comes to my specific datasets, it does not show the confidence interval.
For that, my code is based on:
x_x = np.array(y_test[:, 0]) #about 700,000 points
y_y = np.array(y_pred[:, 0]) #about 700,000 points
sns.set(style = 'whitegrid')
p = sns.FacetGrid(d, size = 4, aspect = 1.5)
p.map(plt.scatter, 'x_x', 'y_y', color = 'red')
p.map(sns.regplot, 'x_x', 'y_y', scatter = False, ci = 95,
fit_reg = True, color = 'blue')
p.map(sns.regplot, 'x_x', 'y_y', scatter = False, ci = 0,
fit_reg = True, color = 'darkgreen')
And also the Figure so far:

Verifying iterative edge insertion in Gremlinpython

Trying to iteratively add vertices and edges. It seems to work, there are no errors, but I wish to verify that the edges are also correctly added.
The loops below insert at least the nodes, as the printing of the list length at the end shows, but the edges are either 1) not inserted, or 2) the way to collect them in a list is incorrect.
Any help is much appreciated!
def vertices01(nodename, rangelb, rangeub, prop1name, prop1val, prop2name):
t = g.addV(nodename).property(prop1name, prop1val).property(prop2name, rangelb)
for i in range(rangelb + 1, rangeub):
t.addV(nodename).property(prop1name, prop1val).property(prop2name, i)
t.iterate()
def edges01(from_propname, from_propval, to_propname, rangelb, rangeub, edge_name, edge_prop1name):
to_propval = rangelb
edge_prop1val = rangelb
t = g.V().has(from_propname, from_propval).as_("a").V().has(to_propname, to_propval).as_("b").addE(edge_name).from_("a").to("b").property(edge_prop1name, edge_prop1val)
for i in range(rangelb, rangeub):
to_propval = i + 1
edge_prop1val = i
# changing this to t.has(...) seems to not influence the results (still 0 picked up by the loop)
t.has(from_propname, from_propval).as_("a").V().has(to_propname, to_propval).as_("b").addE(edge_name).from_("a").to("b").property(edge_prop1name, edge_prop1val)
t.iterate()
vertices01("ABC", 1, 21, "aa01", 1, "bb01")
edges01("aa01", 1, "bb01", 1, 10 , "aa01-to-bb01", "aa01-to-bb01-propX")
ls1 = []
ls1 = g.V().outE("aa01-to-bb01").has("aa01-to-bb01-propX", 2).toList()
print(len(ls1))
ls2 = []
ls2 = g.V().has("aa01", 1).toList()
print(len(ls2))
> results:
0
20
Expected results:
> results:
1
20
EDIT: I have changed this bit in the edges01 loop:
t = g.V().has(from_propname, from_propval) ...
to
t.has(from_propname, from_propval) ...
But the results are still 0.
You are starting the traversal over again each time with t = g.V()... in the code that adds edges. Only the very last traversal created is going to get iterated. In the code that creates the vertices you are extending the traversal. That is the difference.
UPDATED
You should be able to do something along these lines
t = g.V().has('some-property','some-value').as_('a').
V().has('some-property','some-value').as_('b')
and then inside the loop
t.addE('myedge').from_('a').to('b')

How to draw horizontal line from yesterdays high and close points? and how to solve time format? Fill between lines

I'm new here and i want to ask about my work. So I'm using this code for now but result is shown only full horizontal line not from the high from highestbars . How can i draw from exact highest price?
And im using time.session like "0000-0500" but this session in 1 exchange (broker)is different from other
exchanges. So how can I use same Session?
high = security(syminfo.tickerid, 'D', time[1], lookahead = barmerge.lookahead_on)
prevhigh = security(syminfo.tickerid, 'D', high[1], lookahead = barmerge.lookahead_on)
var high_line = line.new(x1 = high, x2 = right(extend_right), y1 = prevhigh, y2 = prevhigh, color = line_color, width = line_width, xloc = xloc.bar_time)
line.set_x1(high_line, high)
And can i fill between 2 lines which drawn by above code?
i used Line.set
Thank you.

Data handling on multiple Heart rate files

I have been collecting the Heart rates of 12 calves who each received an anesthetic through four different routes of administration. I now have 48 txt files of this format:
Time HRbpm
0:00:01.7 97
0:00:02.3 121
0:00:02.8 15
... ...
HR was recorded for around 2hours. The Time column was dependent of the monitor, resulting in inconsistent time intervals between two measures.
The txt files are named as follows: 6133_IM_27.00.txt
With 6133 being the ID, IM the route and 27.00 the time (min:min.s:s) at which the treatment was injected.
My first goal is to have all the HR data so I can do an outlier analysis.
Then, I would like to include all this data in a single data frame that would look like this:
data.frame(ID=c(6133,6133,6133,6133,"...",6134,6134,"..."),
Route = c("IM","IM","IM","IM","...","SC","SC","..."),
time=c(0, 10, 20, 30,"...",0,10,"..."),
HR=c(160, 150, 145, 130,"...",162,158,"..."))
Time column going from 0 to 120 in 10min increments.
Each HR of this df would represent the mean of the HR values for the preceding minute for a given time (e.g. for time = 30, HR would represent the mean between 29 and 30 minutes for a given ID/Route combination).
I'm fairly new to R, so I've been having trouble just knowing by what angle starting on that problem. Any help would be welcome.
Thanks,
Thomas
For anyone who stumbles on this post, here's what I've done, seems to be working.
library(plyr)
library(reshape)
library(ggplot2)
setwd("/directory")
filelist = list.files(pattern = ".*.txt")
datalist = lapply(filelist, read.delim)
for (i in 1:length(datalist))
{datalist[[i]][3] = filelist[i]}
df = do.call("rbind", datalist)
attach(df)
out_lowHR = quantile(HRbpm,0.25)-1.5*IQR(HRbpm)
out_highHR = quantile(HRbpm,0.75)+1.5*IQR(HRbpm) #outliers thresholds: 60 and 200
dfc = subset(df,HRbpm>=60 & HRbpm<=200)
(length(df$HRbpm)-length(dfc$HRbpm))/length(df$HRbpm)*100 #8.6% of values excluded
df = dfc
df$ID = substr(df$V3,4,7)
df$ROA = substr(df$V3,9,11)
df$ti = substr(df$V3,13,17)
df$Time = as.POSIXct(as.character(df$Time), format="%H:%M:%S")
df$ti = as.POSIXct(as.character(df$ti), format="%M.%S")
df$t = as.numeric(df$Time-df$ti)
m=60
meanHR = ddply(df, c("ROA","ID"), summarise,
mean0 = mean(HRbpm[t>-60*m & t <=0]),
mean10 = mean(HRbpm[t>9*m & t <=10*m]),
mean20 = mean(HRbpm[t>19*m & t <=20*m]),
mean30 = mean(HRbpm[t>29*m & t <=30*m]),
mean45 = mean(HRbpm[t>44*m & t <=45*m]),
mean60 = mean(HRbpm[t>59*m & t <=60*m]),
mean90 = mean(HRbpm[t>89*m & t <=90*m]),
mean120 = mean(HRbpm[t>119*m & t <=120*m]))
meanHR = melt(meanHR)
meanHR$time = as.numeric(gsub("mean", "", meanHR$variable))
ggplot(meanHR, aes(x = time, y = value, col = ROA))+
geom_smooth()+
theme_classic()