Author: Copyright � 2005, tageiger aka fxid10t@yahoo.com
Profit factor:
0.00

This script is an automated trading system designed to manage market entries, risk management, and dynamic price protection using a combination of technical indicators. Below is a breakdown of its logic in plain language:

Core Strategy Logic

The script works by comparing two primary technical indicators: Bollinger Bands and Keltner Channels.

  • Buy Signals: The system looks for moments when the Upper Bollinger Band falls below (or meets) the Upper Keltner Channel. When this condition is met and there are no active buy positions, it places a "Buy Stop" order.
  • Sell Signals: Conversely, if the Lower Bollinger Band rises above (or meets) the Lower Keltner Channel and no sell positions are active, it places a "Sell Stop" order.

Automated Trade Management

Once a trade is triggered, the script takes over several management tasks:

  • Dynamic Stop Loss: When an order is first placed, the system automatically calculates a safety exit point (Stop Loss) based on recent price extremes (the highest highs or lowest lows of a specific period), adjusted by the current market spread.
  • Trailing Stop Loss (TSL): To protect profits as the market moves in your favor, the script uses the Average True Range (ATR) indicator. It monitors the current price and "trails" the stop loss. If the price moves significantly into profit, the stop loss is automatically moved forward to lock in gains while maintaining a buffer based on current market volatility.
  • Position Tracking: The script actively counts open orders to ensure it doesn't over-leverage the account by opening multiple identical positions simultaneously.

Risk and Lot Management

The script includes a sophisticated "smart" sizing logic to protect your account balance:

  • Risk Percentage: It calculates your position size based on a fixed percentage of your available account margin.
  • Loss Mitigation (Decrease Factor): One of the script's key features is its ability to learn from losing streaks. If the system detects a series of consecutive losses, it automatically reduces the lot size of the next trade. This "shrinking" mechanism helps preserve capital during periods of high market volatility or poor trend alignment.

Visual Feedback

For users monitoring the platform manually, the script provides real-time visual updates on the chart. It displays the current time and the specific numerical values for both the Bollinger Bands and Keltner Channels, allowing you to see exactly what data the logic is using to make its decisions.

Price Data Components
Series array that contains open time of each bar
Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategy
Indicators Used
Bollinger bands indicatorIndicator of the average true range
13 Views
0 Downloads
0 Favorites
bbkc
/*-----------------------------+
|			       |
| Shared by www.Aptrafx.com    |
|			       |
+------------------------------*/

//+------------------------------------------------------------------+
//|                                                     bbkc.mq4 |
//|                 Copyright © 2005, tageiger aka fxid10t@yahoo.com |
//|                                        http://www.metatrader.org |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, tageiger aka fxid10t@yahoo.com"
#property link      "http://www.metatrader.org"

extern int        BB.Period         =20;
extern int        BB.Deviation      =2;

extern int        KC.Period         =10;

extern int        Spread.Multiplier =1;
extern int        Atr.Period        =13;
extern double     Atr.Multiplier    =1.5;

extern double     MaximumRisk       =0.02;   //%account balance to risk per position
extern double     DecreaseFactor    =3;      //lot size divisor(reducer) during loss streak

extern int        MagicNumber       =851;
extern string     comment           ="m bbkc";

int b,s,ticket;
double spread;spread=Ask-Bid;

int init(){return(0);}
int deinit(){return(0);}
int start(){
   
   PosCounter();
   if(BB.hi()<=KC.hi() && b==0)  {Buy();}
   if(BB.lo()>=KC.lo() && s==0)  {Sell();}
   
   for(int j=0;j<OrdersTotal();j++) {
   OrderSelect(j,SELECT_BY_POS,MODE_TRADES);
   if(OrderSymbol()==Symbol() && OrderComment()==Period()+comment)   {
      if(OrderType()==(OP_BUY || OP_SELL))         {TSL();}
      if(OrderType()==(OP_BUYSTOP || OP_SELLSTOP)) {OrderMod();}}}
      
   if(!IsTesting())  {Comments();}
   
return(0);
}
//functions
void PosCounter() {
   b=0;s=0;
   for(int cnt=0;cnt<=OrdersTotal();cnt++)   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber) {
         if(OrderType()== OP_SELLSTOP) s++;
         if(OrderType()==OP_SELL)      s++;
         if(OrderType()==OP_BUYSTOP)   b++;
         if(OrderType()==OP_BUY)       b++;}}}

