traffic_light_strategy_m00013-capsule

Author: Copyright 2015, vicas.
Orders Execution
It automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategyIt Closes Orders by itself Checks for the total of open orders
0 Views
0 Downloads
0 Favorites
traffic_light_strategy_m00013-capsule
//+------------------------------------------------------------------+
//|                                       Traffic light_strategy.mq4 |                               
//|                                           Copyright 2015, vicas. |
//|                                    http://www.robotrading.com.ua |
//+------------------------------------------------------------------+
//---   Modification M000013 capsule version
//---   
#property copyright "Copyright 2015, vicas."
#property link      "http://www.robotrading.com.ua"
#property version   "1.0"
#property strict
//---
extern string s1="Ðèñê MM è ïàðàìåòðû îðäåðà";
extern double      MM_Lots            = 0.1;    // îáúåì ëîòà MM
extern int         MM_Mode            = 1;      // 0 MM âûêëþ÷åí 1 âêëþ÷åí 
extern int         LotsDecimal        = 1;      // òî÷íîñòü ðàñ÷åòà 0/1/2 çíàêîâ ïîñëå çàïÿòîé
extern double      RiskPercent        = 1;      // ðèñê íà ñäåëêó
extern int         MagicNumber        = 134201; // ìàãè÷åñêèé íîìåð 
//---
extern string s2="Òîðãîâûå íàñòðîéêè";
extern int         StyleTrade         = 0;      // ñòèëü òîðãîâëè 0 êîíñåðâàòèâíûé 1 àãðåññèâíûé
extern int         TimeOpenBar        = 0;      // îòêðûòèå ïîçèöèè 0 òåêóùèé áàð 1 íîâûé áàð 
extern double      TakeProfit         = 240;    // òåéêïðîôèò â ïóíêòàõ
extern double      StopLoss           = 60;     // ñòîïëîññ â ïóíêòàõ
extern int         CloseProfit        = 1;      // çàêðûòèå ïîçèöèè ïî iMA 1 âêë. 
extern int         TimeCloseBar       = 1;      // çàêðûòèå ïîçèöèè 1 íîâûé áàð 0 òåêóùèé áàð
//---
extern string s3="Òðåéëèíã ñòîï Íàñòðîéêè";
extern int         Trailing           = 1;      // 1 òðåéëèíãñòîï (0 - îòêëþ÷åí)
extern double      TrailOtstupiMA     = 5;      // îòñòóï ñòîïëîññà îò iMA
extern double      TrailStep          = 3;      // øàã òðåéëèíãà
extern int         TralliMA           = 85;     // òðåéëèíã iMA
//---
extern string s4="Ñèãíàëû èíäèêàòîðîâ";
extern int         RedMA              = 120;    // êðàñíàÿ iMA
extern int         YellowMA           = 55;     // æåëòàÿ iMA
extern int         GreenMA            = 5;      // çåëåíàÿ iMA
extern int         BlueMA             = 24;     // ñèíÿÿ iMA
//---
bool Sg_IMA_Buy=False,Sg_IMA_Sell=False;
bool OrderBuy=False,OrderSell=False;
bool Sg_Init=False;
bool TradeBuy,TradeSell;
//---
double Lots,MaxLots,MinLots;
double PunktSize;
//---
int Slip=3.0;
int total,ticket,Order_id;
datetime TimeNewOpenBar=0,TimeNewCloseBar=0;
//---
string s="Traffic light_m00013 capsule : ";
//+------------------------------------------------------------------+
//| Init function                                                    |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   MaxLots = MarketInfo(Symbol(), MODE_MAXLOT);
   MinLots = MarketInfo(Symbol(), MODE_MINLOT);
//---
   PunktSize=NormalizeDouble(MarketInfo(Symbol(),MODE_LOTSIZE)*Point,Digits);
//---
   if(Digits==3 || Digits==5)
     {
      TakeProfit*=10;
      StopLoss*=10;;
      Slip*=10;
     }
//---
   Sg_IMA_Buy=False;
   Sg_IMA_Sell=False;
//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double TP=0;
   double SL=0;
   double Spread=MarketInfo(Symbol(),MODE_SPREAD)*Point;
   double StopLevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
//---
   double SignalBlueiMAHigh=iMA(Symbol(),NULL,BlueMA,0,MODE_EMA,PRICE_HIGH,0);
   double SignalBlueiMALow=iMA(Symbol(),NULL,BlueMA,0,MODE_EMA,PRICE_LOW,0);
   double SignalYellowiMA=iMA(Symbol(),NULL,YellowMA,0,MODE_SMA,PRICE_CLOSE,0);
   double SignalRediMA=iMA(Symbol(),NULL,RedMA,0,MODE_SMA,PRICE_CLOSE,0);
   double SignalGreeniMA=iMA(Symbol(),NULL,GreenMA,0,MODE_EMA,PRICE_CLOSE,0);
   double SignalTralliMA=iMA(Symbol(),NULL,TralliMA,0,MODE_EMA,PRICE_CLOSE,0);
//---
   TradeBuy=False;
   TradeSell=False;
//---   
   total=CountTrades();
//---
   if(total==0)
     {
      //---
      if(StyleTrade == 0 && Bid < SignalRediMA && Bid > SignalYellowiMA) Sg_Init=TRUE;
      if(StyleTrade == 0 && Bid < SignalYellowiMA && Bid > SignalRediMA) Sg_Init=TRUE;
      if(StyleTrade!=0 && Bid<SignalBlueiMAHigh && Bid>SignalBlueiMALow) Sg_Init=TRUE;
     }
//---  
   if(Sg_Init)
     {
      if(MM_Mode==0 || StopLoss==0) Lots=MM_Lots;
      else
        {
         Lots=NormalizeDouble((AccountBalance()*RiskPercent/100.0)/(PunktSize*StopLoss),LotsDecimal);
         if(Lots < MinLots) Lots = MinLots;
         if(Lots > MaxLots) Lots = MaxLots;
        }
     }
//---
   if(total==0)
     {
      //---
      if(TakeProfit==0 && StopLoss==0 && CloseProfit==0) return;
      //---
      if((SignalGreeniMA>SignalBlueiMAHigh) && (SignalBlueiMAHigh>SignalYellowiMA) && (SignalYellowiMA>SignalRediMA))
        {
         if(Bid>SignalGreeniMA) Sg_IMA_Buy=TRUE;
        }
      //---
      if((SignalGreeniMA<SignalBlueiMALow) && (SignalBlueiMALow<SignalYellowiMA) && (SignalYellowiMA<SignalRediMA))
        {
         if(Bid<SignalGreeniMA) Sg_IMA_Sell=TRUE;
        }
      //--
      if(TimeNewOpenBar == Time[0] && TimeOpenBar != 0) return;
      TimeNewOpenBar=Time[0];
      //---
      if(Sg_IMA_Buy && Sg_Init)
        {                            // Open order Buy
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slip,0,0,s,MagicNumber,0,Green);
         if(ticket<0)
           {
            Print("Error: ",GetLastError());
            return;
              } else {
            OrderBuy=TRUE;
            Sg_IMA_Buy=FALSE;
            Sg_Init=False;
           }
        }
      //---
      if(OrderBuy)
        {
         //---
         if(TakeProfit!=0) TP=NormalizeDouble(Bid+MathMax(TakeProfit,StopLevel)*Point,Digits);
         if(StopLoss!=0) SL=NormalizeDouble(Bid-MathMax(StopLoss,StopLevel)*Point,Digits);
         if(!OrderModify(ticket,OrderOpenPrice(),SL,TP,0))
           {
            Print("Error: ",GetLastError());
            return;
           }
         OrderBuy=FALSE;
        }
      //---
      if(Sg_IMA_Sell && Sg_Init)
        {                          // Open Sell order
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slip,0,0,s,MagicNumber,0,Red);
         if(ticket<0)
           {
            Print("Error: ",GetLastError());
            return;
              } else {
            OrderSell=TRUE;
            Sg_IMA_Sell=FALSE;
            Sg_Init=False;
           }
        }
      //---
      if(OrderSell)
        {
         //---
         if(TakeProfit!=0) TP=NormalizeDouble(Ask-MathMax(TakeProfit,StopLevel)*Point,Digits);
         if(StopLoss!=0) SL=NormalizeDouble(Ask+MathMax(StopLoss,StopLevel)*Point,Digits);
         if(!OrderModify(ticket,OrderOpenPrice(),SL,TP,0))
           {
            Print("Error: ",GetLastError());
            return;
           }
         OrderSell=FALSE;
        }
     }
   else
     {
      //---
      if(TimeNewCloseBar == Time[0] && TimeCloseBar != 0) return;
      TimeNewCloseBar=Time[0];
      //---
      if(CloseProfit!=0)
        {
         if((SignalGreeniMA<SignalYellowiMA) && TradeBuy)
           {
            if(OrderClose(Order_id,OrderLots(),Bid,Slip,Blue)) Print("Error: ",GetLastError());
           }
         if((SignalGreeniMA>SignalYellowiMA) && TradeSell)
           {
            if(OrderClose(Order_id,OrderLots(),Ask,Slip,Blue)) Print("Error: ",GetLastError());
           }
        }
      //---
      if(Trailing!=0) RealTrailOrder(SignalTralliMA,TrailOtstupiMA,TrailStep,MagicNumber);
     }
  }
