How to: New order Binance API via RStudio - r

I am trying to create a new order via the Binance API using RStudio.
I found the Binance Official API Docs and figured out that I should use
POST /api/v3/order (HMAC SHA256).
The following script doesn't work out for me:
url='https://api.binance.com/api/v3/account'
GET(url,
add_headers("X-MBX-APIKEY"= *[my API key]*),
query=list("symbol"="ETHBTC",
"side"="BUY",
"type"="MARKET",
"quantity"=1,
recvWindow=5000,
"timestamp"=1499827319559,
"signature"=**???**),
verbose())
Does anyone know what I'm doing wrong and how I can create an order via the Binance API using RSTUDIO and how I can create my signature?

library(httr)
timestamp <-
as.character(jsonlite::fromJSON(content(
GET("https://api.binance.com/api/v1/time"), "text"
))$serverTime + 999)
query <-
list(
"symbol" = "VENBTC",
"side" = "BUY",
"type" = "MARKET",
"quantity" = 1,
"recvWindow" = 5000,
"timestamp" = timestamp
)
signature <-
digest::hmac(
key = "*[my secret key]*",
object = paste(names(query), query, sep = "=", collapse = "&"),
algo = "sha256"
)
POST(
url,
add_headers("X-MBX-APIKEY" = "*[my API key]*"),
query = c(query, signature = signature),
verbose()
)

Related

getting error when trying post tweet using httr and twitter PIN-based authorization

I am trying to post a new tweet from R using httr. But I am getting the following error:
{"errors":[{"code":32,"message":"Could not authenticate you."}]}
I am using the following code to authorize my app using PIN-based authorization
app <- oauth_app(
app = "",
key = "CONSUMER_KEY",
secret = "CONSUMER_SECRET"
)
create_oauth_signature <- function(url, method, oauth_app, token = NULL, token_secret = NULL, private_key = NULL, ...){
httr::oauth_header(
httr::oauth_signature(
url,
method,
app = oauth_app,
token,
token_secret,
private_key,
other_params = list(...)
)
)
}
get_authorization_url <- function(app, callback, permission = NULL){
response <- POST(
url = "https://api.twitter.com/oauth/request_token",
create_oauth_signature("https://api.twitter.com/oauth/request_token", "POST", app, oauth_callback = callback)
)
stop_for_status(response)
params <- httr::content(
response,
type = "application/x-www-form-urlencoded"
)
authorization_url <- modify_url(
"https://api.twitter.com/oauth/authenticate",
query = list(
oauth_token = params$oauth_token
)
)
return(list(authorization_url, params$oauth_token))
}
get_user_oauth_token <- function(verfier_code, token){
response <- POST(
modify_url(
url = "https://api.twitter.com/oauth/access_token",
query = list(
oauth_verifier = verfier_code,
oauth_token = token
)
)
)
return(response)
}
authUrl <- get_authorization_url(app, callback = "oob")
after this, I get authorization link from authUrl[[1]] and visit the link from my browser. Authorize the app and copy the code. Then use the get_user_oauth_token() to get the token and secret as follows:
token <- get_user_oauth_token("THE_CODE_FROM_TWITTER", authURL[[2]])
token <- content(token, type = "application/x-www-form-urlencoded")
Now I want to use the user's oauth_token and secret to post a tweet. I am following this documentation.
response <- POST(
url = modify_url(
url = "https://api.twitter.com/1.1/statuses/update.json",
query = list(status = "Hello")
),
create_oauth_signature("https://api.twitter.com/1.1/statuses/update.json", "POST", app, token = token$oauth_token, token_secret = token$oauth_token_secret),
content_type("application/json")
)
But I am getting the following error:
$`{"errors":[{"code":32,"message":"Could not authenticate you."}]}`
I am sure that the credentials are valid. Because If I use the same credentials with rtweet::post_tweet() it works just fine.
It would be so helpful if anybody could just point out what I am doing wrong.
Thanks in advance.

Cant fetch all records in Qualtrics API using httr package

I am trying to fetch all my mailinglists contacts using the following custom function, but contact lists didn't download all the records inside them. Idk what I am doing wrong?
get_all_contacts<-function(mailingListID){
directoryId<-"POOL_XXXXXXXXXX"
apiToken<-"XXXXXXXXXX"
fetch_url<- VERB(verb = "GET", url = paste("https://iad1.qualtrics.com/API/v3/directories/", directoryId,
"/mailinglists/",mailingListID ,"/contacts",sep = ""),
add_headers(`X-API-TOKEN` = apiToken), encode = "json")
fetch_url<-content(fetch_url, "parse",encoding = "UTF-8")
fetch_url<-fetch_url$result$nextPage
elements <- list()
while(!is.null(fetch_url)){
res<- VERB(verb = "GET", url = fetch_url,
add_headers(`X-API-TOKEN` = apiToken),
encode = "json")
res<-content(res, "parse",encoding = "UTF-8")
elements <- append(elements,res$result$elements)
fetch_url <- res$result$nextPage
}
return(elements)
}

