#property indicator_style4 STYLE_DASH
//+----------------------------------------------------------------------------+
//| индикатор Medium-Term Scalper |
//| Konstantin Karpov *_Konstantin_* kkw.mobile@gmail.com |
//| BE FOREX GURU ---- http://www.beforexguru.com |
//+----------------------------------------------------------------------------+
#property copyright "Copyright © 2013, FSD Team & Konstantin Karpov"
#property link "http://www.beforexguru.com, kkw.mobile@gmail.com"
#property strict
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_color1 clrOrchid
#property indicator_color2 clrMediumSlateBlue
#property indicator_color3 clrTomato
#property indicator_color4 clrBlue
#property indicator_color5 clrRed
//---------------------- Входные параметры ---------------------------------------------------+
input int inSensitivity = 38;
input bool inPopUpAlert = TRUE;
input bool inEmailAlert = FALSE;
//---------------------- Глобальные переменные -----------------------------------------------+
bool bKey = true; // какой то включатель
bool bKeyCOrHL = false; // переключатель отображения Close или Low/High
bool bKeyTwo = true; // переключатель на показ только двух линий
input int iDrawBegin = 10; // период
input int iShift = 0; // сдвиг
input int iRange = 8000; // диапазон расчета в барах
int iBar; // количество баров на графике
int iRatio_1 = 3; // какой то коэффициент
int iRatio_2 = 0; // какой то коэффициент
int iDistLine = 100; // отступ линий от баров
int iDistArrow = 100; // отступ стрелок от баров
datetime dtFixTtime; // время фиксации сигнала
double dBufLine0[],dBufLine1[],dBufLine2[],dBufLine3[],dBufLine4[],dBufLine5[],dBufLine6[]; // буферы линий
double dTheTrend = 0.0;
int iTF;
string sSy, sPeriod;
//---------------------- Иинициализация программы --------------------------------------------+
int OnInit() {
IndicatorBuffers(8);
SetIndexStyle(1,DRAW_LINE,STYLE_DOT,2);
SetIndexStyle(2,DRAW_LINE,STYLE_DOT,2);
SetIndexStyle(3,DRAW_ARROW,STYLE_SOLID,2);
SetIndexStyle(4,DRAW_ARROW,STYLE_SOLID,2);
SetIndexArrow(1,159);
SetIndexArrow(2,159);
SetIndexArrow(3,233);
SetIndexArrow(4,234);
SetIndexBuffer(1,dBufLine0);
SetIndexBuffer(2,dBufLine1);
SetIndexShift(1,iShift);
SetIndexShift(2,iShift);
SetIndexBuffer(3,dBufLine2);
SetIndexBuffer(4,dBufLine3);
SetIndexBuffer(5,dBufLine4);
SetIndexBuffer(6,dBufLine5);
SetIndexBuffer(7,dBufLine6);
IndicatorShortName("Medium-Term Scalper");
SetIndexLabel(0,"Medium-Term Scalper");
SetIndexLabel(1,"UpTrend");
SetIndexLabel(2,"DownTrend");
SetIndexDrawBegin(0,iDrawBegin);
SetIndexDrawBegin(1,iDrawBegin);
SetIndexDrawBegin(2,iDrawBegin);
SetIndexDrawBegin(3,iDrawBegin);
SetIndexDrawBegin(4,iDrawBegin);
SetIndexDrawBegin(6,iDrawBegin);
SetIndexDrawBegin(7,iDrawBegin);
iTF=Period(); sSy=Symbol(); sPeriod=IntegerToString(iTF);
return(INIT_SUCCEEDED);
}
//---------------------- Деинициализация программы -------------------------------------------+
void OnDeinit(const int reason) {}
//---------------------- Точка входа программы -----------------------------------------------+
int OnCalculate (const int rates_total, // размер входных таймсерий
const int prev_calculated, // обработано баров на предыдущем вызове
const datetime &time[], // Time
const double &open[], // Open
const double &high[], // High
const double &low[], // Low
const double &close[], // Close
const long &tick_volume[], // Tick Volume
const long &volume[], // Real Volume
const int &spread[]) { // Spread
int _iBar, _iIndCounted=IndicatorCounted(); double _dCalcSens;
if(iRange > 0) _iBar=iRange;
else _iBar = iBars(sSy,iTF);
if(_iIndCounted > 0) iBar=_iBar-_iIndCounted-1;
if(_iIndCounted < 0) return(0);
if(_iIndCounted == 0) iBar=_iBar-iDrawBegin-1;
for(int i = iBar; i >= 0; i--) {
dBufLine0[i]=EMPTY_VALUE;
dBufLine2[i]=EMPTY_VALUE;
dBufLine1[i]=EMPTY_VALUE;
dBufLine3[i]=EMPTY_VALUE;
}
for(int i=iBar;i>=0;i--) {
_dCalcSens=CalcSens(iDrawBegin,inSensitivity,iRatio_1,i);
dTheTrend=Trend(bKeyCOrHL,_dCalcSens,_iIndCounted,i)+iRatio_2/100.0*_dCalcSens*_Point;
if(bKeyTwo) {
if(dBufLine4[i] > 0.0) {
dBufLine0[i]=dTheTrend+iDistLine*_Point;
if(dBufLine4[i+1] < 0.0) {
dBufLine0[i+1]=dBufLine1[i+1];
dBufLine2[i]=dBufLine1[i+1]-iDistArrow*_Point;
}
if(i < 3 && dBufLine1[i] == dBufLine0[i] && dtFixTtime != Time[0]) {
if(inPopUpAlert) Alert("Medium-Term Scalper - Sell signal on ",sSy,", TimeFrame: ",sPeriod);
dtFixTtime = Time[0];
if(inEmailAlert) {
SendMail("Sell signal on " + sSy+", TimeFrame: "+sPeriod+" at " + TimeToStr(dtFixTtime,TIME_DATE),
"Medium-Term Scalper Sell signal on "+sSy+", TimeFrame: "+sPeriod+" at "+TimeToStr(dtFixTtime,TIME_DATE));
}
}
dBufLine1[i] = EMPTY_VALUE;
}
if(dBufLine4[i] < 0.0) {
dBufLine1[i]=dTheTrend-iDistLine*_Point;
if(dBufLine4[i+1] > 0.0) {
dBufLine1[i+1]=dBufLine0[i+1];
dBufLine3[i]=dBufLine0[i+1]+iDistArrow*_Point;
}
if(i < 3 && dBufLine1[i] == dBufLine0[i] && dtFixTtime != Time[0]) {
if(inPopUpAlert) Alert("Medium-Term Scalper - Buy signal on ", sSy, ", TimeFrame: ", sPeriod);
dtFixTtime = Time[0];
if(inEmailAlert) {
SendMail("Buy signal on " + sSy + ", TimeFrame: " + sPeriod + " at " + TimeToStr(dtFixTtime, TIME_DATE),
"Medium-Term Scalper Buy signal on " + sSy + ", TimeFrame: " + sPeriod + " at " + TimeToStr(dtFixTtime, TIME_DATE));
}
}
dBufLine0[i] = EMPTY_VALUE;
}
} else {
dBufLine0[i] = EMPTY_VALUE;
dBufLine1[i] = EMPTY_VALUE;
dBufLine2[i] = -1;
dBufLine3[i] = -1;
}
}
return(0);
}
//+-------------------------------------------------------------------------------------------+
/*!
Расчет чувствительности
\param int _iDrawBegin
\param double _iSensitivity
\param int _iRatio
\param int _iIndexBar
\return расчитанную чувствительность индикатора
*/
double CalcSens(int _iDrawBegin,int _iSensitivity,int _iRatio,int _iIndexBar) {
double _dCalcSens, _dSens=0.0, _dMin=-100000.0, _dMax=1000000.0; int _iFactor;
if(iClose(sSy,iTF,0)>10.0) _iFactor=10;
else _iFactor=1;
if(_iRatio == 0) {
double dDividend=0.0, dDivider=0.0, dQuotientOfDrawBegin=0.0;
for(int i=_iDrawBegin-1;i>=0;i--) {
if(bKey) dQuotientOfDrawBegin=1.0;
else dQuotientOfDrawBegin=(_iDrawBegin - i)/_iDrawBegin;
dDividend+=dQuotientOfDrawBegin*(High[_iIndexBar+i]-(Low[_iIndexBar+i]));
dDivider+=dQuotientOfDrawBegin;
}
_dSens=dDividend/dDivider;
if(_dSens > _dMin) _dMin=_dSens;
if(_dSens < _dMax) _dMax=_dSens;
_dCalcSens=MathRound(_iSensitivity/2.0*(_dMin+_dMax)/_Point)*_iFactor;
} else _dCalcSens=_iSensitivity*_iRatio*_iFactor;
return(_dCalcSens);
}
/*!
Направление тренда
\param bool _bKeyCOrHL
\param const double _dCalcSens
\param int _iIndCounted
\param const int _iIndexBar
\return расчитанное направление тренда
*/
double Trend(bool _bKeyCOrHL,const double &_dCalcSens,const int &_iIndCounted,const int &_iIndexBar) {
double _dTrend;
if(_bKeyCOrHL) {
dBufLine6[_iIndexBar]=Low[_iIndexBar]+2.0*_dCalcSens*_Point;
dBufLine5[_iIndexBar]=High[_iIndexBar]-2.0*_dCalcSens*_Point;
} else {
dBufLine6[_iIndexBar]=Close[_iIndexBar]+2.0*_dCalcSens*_Point;
dBufLine5[_iIndexBar]=Close[_iIndexBar]-2.0*_dCalcSens*_Point;
}
if(_iIndCounted == 0) {
dBufLine6[iBar+1]=dBufLine6[iBar];
dBufLine5[iBar+1]=dBufLine5[iBar];
dBufLine4[iBar+1]=0.0;
}
dBufLine4[_iIndexBar] = dBufLine4[_iIndexBar+1];
if(Close[_iIndexBar] > dBufLine6[_iIndexBar+1]) dBufLine4[_iIndexBar] = 1.0;
if(Close[_iIndexBar] < dBufLine5[_iIndexBar+1]) dBufLine4[_iIndexBar] = -1.0;
if(dBufLine4[_iIndexBar] > 0.0) {
if(dBufLine5[_iIndexBar] < dBufLine5[_iIndexBar + 1]) dBufLine5[_iIndexBar]=dBufLine5[_iIndexBar+1];
_dTrend=dBufLine5[_iIndexBar]+_dCalcSens*_Point;
} else {
if(dBufLine6[_iIndexBar] > dBufLine6[_iIndexBar+1]) dBufLine6[_iIndexBar]=dBufLine6[_iIndexBar+1];
_dTrend=dBufLine6[_iIndexBar]-_dCalcSens*_Point;
}
return(_dTrend);
}
<code>//--- ВХОДНЫЕ ПЕРЕМЕННЫЕ input int MAPeriod = 54; input int MAMethod = 3; input int Shift = 10; input int Delta = 23; extern double Lots = 0.01; // лот extern double KLot = 2; // умножение лота extern double MaxLot = 10; // максимальный лот extern int StopLoss = 9000; // Стоп лосс extern int TakeProfit = 3000; // профит extern int Profit = 5; // профит в валюте extern int Slip = 30; // Проскальзывание цены extern int Reverce = 0; // 1-реверс extern int Magic = 123456; // магик extern string IndName="Diablo_EUR_USD"; datetime t=0; //| Expert initialization function int OnInit() { //-------------------------------------------------------- if(!IsTradeAllowed()) Alert("Для нормальной работы советника необходимо\n"+ "Разрешить советнику торговать"); if(!IsExpertEnabled()) Alert("Отжата кнопка \"Разрешить запуск советников\""); Comment(""); //--- return(INIT_SUCCEEDED); } // Expert deinitialization function void OnDeinit(const int reason) { Comment(""); } //------------------------------------------------------------------------- void PutOrder(int type,double price) { int r=0; color clr=Green; double sl=0,tp=0; if(type==1 || type==3 || type==5) { clr=Red; if(StopLoss>0) sl=NormalizeDouble(price+StopLoss*Point,Digits); if(TakeProfit>0) tp=NormalizeDouble(price-TakeProfit*Point,Digits); } if(type==0 || type==2 || type==4) { clr=Blue; if(StopLoss>0) sl=NormalizeDouble(price-StopLoss*Point,Digits); if(TakeProfit>0) tp=NormalizeDouble(price+TakeProfit*Point,Digits); } r=OrderSend(NULL,type,Lot(type),NormalizeDouble(price,Digits),Slip,sl,tp,"",Magic,0,clr); return; } //-------------------------------------------------------------------------- int CountTrades(int type) { int count=0; for(int i=OrdersTotal()-1;i>=0;i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) { if(OrderType()==type) count++; } } } return(count); } //--------------------------------------------------------------------------- void ClosePos(int ot=-1) { bool cl; for(int i=OrdersTotal()-1;i>=0;i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) { if(OrderType()==0 && (ot==0 || ot==-1)) { RefreshRates(); cl=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),Slip,White); } if(OrderType()==1 && (ot==1 || ot==-1)) { RefreshRates(); cl=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),Slip,White); } } } } } //+------------------------------------------------------------------+ double Lot(int type) { double lot=Lots; if(CountTrades(0)>0) lot=NormalizeDouble(Lots*MathPow(KLot,CountTrades(0)),2)-(0.01*CountTrades(0)); if(CountTrades(1)>0) lot=NormalizeDouble(Lots*MathPow(KLot,CountTrades(1)),2)-(0.01*CountTrades(1)); if(lot>MaxLot)lot=NormalizeDouble(Lots*MathPow(KLot,CountTrades(1)),2); return(lot); } //-------------------------------------------------------------------------- double AllProfit(int type=-1) { double profit=0; for(int i=OrdersTotal()-1;i>=0;i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) { if(OrderType()==type) profit+=OrderProfit()+OrderCommission()+OrderSwap(); if(type==-1) { if(OrderType()<2) profit+=OrderProfit()+OrderCommission()+OrderSwap(); } } } } return (profit); } //------------------------------------------------------------------ void OpenPos() { double ma11=iMA(NULL,0,MAPeriod,0,MAMethod,3,1); double ma12=iMA(NULL,0,MAPeriod,0,MAMethod,3,1+Shift); double ma21=iMA(NULL,0,MAPeriod,0,MAMethod,2,1); double ma22=iMA(NULL,0,MAPeriod,0,MAMethod,2,1+Shift); double dma=NormalizeDouble(MathAbs(ma22-ma21)/Point-MathAbs(ma12-ma11)/Point,0); if(dma>0 && MathAbs(dma)>Delta) { PutOrder(0,Ask); } if(dma<0 && MathAbs(dma)>Delta) { PutOrder(1,Bid); } } //------------------------------------------------------------------ void OnTick() { if(t!=Time[0]) { if(Reverce<1) OpenPos(); t=Time[0]; } if(AllProfit()>Profit && Profit>0) ClosePos(); } </code>
← предыдущая следующая →
Устанавливает новое значение глобальной переменной. Если переменная не существует, то система создает новую глобальную переменную.
datetime GlobalVariableSet(
string name, // имя
double value // устанавлимое значение
);
Эта команда записывает значение в глобальную переменную.
GlobalVariableGet
Возвращает значение существующей глобальной переменной клиентского терминала. Существует 2 варианта функции.
1. Непосредственно возвращает значение свойства.
double GlobalVariableGet(
string name // имя
);
2. Возвращает true или false в зависимости от успешности выполнения функции. В случае успеха значение глобальной переменной клиентского терминала помещается в приемную переменную, передаваемую по ссылке вторым параметром.
bool GlobalVariableGet(
string name, // имя
double& double_var // сюда примем значение глобальной переменной
);
Эта команда считывает значение из глобальной переменной.
vic123