Reader small image

You're reading from  Getting Started with Forex Trading Using Python

Product typeBook
Published inMar 2023
PublisherPackt
ISBN-139781804616857
Edition1st Edition
Right arrow
Author (1)
Alex Krishtop
Alex Krishtop
author image
Alex Krishtop

Alexey Krishtop is a quantitative trader and researcher with 20 years of experience in developing automated trading solutions. He is currently the head of trading and research at Edgesense Technologies and CTO at ForexVox Ltd. He develops market models and trading algorithms for FX, commodities, and crypto. He was one of the first traders who started using Python as the ultimate environment for quantitative trading and suggested a few approaches to developing trading apps that, today, have become standard among many quant traders. He has worked as a director of education with the Algorithmic Traders Association, where he developed an exhaustive course in systematic and algo trading, which covers the worlds of both quantitative models and discretionary approaches.
Read more about Alex Krishtop

Right arrow

Where to Go Now?

Although the previous chapter sounded like the end of the book, I thought it would be unfair to leave you without giving some guidelines regarding further development of your knowledge and skills in FX markets and creating trading algorithms (algo). Unlike previous chapters, where each chapter was dedicated to a single large topic, this one is a collection of short stories about different aspects of FX algo trading, aiming to provide you with starting points for further research.

Mastering any complex subject requires effort and trading is probably the most time- and labor-consuming activity, which requires a very special attitude combining the mindsets of a scientist and a businessman. Any successful trading strategy or algorithm is a result of many hours of work, of which only 10-20% is spent on actual coding, debugging, and refactoring; the majority of time is always spent on studying the markets, in search of trading ideas and endless trial-and-error proofs...

Implementing limit and stop orders

In Chapter 10, Types of Orders and Their Simulation in Python, we considered three main types of orders: market, limit, and stop. However, so far, we have only used market orders in actual codes. Although we noted that a live trading application may not ever use stop and limit orders because they can be emulated on the client side and sent to the market as market orders when necessary, it would be definitely useful to have both types of orders implemented in the backtester to simplify the development of trading strategies.

Let’s quickly recall the essence of limit and stop orders.

A limit order is always executed at a price equal to the order price or better. This means that if the market price is currently 100 and a buy limit order is sent below the market, for example, at 99, then it will be filled only when the price becomes 99 or lower. If a buy limit order is sent above the market, for example, at 101, then it will be executed immediately...

The correct way to calculate the number of trades

When we were working with the trend-following strategy in Chapter 12, Sample Strategy – Trend-Following, we only opened new positions, and each opening closed the previously open one. This is normal for always-in-the-market strategies. In this case, indeed, the number of trades coincides with the number of executed orders.

In our example with a limit and a stop order, we use two orders to actually perform just one trade: buying and then exiting the market with a profit or loss. Therefore, we should only use the amount of entry orders to calculate the average trade. How can we distinguish between opening and closing orders?

There are multiple ways of doing that. One of the possible options would be adding another key to the order with values of Entry or Exit, but we will use a different approach: we will add a new attribute to the tradingSystemMetadata class, which will hold the actual number of trades, and we will update...

From trading ideas to implementation – another sample strategy using limit and stop orders

Let’s consider a practical application of the limit and stop orders that we have just implemented. I like using this example because it illustrates the importance of having a trading idea before writing the code and shows that trading ideas do not have to be complex. In practice, the simpler the trading idea, the greater the chance that it will work in production.

As you may remember from Chapter 3, FX Market Overview from a Developer’s Standpoint, most FX markets undergo a bank settlement procedure, which happens at 5 p.m. New York time. The price at the settlement is very important because it’s used to evaluate many other financial instruments and is used for settlement in all cash trades between any parties. So, comparing an intraday price to the last settlement price may give us an idea about the overall sentiment in this market: if it’s greater than...

Money management and multiple entries

To give you an idea about what money management is and how it may affect strategy performance, let me tell you about probably the most famous – or infamous – kind of money management technique, known as martingale.

The origin of martingale is in gambling. Imagine the simplest gambling game of a coin toss. You toss the coin and if it comes up heads, you win; if it comes up tails, you lose. We can use 1 for wins and -1 for losses and the series of tosses can be represented by a sequence as follows:

S = {1, -1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, ...}

If you put at stake an equal amount of money each time you toss the coin, we can multiply the sequence by that amount and write it like so:

S1 = {b, -b, -b, b, -b, b, b, b, -b, -b, b, -b, ...}

Here, b refers to the size of the bet. Obviously, your total win in the game is the sum of the entire series. In an idealistic model, the results of each toss are independent of each...

Strategy performance revisited – more metrics

In Chapter 13, To Trade or Not to Trade – Performance Analysis, we considered only the very basic performance metrics. Of course, there are many others that are no less important. I recommend starting with the nice overview from Quantinsti (https://blog.quantinsti.com/performance-metrics-risk-metrics-optimization/), implementing each metric in the code, and then you can analyze your strategies as market professionals do.

More about the risks specific to algo trading

We have already considered the main risks in any trading: operational, systemic, and transactional. Let’s highlight another kind of risk that is specific to algo trading.

When you develop and backtest a strategy using compressed data, along with limit or stop orders, there is a risk that more than one of these orders will be simulated on the same bar. Typically, this happens when the order prices are too close to each other and the data resolution is not granular enough. For example, if you place a limit and a stop order at a distance of 5 pips from each other and run a backtest using daily data, then on most days, both orders should be executed during a single bar. This is what you want to avoid at all costs because the backtester has no idea about how the price has actually moved inside this single bar and therefore no one knows which of the two orders will have been triggered first and which next. So, it is extremely important...

Classical technical trading setups

In Chapter 7, Technical Analysis and Its Implementation in Python, we considered a number of classical technical analysis indicators, such as the RSI, a stochastic oscillator, moving averages, and Bollinger bands. We saw that each of these indicators is able to bring into focus a certain property of the price time series: for example, Bollinger bands are a volatility indicator, and moving averages are digital filters that remove higher frequencies from the price data. However, we didn’t consider any classical trading setup with any of these indicators. Why?

The answer to this question is twofold. First, these setups can be found in literally any book or internet publication about technical analysis. You can start with an overview of technical indicators at Investopedia (https://www.investopedia.com/terms/t/technicalindicator.asp) and then follow the links to articles on specific indicators to see how they are supposed to be used to generate...

Optimization – the blessing and the curse of algo trading

Do you remember how the performance of a simple overnight strategy that we created earlier in this chapter radically changed when we replaced a tight stop of 5 pips with a wider stop of 50 pips?

But this fact raises another important question: why 5 and 50 pips? Why not 6 and 45? Or 10 and 76?

Any quantitative strategy depends on the values of its parameters, and the procedure of finding the best combination of parameters that delivers the best results of the backtesting is called optimization.

Optimization is a massive topic. I’d even say it’s overwhelmingly vast and complex. At first glance, it looks straightforward: let’s find the best combination of parameter values and then run the strategy live with these very values. However, the problem is that we always test and optimize our strategies using past data. And I hope you already understood and remember well that markets are anything...

Final words

Well, any story comes to an end sooner or later, and this book is no exception. Even if you opened it with no idea about FX markets and algo trading, now you have definitely taken yourself to a new level. You have knowledge about FX markets comparable to that of a beginner professional desk trader. You know how to develop trading applications for both live trading and producing reliable backtests. You also know the risks pertaining to trading, for algo trading in particular. You have plenty of roads to go down — in terms of money management, performance analysis, and optimization – but there is one thing I really want you to always remember whatever you do:

Any good trading strategy always has a trading idea behind it. No sophisticated mathematics, no money management, and no optimization will help if the strategy is just a randomly chosen combination of technical analysis studies and parameters. Look for ideas in the market and use the mathematical and...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Getting Started with Forex Trading Using Python
Published in: Mar 2023Publisher: PacktISBN-13: 9781804616857
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Alex Krishtop

Alexey Krishtop is a quantitative trader and researcher with 20 years of experience in developing automated trading solutions. He is currently the head of trading and research at Edgesense Technologies and CTO at ForexVox Ltd. He develops market models and trading algorithms for FX, commodities, and crypto. He was one of the first traders who started using Python as the ultimate environment for quantitative trading and suggested a few approaches to developing trading apps that, today, have become standard among many quant traders. He has worked as a director of education with the Algorithmic Traders Association, where he developed an exhaustive course in systematic and algo trading, which covers the worlds of both quantitative models and discretionary approaches.
Read more about Alex Krishtop