Market Update 4/26 – E-mini S&P 500

What a difference a week makes. Since our last update we had the results of the French elections and the world markets seem to like what they see. Bears have failed yet again to do any serious technical damage and the S&P has managed to breakout to the upside from the channel shown below.

Note though that the momentum is still on the weak side and there are resistance levels above that need to be taken out. It seems likely that we will see at least a test of 2400 as it’s only 15 points away. Whether we see more upside will depend a great deal on news coming out of Washington regarding taxes and of course any geopolitical developments.

Market Update 4/19 – E-mini S&P 500

The market is currently in a risk off period due to geopolitical events so we expect more pressure to the downside. We have been seeing a series of lower highs along with decreasing momentum on the daily chart of the E-Mini S&P 500 futures and are approaching the bottom of a descending triangle pattern. A break down below the 2320 area would most likely lead to a significant drop down to support in the 2260 area. An aggressive trader could take a short position towards the upper trend line of the triangle allowing for a tight stop loss.

Getting started with the Interactive Brokers API, Part 1

Interactive Brokers offers an advanced application programming interface (API) that is available to retail brokers allowing for the creating of advanced algorithmic trading strategies. In this series of articles we are going to dive into how to use the API to connect to the broker, stream real time quotes, retrieve historical data, manage positions and much more. This article assumes that the reader has an account with Interactive Brokers and the account has permissions for real-time data.

In this first article we will discuss setting up your development environment and connecting to the Interactive Brokers servers. We are going to use the Python programming language to manage our connection to the Interactive Brokers servers and we are going to stream real-time bid, ask and last price quotes. The Python API was only introduced as an officially supported language by Interactive Brokers fairly recently but is stable and easy to use.

The output you will see will look something like this;

Installing Python

If you do not have Python on your system a good place to start would be to install the Anaconda Python distribution. This makes getting started with Python extremely easy. The installer can be found here;

https://www.continuum.io/downloads

For this article we are using the Windows 64bit installer of Python version 3.6

Getting the API software

To interact with the Interactive Brokers (IB) servers you need to have the Trader Workstation (TWS) API software. It is available on the IB Github page and can be found here;

http://interactivebrokers.github.io/

The TWS API is a programming interface to the IB TWS and as such an instance of TWS is required to connect to. You can do this by either running TWS or by running the IB Gateway. For our purposes running the Gateway is preferable as it’s a lightweight application and we are not going to use any of the features of the TWS application.

Before you start

Before we can connect to the IB Gateway we need to allow connections to TWS.  It needs to be configured to listen for incoming API connections on a very specific port. Please refer to this IB page to setup your TWS settings: https://interactivebrokers.github.io/tws-api/initial_setup.html#gsc.tab=0

Getting the code

The full example code for this article can be found here: https://github.com/scalptrader/ScalpTrader-IBTWS

In the repository you will see a couple of Python files and a folder called ibapi which is the IB TWS API files that you downloaded from the IB servers above.

We will be looking into the main file, ibclient.py. The file logger.py is a simple logging class that creates log files.

IBClient

The IBClient class performs all the logic required to connect to the IB TWS and start streaming real-time data. Let’s look at the main parts of the code starting at the main entry point

The first thing we do is start logging. It’s useful to log the start time to know how long your connection lasted

logger.debug("Start time is %s" % datetime.datetime.now())

Next we create our application

app = IBClientApp()

If you take a look at the IBClientApp class constructor you will see that it is derived from the IBWrapper and IBClient classes

class IBClientApp(IBWrapper, IBClient):

These are the IB TWS API classes that allow us to connect to the IB TWS service. The next line connects us to the IB TWS servers

app.connect("127.0.0.1", 4001, clientId=0)

Remember we are running the IB Gateway and have set that up to allow connections on port 4001 (specified in the connect args)

We check to see if the application connected successfully. If it did, we then request real-time market data for the symbol CLK7 which is the symbol for the WTI Crude Oil futures contract for May 2017

if( app.isConnected() ):
    # Request tick data for WTI Crude futures contract (May 2017)
    symbol = 'CLK7'

    app.requestMarketData(symbol)
    app.run()

Once we have called the app.run() method the application will wait for event callbacks from the IB TWS API. You will get the callbacks as long as you have a wrapper for the tickPrice and tickSize methods

@iswrapper
def tickPrice(self, reqId: TickerId, tickType: TickType, price: float, attrib: TickAttrib):
    super().tickPrice(reqId, tickType, price, attrib)
