Example of CandleStick chart in R using PlotLy

Created a video showing an example of creating Candlestick chart in R using Plotly library:

Here is the code used in the video:

library(tidyverse)
library(httr)
library(jsonlite)
library(plotly)

# Url to get 5m XBTUSD data from BitMex
url <- "https://www.bitmex.com/api/v1/trade/bucketed?binSize=5m&amp;partial=false&amp;symbol=XBTUSD&amp;count=200&amp;reverse=true"

# Parse data to data frame
xbt <- fromJSON(content(GET(url), as = "text"))

# Clean data frame and calculate EMA and RSI indicators
xbt <- xbt %>%
 select(timestamp, symbol, open, high, low, close, volume) %>% 
 mutate(timestamp = as.POSIXct(timestamp, format = "%Y-%m-%dT%H:%M:%OS")) %>%
 arrange(timestamp) %>%
 mutate(
     ema = TTR::EMA(close, 10),
     rsi = TTR::RSI(close, 10)
 )

# Check data frame
head(xbt, 20)

# Plot Candlestick chart and same to variable
p1 <- xbt %>% plot_ly(
  type = "candlestick",
  x = ~timestamp, 
  open = ~open, high = ~high, low = ~low, close = ~close,
    name = "candles"
) %>%
add_lines(x = ~timestamp, y = ~ema, inherit = F, line = list(color = "red", width = 2), name = "EMA") %>%
layout(title = "XBTUSD 5m", xaxis = list(rangeslider = list(visible = F)))

# Plot RSI as separate plot
p2 <- xbt %>% plot_ly(
  type = "scatter", mode = "lines", 
   x = ~timestamp,  y = ~rsi, name = "RSI")

# Join 2 plots together with the same X axis
subplot(p1, p2, nrows = 2, shareX = T, heights = c(0.7, 0.3))

Here is how plot looks:

Leave a Reply

Your email address will not be published. Required fields are marked *