How can a create horizontal line for my bar high on a specified time frame and session of the chart in pine editor - editor

Need help in trading view Pine editor.
How can i Automatically draw an horizontal line based on bar high and low for a specified time frame and session. I need to have a horizontal line drawn for the highest and lowest value of the bar on the 15 minutes time frame chart and exactly for the bar of 9:30 session of Indian time (IST)

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © flashgekko
// https://www.tradingview.com/pine-script-docs/en/v4/essential/Sessions_and_time_functions.html#:~:text=working%20with%20time-,The%20%E2%80%9Ctime%E2%80%9D%20function%20and%20variable,%E2%80%9D%20and%20%E2%80%9CSession%20bars%E2%80%9D
//#version=4
study("Project 002", overlay=true)
var h = high
var l = low
if (high > high[1]) and high >h
h := high
if (low < low[1]) and low <l
l := low
t = time("15","0900-1800")
if na(t[1]) and not na(t) or t[1] <t
l:= low
h:= high
plot(h, color = color.green)
plot(l, color = color.red)

Related

Marking the ATH and ATL in a specific time period at pinescript

Hey guys im struggling with a problem. i want to mark the ATH and ATL in a specific time period. i used this code below but it marks me avery high and low. Is it possible to change this?
//#version=5
indicator('HHLL', overlay=true)
session_time = input.session("0500-0800", "Session")
is_in_session = time(timeframe.period, session_time)
is_new_session = not is_in_session[1] and is_in_session
var float hh = na
var float ll = na
if (is_new_session)
hh := high
ll := low
else if (is_in_session)
if (high > hh)
hh := high
if (low < ll)
ll := low
plot(is_in_session ? hh : na, "HH", color.green, 1, plot.style_circles)
plot(is_in_session ? ll : na, "LL", color.red, 1, plot.style_circles)
Example

Constrain axis limits in chordDiagram (circlize) when making gifs

