Git Product home page Git Product logo

roandaapi's Introduction

ROandaAPI

R Code API for Forex Trading with OANDA Broker (CFTC and SEC regulated retail broker). This code is a series of functions for using the Oanda REST API, more about Oanda can be read at their HomePage

  • Initial Developer: IF.FranciscoME
  • License: GNU General Public License
  • Location: Guadalajara, Mexico

Last Update 16-08-2016

It was added the Count option to the HisPrices function, that is for retrieving a fixed amount of candles instead of retrieving whatever number of candles is present in a date range from Start to End. It is still available the option of getting the historic prices from a date range though. The Count option is to use the smaller granularity values since from 1 day to another there are more than 5000 candles and that is the limit from OANDA for the amount of history available per request. So now every request of Historic prices must include the Count parameter, if the request is for a date range the value of Count must be NULL, if the request is for a fixed amount of candles, the the values of Start and End, both, must be NULL.

Previous Reading

At Oanda one can trade more than just FOREX market, but mainly it is that, so in order to have a better comprehension about what FOREX trading actually is:

And about What and API, REST API are ?

Getting Started

  1. Have an account: You must actually get an account with OANDA, either Live or Practice is ok and exactly the same, if you do not have one you can create it from here Open Account

  2. Get REST API Access: Log in -> Search for Manage API Access link -> Generate Personal Access Token

  3. Save Info Safely: Having that Token is like having your password, so keep it safe. If you ever lost it or need to change it, its ok and the previous one goes deprecated as soon as you generate another one, so you can Revoke it whenever you want.

More Official Resources

OANDA has a dedicated page to provide all sort of help and examples for developers, in many languages, you can always go there and consider have a resource full place for you Algorithmic Trading.

R Requirements

  • Any version its ok.
  • Does not have to be used RStudio or any other GUI for R.
  • Specific packages will be needed, i just added a code in order to autodetect them and install them if you havent yet

The previous packages are actually necessary not for running the functions, those are regular expressions of R, but when you call and execute them in your code. Thats because some functions i used inside the API. in case you prefer have access to this API with one line of code, you can use the following and the functions will available locally (Note: You must run this code every time you begin R Session).

Step by Step for Minimal Example

1. Install Required Libraries

Install required libraries if not already installed, if they are installed just load them.

Pkg <- c("base","downloader","forecast","httr","jsonlite","lubridate","moments",
"PerformanceAnalytics","quantmod","reshape2","RCurl","stats","scales","tseries",
"TTR","TSA","xts","zoo")

inst <- Pkg %in% installed.packages()
if(length(Pkg[!inst]) > 0) install.packages(Pkg[!inst])
instpackages <- lapply(Pkg, library, character.only=TRUE)

2. Load in local environment the ROandaAPI Code

Uses the function source_url from the package downloader to source a R script located in a GitHub repository.

downloader::source_url("http://bit.ly/GitHubROandaAPI",prompt=FALSE,quiet=TRUE)

3. Data Inputs

AccountID is a 7 digit number, the input must be numeric, Token is where yours go, and the Start and End are dates in format *"YYYY-MM-DD".

AccountType <- "practice"
AccountID   <- 1234567
Token       <- "ba207fab3522f33fda6a91dbfee0522f6-cdbba372874e6e69e4694f050f890277"
TimeAlign   <- "America%2FMexico_City"
Granularity <- "H6"
Start <- "2015-01-01"
End   <- "2015-10-01"

4. Two Functions as an example

InstList in order to get the available instruments in Oanda , and HisPrices* to get the historical prices of the selected instrument, in this case the 117th so is the XAU_USD, that is Gold Vs Usd.

InstList     <- data.frame(InstrumentsList(AccountType,Token,AccountID))[,c(1,3)]
Instrument   <- InstList[117,1]
PastPriceAPI <- HisPrices(AccountType,Granularity,DayAlign,TimeAlign,Token,Instrument,Start,End)

