Viewing the resource: CCI EA: Ride Overbought/Oversold Reversals

CCI EA: Ride Overbought/Oversold Reversals

Allan Munene Mutiiria 2025-06-21 01:09:31 67 Views
Join our fun, beginner-friendly guide to the CCI EA MQL5 code! We’ll explain every function in det...

Introduction

Ahoy, future forex captain! Picture the forex market as a vast ocean, with prices surging and retreating like waves hitting the shore. The CCI EA is your sturdy ship, harnessing the Commodity Channel Index (CCI) to navigate overbought and oversold conditions, spotting reversal points to launch buy or sell trades. This article is your nautical chart, guiding you through the MQL5 code on MetaTrader 5 with vivid detail. We’ll unpack every major function with clarity for beginners, weaving humor and flow like a sea shanty sung by a crew. By the end, you’ll be ready to let this Expert Advisor (EA) sail your trades to profit. Let’s set sail!

Strategy Blueprint

The CCI EA uses the Commodity Channel Index (CCI), a 14-period indicator based on typical price ([high + low + close]/3), to detect momentum extremes:

  • Below -170: Oversold, signaling a potential buy as prices may rebound.

  • Above +170: Overbought, signaling a potential sell as prices may drop.

The EA triggers a buy when CCI crosses above -170 from below, indicating a shift from oversold conditions, and a sell when CCI crosses below +170 from above, signaling an overbought reversal. Trades use a 0.01-lot size with a 300-pip stop loss and take profit, executed only on new candles to ensure discipline. It’s like catching a wave’s trough or crest and riding it back to calmer waters. See below.

Code Implementation

Let’s sail through the MQL5 code like a ship cutting through waves, unfolding the logic as a seamless voyage. Our journey starts with rigging the ship by initializing the CCI, moves to charting the waters with data retrieval, spots reversal signals, and ends with launching trades. Each function builds on the last, with transitions that keep the narrative flowing like a steady current. We’ll explain every major function in detail, quoting variables (e.g., "CCIdata") and functions (e.g., "OnInit()") for clarity, keeping it beginner-friendly with a playful sailing theme.

Rigging the Ship: Header, Includes, and Initialization

Our adventure begins by preparing the vessel, setting up the EA to navigate market waves.

//+------------------------------------------------------------------+
//|                                                       CCI EA.mq5 |
//|                        Copyright 2025, Allan Munene Mutiiria      |
//|                            https://t.me/Forex_Algo_Trader         |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Allan Munene Mutiiria"
#property link      "https://t.me/Forex_Algo_Trader"
#property version   "1.00"

#include <Trade/Trade.mqh>
CTrade obj_Trade;

int handleCCI;
double CCIdata[];

int OnInit(){
   handleCCI = iCCI(_Symbol,_Period,14,PRICE_TYPICAL);
   if (handleCCI == INVALID_HANDLE) return (INIT_FAILED);
   
   ArraySetAsSeries(CCIdata,true);
   
   return(INIT_SUCCEEDED);
}

The header declares the EA as “CCI EA,” crafted by Allan in 2025, with a link to your Telegram channel and version 1.00, setting the course for our journey.

  • Includes and Globals: The #include <Trade/Trade.mqh> directive imports the MQL5 trade library, creating "obj_Trade" via the "CTrade" class for trade execution. "handleCCI" stores the CCI indicator’s handle, and "CCIdata[]" holds CCI values, like a ship’s compass and logbook.

  • "OnInit()": The EA’s launch, called when attached to a chart. It sets up:

    • "iCCI()": Creates a 14-period CCI using "PRICE_TYPICAL" ([high + low + close]/3), storing the handle in "handleCCI".

    • "INVALID_HANDLE": A constant (-1) for failed indicator loads, triggering a return of INIT_FAILED.

    • "ArraySetAsSeries()": Configures "CCIdata[]" as a time series (index 0 = latest), like sorting the ship’s log newest first.

    • INIT_SUCCEEDED, INIT_FAILED: Constants for initialization success or failure. It returns INIT_SUCCEEDED if successful, like hoisting the sails with a clear horizon.

This rigs the ship, preparing the EA to navigate CCI signals.

Clearing the Deck: OnDeinit Function

When the voyage ends, this function tidies up.

void OnDeinit(const int reason)
{
}

The "OnDeinit()" function is the EA’s cleanup crew, called when removed from the chart. It’s empty, like leaving the deck spotless, as no resources (e.g., indicator handles) need freeing, keeping things lightweight for the next sail.

Charting the Waters: OnTick Function

With the ship rigged, we sail into the EA’s core, where it detects CCI signals and launches trades.

void OnTick(){
   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);

   int barsCurr = iBars(_Symbol,_Period);
   static int barsPrev = 0;
   if (barsPrev == barsCurr) return;
   barsPrev = barsCurr;
   
   CopyBuffer(handleCCI,0,1,3,CCIdata);
   ArrayPrint(CCIdata,2," , ");
   
   if (CCIdata[0] < -170 && CCIdata[1] > -170){
      Print(">>> BUY SIGNAL <<<");
      obj_Trade.Buy(0.01,_Symbol,Ask,Bid-300*_Point,Bid+300*_Point);
   }
   else if (CCIdata[0] > 170 && CCIdata[1] < 170){
      Print(">>> SELL SIGNAL <<<");
      obj_Trade.Sell(0.01,_Symbol,Bid,Ask+300*_Point,Ask-300*_Point);
   }
}

The "OnTick()" function is the EA’s voyage, running on every price tick to navigate reversal signals. Here’s how it flows:

  • "SymbolInfoDouble()": Fetches real-time ask ("SYMBOL_ASK", "Ask") and bid ("SYMBOL_BID", "Bid") prices for trading.

  • "NormalizeDouble()": Rounds prices to "_Digits" (e.g., 5 for EURUSD), ensuring trade-ready formatting, like calibrating the ship’s compass.

  • "iBars()": Returns the chart’s bar count, stored in "barsCurr". If static "barsPrev" equals "barsCurr", the EA skips to avoid reprocessing; otherwise, updates "barsPrev", ensuring new-candle trades, like checking the tide before sailing.

  • "CopyBuffer()": Copies three CCI values (shift 1) from buffer 0 into "CCIdata[]" for analysis.

  • "ArrayPrint()": Logs "CCIdata[]" to the journal with 2 decimal places, like recording wave heights for debugging.

  • Buy Signal: If "CCIdata[0] < -170 && CCIdata[1] > -170", indicating a CCI crossover above -170 (oversold), logs “BUY SIGNAL” with "Print()", and opens a buy trade with "obj_Trade.Buy()", using 0.01 lots, "Ask", stop loss 300 pips below "Bid", and take profit 300 pips above "Bid".

  • Sell Signal: If "CCIdata[0] > 170 && CCIdata[1] < 170", indicating a crossover below +170 (overbought), logs “SELL SIGNAL” and opens a sell trade with "obj_Trade.Sell()", using 0.01 lots, "Bid", stop loss 300 pips above "Ask", and take profit 300 pips below "Ask".

  • "Buy()", "Sell()": Methods of the "CTrade" class, opening trades with lot size (0.01), symbol ("_Symbol"), price, stop loss, and take profit.

  • "_Point": A built-in variable for the symbol’s pip size, used for stop loss and take profit calculations.

This function sails the market’s waves, spotting CCI crossovers and launching trades like a ship riding a favorable current. See below.

Putting It All Together

To launch this EA:

  1. Open MetaEditor in MetaTrader 5.

  2. Paste the code into a new Expert Advisor file.

  3. Compile (F5). If errors appear, double-check your copy-paste.

  4. Drag the EA onto your chart, enable AutoTrading, and watch for buy or sell trades triggered by CCI crossovers.

  5. Trade smart—don’t bet your ship on one wave!

Conclusion

The CCI EA is your sturdy ship, navigating overbought and oversold reversals with CCI signals. We’ve sailed through its MQL5 code with clear, detailed explanations, so you understand every move like a seasoned captain. Now you’re set to automate your trades and ride market waves. Want to see it in action? Check our video guide on the website!

Disclaimer: Trading’s like sailing a stormy sea—exciting but risky. Losses can exceed deposits. Test on a demo account before going live.

Disclaimer: The ideas and strategies presented in this resource are solely those of the author and are intended for informational and educational purposes only. They do not constitute financial advice, and past performance is not indicative of future results. All materials, including but not limited to text, images, files, and any downloadable content, are protected by copyright and intellectual property laws and are the exclusive property of Forex Algo-Trader or its licensors. Reproduction, distribution, modification, or commercial use of these materials without prior written consent from Forex Algo-Trader is strictly prohibited and may result in legal action. Users are advised to exercise extreme caution, perform thorough independent research, and consult with qualified financial professionals before implementing any trading strategies or decisions based on this resource, as trading in financial markets involves significant risk of loss.

Recent Comments

Go to discussion to Comment or View other Comments

No comments yet. Be the first to comment!