Join the Quantcademy private membership portal that caters to the rapidly-growing retail quant trader community. You'll find a knowledgeable, like-minded group of quant traders ready to answer your most pressing quant trading questions. Check out my ebook on quant trading where I teach you how to build profitable systematic trading strategies with Python tools, from scratch.
Take a look at my new ebook on advanced trading strategies using time series analysis, machine learning and Bayesian statistics, with Python and R. I previously mentioned in the QuantStart: Given that I myself usually carry out research in equities and futures markets, I thought it would be fun and educational!
Each "diary entry" will attempt to build on all those before, but should also be relatively self-contained. In this first entry of the diary I'll be describing how to set up a new practice brokerage account with OANDA as well as how to create a basic multithreaded event-driven trading engine that can automatically execute trades in both a practice and live setting.
Last year we spent a lot of time looking at the event-driven backtester , primarily for equities and ETFs. The one I present below is geared towards forex and can be used for either paper trading or live trading. I have written all of the following instructions for Ubuntu Since this is the first post directly about foreign exchange trading, and the code presented below can be straightforwardly adapted to a live trading environment, I would like to present the following disclaimers:.
Trading foreign exchange on margin carries a high level of risk, and may not be suitable for all investors. Past performance is not indicative of future results. The high degree of leverage can work against you as well as for you. Before deciding to invest in foreign exchange you should carefully consider your investment objectives, level of experience, and risk appetite.
The possibility exists that you could sustain a loss of some or all of your initial investment and therefore you should not invest money that you cannot afford to lose. You should be aware of all the risks associated with foreign exchange trading, and seek advice from an independent financial advisor if you have any doubts.
This software is provided "as is" and any expressed or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the regents or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption however caused and on any theory of liability, whether in contract, strict liability, or tort including negligence or otherwise arising in any out of the use of this software, even if advised of the possibility of such damage.
After reading through their developer API documentation , I decided to give them a try, at least with a practice account. To be clear - I have no prior or existing relationship with OANDA and am only providing this recommendation based on my limited experience playing around with their practice API and some brief usage for market data download while employed at a fund previously.
If anybody has come across any other forex brokers that also have a similarly modern API then I'd be happy to give them a look as well. Before utilising the API it is necessary to sign up for a practice account.
To do this, head to the sign-up link. You will see the following screen:. You will then be able to sign in with your login credentials. Make sure to select the "fxTradePractice" tab from the sign-in screen:. Once in you will need to make a note of your Account ID. It is listed underneath the black "My Funds" header next to "Primary". Mine is a 7-digit number. In addition you will also need to generate a personal API token.
At this stage you will be able to generate an API token. You will need the key for use later, so make sure to write it down as well. You will now want to launch the FXTrade Practice application, which will allow us to see the executed orders and our paper! If you are running a Ubuntu system you will need to install a slightly different version of Java.
In particular, the Oracle version of Java 8. If you don't do this then the practice simulator will not load from the browser. I ran these commands on my system:. You will now be able to launch the practice trading environment.
It will bring up a Java dialog asking whether you want to run it. Click "Run" and the fxTrade Practice tool will load. If you have been following the event-driven backtester series for equities and ETFs that I created last year, you'll be aware of how such an event-driven trading system functions.
For those of you who are new to event-driven software , I would strongly suggest reading through the article in order to gain some insight into how they work. In essence, the entire program is executed in an infinte while loop that only terminates when the trading system is shut off. The central communication mechanism of the program is given via a queue that contains events.
The queue is constantly queried to check for new events. Once an event has been taken off the top of the queue it must be handled by an appropriate component of the program. Hence a market data feed might create TickEvent s that are placed onto the queue when a new market price arrives. A signal-generating strategy object might create OrderEvent s that are to be sent to a brokerage. The usefulness of such a system is given by the fact that it doesn't matter what order or types of events are placed on the queue, as they will always be correctly handled by the right component within the program.
In addition different parts of the program can be run in separate threads , meaning that there is never any waiting for any particular component before processing any other. This is extremely useful in algorithmic trading situations where market data feed handlers and strategy signal generators have vastly different performance characteristics.
As we stated above the code runs in an infinite loop. Firstly, the queue is polled to retrieve a new event. If the queue is empty, then the loop simply restarts after a short sleep period known as the "heartbeat". If an event is found its type is assessed and then the relevant module either the strategy or the execution handler is called upon to handle the event and possibly generate new ones that go back onto the queue.
We will now discuss the implementation of the code in detail. At the bottom of the article is the complete listing of all source code files. If you place them in the same directory and run python trading. It is bad practice to store passwords or authentication keys within a codebase as you can never predict who will eventually be allowed access to a project.
In a production system we would store these credentials as environment variables with the system and then query these "envvars" each time the code is redeployed. This ensures that passwords and auth tokens are never stored in a version control system. However, since we are solely interested in building a "toy" trading system, and are not concerned with production details in this article, we will instead separate these auth tokens into a settings file. In the following settings. Each sub dictionary contains three separate API endpoints: The sandbox API is purely for testing code and for checking that there are no errors or bugs.
It does not have the uptime guarantees of the real or practice APIs. The practice API, in essence, provides the ability to paper trade. That is, it provides all of the features of the real API on a simulated practice account. The real API is just that - it is live trading! If you use that endpoint in your code, it will trade against your live account balance.
When trading against the practice API remember that an important transaction cost, that of market impact , is not considered. Since no trades are actually being placed into the environment this cost must be accounted for in another way elsewhere using a market impact model if you wish to realistically assess performance. We need two separate dictionaries for the domains, one each for the streaming and trading API components. The next step is to define the events that the queue will use to help all of the individual components communicate.
The second is used to transmit orders to the execution handler and thus contains the instrument, the number of units to trade, the order type "market" or "limit" and the "side" i.
To future-proof our events code we are going to create a base class called Event and have all events inherit from this. The code is provided below in events. The next class we are going to create will handle the trading strategy. Clearly this is a ridiculous "strategy"! However, it is fantastic for testing purposes because it is straightforward to code and understand.
In future diary entries we will be replacing this with something significantly more exciting that will hopefully turn a profit! Let's work through it and see what's going on. Firstly we import the random library and the OrderEvent object from events.
We need the random lib in order to select a random buy or sell order. We need OrderEvent as this is how the strategy object will send orders to the events queue, which will later be executed by the execution handler.
It then creates a ticks counter that is used to tell how many TickEvent instances it has seen. It then checks to see if the count is divisible by 5 and then randomly buys or sells, with a market order, the specified number of units.
The next component is the execution handler. That is, there is no risk management or potfolio construction overlay. The execution handler will simply execute any order that it has been given. We must pass all of the authentication information to the Execution class, including the "domain" practice, real or sandbox , the access token and account ID.
We then create a secure connection with httplib , one of Pythons built in libraries. The method requires an event as a parameter. It then constructs two dictionaries - the headers and the params. We pass the Content-Type and Authorization header parameters, which include our authentication information. Finally, we make the request and save the response:. There are two methods:More...