On technical analysis and fuzzy logic for mechanical trading
Technical traders realize that technical analysis is more of an art than science. Until you draw a plethora of lines to fill your chart, which would render it practically useless, prices rarely “hit the spot” based on your doodles. This doesn’t matter though because trading is not about charts and guessing numbers. It is about costs and risks (pardon me if you’ve heard this a thousand times already). To whom this would matter though, are the mechanical traders using technical analysis.
It may be obvious to a human to discern price patterns because a trading setup looks like something you know. However, figuring out “obvious” and “looks like” is not trivial in a program. Common ways of tackling this problem is with stochastic algorithms or Bayesian logic. The drawback with using these methods though, is that they are difficult to conjure unless you have some vigorous background in math.
Hereby I suggest an alternative–fuzzy logic.
In it’s simplest implmentation, fuzzy logic are mere if-then statements. Here’s a sample fuzzy logic control system for regulating temperature with a fan (it is also a trick solution to the infamous hysteresis problem in control theory…but I digress),
IF temperature IS very cold THEN stop fan
IF temperature IS cold THEN turn down fan
IF temperature IS normal THEN maintain level
IF temperature IS hot THEN speed up fan
As you can see, there can be more than two values for a result. The classic and ubiquitous TRUE or FALSE boolean is thrown out the window.
Let’s dive right into an example of applying fuzzy logic to technical analysis. Say you are using the RSI as one of your indicators. Typically, you set a pair of threshold values to determine if the instrument is overbought or oversold.
String rsiCondition;
if (RSI > 70) rsiCondition = "Overbought";
if (RSI >= 30 && RSI <= 70) rsiCondition = "Neutral";
if (RSI < 30) rsiCondition = "Oversold";
Then here is what a fuzzy logic implementation would look like.
String rsiCondition;
if (RSI > 90) rsiCondition = "Very overbought!";
if (RSI > 70) rsiCondition = "Overbought";
if (RSI > 60) rsiCondition = "a little overbought";
if (RSI >= 40 && RSI <= 60) rsiCondition = "Neutral";
if (RSI < 40) rsiCondition = "a little oversold";
if (RSI < 30) rsiCondition = "Oversold";
if (RSI < 10) rsiCondition = "Very oversold!";
In fact, you may have noticed that the first RSI example is already a 3-valued fuzzy logic. And you’re right! Fuzzy logic is that easy.
So what can you do with that second RSI example? Well, perhaps you want to implement fuzzy logic on a MACD as a second indicator. Then you can implement a “conviction” algorithm (which isn’t possible with TRUE/FALSE algorithms) by summing the two fuzzy logic (see wiki or google for more information on performing fuzzy logic operations). And then… well.
This is a basic example of exploiting the benefits of fuzzy logic in automated trading strategies. More advanced use of fuzzy logic is demonstrated in this seminal work by Lin and Lee, Neural-network-based fuzzy logic control and decision system, 1991. Fuzzy logic + neural net! Well, as you can see, this is only the tip of the iceberg.
P.S. I have discussed a lot recently about the frontend work that I have been working on. This post is a break for the reader and a glimpse at what I am really doing behind the scenes. Let me know in the comments below if this is your cup of tea and I’ll write more of this type of posts in the future.
read moreA whole year, two hundred and six posts later
Recent lack of actions in the market has given me opportunities to focus less on the day-to-day market action and more on my own trading development. Besides working on my quantitative research, one of the tasks that I like to do is to review what I have thought previously in a similar time. This takes us back to a year ago, August of 2009.
Headlines from my fifteen posts back then shows that I was trying desperately (in hindsight) to short the market. Why would I do that? Take a look at this 3-year long weekly chart of S&P500.
On the chart, August 2009 looked like a great shorting opportunity. The resistance level at 1000 seem too good to be true (it was). In fact, I said the following words on August 22, 2009:
While there’s been much talk of economic recovery and a new bull market is already with us, I still am not convinced just yet. True, the bears might be MIA. But all signs say that this bull we’re seeing is standing on thin ice.
How wrong I was. Since breaking the 1000 resistance back then, the S&P hitched on the bull train to steam upward steadily on to 1150 (Figure 1). It took a break there and continued on to 1207.
Looking through my trades back then, I eventually stopped shorting the market after S&P broke above 1025. That was the good part.
The bad part is that I wasn’t able to change my view and remained stubbornly bearish (but at least didn’t commit to any new shorts) for weeks afterward.
If I were to sum up my lesson in the past year, here’s what I would say to myself back in August 2009.
Trading is not about being right. It is about knowing when you are wrong and doing something about it.
On a final note, it was in August of last year that I started to paper trade the forex market. I can’t believe it has been a whole year already!
read moreJForex Example: Automatic position sizing
Proper position sizing is an integral part of risk management. It can be one of the easiest thing to do too. For example, I typically size my trading position based on the following factors:
- Amount of capital willing to put at risk.
- Stop price level.
- Volatility of the instrument.
The following JForex code calculates a lot size based on these three factors. It is part of my Dukascopy JForex July strategy (complete source code to the strategy is available via that link).
private double getLot(Instrument instrument) throws JFException
{
double riskAmt;
double lotSize = 0;
riskAmt = this.acctEquity * (this.riskPct / 100d); // CCYUSD only
lotSize = riskAmt / (this.atr[instrument.ordinal()] * this.atrFactor);
lotSize /= 1000000d; // in millions
return roundLot(lotSize);
}
Referring to line 237, riskAmt is the amount of capital to put at risk for a trade (#1). Line 238 calculates lotSize, which is the position size that we want. The denominator in that division is the distance of the stop in pips. The strategy uses a multiple of ATR to set the stop loss. Nothing fancy here.
Lines 240–241 are to set the lotSize value according to the JForex API specification. In which the lot amount is in millions and in steps of a thousand units, or 0.001 step size.
As I’ve noted in the code, the caveat to this implementation is that the secondary currency of the instrument and your account currency needs to be in U.S. dollar. However, it’s just a matter of conversion to extend this method for other currencies.
Update: I expanded on this functionality in the JFUtil open source project.
read moreJForex Example: Not letting profit turn to losses with a breakeven stop
While the dual-timeframe trading setup and much of the algorithm in my contest strategy are for competition only (read: not for use with real money) as I’ve warned numerous times, some of the risk management techniques used there are really what I use in real life. This being one of them.
There’s a saying in trading that “never let profits turns into losses.” That is exactly the motivation behind this JForex code snippet. The following source code are excerpts from my Dukascopy JForex contest’s July strategy. The complete source code file is available in that link.
Back to this concept of not letting profits turn to losses. This is a matter of balancing between giving room for your trade to reach its potential and limiting your drawdown. If you’re too careful, you may find yourself being whipsawed out before a price move can materialize. If you keep your leash too loose though, well, you may watch your profits turn into losses.
The way I intrepret the saying is that once your trade is profitable enough, you shouldn’t let it slip back into a loss.
I implement the above statement in my automated strategy as follows. Note that everything goes in the onTick() method so that it watches your position on every tick. The line numbers correspond to the complete source code of my automated strategy.
boolean isLong;
double open, stop, diff, newStop;
for (IOrder order : engine.getOrders(instrument)) {
if (order.getState() == IOrder.State.FILLED) {
isLong = order.isLong();
open = order.getOpenPrice();
stop = order.getStopLossPrice();
diff = (open - stop);
// ********* BREAKEVEN ***********************
if (isLong && diff > 0 && tick.getBid() > (open + diff))
{
order.close(roundLot(order.getAmount() * beRatio)); // close a portion
newStop = open + instrument.getPipValue() * LOCKPIP;
order.setStopLossPrice(newStop);
print(order.getLabel() + ": Moved STOP to breakeven");
}
else if (!isLong && diff < 0 && tick.getAsk() < (open + diff))
{
order.close(roundLot(order.getAmount() * beRatio));
newStop = open - (instrument.getPipValue() * LOCKPIP);
order.setStopLossPrice(newStop);
print(order.getLabel() + ": Moved STOP to breakeven");
}
What this does is that it will partially exit a position and move the stop to breakeven once the price is equidistantly positive from your initial stop loss. For example, if my stop loss is 100 pips, then once the position is 100 pips in profit, it will exit partially and set the new stop to breakeven.
Update: This is now integrated into the JFUtil open source project.
read moreJForex Example: Dual-Timeframe Moving Averages Setup
This post describes the setup for my Dukascopy JForex automated trading strategy in July. Note that this strategy is built for competing in a contest and not for real trading (i.e., it’s purely a no cost gamble).
Here is the step by step process of the setup for a long position:
- Determine the current trend by the relative position of current price to its moving average in a higher time frame. In particular, a price above the moving average in the higher time frame is deemed as bullish.
- Entry: Price moves above a moving average in the current time frame (red line in Figure 1) with a higher high, low, and close (HLC). As illustrated in Figure 1, the two bars circled.
- Exit: Crossing below a regular moving average (blue dotted line).
As you can see, the setup itself is simple. Less than a fifth of the source code is devoted to the entry and exit. Most of this strategy involves automated position sizing and risk management to not let profits turn into losses.
The complete source code of this strategy is available in the introductory post.
read more



Recent Comments