Issues compiling simple EMA script for PineScript - pine-script-v5

I am trying to compile this simple script that has two EMA's... when one is above the other, it's shaded in between the EMA's. When they are the opposite, then there is a different color shaded inbetween. When I compile, there are a few issues. I don't know how to find out what version of pinescript I even have, or if I can updated it to V5 or not... Please let me know the issues I'm having to get this compiled correctly, Here is my script for it:
//#version=5
ta=lib.ema
// Define inputs for the first moving average
length1 = input.int(14, minval=1, title="Length 1", group="Settings")
color1 = input("red", title="Color 1", group="Settings")
// Define inputs for the second moving average
length2 = input.int(50, minval=1, title="Length 2", group="Settings")
color2 = input("blue", title="Color 2", group="Settings")
// Define input for the shaded area
fill_color_above = input("green", title="Fill Color Above", group="Settings")
fill_color_below = input("orange", title="Fill Color Below", group="Settings")
// Calculate the first moving average
ema1 = ema(close, length1)
// Calculate the second moving average
ema2 = ema(close, length2)
// Plot the first moving average
plot(ema1, color=color1)
// Plot the second moving average
plot(ema2, color=color2)
// Shade the area between the moving averages
fill(ema1, ema2, color=ema1 > ema2 ? fill_color_above : fill_color_below, transp=70)
I tried compiling and didn't work.

Several issues on your code :
In pinescript, you must decide if it is an indicator or a strategy
In your case it is an indicator, you should write :
indicator("Ema", overlay=true)
You are in the version5 of pinescript. The color are defined by color.thenameofthecolor and and the inputs should hint the type of the waited variable.
color2 = input.color(color.blue, title="Color 2", group="Settings")
The correct code is :
//#version=5
indicator("Ema", overlay=true)
// Define inputs for the first moving average
length1 = input.int(14, minval=1, title="Length 1", group="Settings")
color1 = input.color(color.red, title="Color 1", group="Settings")
// Define inputs for the second moving average
length2 = input.int(50, minval=1, title="Length 2", group="Settings")
color2 = input.color(color.blue, title="Color 2", group="Settings")
// Define input for the shaded area
fill_color_above = input.color(color.green, title="Fill Color Above", group="Settings")
fill_color_below = input.color(color.orange, title="Fill Color Below", group="Settings")
// Calculate the first moving average
ema1 = ta.ema(close, length1)
// Calculate the second moving average
ema2 = ta.ema(close, length2)
// Plot the first moving average
plot1 = plot(ema1, color=color1)
// Plot the second moving average
plot2 = plot(ema2, color=color2)
// Shade the area between the moving averages
fill(plot1, plot2, color=color.new(ema1 > ema2 ? fill_color_above : fill_color_below, transp=70))
You should read this, is it very easy to understand to improve your pinescript coding : https://www.tradingview.com/pine-script-docs/en/v5/primer/First_steps.html

Related

Cannot get the color to work in a biplot from the RDA procedure in Vegan

