This Strategy Shows Promise For Trading Coffee Futures

Comments
Loading...

The Trend-Following strategy described in this article has shown considerable promise in trading Coffee futures. Read on.

In this article, we explore the development of a systematic trading strategy for coffee futures (@KC), which are traded on the Intercontinental Exchange (ICE) in New York. Our goal is to diversify a trading portfolio by incorporating lesser-known assets compared to more commonly traded futures.

Coffee futures belong to a category known as "soft commodities," which also includes futures contracts for sugar, cocoa, cotton, and orange juice. This market offers several appealing characteristics, including significant intraday volatility, a low correlation with equity futures, and decent trading volumes.

To analyze this market, we employ a Trend-Following approach, a strategy that has historically performed well across various commodity markets. Our objective is to determine whether this approach is equally effective for trading coffee futures.

Logic and Code Behind a Trend-Following Strategy for Coffee Futures

The strategy we aim to develop follows a Trend-Following approach, based on the breakout of significant highs and lows.

Specifically, the system enters a long position when the price surpasses the highest high recorded over a given number of sessions, defined as Highest(High, n_sessions). Conversely, it enters a short position when the price breaks below the lowest low over a set number of sessions, denoted as Lowest(Low, n_sessions).

The system remains active throughout the entire trading session of Coffee futures, which runs from 4:15 AM to 1:30 PM (exchange time), Monday through Friday. Entries and exits occur within the same trading day, meaning that all positions are closed by the end of the session unless the stop loss is triggered earlier. For this initial analysis, we set the Stop Loss at $1,500.

We evaluate the performance of our trading system in a 15-minute timeframe (data1) for trade execution and a daily timeframe (data2) for calculating entry levels, with historical data spanning from early 2010 to the end of 2023.

This concept translates into a few concise lines of code:

input:n_sessioni(5),mystop(1000),myprofit(0);

if EntriesToday(d)=0 then Buy next  bar at Highest(High,n_sessioni)data2 stop;

if EntriesToday(d)=0 then Sellshort next bar at Lowest(Low,n_sessioni)data2 stop;

if mystop>0 then setstoploss(mystop);

if myprofit>0 then setprofittarget(myprofit);

setstopcontract;

setexitonclose;

The first step in refining the strategy involves optimizing the number of sessions ("n_sessions") used to calculate breakout levels. To do this, we test values from 1 to 10 in increments of 1 and evaluate the impact on performance.

Figure 1 – Optimization of the "n_sessions" input to identify the optimal number of sessions for calculating highs and lows.

The optimization reveals that as the number of sessions increases, net profit and overall performance metrics tend to deteriorate, except for maximum drawdown, which remains relatively stable. Based on this analysis, we select n_sessions = 2, meaning that our entry levels are calculated based on the past two sessions’ highs and lows. A breakout of these levels triggers a position entry.

Examining the results from our first test, we observe a profitable and steadily growing equity curve, confirming that Coffee futures respond well to Trend-Following logic. While further refinements will be necessary, the initial results are promising, with an average trade of $62 and a net profit of $151,000. Not bad for an early-stage system without any additional filtering or optimizations!

Figure 2 – Detailed equity curve of the Trend Following strategy on Coffee futures.

Figure 3 – Strategy Performance Summary and Total Trade Analysis of the Trend Following strategy on Coffee futures.

To refine our Trend-Following trading system, the first step is to analyze whether adjusting the operational time window—rather than running the system for the full trading session—can lead to improved performance.

We modify the code by introducing a custom function and incorporating two new input parameters: "MyStartTrade" and "MyEndTrade", which specify the time window in which trades are allowed. We then proceed to optimize these parameters.

var:istartofsession(false);

istartofsession=_OHLCMulti5(0415,1330,ohlcvalues);

array:ohlcValues[23](0);

input: stoploss(1500), takeprofit(0);

input: MyStartTrade(415),MyEndTrade(1330);

input: n_sessioni(2);

//ingressi

if tw(MyStartTrade,MyEndTrade)

and EntriesToday(d)=0

then begin

               Buy next  bar at Highest(High,n_sessioni)data2 stop;

               Sellshort next bar at lowest(Low,n_sessioni)data2 stop;

end;

if stoploss>0 then setstoploss(stoploss);

if takeprofit>0 then setprofittarget(takeprofit);

setstopcontract;

setexitonclose;

Figure 4 – Optimization of the "MyStartTrade" input to determine the best time to start trading.

Figure 5 – Optimization of the "MyEndTrade" input to determine the best time to stop trading.

The optimization results indicate that shortening the trading window improves overall system performance. Specifically, adjusting the start time to 5:00 AM and the end time to 12:00 PM leads to a clear reduction in maximum drawdown from over $25,000 to less than $20,000.