double BB.hi()  {
   double bbhi;
   bbhi=iBands(Symbol(),0,BB.Period,BB.Deviation,0,PRICE_CLOSE,MODE_UPPER,0);
   return(NormalizeDouble(bbhi,Digits));}
double BB.lo()  {
   double bblo;
   bblo=iBands(Symbol(),0,BB.Period,BB.Deviation,0,PRICE_CLOSE,MODE_LOWER,0);
   return(NormalizeDouble(bblo,Digits));}
double KC.hi()  {
   double kchi;
   kchi=iCustom(Symbol(),0,"Keltner_Channels",KC.Period,0,0);
   Print("KC.hi:",kchi);
   return(NormalizeDouble(kchi,Digits));}
double KC.lo() {
   double kclo;
   kclo=iCustom(Symbol(),0,"Keltner_Channels",KC.Period,2,0);
   Print("KC.lo:",kclo);
   return(NormalizeDouble(kclo,Digits));}

void Buy()  {if(b==0){ticket=OrderSend(Symbol(),
                              OP_BUYSTOP,
                              LotsOptimized(),
                              KC.hi(),
                              0,//slippage
                              B.sl(),
                              0,//takeprofit
                              Period()+comment,
                              MagicNumber,
                              0,//OrderExpiration
                              Aqua);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                                    {  Print(ticket); PosCounter();}
                              else Print("Error Opening BuyStop Order: ",GetLastError());
                              return(0);   }}}

void Sell() {if(s==0){ticket=OrderSend(Symbol(),
                              OP_SELLSTOP,
                              LotsOptimized(),
                              KC.lo(),
                              0,//slippage
                              S.sl(),
                              0,//takeprofit
                              Period()+comment,
                              MagicNumber,
                              0,//OrderExpiration
                              Magenta);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                                    {  Print(ticket); PosCounter(); }
                              else Print("Error Opening SellStop Order: ",GetLastError());
                              return(0);   }}}

double LotsOptimized()  {
   double lot;
   int    orders=HistoryTotal();
   int    losses=0;
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,2);
   if(DecreaseFactor>0) {
      for(int i=orders-1;i>=0;i--)  {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++; }
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,2);   }
   if(lot<0.05) lot=0.05;
return(lot);   }//end LotsOptimized

double B.sl()  {
   double b.lo;
   b.lo=Low[Lowest(Symbol(),0,MODE_LOW,BB.Period,0)];
   return(b.lo-(spread*Spread.Multiplier));}

double S.sl()  {
   double s.hi;
   s.hi=High[Highest(Symbol(),0,MODE_HIGH,BB.Period,0)];
   return(s.hi+(spread*Spread.Multiplier));}

void TSL()   {
   double tsl;
   tsl=iATR(Symbol(),0,Atr.Period,0)*Atr.Multiplier; 
   for(int z=0;z<OrdersTotal();z++) {
   OrderSelect(z,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()==Symbol() && OrderComment()==Period()+comment && OrderMagicNumber()==MagicNumber){
         if(OrderType()==OP_BUY && OrderProfit()>OrderSwap()) {
            if(Bid-NormalizeDouble(tsl,Digits)>OrderStopLoss())  {
               OrderModify(OrderTicket(),
                           OrderOpenPrice(),
                           Bid-NormalizeDouble(tsl,Digits),
                           OrderTakeProfit(),
                           OrderExpiration(),
                           CadetBlue);}}
         if(OrderType()==OP_SELL && OrderProfit()>OrderSwap()) {
            if(Ask+NormalizeDouble(tsl,Digits)<OrderStopLoss())  {
               OrderModify(OrderTicket(),
                           OrderOpenPrice(),
                           Ask+NormalizeDouble(tsl,Digits),
                           OrderTakeProfit(),
                           OrderExpiration(),
                           Sienna);}}}}}

void OrderMod()   {
}

void Comments()   {
Comment("Last Tick: ",TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS),"\n",
        "Upper BB:",BB.hi()," Upper KC:",KC.hi(),"\n",
        "Lower BB:",BB.lo()," Lower KC:",KC.lo());}

Comments