I have run RDA from Vegan, and cannot generate four different colors in the "sites" on the plot that correspond to the Group trait which really is countries. The problem is colvec[Group] that fails to link up the four colors with the four different countries. I avoided this for the legend by just spelling out the colors for each country, and that worked (produced a legend with the correct colors for the country). When I take out the col = colvec[Group], the plot does produce the points ("sites"), but they all are black in color and do not differentiate the countries. I have been using the suggested code at:
https://fromthebottomoftheheap.net/2012/04/11/customising-vegans-ordination-plots/
Can anyone help suggest a modification that would produce the correct colors in the points (sites)?
Thanks much.
plot(R EDUNENVONLY)
scl <- 2
par(pty="s") #makes plot square
colvec <- c("dark green", "red", "purple", "blue")
Group <- ENVIR$Group
plot(REDUNENVONLY, choices = c(1, 2), type = "n", xlim = c(-1.5, 1.5))
with(ENVIR, points(REDUNENVONLY, display = "sites",
bg = colvec[Group], col = colvec[Group],
scaling = scl, pch = 21))
text(REDUNENVONLY, display="bp", scaling = scl, cex = 1,col=1) # add black arrows
with(ENVIR, legend("topright", legend = c("CCHINA", "JAPAN", "KOREA", "NCHINA"),
col = c("dark green", "red", "purple", "blue"), pch = c(16,16)))
[![Biplot produced from code above](https://i.stack.imgur.com/zTqHW.png)](https://i.stack.imgur.com/zTqHW.png)
[![Biplot without col = colvec[Group] ](https://i.stack.imgur.com/G4XjU.png)](https://i.stack.imgur.com/G4XjU.png)
I have tried various other solutions, and I know ggplot is another possibility, but this would require more learning (I am a novice at R) and surely some simply change to the present code will get this to work.

How to display labels for overlapping polygons with leaflet

I'm trying to display labels of several overlapping polygons but unfortunately only the upper polygons gets a label.
Here is a reproductible example :
poly_a <-st_sf(st_sfc(st_polygon(list(as.matrix(data.frame(lng = c(0, 0.5, 2, 3,0),
lat = c(0, 4, 4, 0,0))))), crs = 4326))%>%
rename(geometry=st_sfc.st_polygon.list.as.matrix.data.frame.lng...c.0..0.5..2..)%>%
mutate(ID= "poly_a")
poly_b <- st_sf(st_sfc(st_polygon(list(as.matrix(data.frame(lng = c(1, 1.5, 1.8,1),
lat = c(2, 3, 2,2))))), crs = 4326))%>%
rename(geometry=st_sfc.st_polygon.list.as.matrix.data.frame.lng...c.1..1.5..1.8..)%>%
mutate(ID= "poly_b")
layer <- rbind(poly_a,poly_b)
pal <- colorFactor(
palette = c("red","green"),
domain = layer$ID)
label <- sprintf(
"<strong>%s",
layer$ID
) %>% lapply(htmltools::HTML)
leaflet(layer) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addPolygons(
fillColor = ~pal(ID),
color="black",
label=label,
opacity = 0.5,
fillOpacity = 0.5)%>%
addLegend("topleft", pal = pal, values = layer$ID,
title = "Legend",
opacity = 0.25)
I would like to see "poly_a, poly_b" when I pass my mouse on the smallest polygon and "poly_a" when it s only on the biggest one.
I saw maybe I could use the plugin "point in polygon" but I don't know how.
Thank you for your help !
Paco

Plot standard deviation lines in Pine Script

I have this pine script I'm using on tradingview to plot a line that is the average of the highs and lows of a given time period.
I'd like to plot the standard deviation on the chart of this value:
highLowAvg =(sum(maxValue,length_avg) + sum(minValue,length_avg)) / (length_avg*2)
Is there an easy way to do this? Below is the whole script.
//Fill Arrays with latest LOWS/HIGHS
//Get highest HIGH and lowest LOW values from the arrays.
//Do Average between X highest highs and X lowest lows and plot line (Length can be modified)
//If price LOW is above line, Up Trending (Green) (Source can be modified)
//If price HIGH is below line, Down Trending (Red) (Source can be modified)
//If neither above, slow down in trend / reversal might occur (White)
study("Low - High Simple Tracker",overlay=true)
////==================Inputs
length = input(8)
length_avg = input(8)
up_Trend_Condition = input(high)
down_Trend_Condition = input(low)
stdev = stdev(highLowAvg, length)
////==================Array setup and calculations
lowArray = array.new_float(0)
highArray = array.new_float(0)
//Fill Lows to an array
for i = 0 to length-1
array.push(highArray,high[i])
//Fill Highs to an array
for i = 0 to length-1
array.push(lowArray,low[i])
//Get the highest value from the high array
maxValue= array.max(highArray)
//Get the lowest value from the low array
minValue= array.min(lowArray)
//Average between highest and lowest (length can be modifed)
highLowAvg =(sum(maxValue,length_avg) + sum(minValue,length_avg)) / (length_avg*2)
////////==================Plotting
colorHL = down_Trend_Condition > highLowAvg ? color.green : up_Trend_Condition < highLowAvg ?
color.red : color.white
plot(highLowAvg, color =colorHL, style = plot.style_line, linewidth = 2)

Merging neighboring connected components with different labels

Consider the following image:
On the left, let's say I have 3 labels. The background = 1, the black = 2, the orange = 3. What I want to do is be able to first identify all connected components that are orange, then if there are black objects touching the orange, then I'd like to convert this to orange as well.
I know the following steps:
Assume the labeled image is called labeled. I do orange = labeled == 3
CC = bwconncomp(orange);
But from here, I'm not sure how I can check if any of the black components are touching the orange. Once I know which black components are touching the orange, I can do the following: RP = regionprops(black, 'PixelIdxList'); labeled(RP(index).PixelIdxList) = 3;
To test code: here is an example input and output generation:
%input matrix
I = zeros([8 8]);
I(1:5, 1:5) = 1;
I(2:4, 3:7) = 2;
I(7:8, 1:2) = 1;
I(7:8, 7:8) = 2;
I
%output
O = zeros([8 8]);
O(1:5, 1:5) = 1;
O(2:4, 3:7) = 1;
O(7:8, 1:2) = 1;
O(7:8, 7:8) = 2;
O
You can do it as follows. Let target denote the target value, corresponding to orange.
Identify regions defined as connected components without regard to color, using bwlabel.
For each region, if it contains at least a pixel equal to target, set the whole region to target.
target = 1; % value corresponding to orange
O = I;
[regions, numRegions] = bwlabel(I);
for regionId = 1:numRegions
ind = regions==regionId;
if any(I(ind)==target)
O(ind) = target;
end
end
This can be quite simply solved using imreconstruct. This function, for binary (logical) inputs, does a flood fill. The idea is to find an mask image (the orange and the black regions together) and a marker (or seed) image (the orange regions).
As a demo, let's start with what OP already has:
orig = readim('https://i.stack.imgur.com/rH7yT.png');
labeled = uint8(round((255-orig{2}(0:866,:))/127));
orange = labeled==1; % for OP this is 3
black = labeled==2; % for OP this is 2 also
(Note that labeled is not identical to the one that OP has, the numbers for each label are different.)
Now we can apply imreconstruct:
black_or_orange = orange | black;
output = imreconstruct(orange,black_or_orange);
output now contains the orange regions, grown to encompass any touching black regions. We can create a new labeled image as follows:
new_labeled = uint8(output) + 2*uint8(black & ~output);

How to choose correct value range of green colour from histogram charts

I tried to segment just leaves from plant image. I spend 2 weeks googling about how to extract correct range value for green colour from the histogram of the hue, saturation and value colour space. I used the following codes:
hsv=rgb2hsv(INSUM);
H1=hsv(:,:,1);
figure, imshow(H1);
H2=hsv(:,:,2);
figure, imshow(H2);
H3=hsv(:,:,3);
figure, imshow(H3)
H1(H1(:)==0)=[];
H2(H2(:)==0)=[];
H3(H3(:)==0)=[];
figure,imhist(H1);
figure,imhist(H2);
figure,imhist(H3);
limitUpperH = 0.3; limitLowerH = 0.19;
limitUpperS = 1; limitLowerS = 0.95;
limitUpperV = 0.6; limitLowerV = 0.02;
LOGICH = (hsv(:,:,1)<limitUpperH) & (hsv(:,:,1)>limitLowerH);
LOGICS = (hsv(:,:,2)<limitUpperS) & (hsv(:,:,2)>limitLowerS);
LOGICV = (hsv(:,:,3)<limitUpperV) & (hsv(:,:,3)>limitLowerV);
LOGIC = LOGICH & LOGICS & LOGICV;
figure() imshow(LOGIC);
I choose the limitUpper and limitLower for the H, S and V works for just one image by trial and error and they give good result for just one image, but when I apply these values on other images it doesn’t work.
I read many things and saw many examples about the HSV and image histogram but none say how to extract green range of h, s and v from histogram chart. Can any one help me?