<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Benson on Medium]]></title>
        <description><![CDATA[Stories by Benson on Medium]]></description>
        <link>https://medium.com/@benson.aw?source=rss-dbf46b730ee7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6GBZnDfWccQrmm9pfiwZDA@2x.jpeg</url>
            <title>Stories by Benson on Medium</title>
            <link>https://medium.com/@benson.aw?source=rss-dbf46b730ee7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:18:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benson.aw/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Working with Oanda’s API, Part 3— Create a Golang server to aggregate Oanda’s data concurrently]]></title>
            <link>https://medium.com/@benson.aw/working-with-oandas-api-part-3-create-a-golang-server-to-aggregate-oanda-s-data-concurrently-d227bedeb450?source=rss-dbf46b730ee7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d227bedeb450</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[oanda]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Benson]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 01:49:43 GMT</pubDate>
            <atom:updated>2021-08-08T01:45:16.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Working with Oanda’s API, Part 3 — Create a Golang server to aggregate Oanda’s data concurrently</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*gAaR6jhGRwKg4MkVhMVsmA.png" /></figure><p>This is the continuation from <a href="https://medium.com/@naganeo.benson.aw/working-with-oandas-api-part-2-http-request-and-storing-data-in-mongodb-with-golang-ab5e9e5b9812">Part 2</a> for building automated Forex trading bots.</p><p><strong>Q: What will be in this Part 3 guide?</strong></p><p>With some basic understandings of how to conduct HTTP request with Golang in Part 2, we will be building a server that collects different periods of candle data from Oanda’s database. This chapter will also be a good introduction into Golang’s server application libraries (or packages, I will be using this term interchangeably) and concurrency processing. Some may ask why do I need to build a server for such application, given that data is always available on Oanda’s database? Well, allow me to justify,</p><ol><li>Golang has gifted us with a lot of native library (pre-built codes) for building HTTP requests, server handling and concurrent processing. This will help us build a general purpose API server to gather data not only from Oanda but also from other sources (i.e. Twitter API etc). For the purpose of this Part 3 guide, I will be focusing on data available to Oanda and will gradually include other information that our Golang server mastermind will try to gather for helping our analysis in the future.</li><li>Having a dedicated server between Oanda and the analysis part of our programme can allow us better manage our entire system by separating core functionalities into manageable size rather than entangling them altogether (e.g. analysis programme will only focus on analysis, and information gathering will only be conducted by Golang).</li><li>A dedicated server can help us build on top of the Oanda’s API service, or improve any other service that we want to add in the future. Oanda’s API for retrieving candle data has a limit of “maximum=5000” set of data for each API request, and as you can imagine, this maximum number can easily be capped. For instance, data for every 5 second will cap after 1000 tires which is almost 7 hours (6.94444… to be exact). Therefore, this will be a problem when we want to analyse second or even minute based data for over half a year, thus an improved version of the get candle API should be created for the purpose of gathering long term information.</li></ol><p><strong>Q: What will I need?</strong></p><p>Golang installed on your PC (ver 1.13.3 as of the time of this publication) and an IDE (preferably Visual Studio Code with Golang Extensions installed) for building your codes. Refer to Part 2 if you want an instruction from me, otherwise, Google will be a massive help.</p><p><strong>Step 1: Create and updated the necessary files.</strong></p><p>Create “candle.go” under oandaapi folder which we created in Part 2, and a new tooling folder to include “time.go” as well as a controller folder for “candleRequest.go”. Further, the ones marked with update are files that we created in the previous Part and will require need codes to be included.</p><pre>go<br>├── bin/<br>├── pkg/<br>└── src/ <br>    └──tradingServer/    <br>           └──realtimeAPI/<br>                   ├── controller/<br>                   │   ├── candleRequest.go  &lt;- <strong>new</strong>        <br>                   │   └── commonType.go  &lt;- <strong>new</strong>        <br>                   ├── mongoop/ <br>                   │   ├── commonType.go<br>                   │   ├── mongoConnect.go<br>                   │   └── mongoWrite.go<br>                   ├── oandaapi/<br>                   │   ├── accountStatus.go<br>                   │   ├── candle.go  &lt;- <strong>new</strong><br>                   │   ├── commonType.go  &lt;- <strong>update</strong><br>                   │   └── orders.go<br>                   ├── tooling/<br>                   │   ├── time.go  &lt;- <strong>new</strong>        <br>                   └── main.go</pre><p><strong>Step 2: Understanding what we need to complete for Part 3.</strong></p><ol><li>How to send a request that fits Oanda’s HTTP request for retrieving candle data.</li><li>Create a function that sends our HTTP request for gathering singular data or data on multiple periods.</li><li>Set up a server that listens for incoming HTTP requests and processes our Oanda API.</li></ol><p>The rest of Part 3 will be based on the above 3 points.</p><p><strong>Step 3: “1. How to send a request that fits Oanda’s HTTP request for retrieving candle data.”</strong></p><p>Let’s take a look at a <a href="https://curl.haxx.se/docs/manpage.html">CURL</a> example <a href="https://developer.oanda.com/rest-live-v20/instrument-ep/">taken from Oanda</a>.</p><pre>curl \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;Authorization: Bearer &lt;AUTHENTICATION TOKEN&gt;&quot; \<br>  &quot;https://api-fxtrade.oanda.com/v3/instruments/USD_JPY/candles?price=BA&amp;from=2016-10-17T15%3A00%3A00.000000000Z&amp;granularity=M1&quot;</pre><p>We see this is a HTTP GET method request (set as default for CURL that uses HTTP request). And according to it, you will need to add “Content-Type: application/json” to specify the body content of this exchange. Also, we are also required to insert the Bearer token issued to your account in the Authorization header of the request.</p><p>The request URL is very simple, you follow their required path (i.e. <em>/USD_JPY</em> for currency pair and <em>/candles</em> for the chosen instrument) and input the types of data at the end as query. Now, let us dive deeper to familiarise ourselves with what each query’s parameter indicates.</p><pre>?price=BA&amp;from=2016-10-17T15%3A00%3A00.000000000Z&amp;to=2016-10-18T15%3A00%3A00.000000000Z&amp;granularity=M1</pre><ul><li>“Price=BA” : “B” for (bid candles) and “A” (ask candles). The price can be of any combination of “B” and “A”, as well as “M” which is the (midpoint candles).</li><li>“from=2019–3–13T12%3A00%3A00.000000000Z” and “to=2019–3–13T13%3A00%3A00.000000000Z” : Oanda’s specified <a href="https://tools.ietf.org/rfc/rfc3339.txt">RFC 3339 format</a> DateTime for gathering data. With “from” and “to”, you can specify a period of data that you want from the database. Whereas, “from” without “to” will retrieve data from the specified starting date to the latest data available or until the data reaches the return limit of 5000. Likewise, not inputting time will retrieve the latest 500 sets of data; specifying “&amp;count=&quot; with a number behind will help us a specified set of data. Note: you can also use <a href="https://en.wikipedia.org/wiki/Unix_time">UNIX format</a>, which will return UNIX time in the response.</li><li>“granularity=M1” : This is the part where you get to specify the granularity of candle sticks (e.g. “M1” stands for 1 minute worth of candle sticks data).</li></ul><p>With the structure hopefully being understood, we can then figure out how to build it.</p><p>Note: Price and granularity are easy to be included in the query (I will leave this input requirement to the reader to code it), but for now, we will hard code both of these as “BA” and “S5” respectively in our example. Additionally, we will also hard code Count as “1” for retrieving singular data. On the other hand, our input time will require a little conversion work.</p><p>The design we have in mind is to allow user to input the specified time in JSON for gathering candle date. The input should look something like this.</p><pre>{<br> &quot;From&quot;: {<br>  &quot;Year&quot;: 2019,<br>  &quot;Month&quot;: 3,<br>  &quot;Day&quot;: 13,<br>  &quot;Hour&quot;: 12<br> },<br> &quot;To&quot;: {<br>  &quot;Year&quot;: 2019,<br>  &quot;Month&quot;: 3,<br>  &quot;Day&quot;: 13,<br>  &quot;Hour&quot;: 13<br> }<br>}</pre><p>We can use our code to turn this into Oanda’s requested format. Take a look at the following code which you should include in the newly created “time.go”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d4f8efdcc8485260f858c6f1ad9fa08/href">https://medium.com/media/8d4f8efdcc8485260f858c6f1ad9fa08/href</a></iframe><p>We need to let our programme know what it needs to expect from user’s input then how it shall process it to RFC 3339.</p><p>PeriodType, “From” and “To”, is the first layer of struct that wraps around TimeType struct, “Year”, “Month”, “Day” and “Hour”.</p><p>Note: In our example for this part, we will always be using “From” and “To” together for a POST request to get data from a period of time, and a GET request without “From” and “To” as well as “Count=1” to retrieve the latest single set of candle data.</p><p>Our TimeNow(), TimeApoint() helps us morph the input data into RFC 3339 format. TimeFormat() is used to convert the dates into UNIX time. Golang’s time package has provided us with easy to use tools to convert time related data and it is worth studying it. Refer to this <a href="https://golang.org/pkg/time/">link</a> for more information.</p><p>Once the JSON input for time is received by the server, it will call the above functions to convert it into Oanda specified format(e.g. 2019–3–13T12%3A00%3A00.000000000Z), which will then be placed in our outgoing request query along with our pre-coded price and granularity.</p><p><strong>Step 3: “2.Create a function that sends our HTTP request for gathering singular data or data on multiple periods.”</strong></p><p>For retrieving the latest single set of candle data, we just have to ignore the inclusion of “From” and “To”. It’s as simple as sending the following URL in our code.</p><pre>&quot;https://api-fxtrade.oanda.com/v3/instruments/USD_JPY/candles?price=BA&amp;count=1&amp;granularity=M1&quot;</pre><p>This, however, becomes more complicated for multiple periods.</p><p>Due to the restriction of having a “maximum=5000” on each candle data API request. We need to create a loop that can help us iterate through multiple intervals for gathering more than 5000 set of data in each request we send with our server. And we are going to do it with goroutine, channel and WaitGroup.</p><p>Include the following code in “candle.go”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e59b3e737abeb8db172adf8fcc6224f/href">https://medium.com/media/3e59b3e737abeb8db172adf8fcc6224f/href</a></iframe><p>Before I go any further to explain each part of the function, let me try to introduce goroutine, channel and WaitGroup<strong> </strong>as quick and as easily understandable as possible.</p><ul><li>Goroutine : Goroutines are functions that are run concurrently, using modern multi-core structure to execute functions on parallel. Think of it like having a race where everyone starts at the same starting line, instead of lining in a line to start the race one by one. To run a function as a goroutine, simply add a <em>go</em> statement in front of your function.</li><li>WaitGroup: The WaitGroup, which is a type of sync package, is used to count and wait for all the goroutine to finish. It’s like counting and calling the race done when all racers have crossed the finish line.</li><li>Channel: A channel is a pipeline that connects running goroutines, and its function is to send or receive value between goroutines or to a synchronous function. Using the racer example again, having a channel means the racers can talk to each other or people outside of the race and share their findings of their own side of race track — whether that is at the middle of the race or at the end.</li></ul><p>OK, I hope you have a brief understanding of how each of the above works. If not, visit Golang’s <a href="https://golang.org/pkg/">official package website</a> for more information.</p><p>Back to how our functions works.</p><p>We have 2 main functions here, PeriodGetCandle() or SingleGetCandle(). The first one is for retrieving a period of data, and the second one is for only a single latest data.</p><p>SingleGetCandle() is a simple function that sends out a single HTTP request to Oanda, it then returns to us the result from Oanda.</p><p>On the other hand, the start of PeriodGetCandle() takes in an additional parameter <em>p </em>as period for segregating our HTTP requests into multiple calls. For the gathering of a period of data to happen we need to add in more logic to process each request on parallel. In PeriodGet Candle(), we have WaitGroup initialised as<em> wg</em>. And also a slice of <em>[]CandleResponse</em> with type CandleResponse. I have placed my definition of CandleResponse in oandaapi’s “commonType.go” which we created in Part 2. Following by a HTTP request function, <em>var httpIteration func(…).</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a8b300913ce7f62cd169400f7f5b353/href">https://medium.com/media/1a8b300913ce7f62cd169400f7f5b353/href</a></iframe><p>The flow of our request logic in these function should go like this.</p><p>— Using PeriodGetCandle()—</p><p>Once the period is being fed into the function, the “From” and “To” time of it will be transformed to RFC 3339 format and URL encoded. We then calculate the Hour difference between “From” and “To” to split our requests, in seconds, based on how many Hours apart.</p><p>↓</p><p>Create an unbuffered Channel for handling the communication from our HTTP request with <em>make</em>.</p><p>↓</p><p>Loop through the intervals we calculated from timeIntervalCalc() (this function was imported from tooling). PeriodGetCandle() will add 1 count to our <em>wg</em> and send out our HTTP requests using httpIteration() with goroutine<em>, go</em>, attached. The <em>go func() </em>below will wait until the HTTP request is being processed to close our <em>ch</em> channel.</p><p>↓</p><p>Our HTTP requests will gather data that was we sent out with different specified intervals and store it in <em>ch</em>. Once that is done, <em>wg.Done()</em> will decrement our <em>wg </em>count by 1.</p><p>↓</p><p>When the <em>wg </em>count is down to 0, all the stored data in channel will be released to <em>responses </em>and returned as PeriodGetCandle()’s output.</p><p>— Using SingleGetCandle() —</p><p>The HTTP response from Oanda is then released from the channel to <em>responses</em> and returned as SingleGetCandle()’s output. It’s that simple.</p><p>Ta-da <a href="https://getemoji.com/">👌!</a></p><p>This is how we can gather Candle data from Oanda using Golang’s concurrent processing feature.</p><p><strong>Step 3: “3. Set up a server that listens for incoming HTTP requests and processes our Oanda API.”</strong></p><p>Remember how we had all our information for sending HTTP request to Oanda saved in “main.go” in Part 2? Let’s move that into our controller folder’s “commonType.go” to help use keep “main.go” clean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef761a72827e125e8fc67dc12871002e/href">https://medium.com/media/ef761a72827e125e8fc67dc12871002e/href</a></iframe><p>We can then build our controller for trafficking the incoming HTTP requests in our server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e39fcd4f98479e330b214208da9b5a40/href">https://medium.com/media/e39fcd4f98479e330b214208da9b5a40/href</a></iframe><p>The handling of incoming API is simple. If POST method is detected, then it will call the PeriodGetCandle() function with period input. If GET method is detected, then it will call the SingleGetCandle() function without period input. Lastly, if nothing fits then it will return a StatusNotFound error response.</p><p>Once a PeriodGetCandle() or SingleGetCandle() is called through incoming request, the<em> response[s</em>] with all its candle data in it will be returned to the requester through our server.</p><p>Our last step is to have the programme open a port, in our case 8080, to listen for incoming requests. The server will handle the request accordingly based on the request URL path.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae6e52d5dcc3ad2b54b7e0db97f90841/href">https://medium.com/media/ae6e52d5dcc3ad2b54b7e0db97f90841/href</a></iframe><p>run <em>go run main.go </em>in your command line where “main.go” is placed. After you see the “Server has successfully started at port 8080”, you can then test your server’s API by sending POST or GET request to localhost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*xpf6EBgaa32eQs3hXYegDA.png" /><figcaption>POST request example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*RVENGj-66q1kUD9qMgVW8Q.png" /><figcaption>GET request example</figcaption></figure><p>With the above response shown, it means you are good to go and we can concluded our work for Part 3!</p><p>Checklist:</p><ol><li>To fit Oanda’s API, or HTTP request, specification, we learn how to create different date formats in Golang — e.g. RFC 3339 or UNIX.</li><li>We created HTTP requests to Oanda’s database using concurrent features.</li><li>We then created a server that helps us handle incoming API and HTTP requests to Oanda based on the inputs.</li></ol><p>Points to keep in mind:</p><ul><li>We have not considered a scenario where the data gathering in our candle.go exceeds the waiting time for incoming API. In this case, it will timeout on the person making request to our server. There are many ways we can handle this, one is to issue a token to the requester and have he/she check the data gathering status after a period of time; a second option can be having the server post back the <em>responses </em>to the requester’s webhook endpoint.</li><li>Our error checks for the incoming API’s request headers and body are not robust enough. Deviation from the format specified in our code will cause error response, and in some cases, panic in our server.</li></ul><p>That sums up this Part.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d227bedeb450" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Oanda’s API, Part 2 — HTTP request and storing data in MongoDB with Golang]]></title>
            <link>https://medium.com/@benson.aw/working-with-oandas-api-part-2-http-request-and-storing-data-in-mongodb-with-golang-ab5e9e5b9812?source=rss-dbf46b730ee7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab5e9e5b9812</guid>
            <category><![CDATA[oanda]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Benson]]></dc:creator>
            <pubDate>Thu, 09 May 2019 13:19:41 GMT</pubDate>
            <atom:updated>2019-12-23T16:35:45.426Z</atom:updated>
            <content:encoded><![CDATA[<h3>Working with Oanda’s API, Part 2 — HTTP request and storing data in MongoDB with Golang</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7yjI5SpOjrmundTTNDgLg.png" /></figure><p>This is the continuation from <a href="https://medium.com/@naganeo.benson.aw/working-with-oandas-api-part-1-setting-up-your-api-trading-account-8adfd3a1ca7a?source=friends_link&amp;sk=f7021b3e89a48dfa619fea2e1f6b7ece">Part 1</a> for building automated Forex trading bots.</p><p>Now that we have a general understanding of what we expect from Oanda’s API, let’s get our hands dirty by writing codes to automate our API request and store the response in a database.</p><p><strong>Q: What will be in this Part 2 guide?</strong></p><p>A: We will quickly go through the necessary installation for us to programme in Golang (also known as Go, and I will be using the word Go hereinafter) and have access to a local database, MongoDB. We will then walk through code samples for sending buy orders and storing our open positions as well as updated account details in MongoDB.</p><p><strong>Q: What will I need?</strong></p><p>You will need the account that you have created in Part 1, some programming knowledge and the following installed:</p><ol><li>An IDE (Integrated Development Environment) or text editor for writing Go.</li></ol><p>Although any code-centric text editor such as <a href="https://atom.io/">Atom</a> and <a href="https://www.sublimetext.com/">Sublime</a> will work fine, <a href="https://code.visualstudio.com/">Visual Studio Code</a> IDE and the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.Go">Go Extension</a> in its Marketplace are a good combination for writing, testing and debugging Go codes.</p><p>All my Go codes are programmed in Visual Studio Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYJeu3-fTYVqUO-QmWQNGw.png" /><figcaption>Helpful reference: once you have downloaded Visual Studio Code, download the Go Extension as well.</figcaption></figure><p>2. Install Go programming language on your computer.</p><p>Download and install Go from <a href="https://golang.org/">here</a>. Pick the right installation for your operating system.</p><p>Test your installation by typing <em>go version</em> in your terminal (or cmd for Windows user. In order to avoid confusion, I will only be using the term terminal hereinafter). You will see a similar output like the one below printed on a new line.</p><pre>$ go version<br>go version go1.12.4 darwin/amd64</pre><p>If you want to get more familiar with Go before jumping into codes, then I would suggest reading Caleb Doxsey’s Introducing Go (free PDF <a href="https://pepa.holla.cz/wp-content/uploads/2016/10/Introducing-Go.pdf">here</a>). However, if you prefer learning while coding then the official <a href="https://tour.golang.org/welcome/1">A Tour of Go</a> is the place to go. (Ha! you see what I did there?)</p><p>Go is my choice of language because of the vast amount of native packages available for me to run my application (i.e. excellent HTTP request and multi-threading support) so I don’t have to worry too much about my dependencies on third party packages.</p><p>3. Install MongoDB.</p><p>Download and install MongoDB from <a href="https://docs.mongodb.com/manual/installation/">here</a>. Again, pick the right installation for your operating system.</p><p>Test your installation by typing <em>which </em>mongo in your terminal. You will see a path to the mongo installed returned from the system. An example of the path in my system is as follows.</p><pre>$ which mongo<br>/usr/local/bin/mongo</pre><p>Introduction to MongoDB can be found <a href="https://docs.mongodb.com/manual/introduction/">here</a>.</p><p>I chose MongoDB because of its JSON-like documents, BSON to be exact, for storing data. This data type can be easily understood if you are familiar with JSON format.</p><p>Checklist:</p><ol><li>An IDE of your choice.</li><li>Go programming language on your computer.</li><li>MongoDB on your computer.</li></ol><p><strong>Step 1: Checking your environment and create the necessary Go files.</strong></p><p>If you installed Go with the default setting, then typing <em>go env </em>into your terminal will give you a list of Go config. Check your GOPATH and GOROOT from within.</p><p>For Mac/Linux:</p><pre>GOPATH=”$HOME/go”</pre><pre>// Note: $HOME is the home directory on your system. In my case, $HOME = /Users/benson.</pre><pre>GOROOT=”/usr/local/go”</pre><pre>// Note: This is the root of GO installation. Go will find the packages you are using in your programme from GOROOT first. If the specified packages in your programme cannot be found in GOROOT, then GOPATH will be searched. GOROOT path can vary system by system, for Mac it will look something like the one above.</pre><p>For Windows:</p><pre>GOPATH=”%USERPROFILE%\go”</pre><pre>// Note: %USERPROFILE% should be the directory from your C drive to the logged in user&#39;s folder, which can be for example C:\Users\benson.</pre><pre>GOROOT=”c:\Go”</pre><pre>// Note: GOROOT will be installed in a Go folder in your C drive by default. As mentioned in &quot;For Mac/Linux&quot;, this is the first stop for Go to find package[s] that you have specified in your programme.</pre><p>Why do we need to know these? Well, Go is designed with a strict policy on how you construct your projects’ workspace. The intention is for you to better manage your projects, dependencies and distributions. Changing these 2 paths will impact Go’s search for import packages in your codes, which will affect your project’s dependencies. For simplicity’s sake, let’s leave GOPATH and GOROOT as default.</p><p>Visit <a href="https://medium.com/rungo/working-in-go-workspace-3b0576e0534a">here</a> for more resources on how to create and control your Go workspace.</p><p>Back to our project. Your workspace is in go folder from GOPATH, and in it you will see bin, pkg and src folders. Below is a simple representation of the workspace’s directory tree.</p><pre>go/<br>├── bin/<br>├── pkg/<br>└── src/</pre><p>Don’t worry if you see other folders and files within bin, pkg and src. If you are using Visual Studio Code and have installed Go Extension, chances are they are there to assist you with syntax highlight, import explanation and etc in Go.</p><p>We will come back to bin and pkg later, but our main concern is the src folder. This folder will store all of our Go source codes, so let’s go in and create our files.</p><p>For Part 2, let’s create the following folders and files in src.</p><pre>go<br>├── bin/<br>├── pkg/<br>└── src/ <br>    └──tradingServer/    <br>           └──realtimeAPI/<br>                   ├── mongoop/ <br>                   │   ├── commonType.go<br>                   │   ├── mongoConnect.go<br>                   │   └── mongoWrite.go<br>                   ├── oandaapi/<br>                   │   ├── accountStatus.go<br>                   │   ├── commonType.go<br>                   │   └── orders.go<br>                   └── main.go</pre><p>That will be a total of 3 folders and 7 Go files. You can create.go files in IDE by right-clicking New File or creating them via command lines in terminal. You can also name whatever you want for the .go files other than main.go. In Go, main.go is a special file in which it’s the only file that can be executed in a project. Folder names are also important as they are directly linked to the exported packages we’ve made.</p><p>Note: I am building this project based on what I think is best with what I know as of early 2019. There may be better ways to structure the project and I will leave that the smart readers to it find out. A good start on how to structure your project can be found in <a href="https://www.youtube.com/watch?v=1rxDzs0zgcE">this YouTube video</a>.</p><p><strong>Step 2: Build our first Market Order.</strong></p><p>Let’s start with the code for executing our orders in orders.go, and print it out in the terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9186fd8b26893f79d98ac8b3fab2be44/href">https://medium.com/media/9186fd8b26893f79d98ac8b3fab2be44/href</a></iframe><p>We made this file belong to the oandaapi package. In Go, all the files in oandaapi folder have to belong to the package named after the folder name.</p><p>func Trade is the function that will perform the order placement where it accepts our ULR (u parameter as string type), accountID (a parameter as string type), Token (t parameter as string type) and order (o parameter as Order type).</p><p>Additionally, we have defined 2 struct types in this file — Order and OrderDetail. Combining the 2 together and we have a nested structure readily to be converted into JSON format and send it to Oanda as an order.</p><p>Note: Each struct is populated with fields. A field should have its name and type defined initially. The first letter of the struct and its fields are in capital letters so other packages are able to leverage this data property.</p><p>Note, again: A JSON tag is being added behind each field, e.g. `json:”units”`. This is so we can tell the JSON parser where to actually look or construct our values. Or else, all of our field names in JSON will have their first letter in capitals without the tags.</p><p>The first thing func Trade will do is to encode our Order to JSON using preinstalled encoding/json package’s Marshal in Go. When we pass the following variable, marketOrder, through o parameter into func Trade,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/243a962f195f9e1f56bae04f876717a5/href">https://medium.com/media/243a962f195f9e1f56bae04f876717a5/href</a></iframe><p><em>jOrder </em>in<em> jOrder, err := json.Marshal(o) </em>turns the struct into JSON encoding. If we try to print it out at this stage, it will look a little like this.</p><pre>{<br>  &quot;order&quot;: {<br>    &quot;units&quot;: &quot;100&quot;,<br>    &quot;instrument&quot;: &quot;USD_JPY&quot;,<br>    &quot;timeInForce&quot;: &quot;FOK&quot;,<br>    &quot;type&quot;: &quot;MARKET&quot;,<br>    &quot;positionFill&quot;: &quot;DEFAULT&quot;<br>  }<br>}</pre><p>Well done. Not only are you able to create a nested struct in Go and convert it to JSON encoding, but you have also created an Oanda defined Market Order to buy 100 units of USD_JPY (i.e. use JPY to buy $100 worth of USD at whatever the current price is at now as long as the order is filled). Now we just have to send it to Oanda.</p><p>Line 32 to 42 basically describes how we set up an HTTP client in Go to send the encoded JSON data to Oanda. We did a POST request using the URL and AccountID from the passed in u and a parameters respectively. We also added two different Headers, one for our Bearer Token and another as “application/json” to inform Oanda that we are attaching a JSON body as apart of our request. The response from Oanda is stored in the initialised<em> var data map[string]interface{} </em>from line 32. This <em>map[string]interface{} </em>allows us to<em> </em>hold a map, which is another data type in Go, of strings to arbitrary data types. It’s a quick way around to store decoded JSON without specifying all the data types within. Line 43 to 45 is just for printing out the response in your terminal so you can have a better understanding of what it looks like.</p><p>Note: <em>defer resp.Body.Close() </em>at line 41 is there to close the response body so we can reuse the connection again in our next request.</p><p>Before we leave Step 2, define another type in the commonType.go of <strong>oandapai’</strong>s folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/877e89638a1ef6564477693b020b232e/href">https://medium.com/media/877e89638a1ef6564477693b020b232e/href</a></iframe><p><strong>Step 3: Execute/validate our Market Order.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4ca8ea21a06856034935dd2ed4cf336/href">https://medium.com/media/c4ca8ea21a06856034935dd2ed4cf336/href</a></iframe><p>I have gathered all the configs and variables used in our func Trade in main.go. These will probably be moved to another file in the future. As we move further down the road of this series, we will be constantly changing main.go to make our programme more adapt and robust to our goals.</p><p>Notice how we can import the types and func Trade we made in oandaapi by specifying <em>oandaapi.{what you want to get from the package} </em>in front. Remember to set a capital letter at the start of your exports so it can be imported in other packages.</p><p>Go to the directory where our main.go is located and type <em>go run main.go </em>in the terminal<em>.</em></p><p>Note: <em>go run</em> is just a shortcut for compiling and running the complied codes in a single step. We use it for development purpose. Once we finish the project, we will build and run it in binary.</p><pre>{<br>  &quot;lastTransactionID&quot;: &quot;9&quot;,<br>  &quot;orderCreateTransaction&quot;: {<br>    &quot;accountID&quot;: &quot;101-xxx-xxxxxxxx-001&quot;,<br>    &quot;batchID&quot;: &quot;8&quot;,<br>    &quot;id&quot;: &quot;8&quot;,<br>    &quot;instrument&quot;: &quot;USD_JPY&quot;,<br>    &quot;positionFill&quot;: &quot;DEFAULT&quot;,<br>    &quot;reason&quot;: &quot;CLIENT_ORDER&quot;,<br>    &quot;requestID&quot;: &quot;605xxxxxxxxxxx136&quot;,<br>    &quot;time&quot;: &quot;2019-05-06T05:10:20.192608807Z&quot;,<br>    &quot;timeInForce&quot;: &quot;FOK&quot;,<br>    &quot;type&quot;: &quot;MARKET_ORDER&quot;,<br>    &quot;units&quot;: &quot;100&quot;,<br>    &quot;userID&quot;: 10xxxx81<br>  },<br>  &quot;orderFillTransaction&quot;: {<br>    &quot;accountBalance&quot;: &quot;3000000.9000&quot;,<br>    &quot;accountID&quot;: &quot;101-xxx-xxxxxxxx-001&quot;,<br>    &quot;batchID&quot;: &quot;8&quot;,<br>    &quot;commission&quot;: &quot;0.0000&quot;,<br>    &quot;financing&quot;: &quot;0.0000&quot;,<br>    &quot;fullPrice&quot;: {<br>      &quot;asks&quot;: [<br>        {<br>          &quot;liquidity&quot;: &quot;250000&quot;,<br>          &quot;price&quot;: &quot;110.799&quot;<br>        }<br>      ],<br>      &quot;bids&quot;: [<br>        {<br>          &quot;liquidity&quot;: &quot;250000&quot;,<br>          &quot;price&quot;: &quot;110.795&quot;<br>        }<br>      ],<br>      &quot;closeoutAsk&quot;: &quot;110.818&quot;,<br>      &quot;closeoutBid&quot;: &quot;110.776&quot;,<br>      &quot;timestamp&quot;: &quot;2019-05-06T05:10:16.388914934Z&quot;<br>    },<br>    &quot;fullVWAP&quot;: &quot;110.799&quot;,<br>    &quot;gainQuoteHomeConversionFactor&quot;: &quot;1&quot;,<br>    &quot;guaranteedExecutionFee&quot;: &quot;0.0000&quot;,<br>    &quot;halfSpreadCost&quot;: &quot;0.2000&quot;,<br>    &quot;id&quot;: &quot;9&quot;,<br>    &quot;instrument&quot;: &quot;USD_JPY&quot;,<br>    &quot;lossQuoteHomeConversionFactor&quot;: &quot;1&quot;,<br>    &quot;orderID&quot;: &quot;8&quot;,<br>    &quot;pl&quot;: &quot;0.0000&quot;,<br>    &quot;price&quot;: &quot;110.799&quot;,<br>    &quot;reason&quot;: &quot;MARKET_ORDER&quot;,<br>    &quot;requestID&quot;: &quot;605xxxxxxxxxxx136&quot;,<br>    &quot;requestedUnits&quot;: &quot;100&quot;,<br>    &quot;time&quot;: &quot;2019-05-06T05:10:20.192608807Z&quot;,<br>    &quot;tradeOpened&quot;: {<br>      &quot;guaranteedExecutionFee&quot;: &quot;0.0000&quot;,<br>      &quot;halfSpreadCost&quot;: &quot;0.2000&quot;,<br>      &quot;initialMarginRequired&quot;: &quot;443.1880&quot;,<br>      &quot;price&quot;: &quot;110.799&quot;,<br>      &quot;tradeID&quot;: &quot;9&quot;,<br>      &quot;units&quot;: &quot;100&quot;<br>    },<br>    &quot;type&quot;: &quot;ORDER_FILL&quot;,<br>    &quot;units&quot;: &quot;100&quot;,<br>    &quot;userID&quot;: 107xx881<br>  },<br>  &quot;relatedTransactionIDs&quot;: [<br>    &quot;8&quot;,<br>    &quot;9&quot;<br>  ]<br>}</pre><p>Ta-da! Our programme has successfully requested and filled our 1st order with Oanda. From my example, I have a long position on USD_JPY with 100 units opened. Don’t worry if some parts look different. I am using my Japanese account and the accountBalance is in JPY, specifically JPY¥3,000,000.9. I also did some practice transactions before this to be sure my code actually works 😁. Nevertheless, a good practice that I can suggest is to check your request requirements with an HTTP REST client first so you know what you need and expect.</p><p><strong>Step 4: Allow MongoDB to store our account details with the position opened.</strong></p><p>Many of you smart people out there know how to hold your open position for when the timing is right to close it. This can be based on your decision or on an algorithm you’ve built (more to come later in the series). For now, let’s pretend we want to hold this position until tomorrow, and this is your last trade of the day. You will most likely want to keep track of your account’s position and Profit &amp; Loss (P/L) after this trade, and for the last trade of every day. This is where we start to discuss how to save the data you requested from Oanda into your local MongoDB.</p><p>Since MongoDB’s feature does not come preinstalled with Go, we need to install MongoDB Go Driver by downloading the “go.mongodb.org/mongo-driver/mongo” package to a place where Go can find.</p><p>Note: There are many ways to install the package based on your preference to control package dependencies. You can download <em>dep </em>package <a href="https://github.com/golang/dep">her</a>e to manage your package dependencies, then install mongo-driver from the dep instruction <a href="https://github.com/mongodb/mongo-go-drivera">here</a>. You can also use the new and preinstalled way (starting from Go1.11) with Go module. The instruction is over <a href="https://blog.golang.org/using-go-modules">here</a>. However, for demonstration purpose, I’m going to install the package in our GOPATH by running the following<em> go get </em>command.</p><pre>$ go get go.mongodb.org/mongo-driver/mongo</pre><p>Starting with a package name and struct that can be used in other places, we add the following contents in <strong>mongoop </strong>folder’s commonType.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8d42ff0f2308588051bb68086c0312f/href">https://medium.com/media/b8d42ff0f2308588051bb68086c0312f/href</a></iframe><p>We will need to have a way to connect and disconnect with your MongoDB, so populate mongoConnect.go with the followings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97c49fbf1f6d0185da726d8196100d4c/href">https://medium.com/media/97c49fbf1f6d0185da726d8196100d4c/href</a></iframe><p>We define <em>mdbc </em>with type <em>*mongo.Client</em>, a MongoDB defined Client type where we attach a “*” in front to tell Go that this variable holds a <a href="https://tour.golang.org/moretypes/1">pointer</a> to Client. I didn’t export <em>mdbc </em>because this will only be used in <em>mongoop</em>.</p><p>ConnectToMongo accepts u parameter with type MongoCall which, if you remember, is defined in commonType.go of the same folder.</p><p><a href="https://golang.org/pkg/context/"><em>context.WithTimeout</em></a> in line 18 to 19 and 30 to 31 is the rule we set on the connection timeout with our MongoDB. This is a required parameter for manipulating our connection with MongoDB. It doesn’t matter to us what our settings for the timeout are at this point as we are connecting to a local database. However, we will need to consider how to handle our connections with the database on cloud servers. Further examples for more complicated situation handling will be provided in the future.</p><p>Once the connection can be made, we turn ourselves to writing data in our database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/277b58b65bbed96254af43bd78387599/href">https://medium.com/media/277b58b65bbed96254af43bd78387599/href</a></iframe><p>The func WriteToMongo accepts an empty interface type data that can be written as a document in the database’s collection. It also has a db parameter, (accepting string type) for the name of our database. The c parameter (also accepts string type) is for specifying the collection in our database.</p><p>Note: Refer to this <a href="https://docs.mongodb.com/manual/core/databases-and-collections/">link</a> if you want to be more familiar with the terms used in MongoDB.</p><p>So, where do we use this func WriteToMongo? Well, the place we are using it now is in the HTTP request for acquiring our account detail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58831a7c0f615aa6d8f615ed02ebdd9c/href">https://medium.com/media/58831a7c0f615aa6d8f615ed02ebdd9c/href</a></iframe><p>Line 13 to 22 should look familiar to you. It’s a simpler HTTP request structure from the one we built in Step 2.</p><p>On line 24, we passed in 3 parameters for saving our account detail in a database called “oandaPractice” under the “account” collection.</p><p>Let’s put these all together in our main.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa2a9f8a180fd595e48d7da3cde12587/href">https://medium.com/media/fa2a9f8a180fd595e48d7da3cde12587/href</a></iframe><p>The main.go now has the following execution order.</p><p>Connect to MongoDB -&gt; Send our Market Order to Oanda to have our order filled, then print out the response in the terminal -&gt; Get the updated account detail -&gt; Save the account detail in the “account” collection under MongoDB’s “oandaPractice” database.</p><p>But wait, we are not done yet. We still have one last thing to do before executing our main.go. Our MongoDB still doesn’t have “oandaPractice” database and “account” collection created.</p><p>Go to your terminal and boot a MongoDB instance in our local system.</p><pre>$ mongod</pre><p>Open another tab or window then type in the following to start mongo shell.</p><pre>$ mongo</pre><p>If you see messages like the one below, then congratulation, you’re in your local database.</p><pre>...<br>---<br>Enable MongoDB’s free cloud-based monitoring service, which will then receive and display<br>metrics about your deployment (disk utilization, CPU, operation statistics, etc).</pre><pre>The monitoring data will be available on a MongoDB website with a unique URL accessible to you<br>and anyone you share the URL with. MongoDB may use this information to make product<br>improvements and to suggest MongoDB products and deployment options to you.</pre><pre>To enable free monitoring, run the following command: db.enableFreeMonitoring()<br>To permanently disable this reminder, run the following command: db.disableFreeMonitoring()<br>---</pre><pre>&gt;</pre><p>Create the database with the following command.</p><pre>&gt; use oandaPractice<br>switched to db oandaPractice</pre><p>Then create our collection.</p><pre>&gt; db.createCollection(“account”)<br>{ “ok” : 1 }</pre><p><strong>Step 5: Run our programme.</strong></p><p>Go back to the folder with our main.go and execute <em>go run main.go.</em></p><pre>$ go run main.go<br>Connection established with MongoDB - mongodb://localhost:27017<br>{<br>  &quot;lastTransactionID&quot;: &quot;13&quot;,<br>  &quot;orderCreateTransaction&quot;: {<br>    &quot;accountID&quot;: &quot;101-xxx-xxxxxxxx-001&quot;,<br>    &quot;batchID&quot;: &quot;12&quot;,<br>    &quot;id&quot;: &quot;12&quot;,<br>    &quot;instrument&quot;: &quot;USD_JPY&quot;,<br>    &quot;positionFill&quot;: &quot;DEFAULT&quot;,<br>    &quot;reason&quot;: &quot;CLIENT_ORDER&quot;,<br>    &quot;requestID&quot;: &quot;245xxxxxxxxxxx138&quot;,<br>    &quot;time&quot;: &quot;2019-05-08T15:57:16.789520364Z&quot;,<br>    &quot;timeInForce&quot;: &quot;FOK&quot;,<br>    &quot;type&quot;: &quot;MARKET_ORDER&quot;,<br>    &quot;units&quot;: &quot;100&quot;,<br>    &quot;userID&quot;: 10xxxx81<br>  },<br>  &quot;orderFillTransaction&quot;: {<br>    &quot;accountBalance&quot;: &quot;3000002.2017&quot;,<br>    &quot;accountID&quot;: &quot;101-xxx-xxxxxxxx-001&quot;,<br>    &quot;batchID&quot;: &quot;12&quot;,<br>    &quot;commission&quot;: &quot;0.0000&quot;,<br>    &quot;financing&quot;: &quot;0.0000&quot;,<br>    &quot;fullPrice&quot;: {<br>      &quot;asks&quot;: [<br>        {<br>          &quot;liquidity&quot;: &quot;250000&quot;,<br>          &quot;price&quot;: &quot;110.131&quot;<br>        }<br>      ],<br>      &quot;bids&quot;: [<br>        {<br>          &quot;liquidity&quot;: &quot;250000&quot;,<br>          &quot;price&quot;: &quot;110.127&quot;<br>        }<br>      ],<br>      &quot;closeoutAsk&quot;: &quot;110.150&quot;,<br>      &quot;closeoutBid&quot;: &quot;110.108&quot;,<br>      &quot;timestamp&quot;: &quot;2019-05-08T15:57:08.966302387Z&quot;<br>    },<br>    &quot;fullVWAP&quot;: &quot;110.131&quot;,<br>    &quot;gainQuoteHomeConversionFactor&quot;: &quot;1&quot;,<br>    &quot;guaranteedExecutionFee&quot;: &quot;0.0000&quot;,<br>    &quot;halfSpreadCost&quot;: &quot;0.2000&quot;,<br>    &quot;id&quot;: &quot;13&quot;,<br>    &quot;instrument&quot;: &quot;USD_JPY&quot;,<br>    &quot;lossQuoteHomeConversionFactor&quot;: &quot;1&quot;,<br>    &quot;orderID&quot;: &quot;12&quot;,<br>    &quot;pl&quot;: &quot;0.0000&quot;,<br>    &quot;price&quot;: &quot;110.131&quot;,<br>    &quot;reason&quot;: &quot;MARKET_ORDER&quot;,<br>    &quot;requestID&quot;: &quot;245xxxxxxxxxxx138&quot;,<br>    &quot;requestedUnits&quot;: &quot;100&quot;,<br>    &quot;time&quot;: &quot;2019-05-08T15:57:16.789520364Z&quot;,<br>    &quot;tradeOpened&quot;: {<br>      &quot;guaranteedExecutionFee&quot;: &quot;0.0000&quot;,<br>      &quot;halfSpreadCost&quot;: &quot;0.2000&quot;,<br>      &quot;initialMarginRequired&quot;: &quot;440.5160&quot;,<br>      &quot;price&quot;: &quot;110.131&quot;,<br>      &quot;tradeID&quot;: &quot;13&quot;,<br>      &quot;units&quot;: &quot;100&quot;<br>    },<br>    &quot;type&quot;: &quot;ORDER_FILL&quot;,<br>    &quot;units&quot;: &quot;100&quot;,<br>    &quot;userID&quot;: 10xxxx81<br>  },<br>  &quot;relatedTransactionIDs&quot;: [<br>    &quot;12&quot;,<br>    &quot;13&quot;<br>  ]<br>}Write account detail to MongoDB.<br>Finished saving data.<br>Ended Connection to MongoDB.</pre><p>Go back to “oandaPractice” in the mongo shell and check the data we saved with <em>db.account.find().pretty()</em>.</p><pre>&gt; db.account.find().pretty()<br>{<br> &quot;_id&quot; : ObjectId(&quot;5cd2fc5d97c158514e66d2a3&quot;),<br> &quot;account&quot; : {<br>  &quot;createdTime&quot; : &quot;2019-03-10T10:32:54.993100897Z&quot;,<br>  &quot;currency&quot; : &quot;JPY&quot;,<br>  &quot;alias&quot; : &quot;Primary&quot;,<br>  &quot;lastTransactionID&quot; : &quot;13&quot;,<br>  &quot;unrealizedPL&quot; : &quot;-67.6000&quot;,<br>  &quot;orders&quot; : [ ],<br>  &quot;trades&quot; : [<br>   {<br>    &quot;instrument&quot; : &quot;USD_JPY&quot;,<br>    &quot;currentUnits&quot; : &quot;100&quot;,<br>    &quot;realizedPL&quot; : &quot;0.0000&quot;,<br>    &quot;financing&quot; : &quot;1.3017&quot;,<br>    &quot;unrealizedPL&quot; : &quot;-67.2000&quot;,<br>    &quot;id&quot; : &quot;9&quot;,<br>    &quot;price&quot; : &quot;110.799&quot;,<br>    &quot;openTime&quot; : &quot;2019-05-06T05:10:20.192608807Z&quot;,<br>    &quot;initialUnits&quot; : &quot;100&quot;,<br>    &quot;initialMarginRequired&quot; : &quot;443.1880&quot;,<br>    &quot;state&quot; : &quot;OPEN&quot;,<br>    &quot;marginUsed&quot; : &quot;440.5160&quot;<br>   },<br>   {<br>    &quot;id&quot; : &quot;13&quot;,<br>    &quot;instrument&quot; : &quot;USD_JPY&quot;,<br>    &quot;price&quot; : &quot;110.131&quot;,<br>    &quot;realizedPL&quot; : &quot;0.0000&quot;,<br>    &quot;financing&quot; : &quot;0.0000&quot;,<br>    &quot;unrealizedPL&quot; : &quot;-0.4000&quot;,<br>    &quot;openTime&quot; : &quot;2019-05-08T15:57:16.789520364Z&quot;,<br>    &quot;initialUnits&quot; : &quot;100&quot;,<br>    &quot;initialMarginRequired&quot; : &quot;440.5160&quot;,<br>    &quot;state&quot; : &quot;OPEN&quot;,<br>    &quot;currentUnits&quot; : &quot;100&quot;,<br>    &quot;marginUsed&quot; : &quot;440.5160&quot;<br>   }<br>  ],<br>  &quot;marginUsed&quot; : &quot;881.0320&quot;,<br>  &quot;marginAvailable&quot; : &quot;2999053.5697&quot;,<br>  &quot;guaranteedStopLossOrderMode&quot; : &quot;DISABLED&quot;,<br>  &quot;marginRate&quot; : &quot;0.04&quot;,<br>  &quot;positionValue&quot; : &quot;22025.8000&quot;,<br>  &quot;marginCloseoutPercent&quot; : &quot;0.00029&quot;,<br>  &quot;openTradeCount&quot; : 2,<br>  &quot;resettablePL&quot; : &quot;0.9000&quot;,<br>  &quot;guaranteedExecutionFees&quot; : &quot;0.0000&quot;,<br>  &quot;NAV&quot; : &quot;2999934.6017&quot;,<br>  &quot;withdrawalLimit&quot; : &quot;2999053.5697&quot;,<br>  &quot;createdByUserID&quot; : 10xxxx81,<br>  &quot;balance&quot; : &quot;3000002.2017&quot;,<br>  &quot;resettablePLTime&quot; : &quot;0&quot;,<br>  &quot;positions&quot; : [<br>   {<br>    &quot;marginUsed&quot; : &quot;881.0320&quot;,<br>    &quot;instrument&quot; : &quot;USD_JPY&quot;,<br>    &quot;financing&quot; : &quot;1.3017&quot;,<br>    &quot;unrealizedPL&quot; : &quot;-67.6000&quot;,<br>    &quot;resettablePL&quot; : &quot;0.9000&quot;,<br>    &quot;commission&quot; : &quot;0.0000&quot;,<br>    &quot;guaranteedExecutionFees&quot; : &quot;0.0000&quot;,<br>    &quot;long&quot; : {<br>     &quot;pl&quot; : &quot;0.9000&quot;,<br>     &quot;resettablePL&quot; : &quot;0.9000&quot;,<br>     &quot;financing&quot; : &quot;1.3017&quot;,<br>     &quot;guaranteedExecutionFees&quot; : &quot;0.0000&quot;,<br>     &quot;tradeIDs&quot; : [<br>      &quot;9&quot;,<br>      &quot;13&quot;<br>     ],<br>     &quot;unrealizedPL&quot; : &quot;-67.6000&quot;,<br>     &quot;units&quot; : &quot;200&quot;,<br>     &quot;averagePrice&quot; : &quot;110.465&quot;<br>    },<br>    &quot;short&quot; : {<br>     &quot;units&quot; : &quot;0&quot;,<br>     &quot;pl&quot; : &quot;0.0000&quot;,<br>     &quot;resettablePL&quot; : &quot;0.0000&quot;,<br>     &quot;financing&quot; : &quot;0.0000&quot;,<br>     &quot;guaranteedExecutionFees&quot; : &quot;0.0000&quot;,<br>     &quot;unrealizedPL&quot; : &quot;0.0000&quot;<br>    },<br>    &quot;pl&quot; : &quot;0.9000&quot;<br>   }<br>  ],<br>  &quot;hedgingEnabled&quot; : false,<br>  &quot;id&quot; : &quot;101-xxx-xxxxxxxx-001&quot;,<br>  &quot;pendingOrderCount&quot; : 0,<br>  &quot;pl&quot; : &quot;0.9000&quot;,<br>  &quot;marginCloseoutUnrealizedPL&quot; : &quot;-67.2000&quot;,<br>  &quot;marginCloseoutMarginUsed&quot; : &quot;881.0320&quot;,<br>  &quot;commission&quot; : &quot;0.0000&quot;,<br>  &quot;marginCloseoutNAV&quot; : &quot;2999935.0017&quot;,<br>  &quot;marginCloseoutPositionValue&quot; : &quot;22025.8000&quot;,<br>  &quot;openPositionCount&quot; : 1,<br>  &quot;financing&quot; : &quot;1.3017&quot;<br> },<br> &quot;lastTransactionID&quot; : &quot;13&quot;<br>}</pre><p>You will find a snapshot of your account detail saved with an ObjectId attached to it. If you look carefully to where your “position” array is at in the data, you will discover that you’re holding 200 units of USD_JPY. 100 units from our first test run in Step 3’s main.go, and another 100 units for executing the 2nd version of our main.go.</p><p><strong>That’s it!</strong> 😎</p><p>This is a long run, but I hope it’s worth it.</p><p>Checklist:</p><ol><li>Create a workplace to save our Go codes.</li><li>Build a Market Order to buy 100 units of USD_JPY and run a simple validation on it. Again, a good practice I would suggest is to always test your HTTP request with an HTTP client before writing the code.</li><li>Build functions that will connect and store our account detail to a local MongoDB after a trade.</li></ol><p>Points to keep in mind:</p><ul><li>This is a very simple code structure that has the order we want to send hard coded in the source code. I will be improving the programme in the future so that our Go programme will be set up as a server that can respond to inputs from external programmes. The server will then build orders for us, execute them, save data in the database and return the results back to us, all of which are based on the inputs we give.</li><li>The current programme does not have any logic in handling errors. Right now, it only logs our error in the terminal. This will be troublesome when we face any anomaly when running the programme in real life, and it’s a big nono because we may lose money from it.</li></ul><p>Hopefully, with everything we need for our servers installed after the next few parts, we can start coding some simple trading strategies and backtest examples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab5e9e5b9812" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Oanda’s API, Part 1 — Setting up your API trading account]]></title>
            <link>https://medium.com/@benson.aw/working-with-oandas-api-part-1-setting-up-your-api-trading-account-8adfd3a1ca7a?source=rss-dbf46b730ee7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8adfd3a1ca7a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[forex]]></category>
            <dc:creator><![CDATA[Benson]]></dc:creator>
            <pubDate>Sun, 21 Apr 2019 13:01:31 GMT</pubDate>
            <atom:updated>2019-04-21T13:01:31.212Z</atom:updated>
            <content:encoded><![CDATA[<h3>Working with Oanda’s API, Part 1 — Setting up your API trading account</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gNdxff6Ecto6qL8Z7OdFZA.jpeg" /></figure><p>So you want to learn how to make millions from trading Forex? Well, I can’t offer that, but what I can do is to help you by walking through examples of setting up your system. Hopefully, this will provide you some insights on how to automate Forex trading with Oanda’s API. For my examples, I will be using <a href="https://www.mongodb.com/">MongoDB</a> for our database management, <a href="https://golang.org/">Go</a> programming language for our server, and <a href="https://www.python.org/about/gettingstarted/">Python</a> programming language for creating trading strategies. All of these will be gradually released in different parts.</p><p><strong>Q: What will be in this Part 1 guide?</strong></p><p>A: Setting up a practice account for Forex trading. Using a HTTP REST client/tool (a good REST summary can be found <a href="https://www.codecademy.com/articles/what-is-rest">here</a>) to confirm your account information over API requests (explanation of API can be found <a href="https://www.quora.com/What-is-an-API-4">here</a>) — REST and API combined, often referred to as RESTful API, are basically the standard way these days to define how 2 computers talk to each other over the internet.</p><p>I will try to explain these procedures in a beginner friendly approach.</p><p><strong>Q: What do I need?</strong></p><p>A: You will need the following.</p><ol><li>Register a practice trading account.</li></ol><p>Fill in your Name, Email, Username, Password, Country and Phone at <a href="https://www.oanda.com/register/#/sign-up/demo">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiuLnU5C6rSV9iqlbZTAcQ.png" /><figcaption>Sign up page. (I registered from the Japanese side so the requirements are a little different for me.)</figcaption></figure><p>2. <a href="https://www.oanda.com/demo-account/login?app_name=SecureSignIn">Login</a> to “fxTrade Practice” using your account, and generate an API key. (Note: Some country, like in Japan, will auto generate your login information for you).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sq72itK_JKoZLQwaChwloQ.png" /><figcaption>Login page for your Practice account.</figcaption></figure><p>At your main menu’s screen, you should see a “Manage API Access” link. Access the link and it will transfer you to a Manage API Access page with a <strong>Generate</strong><em> </em>button in the middle. Click on the button and, voila, it will give you an API key. Save the API key in somewhere safe where no one else can copy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*Xc4gzUWVeeYSixstAWFHyA.png" /><figcaption>Your API key will be shown here. It’s your personal key to access your account over API requests. I coloured part of mine in purple strip.</figcaption></figure><p>3. We will be testing our API requests with a HTTP REST client/tool called Insomnia, which can be found <a href="https://insomnia.rest/">here</a>. You can also use another popular client/tool called Postman, which can be <a href="https://www.getpostman.com/">found</a> here, but I will be using Insomnia for this guide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*FO15cEjIlx8LAxqF77S0rw.png" /><figcaption>You can Download it from the homepage, or download the OS specific through the download page.</figcaption></figure><p>These clients are the first step to test an API request before implementing it into our codes.</p><p>Checklist:</p><ol><li>A practice Oanda account.</li><li>An API key associated with the Oanda account.</li><li>An installed HTTP REST client/tool.</li></ol><p>Now that you are ready to make API requests to Oanda’s server, let us begin by understanding Oanda’s API structure in order to create our first HTTP request.</p><p><strong>Step 1: Understanding the request URL</strong></p><p>Everything you need to know can be found reading the <a href="http://developer.oanda.com/rest-live-v20/introduction/">official documentation</a>. With that said, telling you to read it so I can jump to the conclusion defeats the purpose of a guide. Therefore, I will try to condense the important parts in the following section, but also feel free to jump right in to the document and experiment around.</p><p>We will be using Oanda’s REST-V20, their latest API for connecting to V20 trading engine as of early 2019.</p><p>Let’s look at our 1st goal, which is to get the available accounts. The URL for getting all of your available accounts look like this.</p><blockquote>https://api-fxpractice.oanda.com/v3/accounts</blockquote><p>Let us split the URL into 3 parts and analyse it.</p><ol><li>https://api-fxpractice.oanda.com -&gt; host name</li></ol><p>This is where we put in the internet address to locate Oanda’s API service on a domain. The one above is for practice accounts. If you are ready to trade with real money then use https://api-fxtrade.oanda.com.</p><p>2. /v3 -&gt; version</p><p>This is the version of the API service. You don’t have to worry about this unless there is a version change.</p><p>3. /accounts -&gt; endpoint</p><p>This is the endpoint pointing at Oanda’s account service. You can find the rest of their endpoints in their “Endpoints” section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d44S6jWB730AXZCI8jsiqw.png" /><figcaption>The Endpoints section has Account, Instrument down to Forex Labs.</figcaption></figure><p>With the URL to request account information being set, we also need to let Oanda’s server know who is doing the request for obvious security reasons. This is where the generated API key comes into play.</p><p><strong>Step 2: Constructing a request</strong></p><p>2 things that we need to make your request for account information to be accepted by Oanda’s server.</p><ul><li>URL</li><li>API key under <a href="https://swagger.io/docs/specification/authentication/bearer-authentication/">Bearer Authentication</a></li></ul><p>The API key is required to be passed as Bearer Token into Oanda’s system, so it can authenticate and process or pass information that is associated with the associated account.</p><p>Also, we know that Oanda’s server will be accepting HTTP GET method for retrieving account information. (Note: GET method is part of the REST architectural style commonly used for data retrieval)</p><p>Let’s put all the information in Insomnia.</p><p>Create a “New Request” in Insomnia. You can also use the Ctrl(or Cmd if you use Mac) + N to create one. Remember to choose the GET method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dRynguPES93hF8XDMmrQQ.png" /><figcaption>You can name it what you want, but remember to choose the right method.</figcaption></figure><p>Paste the URL in the URL section, which is next to the GET method in the request. Choose the Bearer Token for your authentication scheme. (Note: this is the only request header requirement for this API). Then input your API key beside the “TOKEN” section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*ntpdbYYY8Oq6e4_Z2bz2kA.png" /><figcaption>1. Place your URL, 2. Select authentication type, 3. Input API Key, 4. Then press send.</figcaption></figure><p>Press <strong>Send</strong>! You will get the following result if everything goes right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*1slXU6J6UOfH-gTRPSkjTQ.png" /><figcaption>This is an example of the returning response with only one account. I covered part of the digits in purple strip.</figcaption></figure><p>The response body, which is in <a href="https://www.w3schools.com/whatis/whatis_json.asp">JSON</a> format, contains your account id and tags in an array of object[s]. (Note: if you have multiple sub accounts then those will be returned in multiple objects in the array).</p><pre>{<br>  “accounts”: [<br>    {<br>      “id”: “101–xxx–xxxxxxxx–001”,<br>      “tags”: []<br>    }<br>  ]<br>}</pre><p><strong>Step 3: Use the accounts’ id to repeat requests on other Account Endpoint</strong></p><p>Using the main account id, “id”: “101–xxx–xxxxxxxx–001” (I replaced some digits in x marks), we can get account details or make changes to it. For this example, I will be pulling the full details of my account.</p><p>Create another request in Insomnia using the same method described “Step 2: Constructing a request”. Same API key (Bearer Token) and same HTTP method. This time, however, change your URL to:</p><blockquote>https://api-fxpractice.oanda.com/v3/accounts/101–xxx–xxxxxxxx–001</blockquote><p>with your account id shown at the end.</p><p>Press <strong>Send</strong> again and you will see a similar result from the following screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*pqCpOA1GkyBccTFKHY8qVQ.png" /></figure><p>That’s it! You can now access your account through API and not from a browser or app. For the next part, I will be demonstrating how to perform API requests using a programme written in Go instead of a REST client/tool.</p><p><strong>Summary</strong></p><p>Let’s summaries what we have done.</p><ol><li>Get your API key from your Oanda account.</li><li>Choose the correct HTTP method, and enter the request URL as well as API key (Bearer Token) in your chosen REST client/tool.</li><li>Test your requests.</li></ol><p>I hope this guide will inspire some of you to try automated Forex trading using Oanda’s API, even if it’s just for fun on a practice account.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8adfd3a1ca7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>