Reputation: 557
I'm trying to draw some kind of trend line using highs and lows from cryptocurrencies (CC) prices. First libraries I'm using:
library(tidyverse)
library(reshape2)
library(lubridate)
library(TTR)
library(binancer)
library(plotly)
Since I choose among many CC, I'm using next scheme to achieve some kind of automation. For this example, I use Bitcoin (BTC). The following code will retrieve data for Bitcoin for 4 hours timeframe. I set "horas" to 900 in order to get 225 observations:
nombre <- "BTC"
tiempo <- "4h"
horas <- 900
data <- binance_klines(paste0(nombre,"USDT"), interval = paste0(tiempo),
start_time=Sys.time()-hours(paste0(as.numeric(horas))), end_time=Sys.time())%>%
select(open_time, open, high, low, close, volume, trades)%>%
rename(time=1)
Next I get lows and highs to use this data for drawing the lines I want. As you can see, I choose exactly two points for either highs and lows:
lows <- arrange(data, low)%>%
slice(c(which.min(low), which.max(low)))%>%
arrange(time)
highs <- arrange(data, high)%>%
slice(c(which.max(high), which.min(high)))%>%
arrange(time)
And I also add some simple moving averages (SMA). My sma database is the source for my plot:
data%>%
mutate(SMA_5= SMA(close, 5), SMA_10= SMA(close,10), SMA_20= SMA(close,20)) -> sma
I'm trying to use add_segments to draw the line I want for lows (if this works I'll use same code for highs) but I got some error:
sma %>% plot_ly(x = ~time, type="candlestick",
open = ~open, close = ~close,
high = ~high, low = ~low) %>%
add_lines(x = ~time, y= ~SMA_5, line = list(color = "gold", width = 2), inherit = F,
name = "SMA 5", showlegend=T)%>%
add_lines(x = ~time, y= ~SMA_10, line = list(color = "deeppink", width = 2), inherit = F,
name = "SMA 10", showlegend=T)%>%
add_lines(x = ~time, y= ~SMA_20, line = list(color = "purple", width = 2), inherit = F,
name = "SMA 20", showlegend=T)%>%
add_segments(
x = ~lows[1,1], xend = ~lows[2,1],
y = ~lows[1,4], yend = ~lows[2,4], color="black")%>%
plotly::layout(title = paste0(nombre, " Simple Moving Average, ", tiempo),
xaxis= list(title="Time", rangeslider = list(visible = F)), yaxis = list(title = "Price"),
sliders=list(visible=F)) -> sma_plot
sma_plot
Error in `*tmp*`[[jj]] : subscript out of bounds
Any idea on what I'm doing wrong? Any feedback will be highly appreciated.
Upvotes: 1
Views: 844
Reputation: 18714
If you are trying to draw a line between the two coordinates, just use the same pattern you used with the other lines.
add_lines(inherit = F, data = lows, x = ~time, y = ~low,
name = "Lows, line = list(color = "black"))
Upvotes: 2