Sending emails in R without outlook app in the system

I'm able to send emails using the following code.
OutlookForSend = RDCOMClient::COMCreate("Outlook.Application")
emailToSend = OutlookForSend$CreateItem(0)
emailToSend[["subject"]] = "Subject"
emailToSend[["HTMLBody"]] = bodyToSend
emailToSend[["To"]] = "Email"
emailToSend$Send()
However, I don't have outlook installed, in the server machine but still need to send emails.
I'm able to achieve the same using the package mailer in Python , what is the best way to achieve the same in R.
Thanks
Any SMTP client implemented in R will do the job.
Check out this one: Rmailer
From their example:
library(Rmailer)
message <- c(
"Hey,",
"",
"I have a nice pic for you!",
"",
"Best",
"C."
)
settings <- list(
server = "smtp.example.org",
username = "user",
password = "password"
)
## send message:
sendmail(
from = "sender#example.org",
to = "receiver#example.org",
subject = "Good news!",
msg = message,
smtpsettings = settings,
attachment = "nice_pic.jpg"
)
Solved the problem, using mailR package and it works well.
library(mailR)
send.mail(from = "email#company.com",
to = "email#company.com",
subject = subjectToSend ,
body = bodyToSend,
html = TRUE,
smtp = list(host.name = "smtp.company.com", port = 25),
send = TRUE)

R interface to imgflip API (https://api.imgflip.com/). Always ends in with the failure "No texts supplied"

A simple post using the httr package always ends with an error?
# Post a random meme and print its url
res <- httr::POST(
url = "https://api.imgflip.com/caption_image",
body = list(
template_id = "61579",
username = "<my-username>",
password = "<my-password>",
text0 = "abc",
text1 = "def",
font = "impact",
max_font_size = "50"
),
httr::verbose(),
encode = "json"
)
httr::content(res, "text")
Im not sure how to do it in R, but I tried using postman and sending the request as JSON do not work you have to send it as a form-data:

sending POST request to azure ML Web service using poster

I have successfully deployed a web service using Azure ML and am able to get output both on Azure ML as well as a sample R client application.
I would like to however get response using the firefox poster.
I have followed the instructions from the Azure page on deploying the web service and tried using the same request headers and parameters as follows
Instructions from azure page
this is what I've tried on Poster
Error message
My R Code which works
library("RCurl")
library("rjson")
# Accept SSL certificates issued by public Certificate Authorities
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
h = basicTextGatherer()
hdr = basicHeaderGatherer()
req = list(
Inputs = list(
"input1" = list(
"ColumnNames" = list("Smoker", "GenderCD", "Age"),
"Values" = list( list( "1", "M", "8" ), list( "1", "M", "8" ) )
) ),
GlobalParameters = setNames(fromJSON('{}'), character(0))
)
body = enc2utf8(toJSON(req))
api_key = "hHlKbffejMGohso5yiJFke0D9yCKwvcXHG8tfIL2d8ccWZz8DN8nqxh9M4h727uVWPz+jmBgm0tKBLxnPO4RyA=="
authz_hdr = paste('Bearer', api_key, sep=' ')
h$reset()
curlPerform(url = "https://ussouthcentral.services.azureml.net/workspaces/79f267a884464b6a95f5819870787918/services/e3490c06c73849f8a78ff320f7e5ffbc/execute?api-version=2.0&details=true",
httpheader=c('Content-Type' = "application/json", 'Authorization' = authz_hdr),
postfields=body,
writefunction = h$update,
headerfunction = hdr$update,
verbose = TRUE
)
headers = hdr$value()
httpStatus = headers["status"]
if (httpStatus >= 400)
{
print(paste("The request failed with status code:", httpStatus, sep=" "))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(headers)
}
print("Result:")
result = h$value()
print(fromJSON(result))
My API key
hHlKbffejMGohso5yiJFke0D9yCKwvcXHG8tfIL2d8ccWZz8DN8nqxh9M4h727uVWPz+jmBgm0tKBLxnPO4RyA==
How can I form a correct URL which works?
The "Content to Send" section is incorrect, you have specified URL-encoded, while you need to put application/json.

Resources