I hope somebody will be able to help me with this chordDiagram visualisation I am trying to create. I am well aware that maybe this visualization type was not suitable for this particular data, but somehow it was something I had in my head (or how I wanted to visualize this data) and what I wanted to create, and now I think it is too late to give it up :) too curious how one can fix it. It is my first real post here, though I am an active user of stackoverflow and I genuinely admire the audience here.
So I have this data on the change in the size of area in km2 over time (d0) and I am trying to create a GIF out of it using example here: https://guyabel.com/post/animated-directional-chord-diagrams/
The data "d0":
Time <- as.numeric(c(10,10,10,100,100,100,200,200,200,5,5,5,50,50,50,0,0,0))
Year <- as.character(c(2050,2100,2200,2050,2100,2200,2050,2100,2200,2050,2100,2200,2050,2100,2200,2050,2100,2200))
Area_km2 <- as.numeric(c(4.3075211,7.1672926,17.2780622,5.9099250,8.2909189,16.9748961,6.5400554,8.9036313,16.5627228,3.0765610,6.3929883,18.0708108,5.3520782,8.4503856,16.7938196,0.5565978,1.8415855,12.5089476))
(d0 <- as.data.frame(cbind(Time,Year,Area_km2)))
I also have the color codes stored in a separate dataframe (d1) following the above mentioned example.
The data "d1":
year <- as.numeric(c(2050,2100,2200))
order1 <- as.character(c(1,2,3))
col1 <- c("#40A4D8","#33BEB7","#0C5BCE")
(d1 <- as.data.frame(cbind(year,order1,col1)))
So the idea was to have self-linking flows within each sector increasing in size over time, which will look like just growing segments in a final animated GIF (or like growing pie segments), but I noticed that regardless how hard I try I can't seem to manage to constrain the axis of each segment to limits of that particular year in an every single frame. It seems that the axis is being added on and keeps on adding over time, which is not what I want.
Like for example in the first figure (figure0) or "starting frame" the size of the links matches well the dataframe:
figure0
So it is
orig_year
Area_km2
.frame
2050
0.557
0
2100
1.84
0
2200
12.5
0
But when one plots next figure (figure1), the axis seems to have taken the values from the starting frame and added on the current values (4, 7.4 and 19 respectively) instead of (3.08, 6.39 and 18.1) or what should have been the values according the data frame:
figure1
orig_year
Area_km2
.frame
2050
3.08
1
2100
6.39
1
2200
18.1
1
And it keep on doing so as one loops through the data and creates new plots for the next frames. I wonder whether it is possible to constrain the axis and create the visualization in a way that the links just gradually increase over time and the axis is, so to say, following the increase or does also increase gradually following the data???
Any help is highly appreciated!
Thanks.
My code:
Sort decreasing
(d0 <- arrange(d0,Time))
Copy columns
(d0$Dest_year <- d0$Year)
Re-arrange data
library(tweenr)
(d2 <- d0 %>%
mutate(corridor=paste(Year,Dest_year,sep="->")) %>%
dplyr::select(Time,corridor,Area_km2) %>%
mutate(ease="linear") %>%
tweenr::tween_elements('Time','corridor','ease',nframes=30) %>%
tibble::as_tibble())
(d2 <- d2 %>%
separate(col=.group,into=c("orig_year","dest_year"),sep="->") %>%
dplyr::select(orig_year,dest_year,Area_km2,everything()))
d2$Time <- NULL
Create a directory to store the individual plots
dir.create("./plot-gif/")
Fixing scales
scale_gap <- function(Area_km2_m,Area_km2_max,gap_at_max=1,gaps=NULL) {
p <- Area_km2_m/Area_km2_max
if(length(gap_at_max)==1 & !is.null(gaps)) {
gap_at_max <- rep(gap_at_max,gaps)
}
gap_degree <- (360-sum(gap_at_max))*(1-p)
gap_m <- (gap_degree + sum(gap_at_max))/gaps
return(gap_m)
}
Function to derive the size of gaps in each frame for an animated GIF
(d3 <- d2 %>% group_by(orig_year) %>% mutate(gaps=scale_gap(Area_km2_m=Area_km2,Area_km2_max=max(.$Area_km2),gap_at_max=4,gaps=9)))
library(magrittr)
Get the values for axis limits
(axmax <- d2 %>% group_by(orig_year,.frame) %>% mutate(max=mean(Area_km2)))
Creating unique chordDiagrams for each frame
library(circlize)
for(f in unique(d2$.frame)){
png(file=paste0("./plot-gif/figure",f,".png"),height=7,width=7,units="in",res=500)
circos.clear()
par(mar=rep(0,4),cex=1)
circos.par(start.degree=90,track.margin=c(-0.1,0.1),
gap.degree=filter(d3,.frame==f)$gaps,
points.overflow.warning=FALSE)
chordDiagram(x=filter(d2,.frame==f),directional=2,order=d1$year,
grid.col=d1$col1,annotationTrack=c("grid","name","axis"),
transparency=0.25,annotationTrackHeight=c(0.05,0.1),
direction.type=c("diffHeight"),
diffHeight=-0.04,link.sort=TRUE,
xmax=axmax$max)
dev.off()
}
Now make a GIF
library(magick)
img <- image_read(path="./plot-gif/figure0.png")
for(f in unique(d2$.frame)[-1]){
img0 <- image_read(path=paste0("./plot-gif/figure",f,".png"))
img <- c(img,img0)
message(f)
}
img1 <- image_scale(image=img,geometry="720x720")
ani0 <- image_animate(image=img1,fps=10)
image_write(image=ani0,path="./plot-gif/figure.gif")
I will start with your d0 object. I first construct the d0 object but I do not convert everything to characters, just put them as the original numeric format. Also I reorder d0 by Time and Year:
Time = c(10,10,10,100,100,100,200,200,200,5,5,5,50,50,50,0,0,0)
Year = c(2050,2100,2200,2050,2100,2200,2050,2100,2200,2050,2100,2200,2050,2100,2200,2050,2100,2200)
Area_km2 = c(4.3075211,7.1672926,17.2780622,5.9099250,8.2909189,16.9748961,6.5400554,8.9036313,16.5627228,3.0765610,6.3929883,18.0708108,5.3520782,8.4503856,16.7938196,0.5565978,1.8415855,12.5089476)
d0 = data.frame(Time = Time,
Year = Year,
Area_km2 = Area_km2,
Dest_year = Year)
d0 = d0[order(d0$Time, d0$Year), ]
The key thing is to calculate proper values for "gaps" between sectors so that the same unit from data corresponds to the same degree in different plots.
We first calculate the maximal total width of the circular plot:
width = tapply(d0$Area_km2, d0$Time, sum)
max_width = max(width)
We assume there are n sectors (where n = 3 in d0). We let the first n-1 gaps to be 2 degrees and we dynamically adjust the last gap according to the total amount of values in each plot. For the plot with the largest total value, the last gap is also set to 2 degrees.
n = 3
degree_per_unit = (360 - n*2)/max_width
Now degree_per_unit can be shared between multiple plots. Every time we calculate the value for last_gap:
for(t in sort(unique(Time))) {
l = d0$Time == t
d0_current = d0[l, c("Year", "Dest_year", "Area_km2")]
last_gap = 360 - (n-1)*2 - sum(d0_current$Area_km2)*degree_per_unit
circos.par(gap.after = c(rep(2, n-1), last_gap))
chordDiagram(d0_current, grid.col = c("2050" = "red", "2100" = "blue", "2200" = "green"))
circos.clear()
title(paste0("Time = ", t, ", Sum = ", sum(d0_current$Area_km2)))
Sys.sleep(1)
}

How can I obtain this specific series data to calculate time-to-funding-weighted average of premium index?

