Coding “The Hammer” candlestick pattern with Python
The “Hammer” is a popular candlestick chart pattern used in technical analysis to help identify potential trend reversals in financial markets. The Hammer is a bullish reversal pattern that is formed at the bottom of a downtrend.
The Hammer candlestick pattern is recognized by a small real body (the difference between the open and close price) at the upper end of the trading range, with a long lower shadow (the difference between the low and the bottom of the real body). The Hammer pattern looks like a hammer, with the long lower shadow representing the handle and the short real body representing the head.
The Hammer pattern indicates that the sellers were in control at the beginning of the trading session, but the buyers took over and pushed the price higher. The long lower shadow shows that the price reached a low point during the session, but the buying pressure was strong enough to push the price back up, creating a small real body at the upper end of the trading range. This suggests that the buyers are gaining strength and the downtrend may be ending.
Traders use the Hammer pattern as a buy signal and often place a stop-loss order below the low of the Hammer. This is because if the price falls below the Hammer’s low, it would indicate that the buyers have failed to hold the price at the new level and the downtrend may continue.
Coding the Hammer with Python
Here’s some sample code for detecting the Hammer in Python using the pandas and ta libraries:
import pandas as pd
import ta
# Load historical price data from a CSV file
df = pd.read_csv('prices.csv')
# Calculate the Hammer pattern using the TA library
df['hammer'] = ta.CandlePatterns(df['Open'], df['High'], df['Low'], df['Close']).cdl_hammer()
# Filter the DataFrame to include only the Hammer patterns
hammer_df = df[df['hammer'] != 0]
# Print the number of Hammer patterns found
print('Number of Hammer patterns found:', len(hammer_df))In this code, we load historical price data from a CSV file into a pandas DataFrame. We then use the ta library's CandlePatterns function to calculate the Hammer pattern for each row of the DataFrame. The cdl_hammer() function returns 100 if the pattern is detected, -100 if the inverted Hammer pattern is detected, or 0 if neither pattern is detected.
We filter the DataFrame to include only the rows where the Hammer pattern is detected, and then print the number of Hammer patterns found.
Note that this is just a basic example, and you may want to add additional code to further analyze the patterns, such as calculating the stop loss and take profit levels, and implementing a trading strategy based on the pattern.
Obviously, my dear reader, more code is needed depending on the broker you´re using and the particular market where you wish to execute a trade when the Hammer appears. If, for example, you're with Interactive Brokers and watching the AAPL stock, waiting for a Hammer to appear, then:
import ibapi.wrapper as wrapper
import ibapi.client as client
import ibapi.order as order
from ibapi.contract import Contract
from ibapi.common import BarData
import pandas as pd
import ta
# Define the parameters for the contract you want to trade
symbol = 'AAPL'
sec_type = 'STK'
exchange = 'SMART'
currency = 'USD'
# Define the trading parameters
quantity = 100
order_type = 'MKT'
account = 'DU1234567'
# Create the contract object
contract = Contract()
contract.symbol = symbol
contract.secType = sec_type
contract.exchange = exchange
contract.currency = currency
# Create a class that inherits from the IB API wrapper and client classes
class MyWrapper(wrapper.EWrapper, client.EClient):
def __init__(self):
wrapper.EWrapper.__init__(self)
client.EClient.__init__(self, wrapper=self)
def nextValidId(self, orderId: int):
self.nextOrderId = orderId
def orderStatus(self, orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice):
print("Order Status: orderId=%s, status=%s, filled=%s, remaining=%s" % (orderId, status, filled, remaining))
def execDetails(self, reqId, contract, execution):
print("Order Executed: ", execution.orderId, contract.symbol, contract.secType, contract.currency, execution.shares, execution.price)
# Define a function to check for the Hammer signal
def is_hammer(candles):
# Calculate the Hammer pattern using the TA library
hammer = ta.CandlePatterns(candles['Open'], candles['High'], candles['Low'], candles['Close']).cdl_hammer()
if hammer[-1] == 100:
return True
else:
return False
# Connect to the IB API gateway
wrapper = MyWrapper()
client = wrapper
client.connect('HOST', 7497, 0)
# Wait for the connection to be established
while not client.isConnected():
time.sleep(1)
# Request historical candlestick data for the contract
client.reqHistoricalData(1, contract, '', '1 d', '1 hour', 'MIDPOINT', 0, 1, False, [])
# Wait for the historical data to be received
while not hasattr(wrapper, 'historicalData'):
time.sleep(1)
# Convert the historical data to a DataFrame and check for the Hammer signal
df = pd.DataFrame(wrapper.historicalData)
if is_hammer(df):
# Create an order object for the trade
ib_order = order.Order()
ib_order.action = 'BUY'
ib_order.totalQuantity = quantity
ib_order.orderType = order_type
ib_order.account = account
# Place the order
client.placeOrder(wrapper.nextOrderId, contract, ib_order)
# Disconnect from the IB API gateway
client.disconnect()This code connects to the IB API gateway, requests historical candlestick data for the specified contract, converts the data to a DataFrame, and checks for the Hammer signal using the is_hammer function. If the signal is detected, it creates an order object for the trade, sets the order parameters, and places the order using the placeOrder function. Finally, it disconnects from the IB API gateway.
The Hammer is a very interesting chart pattern, but there are others that show very profitable behaviors, too, so…
Stay tuned!





