Querying trades from IB using reqExecutions - r

Im trying to query trades from IB by using function reqExecutions:
library(IBrokers)
con <- twsConnect(clientId=1)
id <- reqIds(con)
Order <- twsOrder(orderId=id, action="BUY", totalQuantity = 1, orderType="LMT", lmtPrice = 600, tif="GTC")
placeOrder(con, twsSTK("AAPL", Order)
print(reqExecutions(con, reqId = as.character(.Last.orderId), ExecutionFilter = twsExecutionFilter(clientId="1")))
although trades are executed in IB, it always returns NULL.

Can't you just use reqOpenOrders?
Warning: The following will execute a trade. Make sure you are connected to a paper trading account before running this code!
library(IBrokers)
#con <- twsConnect(clientId=1)
con <- ibgConnect(clientId=1)
id <- reqIds(con)
Order <- twsOrder(orderId=id, action="BUY", totalQuantity = 1, orderType="LMT",
lmtPrice = 600, tif="GTC")
placeOrder(con, twsSTK("AAPL"), Order)
> reqOpenOrders(twsconn=con)
TWS Message: 2 -1 2100 New account data requested. API client has been unsubscribed from account data.
TWS Execution: orderId=1 time=2012-03-26 08:47:29 side=BOT shares=1 symbol=AAPL conId=265598 price=597.91

Related

Im aware im trying to get data for multiple accounts but where can i specify that rather than receiving this error in R?

library(rgoogleads)
library(gargle)
token <- token_fetch()
token
gads_auth(email = 'xx#gmail.com'
Authentication complete.
ad_group_report <- gads_get_report(
resource = "ad_group",
fields = c("ad_group.campaign",
"ad_group.id",
"ad_group.name",
"ad_group.status",
"metrics.clicks",
"metrics.cost_micros"),
date_from = "2021-01-08",
date_to = "2021-01-10",
where = "ad_group.status = 'ENABLED'",
order_by = c("metrics.clicks DESC", "metrics.cost_micros")
)
i Multi account request
! The request you sent did not return any results, check the entered parameters and repeat the opposition.
Why do I receive this error? I have never received it in Radwords package. Where do I mention the argument for the multiple accounts?
https://cran.r-project.org/web/packages/rgoogleads/rgoogleads.pdf

How to change period to 1 minute in Bloomberg API for R

EDIT:
updated the code but still have not been able to get intraday, 1 minute data.
I have the following code:
suppressMessages(library("Rblpapi"))
conn = blpConnect()
sec<-c("eurusd curncy", "eur2y curncy", "eur12m curncy")
flds<-"PX_LAST"
ovr = c("PERIOD" = "1")
a = as.data.frame(bdh(sec,flds,start.date=as.Date("2019-01-01 07:00"),end.date=as.Date("2019-01-31 07:00"), include.non.trading.days="FALSE", overrides = ovr))
Can't seem to get the period to change to 1 minute intervals.

rentrez entrez_summary premature EOF

Trying to move on from my troubles with RISmed (see Problems with RISmed and large(ish) data sets), I decided to use rentrez and entrez_summary to retrieve a large list of pubmed titles from a query:
set_entrez_key("######") #I did provide my real API key here
Sys.getenv("ENTREZ_KEY")
rm(list=ls())
library(rentrez)
query="(United States[AD] AND France[AD] AND 1995:2020[PDAT])"
results<-entrez_search(db="pubmed",term=query,use_history=TRUE)
results
results$web_history
for (seq_start in seq(0, results$count, 100)) {
if (seq_start == 0) {
summary.append.l <- entrez_summary(
db = "pubmed",
web_history = results$web_history,
retmax = 100,
retstart = seq_start
)
}
Sys.sleep(0.1) #slow things down in case THAT'S a factor here....
summary.append.l <- append(
summary.append.l,
entrez_summary(
db = "pubmed",
web_history = results$web_history,
retmax = 100,
retstart = seq_start
)
)
}
The good news...i didn't get a flat out rejection from NCBI like i did with RISMed and EUtilsGet. The bad news...it's not completing. (I get either
Error in curl::curl_fetch_memory(url, handle = handle) :
transfer closed with outstanding read data remaining
or
Error: parse error: premature EOF
(right here) ------^
I almost think there's something about using an affiliation search string in the query, because if I change the query to
query="monoclonal[Title] AND antibody[Title] AND 2010:2020[PDAT]"
it completes the run, despite having about the same number of records to deal with. So...any ideas why a particular search string would result in problems with the NCBI servers?

The New York Times API with R

I'm trying to get articles' information using The New York Times API. The csv file I get doesn't reflect my filter query. For example, I restricted the source to 'The New York Times', but the file I got contains other sources also.
I would like to ask you why the filter query doesn't work.
Here's the code.
if (!require("jsonlite")) install.packages("jsonlite")
library(jsonlite)
api = "apikey"
nytime = function () {
url = paste('http://api.nytimes.com/svc/search/v2/articlesearch.json?',
'&fq=source:',("The New York Times"),'AND type_of_material:',("News"),
'AND persons:',("Trump, Donald J"),
'&begin_date=','20160522&end_date=','20161107&api-key=',api,sep="")
#get the total number of search results
initialsearch = fromJSON(url,flatten = T)
maxPages = round((initialsearch$response$meta$hits / 10)-1)
#try with the max page limit at 10
maxPages = ifelse(maxPages >= 10, 10, maxPages)
#creat a empty data frame
df = data.frame(id=as.numeric(),source=character(),type_of_material=character(),
web_url=character())
#save search results into data frame
for(i in 0:maxPages){
#get the search results of each page
nytSearch = fromJSON(paste0(url, "&page=", i), flatten = T)
temp = data.frame(id=1:nrow(nytSearch$response$docs),
source = nytSearch$response$docs$source,
type_of_material = nytSearch$response$docs$type_of_material,
web_url=nytSearch$response$docs$web_url)
df=rbind(df,temp)
Sys.sleep(5) #sleep for 5 second
}
return(df)
}
dt = nytime()
write.csv(dt, "trump.csv")
Here's the csv file I got.
It seems you need to put the () inside the quotes, not outside. Like this:
url = paste('http://api.nytimes.com/svc/search/v2/articlesearch.json?',
'&fq=source:',"(The New York Times)",'AND type_of_material:',"(News)",
'AND persons:',"(Trump, Donald J)",
'&begin_date=','20160522&end_date=','20161107&api-key=',api,sep="")
https://developer.nytimes.com/docs/articlesearch-product/1/overview

MturkR, R, automatically posting microbatches

I am new to MTurk, but have some fluency with R. I am using the MTurkR package the first time, and I am trying to create "micro-batches" that post on MTurk over time. The code I am using can be found below (the XXXX parts are obviously filled with the correct values). I don't get any error messages, the code runs, and posts the HIT both in the Sandbox and in the real correctly. However, the HITs posted do not show up in the Sandbox Requester account, or the real requester account which means - as far as I understand - that I can't evaluate the workers who submit a completion code before they are paid automatically.
Could anyone point out where the error is, and how could I review the HITs?
Thanks.
K
##### Notes:
# 1) Change sandbox from TRUE to FALSE to run live (make sure to test in sandbox first!!)
##### Step 1: Load library, set parameters
#### Load MTurkR library
library(MTurkR)
#### HIT Layout ID
# Layout ID for the choice task
# my_hitlayoutid = "XXXX"
# Layout ID for the choice task in the Sandbox
my_hitlayoutid = "XXXX"
#### Set MTurk credentials
Sys.setenv(
AWS_ACCESS_KEY_ID = "XXXX",
AWS_SECRET_ACCESS_KEY = "XXXX"
)
#### HIT parameters
## Run in sandbox?
sandbox_val <- "FALSE"
## Set the name of your project here (used to retrieve HITs later)
myannotation <- "myannotation"
## Enter other HIT aspects
newhittype <- RegisterHITType(
title = "hope trial",
description = "Description",
reward = "2.5",
duration = seconds(hours = 1),
keywords = "survey, demographics, neighborhoods, employment",
sandbox = sandbox_val
)
##### Step 2: Define functions
## Define a function that will create a HIT using information above
createhit <- function() {
CreateHIT(
hit.type = newhittype$HITTypeId,
assignments = 2,
expiration = seconds(days = 30),
annotation = myannotation,
verbose = TRUE,
sandbox = sandbox_val,
hitlayoutid = my_hitlayoutid
)
}
## Define a function that will expire all running HITs
## This keeps HITs from "piling up" on a slow day
## It ensures that A) HIT appears at the top of the list, B) workers won't accidentally accept HIT twice
# expirehits <- function() {
# ExpireHIT(
# annotation = myannotation,
# sandbox = sandbox_val
# )
#}
##### Step 3: Execute a loop that runs createhit/expirehit functions every hour, and it will log the output to a file
## Define number of times to post the HIT (totalruns)
totalruns <- 2
counter <- 0
## Define log file (change the location as appropriate)
logfile <- file("/Users/kinga.makovi/Dropbox/Bias_Experiment/MTurk/logfile.txt", open="a")
sink(logfile, append=TRUE, type="message")
## Run loop (note: interval is hourly, but can be changed in Sys.sleep)
repeat {
message(Sys.time())
createhit()
Sys.sleep(10)
#expirehits()
counter = counter + 1
if (counter == totalruns){
break
}
}
## To stop the loop before it finishes, click the "STOP" button
## To stop logging, run sink()
You can't see HITs that are created via the API (through MTurkR or otherwise) in the requester website. It's a "feature". You'll have to access the HITs through MTurkR (e.g., SearchHITs() and GetHIT()).

Resources