Skip to content

Instantly share code, notes, and snippets.

@Athospd
Created August 24, 2017 02:51
Show Gist options
  • Save Athospd/25f8b9b9196893545ae89d366c30399b to your computer and use it in GitHub Desktop.
Save Athospd/25f8b9b9196893545ae89d366c30399b to your computer and use it in GitHub Desktop.
simple app for track and get notifications on telegram from R about bitcoin prices.
library(stats)
library(tidyverse)
library(httr)
library(jsonlite)
library(telegram)
## Create the bot object
bot <- TGBot$new(token = bot_token('AthosDamianiBot'))
bot$getMe()
bot$getUpdates()
bot$set_default_chat_id('135717240')
safe_fromJSON <- safely(fromJSON, as.numeric(NA))
acompanhar_bitcoin <- function(frequencia = 30) {
load("historico.RData")
ultimo <- tail(historico, 1)
while(TRUE) {
# pega a cotação do bitcoin brasil (BTCBRL) da API do blinktrade
nova_consulta <- safe_fromJSON("https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC")
if("list" %in% class(nova_consulta$result)) {
nova_consulta <- nova_consulta$result %>%
as.tibble %>%
mutate(timestamp = lubridate::now())
print(nova_consulta)
# verifica se alguma coisa mudou desde a ultima consulta de 'frequencia' segundos atrás
if(!identical(nova_consulta %>% select(-timestamp), ultimo %>% select(-timestamp))) {
historico <- bind_rows(historico, nova_consulta)
save(historico, file = "historico.RData")
}
# caso o valor da cotação atinja algum critério, envia uma mensagem via telegram.
if(nova_consulta$buy < 13900 & nova_consulta$last > 13900) {
bot$sendMessage('baixa!')
bot$sendMessage(nova_consulta$buy)
}
# caso o valor da cotação atinja algum critério, envia uma mensagem via telegram.
if(nova_consulta$buy > 14300 & nova_consulta$last < 14300) {
bot$sendMessage('alta!')
bot$sendMessage(nova_consulta$buy)
}
# grafico
p <- ggplot(historico %>%
gather(indicador, valor, high, low, buy, sell, last) %>%
arrange(timestamp %>% desc) %>%
slice(1:5760))+
geom_line(aes(x = timestamp, y = valor, colour = indicador))
print(p)
ultimo <- nova_consulta
}
Sys.sleep(frequencia)
}
}
acompanhar_bitcoin(30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment