0% found this document useful (0 votes)
87 views10 pages

Crashautomatico

Uploaded by

david gallegos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views10 pages

Crashautomatico

Uploaded by

david gallegos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

//+------------------------------------------------------------------+

//| MM_CROS_IFR.mq5 |
//| Copyright 2018. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "rafaelfvcs. Copyright 2018."
#property link "https://www.mql5.com"
#property version "1.00"
#include <Trade\Trade.mqh>
CTrade trade;
//---

enum STRATEGY_IN
{
ONLY_RSI, // Only RSI
ONLY_MA, // Only moving averages
MA_AND_RSI // moving averages plus RSI
};

//---
// Variables Input
sinput string s0; //-----------Strategy-------------
input STRATEGY_IN strategy = ONLY_MA; // Trader Entry
Strategy

sinput string s1; //-----------Moving Averages-------------


input int ma_faster_period = 25; // Fast Moving
Average Period
input int ma_fast_period = 50; // Fast Moving Average
Period
input int ma_slow_period = 200; // Slow Moving Average
Period
input ENUM_TIMEFRAMES ma_time_graphic = PERIOD_M1;// Graphic Time
input ENUM_MA_METHOD ma_method = MODE_EMA; // Method
input ENUM_APPLIED_PRICE ma_price = PRICE_CLOSE; // Price Applied

sinput string s2; //-----------RSI-------------


input int rsi_period = 8; // RSI Period
input ENUM_TIMEFRAMES rsi_time_graphic = PERIOD_M1; // Graphic Time
input ENUM_APPLIED_PRICE rsi_price = PRICE_CLOSE; // Price Applied

input int rsi_overbought = 98; // Level Overbought


input int rsi_oversold = 20; // Level Oversold

sinput string s3; //---------------------------


input double num_lots = 0.5; // Number of lots
input double TK = 900000; // Take Profit
input double SL = 40000; // Stop Loss
input int RSI1=90; //apertura de primer sell
input int RSI2=96; //apertura de segundo sell
double SL1= 10000;
double SL2= 0;
double SL3= 0;
double TK1= 2000;
//input double TK1 = 50; // Take Profit
subida
//input double SL1 = 20; // Stop Lostssubida

sinput string s4; //---------------------------


input string limit_close_op = "00:00"; // Time Limit Close
Position

int Opeb=0;
int Opes=0;
int OpesRSI1=0; // contador operaciones abiertas RSI 90
int OpesRSI2=0; // contador operaciones abiertas RSI más alto del día
int totalT=0;
int a=0;
int b=0;
int c=0;
int cruceA=0;
int tiempo=0;
int gananciaB =5; //ganancia buy diferentes de 0.5)
int gananciaS =5; //ganancia sell
int ganancia1 =1; //ganancia buy 0.5
double stop=0;
//+------------------------------------------------------------------+
//| Variables for indicators |
//+------------------------------------------------------------------+
//--- Moving Averages
// FASTER - shorter period
int ma_faster_Handle; // Handle Fast Moving Average
double ma_faster_Buffer[]; // Buffer Fast Moving Average

// FAST - shorter period


int ma_fast_Handle; // Handle Fast Moving Average
double ma_fast_Buffer[]; // Buffer Fast Moving Average

// SLOW - longer period


int ma_slow_Handle; // Handle Slow Moving Average
double ma_slow_Buffer[]; // Buffer Slow Moving Average

//--- RSI
int rsi_Handle; // Handle for RSI
double rsi_Buffer[]; // Buffer for RSI

//+------------------------------------------------------------------+
//| Variables for functions |
//+------------------------------------------------------------------+

int magic_number = 123456; // Magic Number

MqlRates candle[]; // Variable for storing candles


MqlTick tick; // Variable for storing ticks

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
ma_faster_Handle =
iMA(_Symbol,ma_time_graphic,ma_faster_period,0,ma_method,ma_price);
ma_fast_Handle =
iMA(_Symbol,ma_time_graphic,ma_fast_period,0,ma_method,ma_price);
ma_slow_Handle =
iMA(_Symbol,ma_time_graphic,ma_slow_period,0,ma_method,ma_price);
rsi_Handle = iRSI(_Symbol,rsi_time_graphic,rsi_period,rsi_price);

if(ma_faster_Handle<0 || ma_fast_Handle<0 || ma_slow_Handle<0 || rsi_Handle<0)


{
Alert("Error trying to create Handles for indicator - error:
",GetLastError(),"!");
return(-1);
}

CopyRates(_Symbol,_Period,0,4,candle);
ArraySetAsSeries(candle,true);

// To add the indicator to the chart:


ChartIndicatorAdd(0,0,ma_faster_Handle);
ChartIndicatorAdd(0,0,ma_fast_Handle);
ChartIndicatorAdd(0,0,ma_slow_Handle);
ChartIndicatorAdd(0,1,rsi_Handle);
//---

//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
IndicatorRelease(ma_faster_Handle);
IndicatorRelease(ma_fast_Handle);
IndicatorRelease(ma_slow_Handle);
IndicatorRelease(rsi_Handle);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{

if(Opeb==0){
b=0;
gananciaB=3;
}
if(Opes==0){
c=0;
gananciaS=3;
OpesRSI1=0;
OpesRSI2=0;
}

totalT = PositionsTotal();
for(int i=totalT-1 ; i>=0 ; i--){
ulong ticket = PositionGetTicket(i);
if(ticket<=0){Print("Failed to open posistion ticket"); }
if(!PositionSelectByTicket(ticket)){Print("Failed to select
position");}

long type;
double lotaje;
double profit;
if(!PositionGetInteger(POSITION_TYPE,type)){Print("Failed to
get position types");}
if(!PositionGetDouble(POSITION_PROFIT,profit)){Print("Failed
to get position profit");}
if(!PositionGetDouble(POSITION_VOLUME,lotaje)){Print("Failed
to get position profit");}

// modificacion sl buy
if(type==0 && profit>gananciaB && lotaje!=0.5){

SL2=((gananciaB*2000)-(SL1*b));
double sl = NormalizeDouble(tick.bid - SL2*_Point,_Digits);
trade.PositionModify(ticket,sl,0);
b++;
gananciaB=gananciaB+3;
}

if(type==0 && profit>ganancia1 && lotaje==0.5) {


trade.PositionClose(ticket);
}

// modificacion sl sell
if(type==1 && profit>gananciaS){

SL3=((gananciaS*2000)-(SL1*c));
double sl = NormalizeDouble(tick.bid + SL3*_Point,_Digits);
trade.PositionModify(ticket,sl,0);
c++;
gananciaS=gananciaS+3;

//---
// Copy a three-dimensional data vector to Buffer
CopyBuffer(ma_faster_Handle,0,0,4,ma_faster_Buffer);
CopyBuffer(ma_fast_Handle,0,0,4,ma_fast_Buffer);
CopyBuffer(ma_slow_Handle,0,0,4,ma_slow_Buffer);

CopyBuffer(rsi_Handle,0,0,4,rsi_Buffer);

//--- Feed candle buffers with data:


CopyRates(_Symbol,_Period,0,4,candle);
ArraySetAsSeries(candle,true);

// Sort the data vector:


ArraySetAsSeries(ma_faster_Buffer,true);
ArraySetAsSeries(ma_fast_Buffer,true);
ArraySetAsSeries(ma_slow_Buffer,true);
ArraySetAsSeries(rsi_Buffer,true);
//---
// Feed with tick variable data
SymbolInfoTick(_Symbol,tick);

Comment("\nb ", b,
"\nc ", c,
"\nopeb ", Opeb,
"\nGanancia ", gananciaB,
"\nGanancia1 ", ganancia1 );

// LOGIC TO ACTIVATE PURCHASE


bool buy_ma_cros = ma_faster_Buffer[0] > ma_slow_Buffer[0] &&
ma_faster_Buffer[2] < ma_slow_Buffer[2] ;

bool buy_rsi = rsi_Buffer[0] <= rsi_oversold;

// LOGIC TO ACTIVATE SALE


bool sell_ma_cros = ma_slow_Buffer[0] > ma_faster_Buffer[0] &&
ma_slow_Buffer[2] < ma_faster_Buffer[2];

bool sell_rsi = rsi_Buffer[0] >= rsi_overbought;


//---

bool Buy = false; // Can Buy?


bool Sell = false; // Can Sell?

if(strategy == ONLY_MA)
{
Buy = buy_ma_cros;
Sell = sell_ma_cros;

}
else if(strategy == ONLY_RSI)
{
Buy = buy_rsi;
Sell = sell_rsi;
}
else
{
Buy = buy_ma_cros && buy_rsi;
Sell = sell_ma_cros && sell_rsi;
}

// returns true if we have a new candle


bool newBar = isNewBar();

// Every time there is a new candle enter this 'if'


if(newBar)
{

// Sell Condition:
if(rsi_Buffer[0]>RSI1 && OpesRSI1<1 )
{
drawVerticalLine("Sell",candle[1].time,clrRed);
SellAtMarket();
OpesRSI1++;
}
if(rsi_Buffer[0]>RSI2 && OpesRSI2<1 )
{

drawVerticalLine("Sell",candle[1].time,clrRed);
SellAtMarket();
OpesRSI2++;
}

tiempo++;
}
//+------------------------------------------------------------------+
//| FUNCTIONS TO ASSIST IN THE VISUALIZATION OF THE STRATEGY |
//+------------------------------------------------------------------+

void drawVerticalLine(string name, datetime dt, color cor = clrAliceBlue)


{
ObjectDelete(0,name);
ObjectCreate(0,name,OBJ_VLINE,0,dt,0);
ObjectSetInteger(0,name,OBJPROP_COLOR,cor);
}

//+------------------------------------------------------------------+
//| FUNCTIONS FOR SENDING ORDERS |
//+------------------------------------------------------------------+

// BUY TO MARKET
void BuyAtMarket()
{
MqlTradeRequest request; // request
MqlTradeResult response; // response

ZeroMemory(request);
ZeroMemory(response);

//--- For Buy Order


request.action = TRADE_ACTION_DEAL; // Trade
operation type
request.magic = magic_number; // Magic
number
request.symbol = _Symbol; // Trade
symbol
request.volume = num_lots; // Lots
number
request.price = NormalizeDouble(tick.ask,_Digits); // Price to
buy
request.sl = NormalizeDouble(tick.ask - SL*_Point,_Digits);// Stop
Loss Price
request.tp = NormalizeDouble(tick.ask + TK*_Point,_Digits);// Take
Profit
request.deviation = 0; // Maximal
possible deviation from the requested price
request.type = ORDER_TYPE_BUY; // Order
type
request.type_filling = ORDER_FILLING_FOK; // Order
execution type

//---
OrderSend(request,response);
//---
if(response.retcode == 10008 || response.retcode == 10009)
{
Print("Order Buy executed successfully!!");
}
else
{
Print("Error sending Order to Buy. Error = ", GetLastError());
ResetLastError();
}

// SELL TO MARKET
void SellAtMarket()
{
MqlTradeRequest request; // request
MqlTradeResult response; // response

ZeroMemory(request);
ZeroMemory(response);

//--- For Sell Order


request.action = TRADE_ACTION_DEAL; // Trade
operation type
request.magic = magic_number; // Magic
number
request.symbol = _Symbol; // Trade
symbol
request.volume = num_lots; // Lots
number
request.price = NormalizeDouble(tick.bid,_Digits); // Price to
sell
request.sl = NormalizeDouble(tick.bid + (SL1*2)*_Point,_Digits);//
Stop Loss Price
request.tp = NormalizeDouble(tick.bid - TK*_Point,_Digits);// Take
Profit
request.deviation = 0; // Maximal
possible deviation from the requested price
request.type = ORDER_TYPE_SELL; // Order
type
request.type_filling = ORDER_FILLING_FOK; // Order
execution type
//---
OrderSend(request,response);
//---
if(response.retcode == 10008 || response.retcode == 10009)
{
Print("Order to Sell executed successfully!");
}
else
{
Print("Error sending Order to Sell. Error =", GetLastError());
ResetLastError();
}
}
/*
//---
void CloseBuy()
{
MqlTradeRequest request; // request
MqlTradeResult response; // response

ZeroMemory(request);
ZeroMemory(response);

//--- For Sell Order


request.action = TRADE_ACTION_DEAL;
request.magic = magic_number;
request.symbol = _Symbol;
request.volume = num_lots;
request.price = 0;
request.type = ORDER_TYPE_SELL;
// request.type_filling = ORDER_FILLING_RETURN;

//---
OrderSend(request,response);
//---
if(response.retcode == 10008 || response.retcode == 10009)
{
Print("Order to Sell executed successfully!");
}
else
{
Print("Error sending Order to Sell. Error =", GetLastError());
ResetLastError();
}
}

void CloseSell()
{
MqlTradeRequest request; // request
MqlTradeResult response; // response

ZeroMemory(request);
ZeroMemory(response);

//--- For Buy Order


request.action = TRADE_ACTION_DEAL;
request.magic = magic_number;
request.symbol = _Symbol;
request.volume = num_lots;
request.price = 0;
request.type = ORDER_TYPE_BUY;
request.type_filling = ORDER_FILLING_RETURN;

//---
OrderSend(request,response);
//---
if(response.retcode == 10008 || response.retcode == 10009)
{
Print("Order Buy executed successfully!!");
}
else
{
Print("Error sending Order to Buy. Error = ", GetLastError());
ResetLastError();
}
}*/
//+------------------------------------------------------------------+
//| USEFUL FUNCTIONS |
//+------------------------------------------------------------------+
//--- for bar change
bool isNewBar()
{
//--- memorize the time of opening of the last bar in the static variable
static datetime last_time=0;
//--- current time
datetime lastbar_time= (datetime)
SeriesInfoInteger(Symbol(),Period(),SERIES_LASTBAR_DATE);

//--- if it is the first call of the function


if(last_time==0)
{
//--- set the time and exit
last_time=lastbar_time;
return(false);
}

//--- if the time differs


if(last_time!=lastbar_time)
{
//--- memorize the time and return true
last_time=lastbar_time;
return(true);
}
//--- if we passed to this line, then the bar is not new; return false
return(false);
}

void OnTrade()
{//inicio

Opeb=0;
Opes=0;
totalT = PositionsTotal();
for(int i=totalT-1 ; i>=0 ; i--){
ulong ticket = PositionGetTicket(i);
if(ticket<=0){Print("Failed to open posistion ticket"); }
if(!PositionSelectByTicket(ticket)){Print("Failed to select
position");}

long type;

double lotaje;
double profit;
if(!PositionGetInteger(POSITION_TYPE,type)){Print("Failed to
get position types");}
if(!PositionGetDouble(POSITION_PROFIT,profit)){Print("Failed
to get position profit");}
if(!PositionGetDouble(POSITION_VOLUME,lotaje)){Print("Failed
to get position profit");}

if(type==0){
Opeb++;

}
if(type==1){
Opes++;
}

}//fin

// nomalize price

bool NormalizeDouble(double &price){


double tickSize=0;
if(!SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE,tickSize)){
Print("Failed to get tick size");
return false;
}
price = NormalizeDouble(MathRound(price/tickSize)*tickSize,_Digits);
return true;

You might also like