Blog

Latest articles about MachineTrader™
Back

Trade on MACD-QQQ

January 15, 2024

Trade on MACD-QQQ

Intro

This strategy creates a portfolio of QQQ (Invesco Trust Series 1) that is traded in correspondence with logic defined by the Moving Average Convergence/Divergence (MACD) lagging indicator. The MACD strategy is a commonly employed algorithmic trading strategy, and can be calculated using Exponential Moving Averages (EMAs) by hand using the following formulas.

Luckily, all of the technical math behind this indicator is performed by our data provider, Polygon.io. Simply put, the goal behind a MACD strategy is to expose the difference between a “signal line” (in this case, a 9-period EMA) and the MACD line itself, as shown in the following figure.

Using the MACD value and the amount of the stock that is already being held (long or short), trading considerations can be made. For more information on where values in the following flow originate, and comparisons between MACD and Relative Strength Index (RSI) indication, refer here.

Strategy

The following image shows our pre-written MACD trading strategy. 

Before executing the actual trading strategy, we must first define some values to assist in front end reporting using the following flow.

At the beginning of the flow we see the following two nodes.

 

The inject node titled “GO” is used to begin the flow. Within the first function node titled “Define Trading Values” we see the following block of code, where we define all of the initial parameters of the trade.

On line 6, we define the ticker we would like to trade.

On line 9, we define the timespan for which the algorithm is run.

On line 11, we define the name of the algorithm, to be reported on the front end.

On line 12, we define the initial size of the portfolio, to be reported on the front end.

On line 13, we define whether we would like to use the live or paper Alpaca account.

On line 14, we define the desired number of shares to trade with.

On line 15, we define whether we are trading stocks or crypto.

On line 16, we define whether the algorithm is currently running or not, to be reported on the front end.

On line 17, we define whether the algo is interday or intraday, to be reported on the front end.

On line 18, we define the benchmark for the trade.

Finally, lines 21 through 23 define the window parameters of the MACD trade, as described above. These parameters are essentially the windows needed to compute the MACD value, using the formula given in the introduction (more information here). Changing any of these values will result in a different trade (i.e. different ticker or size), or a change in front end reporting. For consistency, ensure all values are correct before running. 

These are all of the necessary values that we, as algorithmic traders, must specify before running a trade. The rest of the nodes in this flow (from the first delay node to the last postgres node) function to store information from the algorithm into tables in postgres in order to update the front end. These nodes need not be altered. 

Moving onto the strategy itself, we begin the flow with an inject node titled “Every min” followed by a gate and a change node. We see next to the GO title a circular arrow, indicating that this is a recurring strategy; in other words, after injecting, it is run repeatedly on a certain interval.

To determine and/or change the timing of the interval, double click the inject node and edit the interval at the bottom of the screen. The default Trade on MACD-QQQ algorithm will be run once every minute.

The gate node is opened by injecting the “Start MACD Algo” node on the home tab. Once open, the algorithm is running. It is important to note that if run in a live account, this trade will trigger Pattern Day Trading, so we must have at least $25,000 in the account. The change node then initializes some variables—specifically ticker position and profit—to zero.

We then see the following six nodes, as shown below. The first function node titled “trading interval 9:30 - 3:50pm” defines the times during the day at which we want the algorithm to run. By default, this is set to the hours of 9:30 am to 3:50 pm. If not in between this range, the order is canceled, as indicated by the two nodes titled “prepare cancel order” and “Alpaca Close One Order.” To edit the time frame, it is possible to double click into the trading interval node and delete the “//” before a different time range. If this is done, ensure to place a “//” before the default range. 

Whether or not the order is canceled, the other three nodes are run. The goal of this part of the algorithm is to get a sense of the current positions of QQQ from Alpaca. If it is desired to run a MACD trade on a ticker other than QQQ, it is possible to edit the ticker of interest on line 2 of the function node titled “create flow vars for this ticker.” If this is done, it is recommended that the ticker within “Define Trading Values” in the flow we ran at start is also edited.

We then see a 1-second delay to ensure all variables are defined appropriately as above, and then a function node titled “Retrieve Flow Variables” where we redefine most of the values inherent to our trade. These nodes need not be changed. The next two nodes finally introduce the indicator of interest. In the function node titled “Hist vars,” the parameters needed to run an order to Polygon are retrieved. Default values are set from above, but can be altered within the function node “Define Trading Values.” 

Once all parameters are defined correctly, they are passed to Polygon. Polygon then passes the MACD results back, alongside other calculated values, such as the signal and the histogram (the difference between the MACD and the signal). All of this bookkeeping is taken care of in the function node titled “store Hist,” as shown below. The final three nodes include all of the logic behind a MACD trading algorithm, an order to Alpaca, and a debug node. The latter two nodes are self-explanatory, but we’ll look into the function node next.

Lines 1 through 23 set all necessary variables to perform MACD logic and complete an Alpaca trade. Following these lines are eight cases specific to MACD algorithms; below, we see the first case. If it is necessary to alter the logic behind these trades, for example, only trade when the histogram value is greater than or less than a certain value other than the default of ±.01, we are able to customize this by simply altering the numbers in the parenthesis next to each “if” statement.

For example, consider case 5 below, which is only executed if and only if the hist value is less than -.01 and we are holding a long position. Following the example above, if we want to only trade when the histogram is more extreme (to render more profit), we can change the highlighted value to whatever we choose.

Once this logic is passed to Alpaca, the order is either completed or nothing is done (i.e. Cases 6 and 8).