5. Minimal Functional Example

# -------------------------------------------------------------- Basic Trade Example -- #
# -- Step 0 .- Get System Time -------------------------------------------------------- #
# -- Step 1 .- Get Instrument Lists --------------------------------------------------- #
# -- Step 2 .- Get current price of a chosen instrument ------------------------------- #
# -- Step 3 .- Open a "buy" MARKET ORDER of previously chosen instrument -------------- #
# -- Step 4 .- Get TradeID of previously Opened trade --------------------------------- #
# -- Step 5 .- Modify TP and SL ------------------------------------------------------- #
# -- Step 6 .- Close TradeID ---------------------------------------------------------- #
# ------------------------------------------------------------------------------------- #

# -- 0.- Get System Time
Step0 <- Sys.time()

# -- 1.- Get Instrument Lists
Step1 <- InstrumentsList(OA_At,OA_Ak,OA_Ai)

# -- 2 .- Get current price of a chosen instrument
OA_In <- Step1[1,] # AU200_AUD
Step2 <- ActualPrice(OA_At,OA_Ak,OA_In$Instrument)

# -- 3 .- Open a "buy" market order of previously chosen instrument
Step3 <- NewOrder(AccountType = OA_At,
         AccountID  = OA_Ai,
         Token = OA_Ak,
         OrderType  = OA_Ot,
         Instrument = OA_In$Instrument,
         Count  = OA_Ls,
         Side   = OA_Sd,
         SL = trunc(Step2$Ask*0.95), # 5  % loss
         TP = trunc(Step2$Ask*1.10), # 10 % Profit
         TS = 100)                   # 10 Pips for Trailing Stop

Step4 <- OpenTrades(AccountType = OA_At,
                    AccountID = OA_Ai,
                    Token = OA_Ak,
                    Instrument = OA_In$Instrument)

Step5 <- ModifyTrade(AccountType = OA_At,
                     AccountID = OA_Ai,
                     Token = OA_Ak,
                     TradeID = 10406993698, 
                     StopLoss = 0, 
                     TakeProfit = 0,
                     TrailingStop = 150)

Step6 <- CloseTrade(AccountType = OA_At,
                    AccountID = OA_Ai,
                    Token = OA_Ak,
                    TradeID = Step4$trades$id[1])

roandaapi's People

Contributors

iffranciscome avatar sehur avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

roandaapi's Issues

Problem for HisPrices function

Dear IFFranciscoME:
I have problem when I use HisPrices from example code, R show :
Error in $<-.data.frame(*tmp*, "time", value = character(0)) :
replacement has 0 rows, data has 1
How can I fix it?
Best wish,
FreedomTrail

Incorrect timestamp returned from ActualPrice function

Over the weekend, the ActualPrice function returns the current date as opposed to the date the instrument last traded. For example, calling the ActualPrice function on a Saturday will return Saturday's date instead of the last date (the previous Friday usually) when the instrument traded.

The fix is straightforward and included below. Don't bother calling as.POSIXct when it isn't used later anyway.

Replace the line below...
DateTime <- as.POSIXct(substr(InstPrecjson[[1]]$time,12,19), format = "%H:%M:%S")

... with this line.
DateTime <- substr(InstPrecjson[[1]]$time,1,19)

Installation nor working

Hi,

I am following your install instructions and am getting the following issues:

InstList <- data.frame(InstrumentsList(AccountType,Token,AccountID))[,c(1,3)]
Show Traceback