This improvement likely occurs because early trading movements (immediately after the market opens) tend to be erratic and lack clear direction, while opening new trades after a certain time of the day makes little sense since all positions are closed by the end of the day.

Enhancing Performance: Implementing a Price Pattern Filter

To further refine our Trend-Following strategy, we now focus on one of the most crucial metrics for real-world trading: average trade value. For our system to be viable in live trading, this metric must be high enough to cover operational costs such as commissions and slippage. This is particularly relevant in the case of coffee futures, where each tick has a relatively high value of $18.75.

One possible enhancement is the addition of a filter based on the “Daily Factor” (DF)—a pattern that measures how much the prices of the prior day moved from the open to the close relative to their total daily range (high to low).

This pattern does not indicate market direction but provides information only about volatility: a low Daily Factor value suggests that prices moved very little relative to their total range, while a high Daily Factor value indicates strong price movement, signaling a clearly bullish or bearish session.

Once the Daily Factor ("DF") value is computed, we compare it against a predefined threshold ("DF_level") to determine whether or not to enter a trade. Both "DF" and "DF_level" range from 0 to 1.

To integrate this filter, we add the following lines to our script and optimize the "DF_level" parameter, testing values between 0.1 and 1 in increments of 0.05.

//Daily Factor

input:DF_level(1);

var: DF(0);

if (highs(1)-lows(1))<>0 then begin

                              DF=absvalue(opens(1)-closes(1))/(highs(1)-lows(1));

                              end;

Figure 6 – Optimization of the "DF_level" input to define the filter based on the Daily Factor pattern.

Based on the optimization, we choose a value of 0.8. In other words, we set the strategy so that it only opens a position if the previous session's body (Open-Close) is less than 80% of the range (High-Low). This approach increases our average trade by $20, pushing it above $80, while further reducing the maximum drawdown and boosting net profit.

Further Developments to Improve Performance: Weekdays

At this stage of our testing, we have a system that is significantly improved but still not ready for live trading with real funds. We need to identify effective solutions to continue refining our approach. One idea, for instance, is to exclude specific days of the week that, over the entire historical period analyzed, have consistently proven to be less profitable.

In parallel, we update our script by introducing two new inputs, "skipdaylong" and "skipdayshort," which designate the trading days to exclude from our strategy. We then optimize these inputs within a range from 1 to 6, since in the programming language of the MultiCharts platform, these values represent the days of the week, with 1 corresponding to Monday and 6 to Saturday.

input: skipdaylong(-1),skipdayshort(-1);

if dayofweek(d)<>skipdaylong then Buy next  bar at Highest(High,len)data2 stop;

if dayofweek(d)<>skipdayshort then Sellshort next bar at Lowest(Low,len)data2 stop;

Figure 7 – Results of the optimization for the "skipdaylong" and "skipdayshort" inputs, sorted by average trade.

To validate our optimization results, we use a proprietary program that enables us to analyze the bias of each instrument at various levels—from intraday hourly bias to monthly and yearly bias. Examining Figure 8, we immediately notice that on Mondays (highlighted in the figure), Coffee futures tend to move sideways without a well-defined trend. In contrast, on the other days, the trend is clearer and generally bearish for this instrument. Furthermore, a Daily Factor measured on Fridays is evidently weaker than one measured on any other day. Based on these observations, we have decided to exclude Mondays from our trading operations, which helps us move closer to a $100 average trade.

Figure 8 – Results of the weekly bias analysis for Coffee futures, carried out using the proprietary Bias Finder software.

Strategy Exit Optimization and Final Performance

As the final step in our test, we perform our usual stop-loss optimization, which had previously been set to $1,500. At the same time, we introduce a profit target to assess whether it provides additional benefits. As a result of this final refinement, we choose $1,700 for both the stop-loss and the profit target.

The final metrics from our study include a net profit of $167,000, an average trade of $107, and a maximum drawdown of about $13,000.

Figure 9 – Optimization of the Stop Loss value for the Trend Following strategy on Coffee futures.

Figure 10 – Optimization of the Profit Target value for the Trend Following strategy on Coffee futures.

Figure 11 – Final equity curve of the strategy on Coffee futures.

Figure 12 – Final Performance Summary and Total Trade Analysis of the strategy on Coffee futures.

Conclusions on the Trend Following Trading System for Coffee Futures

In short, the Trend Following approach described in this article has shown considerable promise for trading Coffee futures. This underscores the importance of exploring less familiar markets—beyond the more widely recognized ones—to achieve greater portfolio diversification. While this analysis has provided valuable insights, further refinement is necessary before transitioning to live trading. This includes identifying the most profitable trades and improving the average trade so it's sufficiently robust for real-world conditions.

Until next time, happy trading!

Andrea Unger

Market News and Data brought to you by Benzinga APIs

Posted In: