1

mail@pastecode.io avatar
unknown
plain_text
2 years ago
9.7 kB
1
Indexable
Never
//+------------------------------------------------------------------+
//|                                                      Pyramid.mq5 |
//|                               Copyright 2022, Bartlomirj Tomaja. |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, Bartlomiej Tomaja."

#include <Trade/Trade.mqh>
MqlTick tick_value, ticks;
CTrade trade;
CPositionInfo Position;
COrderInfo    Order;

string btn1 = "BTN BUY";
string btn2 = "BTN SELL";
string btn3 = "BTN STOP";
string btn4 = "BTN CLOSE";

input int Magic = 1001;
input double lotSize = 0.10;
input int stopLossPoints = 1500;
//input int tslTriggerPoints = 500;
//input double tslPoints = 300;
input double tradeSpread = 200;
input int breakEven = 200;
input int breakEvenAddPoints = 200;


int OnInit()
{
   datetime timer = TimeCurrent();
   string CurrentDate = TimeToString(timer,TIME_DATE);
   if(CurrentDate<="2022.12.24")
    {
      CreateBtn(btn1, 10, 50, 150, 50, "BUY "+DoubleToString(lotSize,2));
      CreateBtn(btn2, 160, 50, 150, 50, "SELL "+DoubleToString(lotSize,2));
      CreateBtn(btn3, 10, 100, 300, 50, "Stop Program");
      CreateBtn(btn4, 10, 160, 300, 50, "CLOSE ALL TRADES");
   
      trade.SetExpertMagicNumber(Magic);
      if(!trade.SetTypeFillingBySymbol(_Symbol))
      {
         trade.SetTypeFilling(ORDER_FILLING_RETURN);
      }
   
      return(INIT_SUCCEEDED);
    }
    else
    {
        return(INIT_FAILED);
        Print("ERROR! Functions can not be loaded! Possible reason: obsolate version. ");
        Print("Call Bart - he knows what to do. ");
    }
}

void OnDeinit(const int reason)
{
   ObjectsDeleteAll(0,"BTN");
   ChartRedraw();
}

bool buyActive = false;
bool sellActive = false;
//input int pointsPerBar = 0;
bool pointsPerBarResult = false;

double actualPrice = 0;
double lastPositionPrice = NULL;
input int TicksCheckInSeconds = 5;
input int timeSlot = 20;
input int pointsJump = 20;

void OnTick()
{
   
   double Ask=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   
   highAndLow(1);
   highAndLow(2);
   
   //if(pointsPerBar != 0)pointsPerBarResult = BarCheckTimer(pointsPerBar, Ask, Bid);
   ProcessTrade(Bid, Ask);
   
   if(buyActive==true)
   {
      //otworz pierwsza pozycje z reki, sprawdz czy cena poszla w gore o X punktow oraz czy poprzednia pozycja zostala zabezpieczona na BE oraz otworz kolejny trade
      if(pointsPerBarResult && ((lastPositionPrice + (NormalizeDouble(tradeSpread,_Digits))*_Point) <= Bid) && (lastPositionPrice + (NormalizeDouble(breakEven+breakEvenAddPoints,_Digits))*_Point < Bid))
      {
         Print("Automatyczne odpalenie pozycji");
         OpenBuy(Bid,Bid - NormalizeDouble( stopLossPoints, _Digits )*_Point);
         lastPositionPrice = Bid;
      }
   }
   if(sellActive==true)
   {  
      if(pointsPerBarResult && ((lastPositionPrice - (NormalizeDouble(tradeSpread,_Digits))*_Point) >= Ask) && (lastPositionPrice - (NormalizeDouble(breakEven+breakEvenAddPoints,_Digits))*_Point > Ask))
      {
         Print("Automatyczne odpalenie pozycji");
         OpenSell(Ask,Ask + NormalizeDouble( stopLossPoints, _Digits )*_Point);
         lastPositionPrice = Ask;
      }
   }
}







//===== ===== ===== ===== ===== ===== ===== ===== ===== LOOK FROM HERE ===== ===== ===== ===== ===== ===== =====






MqlTick tickArray[];
   
bool highAndLow(int direction = 0)                                //find lowest and highest price within X seconds
{
   int ticksCopy = CopyTicks(NULL,tickArray,COPY_TICKS_ALL,0,500);   //copy lat 1000 tick data
   ArrayResize( tickArray, 500 );                                    //assign ticks to array
   bool result = false;                                              //operation result
   
   if(direction == 1)
   {
      for(int i=0;i<ArraySize(tickArray);i++)
        {
            if((tickArray[0].time_msc - timeSlot*1000) < tickArray[i].time_msc)
              {
                  if(tickArray[0].bid - tickArray[i].bid >= NormalizeDouble(pointsJump,_Digits)*_Point)
                    {
                        Print("price jumped by: ", tickArray[0].bid - tickArray[i].bid, " points within ",tickArray[i].time_msc - tickArray[0].time_msc, " miliseconds, ",i," ticks ago.");
                        Print("values BID: ", tickArray[0].bid, " : ", tickArray[i].bid);
                        Print("values msc: ", tickArray[0].time_msc, " : ",tickArray[i].time_msc);
                        result = true;
                        break;
                    }
              }
        }
   }
   
   if(direction == 2)
   {
        for(int i=0;i<ArraySize(tickArray);i++)
        {
            if((tickArray[0].time_msc - timeSlot*1000) < tickArray[i].time_msc)
              {
                  if(tickArray[i].ask - tickArray[0].ask >= NormalizeDouble(pointsJump,_Digits)*_Point)
                    {
                        Print("price dropped by: ", tickArray[i].ask - tickArray[0].ask, " points within ",tickArray[0].time_msc - tickArray[i].time_msc, " miliseconds, ",i," ticks ago");
                        Print("values BID: ", tickArray[0].bid, " : ", tickArray[i].bid);
                        Print("values msc: ", tickArray[0].time_msc, " : ",tickArray[i].time_msc);
                        result = true;
                        break;
                    }
              }
        }
   }
   return result;
   //===== END OF COPY TICKS =====
}

void ProcessTrade(double Bid, double Ask)
{
    for(int i=PositionsTotal()-1;i>=0;i--)
    {
         Order.Select(PositionGetTicket(i));
         if(Position.Magic() == Magic)
         {
            ulong ticket = PositionGetTicket(i);
            long positionDirection = PositionGetInteger(POSITION_TYPE);
            if(positionDirection == POSITION_TYPE_BUY)
            {
               if((Position.PriceOpen()+breakEven*_Point)<Bid)
               {
                  trade.PositionModify(ticket,Position.PriceOpen()+breakEvenAddPoints*_Point,Position.TakeProfit());
               }
            }
            if(positionDirection == POSITION_TYPE_SELL)
            {
               if((Position.PriceOpen()-breakEven*_Point)>Ask)
               {
                  trade.PositionModify(ticket,Position.PriceOpen()-breakEvenAddPoints*_Point,Position.TakeProfit());
               }
            }
         }
    }
}

void OpenBuy(double price, double SL)
{
   trade.Buy(lotSize,_Symbol,price,SL);
   lastPositionPrice = price;
}

void OpenSell(double price, double SL)
{
   trade.Sell(lotSize,_Symbol,price,SL);
   lastPositionPrice = price;
}

void  OnChartEvent( 
   const int       id,
   const long&     lparam,
   const double&   dparam,
   const string&   sparam
   ){
   
   double Bid=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   double Ask=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   
   if(sparam == btn1)
   {
      buyActive = true;
      sellActive = false;
      Print("Pierwsze odpalenie pozycji");
      OpenBuy(Bid,Bid - NormalizeDouble( stopLossPoints, Digits() )*_Point);
      lastPositionPrice = Bid;
      ObjectSetInteger(0,btn1,OBJPROP_STATE,false);
      ChartRedraw();
   }
   if(sparam == btn2)
   {
      buyActive = false;
      sellActive = true;
      Print("Pierwsze odpalenie pozycji");
      OpenSell(Ask,Ask + NormalizeDouble( stopLossPoints, Digits() )*_Point);
      lastPositionPrice = Ask;
      ObjectSetInteger(0,btn2,OBJPROP_STATE,false);
      ChartRedraw();
   }
   if(sparam == btn3)
   {
      buyActive = false;
      sellActive = false;
      ObjectSetInteger(0,btn3,OBJPROP_STATE,false);
      ChartRedraw();
   }
   if(sparam == btn4)
   {
      CloseAll();
      ObjectSetInteger(0,btn4,OBJPROP_STATE,false);
      ChartRedraw();
   }
   
}

void CreateBtn(string btnName, int xDistance, int yDistance, int xSize, int ySize, string txt)
{
   ObjectCreate(0,btnName,OBJ_BUTTON,0,0,0);
   ObjectSetInteger(0,btnName,OBJPROP_XDISTANCE,xDistance);
   ObjectSetInteger(0,btnName,OBJPROP_YDISTANCE,yDistance);
   ObjectSetInteger(0,btnName,OBJPROP_XSIZE,xSize);
   ObjectSetInteger(0,btnName,OBJPROP_YSIZE,ySize);
   ObjectSetString(0,btnName,OBJPROP_TEXT,txt);
   
   
   ChartRedraw();
}

void CloseAll() {

   for ( int i = PositionsTotal() - 1; i >= 0; i-- ) {
      ulong ticket = PositionGetTicket( i );
      if ( !PositionSelectByTicket( ticket ) ) continue;
      if ( Position.Symbol() != Symbol() || Position.Magic() != Magic ) continue;
      if ( !trade.PositionClose( ticket ) ) {
         PrintFormat( "Failed to close position %i", ticket );
      }
   }

   for ( int i = OrdersTotal() - 1; i >= 0; i-- ) {
      ulong ticket = OrderGetTicket( i );
      if ( !OrderSelect( ticket ) ) continue;
      if ( Order.Symbol() != Symbol() || Order.Magic() != Magic ) continue;
      if ( !trade.OrderDelete( ticket ) ) {
         PrintFormat( "Failed to delete order %i", ticket );
      }
   }
}

bool BarCheckTimer(int pointsPerCandleFilter, double Ask, double Bid)
{
   double previousCandle = iClose(_Symbol,PERIOD_M1,1);
   
   if((previousCandle+pointsPerCandleFilter) > Bid && buyActive == true)
   {
      return true;
   }
   if((previousCandle-pointsPerCandleFilter) < Ask && buyActive == false)
   {
      return true;
   }
   return false;
}