@iswrapper
def tickSize(self, reqId: TickerId, tickType: TickType, size: int):
    super().tickSize(reqId, tickType, size

When those methods get called you will receive a tickType.

This will be one of the enums that is defined in the IB TWS API

# From TickTypeEnum
# 0    BID_SIZE
# 1    BID
# 2    ASK
# 3    ASK_SIZE
# 4    LAST
# 5    LAST_SIZE
# 8    VOLUME

As you can see it’s easy to pull out the latest bid, ask and last quotes along with the volume for each tick that the IB TWS gives us.

That’s really all there is to it. The IB TWS API makes it very easy for the Python programmer to access fast, reliable market data with minimal application code.

 

Identifying intraday trading setups

Some of the best setups during the day happen after a period of consolidation over a longer period of time. We are going to look at how to divide the trading day up into 4 hour segments. We will then dive down into those segments to identify patterns that we can use for trading setups. We will discuss how to setup an indicator in to highlight the 4 hour periods on the price chart as this will help us easily visualize the price action we are interested in.

Writing the indicator

For this indicator we are going to be using the TradingView platform. The indicator will be scripted using the Pinescript language. For further reference on Pinescript you can visit TradingView.com for excellent documentation.

The futures markets trade 24 hours a day so there are six 4 hour periods in a single day. We can define those periods as variables in our script;

segment1 = "0200-0600" // 2am to 6am
segment2 = "0600-1000" // 6am to 10am
segment3 = "1000-1400" // 10am to 2pm
segment4 = "1400-1800" // 2pm to 6pm
segment5 = "1800-2200" // 6pm to 10pm
segment6 = "2200-0200" // 10pm to 2am

Now that we have our time periods setup we need to determine if a price bar is inside a given time period. This will allow us to color the background of the price chart to easily identify the 4 hour periods. To do this we will define the following function;

barInSegment(segment) => na(time(period, segment)) == false

This line returns true if a price bar is inside a 4 hour time period segment. We then use this function to alter the background color of each price bar. For example we can set the background color to blue if a price bar is within our first segment with a call like this;

// Color the background for a price bar in the first segment
bgcolor(color=BarInSegment(segment1)[1] ? #0000FF10 : na )

The value #0000FF10 defines the color we will use. The value is in a format called RGBA (red, green, blue, alpha) In this case we are setting the blue value to FF which is the maximum value for the blue component and the alpha component is set to 10 which will make the blue transparent. We can define a couple of variables for a couple of shades of blue to make it easier to read;

blue1 = #0000FF10
blue2 = #0000FF08

To highlight all of the segments in the 24 hour period we repeat the same idea for the six time segments. We alternate the color to a different shade of blue for every different segment to make them easily identifiable;

bgcolor(color=BarInSegment(segment1)[1] ? blue1 : na )
bgcolor(color=BarInSegment(segment2)[1] ? blue2 : na )
bgcolor(color=BarInSegment(segment3)[1] ? blue1 : na )
bgcolor(color=BarInSegment(segment4)[1] ? blue2 : na )
bgcolor(color=BarInSegment(segment5)[1] ? blue1 : na )
bgcolor(color=BarInSegment(segment6)[1] ? blue2 : na )

Once the indicator is applied to the chart we see the 4 hour segmets highlighted. This chart shows the indicator on a 15 minute chart of WTI crude oil

Crude oil futures chart

Finding patterns within segments

Now if we dive into each segment from left to right we can extract the patterns that setup within each segment. We are planning our next trades based on the previous segment.

Crude oil futures chart

Now that we have the price action broken down into segments let’s break it down. In the first segment (1) we see a triangle pattern. When price contracts like this we usually get a break out which happens in this case at (2). Those events both happened in the first segment. Now we watch to see what happens in the next segment. Often after a upwards thrust we will see consolidation or sideways movement and this is exactly what happens at (3). A rectangle is formed with a well defined range . A trader seeing such a range occur will be looking for a breakout of that range which happens in the next segment at (4) and ends in a flag pattern. For the next segment we will be looking to see if price breaks out higher above the flag pattern high or breaks down. In this case price moves lower at (5). Within this segment we have a break down from a flag pattern, a down thrust move and another consolidation pattern all within that segment. At (6) the break out above the previous segments range is bought. The strong upwards thrust move (7) again ends in a sideways consolidation pattern. In the next segment at (8) price runs into some resistance and forms a nice topping pattern (8) & (9). We can easily see the ascending triangle pattern and this time it breaks down.

As you can see just from this short period of time there are many trade setups available to the trained eye. Breaking up the trading session into these 4 hour segments helps give structure to the price action.

The complete script for highlighting the 4 hour segments is available for download at our GitHub site;

https://github.com/scalptrader/IdentifyingIntradayTradingSetupsPart1

If you would like to be notified of new articles from ScalpTrader please subscribe to our mailing list or follow us on Twitter