Discover the inner workings of today's forex market, the essential risks in forex algo trading, and how to mitigate them
Key Features
• Build trading applications with research and without advanced Python programming skills
• Dive into professional fx trading while enhancing your trading apps to be more accurate
• Develop simple yet efficient backtesting applications to help keep your expectations realistic
Book Description
Algorithm-based trading is a popular choice for Python programmers due to its apparent simplicity. However, very few traders get the results they want, partly because they aren't able to capture the complexity of the factors that influence the market. Getting Started with Forex Trading Using Python helps you understand the market and build an application that reaps desirable results.
The book is a comprehensive guide to everything that is market-related: data, orders, trading venues, and risk. From the programming side, you'll learn the general architecture of trading applications, systemic risk management, de-facto industry standards such as FIX protocol, and practical examples of using simple Python codes. You'll gain an understanding of how to connect to data sources and brokers, implement trading logic, and perform realistic tests. Throughout the book, you'll be encouraged to further study the intricacies of algo trading with the help of code snippets.
By the end of this book, you'll have a deep understanding of the fx market from the perspective of a professional trader. You'll learn to retrieve market data, clean it, filter it, compress it into various formats, apply trading logic, emulate the execution of orders, and test the trading app before trading live.
What you will learn
• Explore the forex market organization and operations
• Understand the sources of alpha and the concept of algo trading
• Get a grasp on typical risks and ways to mitigate them
• Understand fundamental and technical analysis
• Connect to data sources and check the integrity of market data
• Use API and FIX protocol to send orders
• Translate trading ideas into code
• Run reliable backtesting emulating real-world market conditions
Who this book is for
This book is for financial traders and python developers who are interested in forex trading. Academic researchers looking to focus on practical applications will find this book useful. This book can also help established fx market professionals who want to take the first steps in algo trading. Familiarity with Python and object-oriented programming within the scope of an online course or self-study is a must. Knowledge of network protocols and interfaces is a plus but not a prerequisite, as is specific knowledge about markets and trading.
Author(s): Alex Krishtop
Publisher: Packt Publishing
Year: 2023
Language: English
Pages: 341
Preface
Part 1: Introduction to FX Trading Strategy Development
1
Developing Trading Strategies – Why They Are Different
Trading strategies – it’s all about how you manage risk
Trading strategies – how we make money in financial markets
Trading app – what can be simpler?
So, what about that risk?
Automated trading – operational risk and regulatory limitations
Retrieving market data – quality and consistency as keys to success
Receiving data – when size does matter
Received data – looking at it from a critical angle
Making actual trading decisions – trading logic and credit risk
Ordering – transactional risk
The general architecture of a trading application
Summary
2
Using Python for Trading Strategies
Technical requirements
The advantages of using Python in trading strategy development
Memory management
Interactive computing
Ease of integration and routing
Native language structures – lists and dictionaries
Libraries
Modeling – forecasting the future doesn’t necessarily mean practical benefits
Paper trading and backtesting – an essential part of a systemic trader’s risk management
What are paper trading and backtesting?
Backtesting and paper trading in Python
The disadvantages of using Python in trading strategy development
Live trading – where Python faces its limits
Summary
3
FX Market Overview from a Developer's Standpoint
Trading venues – where money meets… other money
Organizing chaos – types of trading venues
Auction (open outcry)
Exchange and order book
OTC markets
Liquidity and order limitations
Trade mechanics – again, some terminology
Market makers – comfortable, sophisticated, expensive
Counterparties that provide liquidity
How do market makers make money?
Market risk and how market makers mitigate it
Reasons to trade with market makers
Liquidity providers – the whales that support this planet
Liquidity and volatility – how one transforms into another
ECN – looks like a fair game, but is it?
The organization of ECNs
ECN – not all market participants were created equal
Aggregation – in search of the best price
Trading the FX market – what and how
FX instruments
Naming conventions
How do I place a trade?
Why do I need all this?
Summary
Part 2: General Architecture of a Trading Application and A Detailed Study of Its Components
4
Trading Application: What’s Inside?
Technical requirements
Have your app talk to the world – the gloomy world of communication protocols
FIX – universal but too flexible
Retrieving data – garbage in, garbage out
Tick sequence
Time gaps
Price gaps
Trading logic – this is where a small mistake may cost a fortune
Risk management – your safety belt
Ordering – make sure you are understood correctly
Summary
5
Retrieving and Handling Market Data with Python
Navigating through data
Tick data and snapshots
Timestamps – be careful comparing apples to apples!
Storing and retrieving tick data
Order book (depth of market)
Storing and retrieving order book data
Data compression – keeping the amounts to a reasonable minimum
Retrieving compressed data
Compressing market data in Python
Working with saved and live data – keeping your app universal
Universal data connector
Data compression revisited
Summary
6
Basics of Fundamental Analysis and Its Possible Use in FX Trading
Fundamental analysis – intuitive but of little practical use
Economic news
US non-farm payrolls
Gross domestic product (GDP)
Economic news from a fundamental analysis perspective
Political events
US presidential elections, November 8, 2016
UK Brexit, June 23, 2016
Industry-specific information
Crude oil and the Canadian dollar
Summary
7
Technical Analysis and Its Implementation in Python
Technical analysis – ideal for computing, but missing real market processes
Velocity of the market
Digital filters
Range indicators
Volatility indicators
Key takeaways – what TA indicators are all about and how to use them
Implementation of TA indicators in Python
Sliding windows
Peeking ahead
The ultimate solution to the peek-ahead issue
Sliding window as a queue
Moving average – implementation
Stochastic oscillator – implementation
Summary
8
Data Visualization in FX Trading with Python
Technical requirements
The basics of charting with Python
Graphical backends
Static versus real-time data and related issues
Installing Matplotlib
Using Matplotlib in your code
Simple plots of market data
Visualizing static market data with pandas
Installing pandas
Reading data from CSV files with pandas
Setting index for a dataframe
Creating simple bar charts using pandas and mplfinance
Making slices and subsets in pandas
Plotting market charts with mplfinance
Visualizing live market data
Plotting live tick data
Plotting live bar or candlestick charts
Adding objects to price charts
Summary
Part 3: Orders, Trading Strategies, and Their Performance
9
Trading Strategies and Their Core Elements
Elements
Alpha and beta – widely used, widely confused
Alpha – earn from changes in price
Using currency rates as a benchmark
Common FX benchmarks – the USDX
Bank indices – more details, more confusion
Beta – earn on volatility
Options – stable income with unlimited risk
Alpha classics – trend-following, mean reversion, breakout, and momentum
Trend following
Mean reversion
Breakouts
Arbitrage – let’s earn from others’ mistakes
Statistical arbitrage
Event-driven trading strategies
Market-making – profiting on liquidity provision and associated risks
High frequency, low latency – where Python fails
Summary
10
Types of Orders and Their Simulation in Python
Order ticket – what you send is what you get
Market orders – the way to get maximum control over transactional risk
Possible execution issues
Limit orders – guaranteed price, but not execution
Possible execution issues
Time in force – better control over execution
Immediate or cancel
Fill or kill
Good for a day (GTD) and good till canceled (GTC)
Stop orders – maximum uncontrolled risk
Possible execution issues
Compound orders
Summary
11
Backtesting and Theoretical Performance
Trading app architecture – revised and improved
Market data component
Data aggregation component
Trading logic component
Order execution component
Advantages of the modular architecture
Multithreading – convenient but full of surprises
Trading application with live data feed
Backtesting – speeding up the research
Syncing threads using events
Backtesting platform with a historical data feed
Emulating order execution during backtesting
Equity curve and statistics
Summary – where do we go now?
Part 4: Strategies, Performance Analysis, and Vistas
12
Sample Strategy – Trend-Following
Trend-following revisited – trading setup
Determining a trend, part 1 – market model
Determining a trend, part 2 – moving averages
Entry and exit rules
Money management
Choosing the market and preparing data
Compressing data to a daily timeframe
Be careful with time!
Trend-following strategy – implementation
Summary
13
To Trade or Not to Trade – Performance Analysis
Trade analysis
Average trade and trading costs
Spread
Slippage
Commission
Overnight swaps
Measuring performance – alpha and beta revisited
Alpha in investment and trading
Beta
Net profit versus buy and hold
Drawdown
Risk/reward and return on drawdown
The power of leverage – how much do I need to trade it?
Summary
14
Where to Go Now?
Implementing limit and stop orders
The correct way to calculate the number of trades
From trading ideas to implementation – another sample strategy using limit and stop orders
Contingent orders
Money management and multiple entries
Strategy performance revisited – more metrics
More about the risks specific to algo trading
Classical technical trading setups
Optimization – the blessing and the curse of algo trading
Final words
Index