Another reason we may need to edit this logic is if we desire to work with more or fewer than 100 shares, in correspondence with msg.size defined within the “Store Flow Variables” node. In this case, each time the number 100 (or -100) appears in the parentheses next to an “if,” we must change it to the new desired portfolio size.

With this, finally, the flow is complete and we now have a complete algorithmic MACD trading strategy. 

Other features 

In the Trade on MACD-QQQ file there is one other feature that is worth mentioning. Injecting the following flow will print a report of the holdings for a given stock at a specific time each day. By default, this is set to 3:55 pm and the ticker “QQQ.” To change the time, double click on the inject node and change the time using military format at the bottom of the window. To change the ticker double click into the “prepare Positions query” node and edit the ticker of interest on line 1. The rest of the logic to close positions is taken care of, however, it should be noted that deploying in any capacity will render this flow active. If it is desired to deactivate this feature, disconnect the inject node from the “prepare Positions query” function node (then deploy), and no positions will close at the end of the day.

NOTE: ALL STRATEGIES ARE PROVIDED FOR ILLUSTRATIVE PURPOSES ONLY AND SHOULD NEVER BE IMPLEMENTED IN LIVE TRADING ACCOUNTS WITHOUT CAREFUL REVIEW. MACHINETRADER IS NOT RESPONSIBLE FOR TRADING LOSES INCURRED AS A RESULT OF CODING ERRORS.

BY
Erik Heitsmith, Trading Strategy Analyst

January 18, 2024

Interest in Bitcoin ETFs Falls Fast on the 3rd Day of Trading

Trading activity in the new Bitcoin ETFs fell rapidly yesterday. While several of the ETFs made it into the top 5 most heavily traded ETFs on Friday, interest on Tuesday, when trading resumed after the MLK holiday, the bloom was off the rose.

>Read More

January 15, 2024

Bitcoin ETFs Debut with a Splash

The long-awaited Bitcoin ETFs debuted in yesterday's trading, making quite a splash. Three Bitcoin ETFs were among the five most actively traded ETFs: GBTC, IBIT, and FBTC, all trading more than 10 million shares.

>Read More

January 15, 2024

Day Trading

Day trading is a trading strategy where traders buy and sell securities within the same trading day taking advantage of short-term price fluctuations in various assets to make quick profits. Day traders aim to capitalize on small price movements by entering and exiting positions multiple times throughout the day.

>Read More

January 15, 2024

Day Trading Strategies

Day traders employ a variety of strategies in the quest to make profitable trades. This is a list of the more common ones:

>Read More

January 15, 2024

Quantitative Trading

Quantitative trading, also known as algorithmic trading or algo trading, is a method of trading financial assets using advanced mathematical and statistical models. It involves the use of computer algorithms to execute trades based on predefined rules and strategies. This approach to trading has gained significant popularity in recent years, with many institutional investors and hedge funds adopting it as an integral part of their investment strategies.

>Read More

January 15, 2024

Swing Trading

Swing trading is a popular trading strategy that involves taking advantage of short-term price movements or "swings" within a larger trend. Swing traders aim to capture gains by entering and exiting positions over a period of days or weeks, rather than holding positions for months or years like long-term investors.

>Read More

January 15, 2024

Algorithmic Trading

The main objective of algorithmic trading is to maximize profits by taking advantage of short-term market inefficiencies. It aims to exploit price discrepancies, liquidity imbalances, and other temporary market conditions that might arise within fractions of a second. By automating the trading process, algorithmic trading eliminates human emotions and biases, enabling faster and more efficient execution of trades.

>Read More

January 15, 2024

Trade on MACD-QQQ

This strategy creates a portfolio of QQQ (Invesco Trust Series 1) that is traded in correspondence with logic defined by the Moving Average Convergence/Divergence (MACD) lagging indicator. The MACD strategy is a commonly employed algorithmic trading strategy, and can be calculated using Exponential Moving Averages (EMAs) by hand using the following formulas.

>Read More

April 29, 2024

Trade IWB on News Sentiment

This strategy creates a portfolio of IWB (iShares Russell 1000 ETF) that is bought based on the recent news sentiments. The state of the news being reported has an incredible effect on the stock market, as popular reporting agencies can directly increase/decrease people’s optimism about the economy, leading to a snowball effect, of sorts.

>Read More

January 17, 2024

Build a Crypto ETF in MachineTrader™

Building custom ETFs using MachineTrader™ visual programming toolkit is easy to do and often an effective way to enhance your portfolio. While technically these aren’t algorithmic trading strategies, you can easily add flows that will optimize the ETF based on performance of the individual assets.

>Read More

January 17, 2024

Introducing - Independent Trading Platforms

The latest significant change in the investment world is the rise of what we call, "independent trading platforms" (ITPs). These are software platforms whose user-friendly web and mobile applications provide all of the functionality of trading platforms, but pass the actual trade executions off, through an API, to the registered broker-dealer of the user's choice.

>Read More

January 17, 2024

Why MachineTrader™?

Monitoring minute-by-minute (or second-by-second) changes in time series charts of prices is a pretty tedious task. While a number of trading platforms offer off-the-shelf algorithms or bots for automating strategies, we've found that it's hard to make money using an algo that other traders are employing, or worse, other traders have programmed to work against.

>Read More

January 17, 2024

Trading Stocks, Cryptos and Pattern Day Trading

You're a newbie to trading and you open your Robinhood account and begin to actively trade fractional shares of Tesla (TSLA). Your first dozen trades of the day work great as you pick the best moments to buy and sell. All of a sudden your account is flagged with a 'pattern day trader' warning.

>Read More