Error in colnames<-(*tmp*, value = c("Instrument", "DisplayName", :
'names' attribute [4] must be the same length as the vector [3] > Instrument <- InstList[117,1]
Error: object 'InstList' not found

PastPriceAPI <- HisPrices(AccountType,Granularity,DayAlign,TimeAlign,Token,Instrument,Start,End)
Error in HisPrices(AccountType, Granularity, DayAlign, TimeAlign, Token, :
argument "Count" is missing, with no default
?HisPrices
No documentation for ‘HisPrices’ in specified packages and libraries:
you could try ‘??HisPrices’

I am specifically interested in intraday historical prices, but can't find any documentation. I am also wondering where to find accountID as I suspect this is incorrect.

Your assistance is greatly appreciated.
Fakir

Problem in modify existing order

Thank you for building the code.

I have one problem using your code to modify an existing order. It seems httpOPTIONS is not the function to make PATCH request. Could you please advise what I did wrong or revise the code? Thanks! The following is the error message I have got:

                                                                                 Server 
                                                                    "openresty/1.7.0.1" 
                                                                                   Date 
                                                        "Tue, 05 Jul 2016 02:35:26 GMT" 
                                                                           Content-Type 
                                                                     "application/json" 
                                                                         Content-Length 
                                                                                    "0" 
                                                                             Connection 
                                                                           "keep-alive" 
                                                           Access-Control-Allow-Headers 

"Accept, Authorization, Content-Type, Origin, X-Accept-DateTime-Format, X-HTTP-Method-Override"
Access-Control-Allow-Methods
"GET, PATCH, DELETE, OPTIONS"
Access-Control-Max-Age
"86400"
status
"204"
statusMessage
"NO_CONTENT\r\n"
Warning messages:
1: In mapCurlOptNames(names(.els), asNames = TRUE) :
Unrecognized CURL options: .params
2: In mapCurlOptNames(names(.els), asNames = TRUE) :
Unrecognized CURL options: .params

Support for v20 REST API

Thank you for writing this code. I am using the v20 REST API and your functions use the v1 server. Can you add the capability to select the v20 Oanda server? Thank you.

Warning on HisPrice string to date time convert

Call method HisPrice with this parameters (for example):

HisPrices(AccountType="practice", Count=2, DayAlign=17, Granularity="D", Instrument="EUR_USD", TimeAlign="America%2FMexico_City", Token="23lkj23l4j2l4j2l34j2l4j-mytoken")

always return "Warning messages":

Warning messages:
1: In strptime(xx, f <- "%Y-%m-%d %H:%M:%OS", tz = tz) :
unknown timezone '%d/%m/%y %H:%M:%S'
2: In as.POSIXct.POSIXlt(x) : unknown timezone '%d/%m/%y %H:%M:%S'
3: In strptime(x, f, tz = tz) : unknown timezone '%d/%m/%y %H:%M:%S'
4: In as.POSIXct.POSIXlt(as.POSIXlt(x, tz, ...), tz, ...) :
unknown timezone '%d/%m/%y %H:%M:%S'
5: In as.POSIXlt.POSIXct(x, tz) : unknown timezone '%d/%m/%y %H:%M:%S'

It's easy to solve replace in line 122:

Prices$TimeStamp <- as.POSIXct(Prices$TimeStamp,"%d/%m/%y %H:%M:%S",origin="1970-01-01") 

to

Prices$TimeStamp <- as.POSIXct(strptime(Prices$TimeStamp, "%Y-%m-%d %H:%M:%OS"),origin="1970-01-01")

but I'm not sure if it's my R configuration problem

Problem with InstrumentsList function

Dear IFFranciscoME:
Thank you for this wrapper, it is fantastic -- only problem that I am facing is that when I use InstrumentsList, an error appears:

Error in names(x) <- value : 
  'names' attribute [4] must be the same length as the vector [3]
Called from: `colnames<-`(`*tmp*`, value = c("Instrument", "DisplayName", 
    "PipSize", "MaxTradeUnits"))

I have narrowed it down to this particular line in the function:

QueryInst1 <- getURL(QueryInst,cainfo=system.file("CurlSSL","cacert.pem",
                                                    package="RCurl"),httpheader=auth)

Do you have any idea how I can fix it?

Really appreciate your effort!

Best wishes,
Henrywjr

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.