//+------------------------------------------------------------------+
//| Ïîäñ÷åò îðäåðîâ â ðûíêå                                          |
//+------------------------------------------------------------------+
int CountTrades()
  {
   int count=0;
   for(int pos=OrdersTotal()-1; pos>=0; pos--)
     {
      if(OrderSelect(pos,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=MagicNumber) continue;
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
            if(OrderType()==OP_SELL)
              {
               Order_id=OrderTicket();
               TradeSell=True;
               count++;
               break;
              }
         if(OrderType()==OP_BUY)
           {
            Order_id=OrderTicket();
            TradeBuy=True;
            count++;
            break;
           }
        }
     }
   return (count);
  }
//+------------------------------------------------------------------+
//| Òðåéëèíã-ñòîï ïî ñêîëüçÿùåé iMA                                  |
//+------------------------------------------------------------------+
void RealTrailOrder(double signalima,double otstupima,double trstep,int magic)
  {
   double openprice,openstoploss,calculatestoploss,opentakeprofit,calculatetakeprofit;
   double spread=MarketInfo(Symbol(),MODE_SPREAD)*Point;
   double stlevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
   for(int cmt=OrdersTotal()-1; cmt>=0; cmt--)
     {
      if(OrderSelect(cmt,SELECT_BY_POS,MODE_TRADES)==TRUE)
        {
         if(OrderMagicNumber()==magic && OrderSymbol()==Symbol())
           {
            while(IsTradeContextBusy()) Sleep(500);
            RefreshRates();
            openprice=OrderOpenPrice();
            openstoploss=OrderStopLoss();
            opentakeprofit=OrderTakeProfit();
            calculatestoploss=openstoploss;
            calculatetakeprofit=opentakeprofit;
            if(OrderType()==OP_BUY)
              {
               if(signalima>openstoploss -(otstupima + trstep) * Point) calculatestoploss = ND(signalima - otstupima * Point);
               if(opentakeprofit - Bid <(otstupima + trstep) * Point) calculatetakeprofit = ND(Bid + otstupima * Point);
               if(Bid>ND(calculatestoploss-stlevel*Point) && (calculatestoploss>openstoploss) && 
                  Bid<ND(calculatetakeprofit-stlevel*Point) && (calculatetakeprofit>=opentakeprofit))
                 {
                  if(!OrderModify(OrderTicket(),OrderOpenPrice(),calculatestoploss,calculatetakeprofit,0,Blue))
                     Print("BUY OrderModify Error "+IntegerToString(GetLastError()));
                 }
              }
            if(OrderType()==OP_SELL)
              {
               if(signalima<openstoploss+(otstupima+trstep+spread)*Point) calculatestoploss=ND(signalima+otstupima*Point);
               if(Ask-opentakeprofit<(otstupima+trstep)*Point) calculatetakeprofit=ND(Ask-otstupima*Point);
               if(Ask<ND(calculatestoploss+(stlevel+spread)*Point) && (calculatestoploss<openstoploss) && 
                  Ask>ND(calculatetakeprofit+(stlevel+spread)*Point) && (calculatetakeprofit<=opentakeprofit))
                 {
                  if(!OrderModify(OrderTicket(),OrderOpenPrice(),calculatestoploss,calculatetakeprofit,0,Red))
                     Print("BUY OrderModify Error "+IntegerToString(GetLastError()));
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double ND(double ad_0)
  {
   return (NormalizeDouble(ad_0, Digits));
  }
//+------------------------------------------------------------------+

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---