I'm looking to calculate and plot the funding rate of Binance BTCUSDT Perpetual and have come across the following documentation page: https://www.binance.com/en/support/faq/360033525031
It states:
The Funding Rate formula:
"Funding Rate (F) = Average Premium Index (P) + clamp (interest rate - Premium Index (P), 0.05%, -0.05%)"
I'm obtaining the "Premium Index" just fine, just with "p = request.security("BINANCE:BTCUSDT_PREMIUM", "", close)*100"
However I'm currently struggling with how to obtain the:
"Time-to-funding weighted Average of Premium Index " which apparently is calculated with
"Average Premium Index (P) = (1 * Premium_Index_1 + 2 * Premium_Index_2 + 3 * Premium_Index_3 +···+·480 * Premium_index_480)/(1+2+3+···+480)"
(the funding period for Binance is 8 hours hence the average over 480 minutes)
My exact question is, how do I backtrack to the last funding timestamp of 00:00 / 08:00 / 16:00, then obtain an array / series data of the premium index at each of the last 480 minutes, so that I can then iterate over it to use the above formula for the time weighted average?
Thank you very much for any advice in advance. My apologies if the answer is obvious I'm very new to Pine Script.
I believe you can obtain the time weighted average premium like so:
premium = request.security("BINANCE:BTCUSDT_PREMIUM", "1", close)
new_funding_period = ta.change(time("480")) != 0
var int n = na
var float premium_sum = na
var int n_sum = na
if new_funding_period
n := 1
premium_sum := premium
n_sum := 1
else
n += 1
premium_sum += premium * n
n_sum += n
predicted_TWAP = premium_sum / n_sum
current_TWAP = ta.valuewhen(new_funding_period, predicted_TWAP[1], 0)
However, you are limited to performing the calculation on a 1 minute chart to obtain accurate results due to being unable to reliably retrieve the values from a security call from a lower timeframe when the chart is set to a higher timeframe than 1 minute.

How to efficiently pre-process image for text recognition with tesseract?

How to improve accuracy of character recognition. bellow is the image and the code.
Input image
Image after thresholding
code:
rcz = cv2.resize(img, dsize, fx=1, fy=1, interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(rcz, cv2.COLOR_BGR2GRAY)
bl = cv2.bilateralFilter(gray,9,5,5)
th = cv2.threshold(bl, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
text = pytesseract.image_to_string(th)
output :
5 8EM TDC ECO M*
2018
( November )
ECONOMICS
( Major )
Course : 504
( Monetary Theory and Financial Market }
Full Marks : 80
Pass Marks : 32/24
Time : 3 hours”
The figures in the margin indicate full marks
for the questions
Choose the correct option/Answer the
following : 1*8=8
fa) As per RBI, M2 is composed of
(j M, + all post office deposits
(ii) M,+ time deposits of commercial
banks 5
Ppo/ase (Tusn Ower}

How to split the image into chunks without breaking character - python

I am trying to read image from the text.
I am getting better result if I break the images into small chunks but the problem is when i try to split the image it is cutting/slicing my characters.
code I am using :
from __future__ import division
import math
import os
from PIL import Image
def long_slice(image_path, out_name, outdir, slice_size):
"""slice an image into parts slice_size tall"""
img = Image.open(image_path)
width, height = img.size
upper = 0
left = 0
slices = int(math.ceil(height/slice_size))
count = 1
for slice in range(slices):
#if we are at the end, set the lower bound to be the bottom of the image
if count == slices:
lower = height
else:
lower = int(count * slice_size)
#set the bounding box! The important bit
bbox = (left, upper, width, lower)
working_slice = img.crop(bbox)
upper += slice_size
#save the slice
working_slice.save(os.path.join(outdir, "slice_" + out_name + "_" + str(count)+".png"))
count +=1
if __name__ == '__main__':
#slice_size is the max height of the slices in pixels
long_slice("/python_project/screenshot.png","longcat", os.getcwd(), 100)
Sample Image : The image i want to process
Expected/What i am trying to do :
I want to split every line as separate image without cutting the character
Line 1:
Line 2:
Current result:Characters in the image are cropped
I dont want to cut the image based on pixels since each document will have separate spacing and line width
Thanks
Jk
Here is a solution that finds the brightest rows in the image (i.e., the rows without text) and then splits the image on those rows. So far I have just marked the sections, and am leaving the actual cropping up to you.
The algorithm is as follows:
Find the sum of the luminance (I am just using the red channel) of every pixel in each row
Find the rows with sums that are at least 0.999 (which is the threshold I am using) as bright as the brightest row
Mark those rows
Here is the code that will return a list of these rows:
def find_lightest_rows(img, threshold):
line_luminances = [0] * img.height
for y in range(img.height):
for x in range(img.width):
line_luminances[y] += img.getpixel((x, y))[0]
line_luminances = [x for x in enumerate(line_luminances)]
line_luminances.sort(key=lambda x: -x[1])
lightest_row_luminance = line_luminances[0][1]
lightest_rows = []
for row, lum in line_luminances:
if(lum > lightest_row_luminance * threshold):
lightest_rows.add(row)
return lightest_rows
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ... ]
After colouring these rows red, we have this image:

Resources