In random events, “streaks” have low probability, and this strategy is trying to take advantage of this fact by betting against the “streak”.

Here we see 3 consecutive red candles before the algorithm enters the trade:

entry position (white dot) and exit position (yellow square)

In our code, using the Badger algo-trading framework, we can see that the actual candles taken into consideration are…

  • 4th from the end of the array
  • 3rd from the end
  • 2nd from the end

…but not the last one.

Why?

Because last candle isn’t finished. In fact, it just begun. So we’re taking last 3 completed candles to base our decision upon.

// CANDLE COUNTING STRATEGY

bool hasOpenPosition() {
	return 
		this.positions.length != 0 &&
		this.positions[$-1].action == Action.OPEN;
}

int trades = 0;

override bool trade() {
	if(!super.trade()) return false;
	// ALL CODE HERE - BEGIN //

	if (trades >= 1 && !hasOpenPosition()) {
		return false; // stop the bot
	}

	Candle[] btcCandles = this.candles[c.BTCUSDT];
	double currentPrice = btcCandles[$-1].close;

	bool is3red = 
		btcCandles[$-2].color == Color.RED &&
		btcCandles[$-3].color == Color.RED &&
		btcCandles[$-4].color == Color.RED;

	if (
		is3red &&
		!hasOpenPosition()
	) {
		Order marketBuy = Order(
			c.BTCUSDT,
			OrderType.MARKET,
			Direction.BUY,
			currentPrice * 1.003, // target price
			currentPrice * 0.995, // stop price
		);
		this.order(marketBuy);
		trades++;
	}

	// ALL CODE HERE - END //
	return true;
}