Categories
Forex Basic Strategies Forex Trading Strategies

Algorithmic Trading 101

Algorithmic trading (also called automated trading, black-box trading, or algo-trading) uses a computer program that follows a defined set of instructions (an algorithm) to place a trade. The trade, in theory, can generate profits at a speed and frequency that is impossible for a human trader.

The defined sets of instructions are based on timing, price, quantity, or any mathematical model. Apart from profit opportunities for the trader, algo-trading renders markets more liquid and trading more systematic by ruling out the impact of human emotions on trading activities.

Algorithmic Trading in Practice

Suppose a trader follows these simple trade criteria:

  • Buy 50 shares of a stock when its 50-day moving average goes above the 200-day moving average. (A moving average is an average of past data points that smooths out day-to-day price fluctuations and thereby identifies trends.)  
  • Sell shares of the stock when its 50-day moving average goes below the 200-day moving average.

Using these two simple instructions, a computer program will automatically monitor the stock price (and the moving average indicators) and place the buy and sell orders when the defined conditions are met. The trader no longer needs to monitor live prices and graphs or put in the orders manually. The algorithmic trading system does this automatically by correctly identifying the trading opportunity.

Benefits of Algorithmic Trading

Algo-trading provides the following benefits:

  • Trades are executed at the best possible prices.
  • Trade order placement is instant and accurate (there is a high chance of execution at the desired levels).
  • Trades are timed correctly and instantly to avoid significant price changes.
  • Reduced transaction costs.
  • Simultaneous automated checks on multiple market conditions.
  • Reduced risk of manual errors when placing trades.
  • Algo-trading can be backtested using available historical and real-time data to see if it is a viable trading strategy.
  • Reduced the possibility of mistakes by human traders based on emotional and psychological factors.

    Algorithmic trading provides a more systematic approach to active trading than methods based on trader intuition or instinct.

    Algorithmic Trading Strategies

    Any strategy for algorithmic trading requires an identified opportunity that is profitable in terms of improved earnings or cost reduction. The following are common trading strategies used in algo-trading:

    Trend-following Strategies

    The most common algorithmic trading strategies follow trends in moving averages, channel breakouts, price level movements, and related technical indicators. These are the easiest and simplest strategies to implement through algorithmic trading because these strategies do not involve making any predictions or price forecasts. Trades are initiated based on the occurrence of desirable trends, which are easy and straightforward to implement through algorithms without getting into the complexity of predictive analysis. Using 50- and 200-day moving averages are a popular trend-following strategy.

    Arbitrage Opportunities

    Buying a dual-listed stock at a lower price in one market and simultaneously selling it at a higher price in another market offers the price differential as risk-free profit or arbitrage. The same operation can be replicated for stocks vs. futures instruments as price differentials do exist from time to time. Implementing an algorithm to identify such price differentials and placing the orders efficiently allows profitable opportunities.

    Index Fund Rebalancing

    Index funds have defined periods of rebalancing to bring their holdings to par with their respective benchmark indices. This creates profitable opportunities for algorithmic traders, who capitalize on expected trades that offer 20 to 80 basis points profits depending on the number of stocks in the index fund just before index fund rebalancing. Such trades are initiated via algorithmic trading systems for timely execution and the best prices.

    Mathematical Model-based Strategies

    Proven mathematical models, like the delta-neutral trading strategy, allow trading on a combination of options and the underlying security. (Delta neutral is a portfolio strategy consisting of multiple positions with offsetting positive and negative deltas—a ratio comparing the change in the price of an asset, usually a marketable security, to the corresponding change in the price of its derivative—so that the overall delta of the assets in question totals zero.)

    Trading Range (Mean Reversion)

    Mean reversion strategy is based on the concept that the high and low prices of an asset are a temporary phenomenon that reverts to their mean value (average value) periodically. Identifying and defining a price range and implementing an algorithm based on it allows trades to be placed automatically when the price of an asset breaks in and out of its defined range.

    Implementation Shortfall

    The implementation shortfall strategy aims at minimizing the execution cost of an order by trading off the real-time market, thereby saving on the cost of the order and benefiting from the opportunity cost of delayed execution. The strategy will increase the targeted participation rate when the stock price moves favorably and decrease it when the stock price moves adversely.

    Beyond the Usual Trading Algorithms

    There are a few special classes of algorithms that attempt to identify “happenings” on the other side. These “sniffing algorithms”—used, for example, by a sell-side market maker—have the built-in intelligence to identify the existence of any algorithms on the buying side of a large order. Such detection through algorithms will help the market maker identify large order opportunities and enable them to benefit by filling the orders at a higher price. This is sometimes identified as high-tech front-running.

    Categories
    Forex Videos

    Forex Trading Algorithms Part 5 Elements Of Computer Languages For EA Design!

     

    Trading Algorithms – The Elements of a Computer Language – Part III: Objects

     

    The most striking feature of modern programming is object-oriented programming. This video will explain the underlying philosophy and why OOP is such a big deal in modern app development.

     

    Procedural programming versus OOP

    Traditional programming is based on procedures or functions applied to a pre-defined collection of data structures. The main procedure starts moving and modifying variables and structures to obtain an output to print or display on a screen. 

    The main drawback is that most of the primary data is globally allocated and potentially modified by other application sections. Thus a change to improve or correct one section of the code may interact with other sections, potentially creating hard to detect new bugs. The maintenance of large projects based on procedural programming is a nightmare, especially when a different programmer has to do it.

     

    Object-oriented programming, on the other hand, uses objects with their own inner data structures. So, code mods happen within a single self-contained object, and any new bug is limited to that object.

     

    Classes

    The basic unit on Object-Oriented Programming is the Class. A Class is the description of an Object. Then, several objects are to be created using that Class description, called “instances” of the Class. 

    Simply put, a Class is a collection of data structures and the procedures or functions allowed for these data structures. Classes provide data and function together. 

    In our real-life, we are surrounded by objects with shape and functionality, such as cars, TVs, houses, and pants. All have their intrinsic properties. A vehicle has an engine, four wheels, battery, throttle, brakes, steering wheel, doors, seats, and so forth, and all these parts are also objects. But not all cars are equal; brand, color, engine power, seat materials, etc., change. That also happens with computer objects.

    A new class can be created from a parent class, with new functionality, or with changing functionality from the parent class in a process called “inheritance.”

     

    An example of a class

    The Bag class is just a container for other objects. We can add or take out items to and from the Bag. The main data storage is in the self.data variable. But, bear in mind that self.data is different for every new Bag object created!. We can see that the data structure of the Bag object cannot be accessed but with the supplied methods, addsub, and show.

     

    A Python financial class

    A financial class can be made of around a historical OHLC data structure. Using it, we can create new information such as indicators and various stats, such as swing high/low length and duration statistics, and other information related to price analysis and forecasting.

    You can see an example of what a pro-built class can do by looking at the stock-pandas class package documentation. We can see that the stock-pandas project is solely focused on the creation of a class to handle statistics and indicators for a financial data series, presenting a complete package.

    As we can see, the advantages of OOP are huge. Packages can be built, which, later, can easily be versioned, updated, and expanded. The creation of apps using classes and OOP is much more straightforward, so the time needed to complete a project is shortened drastically.

    Now that we have reviewed the basics of modern programming, let’s move back to trading algorithms.

    Categories
    Forex Videos

    Forex Trading Algorithms Part 4 Elements Of Computer Languages For EA Design!

    Trading Algorithms – The Elements of a Computer Language – Part II

     

    A computer program is a combination of data structures and a set of instructions or commands in the form of functions that process the data structures to construct a solution or solutions.

     

    Control flow tools

    To efficiently process information, a high-level programming language owns specific instructions to do mathematical operations, check for conditions, and control data flow.

     

    The if Statement:

    The if statement is the most basic flow-control instruction. It allows us to check for conditions or the validity of a statement.

    for example, 

    if x > 0 checks for the variable x being higher than zero. If it is zero or negative, it will deliver a False value. If over zero, it will provide a True condition.

    The if statement, combined with the else statement, handles the flow of the information. If/else is mostly similar in all languages. ( Example taken from docs.python.org 

    Iterators

    Iterators are used to move through the components or a data structure, such as lists or arrays. There are several ways to iterate, some language-specific, but most are present in all languages.

     

     The for statement

    The for statement is used to do an orderly iteration on an array or list. In C++, it has the following structure:

    for (initialization; condition; increase) . Initialization is the starting point; condition defines the endpoint, and increase sets the step.

    CPP example, source cplusplus.com

    Python’s for is more versatile and simple. To loop through a list is straightforward (taken from docs.python.org):

    But we can use the range() function to do a similar C++ for (taken from docs.python.org):

    The While statement

    The while statement creates a computer loop that is exited only after a certain condition is met:

    For example, the above while loop appends the Fibonacci numbers up to n, storing them in the fibo list. The loop breaks only when a is bigger than n.

     

    Function definition

    In a computer app, the code repeats itself most of the time, sometimes the values may be different, but the basic computational structure is the same. To organize these computational structures, all computer languages have functions. 

    In C++ a funtion is defined with the following structure:

    <out type> function name (<type> parameter1, …. <type> parameter n){

    body

    }

    The out type is the output type of the function. It can be an integer, a floating-point, or any other data structure, pointer, or no output at all.

    The parameters are inputs to the function but can be used to modify an external structure as well.

    In Python, the definition is simpler. 

    def function_name ( parameter1…parameter n):

    body

    If the function returns a value or data structure, it is delivered through a return statement.

    The following example shows the fib function, which computes the Fibonacci numbers up to the input parameter. The results of the Fibonacci computations are stored in the fibo list, which, after exiting the while loop, is returned. The variable res is assigned the output of the fib function and printed. Please note that the last two statements are not part of the fib function.

    The last introductory article on high-level languages will talk about classes, objects, and object-oriented programming.

    Once we have completed this basic wrap-up on programming language features, we’ll start studying trading-focused algorithms in the coming videos.