Compare commits
40 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff8aa9fcfb | |||
| e8bf23f987 | |||
| a21fd7519e | |||
| 8e17edd4ae | |||
| 01907379e2 | |||
| 721c7965e8 | |||
| 3c271745e1 | |||
| b0012bf2fd | |||
| a1023b573e | |||
| cf3525f7af | |||
| 5cee3f06fd | |||
| f930e88592 | |||
| 908d0e9187 | |||
| 64dc36b1c3 | |||
| 8e6fe91b70 | |||
| a6f6c0510b | |||
| 20315441a5 | |||
| f1d1a2230f | |||
| 4a590b805a | |||
| b79cf56412 | |||
| b45039f91f | |||
| 392706088a | |||
| ae7551ef9d | |||
| f2515243e3 | |||
| 2c32e233e6 | |||
| 78ccb1d819 | |||
| 03e1b290b5 | |||
| 3c4909af0f | |||
| 598917d4ae | |||
| 1cd30c1060 | |||
| 909dbbc60e | |||
| 2c09955da7 | |||
| cd04d6fbd7 | |||
| 654091697b | |||
| 0135d122d9 | |||
| b32b055ee3 | |||
| 3d2bafacad | |||
| 2b113ac0ab | |||
| a09c9111bc | |||
| f4c0e46e29 |
@@ -0,0 +1,407 @@
|
||||
//+------------------------------------------------------------------+
|
||||
//| PaPP_Trading.mq5 |
|
||||
//| PaPP Trading |
|
||||
//+------------------------------------------------------------------+
|
||||
#property copyright "PaPP Trading"
|
||||
#property version "2.00"
|
||||
#property description "PaPP Trading - Multi timeframe MA + volatilita + accelerazione"
|
||||
#property indicator_chart_window
|
||||
#property indicator_buffers 10
|
||||
#property indicator_plots 10
|
||||
|
||||
input bool ShowLines = false;
|
||||
input int FontSize = 9;
|
||||
input int XPos = 10;
|
||||
input int YPos = 30;
|
||||
input int TP_Points = 100; // Take Profit (punti)
|
||||
input int SL_Points = 10000; // Stop Loss (punti)
|
||||
input bool ShowTPSL = true; // Draw TP/SL lines on chart
|
||||
|
||||
//--- indicator buffers (SetIndexBuffer bound)
|
||||
double B1Y[], B6M[], B4M[], B1Mo[], B2W[], B1W[], B3D[], B1D[], BSc[], BAc[];
|
||||
|
||||
//--- handles
|
||||
int hMA[8];
|
||||
int bars[8];
|
||||
string pN[8] = {"1Y","6M","4M","1M","2W","1W","3G","1G"};
|
||||
string _pfx = "PP_";
|
||||
|
||||
//--- rolling volatility window
|
||||
double hMin[8], hMax[8];
|
||||
int volResetBar[8]; // bar index (non-series) of last reset
|
||||
int WINDOW = 200; // rolling window bars
|
||||
|
||||
//--- last bar tracking for dashboard update
|
||||
datetime lastBarTime = 0;
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int TimeToBars(int days)
|
||||
{
|
||||
datetime now = TimeCurrent();
|
||||
if(now==0)
|
||||
{
|
||||
long s = (long)days*86400L;
|
||||
long p = PeriodSeconds((ENUM_TIMEFRAMES)_Period);
|
||||
return (int)MathMax(1,s/p);
|
||||
}
|
||||
datetime then = now - days*86400;
|
||||
int cnt = Bars(_Symbol,_Period,then,now);
|
||||
return MathMax(1,cnt);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int OnInit()
|
||||
{
|
||||
IndicatorSetString(INDICATOR_SHORTNAME,"PaPP Trading v2");
|
||||
IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
|
||||
|
||||
int days[8] = {365,182,121,30,14,7,3,1};
|
||||
for(int i=0;i<8;i++)
|
||||
{
|
||||
bars[i] = (i<7) ? TimeToBars(days[i]) : 1;
|
||||
hMA[i]=iMA(_Symbol,_Period,bars[i],0,MODE_SMA,PRICE_CLOSE);
|
||||
if(hMA[i]==INVALID_HANDLE) return INIT_FAILED;
|
||||
}
|
||||
|
||||
SetIndexBuffer(0,B1Y,INDICATOR_DATA); ArraySetAsSeries(B1Y,true);
|
||||
SetIndexBuffer(1,B6M,INDICATOR_DATA); ArraySetAsSeries(B6M,true);
|
||||
SetIndexBuffer(2,B4M,INDICATOR_DATA); ArraySetAsSeries(B4M,true);
|
||||
SetIndexBuffer(3,B1Mo,INDICATOR_DATA); ArraySetAsSeries(B1Mo,true);
|
||||
SetIndexBuffer(4,B2W,INDICATOR_DATA); ArraySetAsSeries(B2W,true);
|
||||
SetIndexBuffer(5,B1W,INDICATOR_DATA); ArraySetAsSeries(B1W,true);
|
||||
SetIndexBuffer(6,B3D,INDICATOR_DATA); ArraySetAsSeries(B3D,true);
|
||||
SetIndexBuffer(7,B1D,INDICATOR_DATA); ArraySetAsSeries(B1D,true);
|
||||
SetIndexBuffer(8,BSc,INDICATOR_DATA); ArraySetAsSeries(BSc,true);
|
||||
SetIndexBuffer(9,BAc,INDICATOR_DATA); ArraySetAsSeries(BAc,true);
|
||||
|
||||
color cl[10] = {clrRed,clrOrange,clrGold,clrLimeGreen,
|
||||
clrDodgerBlue,clrViolet,clrBrown,clrGray,clrCyan,clrMagenta};
|
||||
for(int i=0;i<8;i++)
|
||||
{
|
||||
PlotIndexSetInteger(i,PLOT_DRAW_TYPE,ShowLines?DRAW_LINE:DRAW_NONE);
|
||||
PlotIndexSetInteger(i,PLOT_LINE_COLOR,cl[i]);
|
||||
PlotIndexSetString(i,PLOT_LABEL,pN[i]+" MA");
|
||||
PlotIndexSetInteger(i,PLOT_LINE_WIDTH,2);
|
||||
}
|
||||
PlotIndexSetInteger(8,PLOT_DRAW_TYPE,DRAW_NONE);
|
||||
PlotIndexSetInteger(9,PLOT_DRAW_TYPE,DRAW_NONE);
|
||||
|
||||
for(int i=0;i<8;i++) { hMin[i]=1e10; hMax[i]=-1e10; volResetBar[i]=0; }
|
||||
|
||||
return INIT_SUCCEEDED;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void OnDeinit(const int reason)
|
||||
{
|
||||
for(int i=0;i<8;i++)
|
||||
if(hMA[i]!=INVALID_HANDLE) IndicatorRelease(hMA[i]);
|
||||
ObjectsDeleteAll(0,_pfx);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| Buffer helpers (separate MA index from bar index) |
|
||||
//+------------------------------------------------------------------+
|
||||
void SetMA(int b, int bar, double v)
|
||||
{
|
||||
if(b==0) B1Y[bar]=v; else if(b==1) B6M[bar]=v; else if(b==2) B4M[bar]=v;
|
||||
else if(b==3) B1Mo[bar]=v; else if(b==4) B2W[bar]=v; else if(b==5) B1W[bar]=v;
|
||||
else if(b==6) B3D[bar]=v; else if(b==7) B1D[bar]=v;
|
||||
}
|
||||
double GetMA(int bar, int m)
|
||||
{
|
||||
if(m==0) return B1Y[bar]; if(m==1) return B6M[bar]; if(m==2) return B4M[bar];
|
||||
if(m==3) return B1Mo[bar]; if(m==4) return B2W[bar]; if(m==5) return B1W[bar];
|
||||
if(m==6) return B3D[bar]; return B1D[bar];
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int OnCalculate(const int rates_total,
|
||||
const int prev_calculated,
|
||||
const datetime &time[],
|
||||
const double &open[],
|
||||
const double &high[],
|
||||
const double &low[],
|
||||
const double &close[],
|
||||
const long &tick_volume[],
|
||||
const long &volume[],
|
||||
const int &spread[])
|
||||
{
|
||||
if(rates_total<2) return 0;
|
||||
|
||||
ArraySetAsSeries(close,true);
|
||||
ArraySetAsSeries(time,true);
|
||||
|
||||
//--- limit = number of new bars to process
|
||||
int limit = rates_total - prev_calculated;
|
||||
if(limit>1) limit = rates_total-1;
|
||||
|
||||
//--- Copy only the needed range (performance)
|
||||
// needed = limit+1 bars from position startPos
|
||||
int needed = limit + 1;
|
||||
int startPos = rates_total - needed;
|
||||
if(startPos<0) { startPos=0; needed=rates_total; }
|
||||
|
||||
//--- Temp arrays for MA data
|
||||
double tmp[8][];
|
||||
for(int m=0;m<8;m++)
|
||||
{
|
||||
ArrayResize(tmp[m],needed);
|
||||
int copied = CopyBuffer(hMA[m],0,startPos,needed,tmp[m]);
|
||||
if(copied<needed)
|
||||
{
|
||||
// Not enough data, zero-fill remaining
|
||||
for(int i=(copied>0?copied:0);i<needed;i++) tmp[m][i]=0;
|
||||
}
|
||||
ArraySetAsSeries(tmp[m],true);
|
||||
}
|
||||
|
||||
//--- Assign temp -> indicator buffers (series indexed: idx=0=newest)
|
||||
for(int idx=limit; idx>=0; idx--)
|
||||
{
|
||||
double mv[8];
|
||||
for(int m=0;m<8;m++)
|
||||
{
|
||||
if(idx<needed) mv[m]=tmp[m][idx];
|
||||
else mv[m]=GetMA(idx,m); // fallback (shouldn't happen)
|
||||
SetMA(m, idx, mv[m]);
|
||||
}
|
||||
|
||||
double p = close[idx];
|
||||
|
||||
//--- Velocities: need prev bar
|
||||
double vel[8];
|
||||
for(int m=0;m<8;m++)
|
||||
{
|
||||
double prv;
|
||||
if(idx+1<rates_total)
|
||||
{
|
||||
if(idx+1<needed) prv=tmp[m][idx+1];
|
||||
else prv=GetMA(idx+1,m); // from previously calculated data
|
||||
}
|
||||
else prv=mv[m];
|
||||
vel[m]=mv[m]-prv;
|
||||
}
|
||||
|
||||
//--- Score
|
||||
int sc=0;
|
||||
for(int m=0;m<8;m++) sc += (p>mv[m]) ? 1 : -1;
|
||||
BSc[idx]=sc;
|
||||
|
||||
//--- Acceleration
|
||||
double aSum=0;
|
||||
for(int m=0;m<7;m++) aSum+=(vel[m]-vel[m+1]);
|
||||
BAc[idx]=aSum/7.0;
|
||||
|
||||
//--- Rolling volatility window: reset & rebuild every WINDOW bars
|
||||
// volResetBar tracks the non-series bar index of last reset
|
||||
// Non-series index = rates_total - 1 - idx (since idx is series)
|
||||
int nsIdx = rates_total - 1 - idx; // non-series index (0=oldest)
|
||||
if(nsIdx == volResetBar[0] + WINDOW)
|
||||
{
|
||||
// Time to reset: scan back WINDOW bars to recompute min/max
|
||||
for(int m=0;m<8;m++) { hMin[m]=1e10; hMax[m]=-1e10; }
|
||||
int scanStart = MathMax(0, nsIdx - WINDOW);
|
||||
int scanEnd = MathMin(rates_total-1, nsIdx);
|
||||
for(int s=scanStart; s<=scanEnd; s++)
|
||||
{
|
||||
int si = rates_total - 1 - s; // series index
|
||||
double pp = close[si];
|
||||
for(int m=0;m<8;m++)
|
||||
{
|
||||
double vm = GetMA(si,m);
|
||||
if(vm>0)
|
||||
{
|
||||
double d = MathAbs(pp - vm);
|
||||
if(d<hMin[m]) hMin[m]=d;
|
||||
if(d>hMax[m]) hMax[m]=d;
|
||||
}
|
||||
}
|
||||
}
|
||||
for(int m=0;m<8;m++) volResetBar[m]=nsIdx;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Normal update: extend min/max if this bar pushes them
|
||||
for(int m=0;m<8;m++)
|
||||
{
|
||||
if(mv[m]>0)
|
||||
{
|
||||
double d = MathAbs(p-mv[m]);
|
||||
if(d<hMin[m]) hMin[m]=d;
|
||||
if(d>hMax[m]) hMax[m]=d;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//--- Dashboard: only on new bar or first run
|
||||
bool newBar = (time[0]!=lastBarTime);
|
||||
if(newBar || prev_calculated==0)
|
||||
{
|
||||
lastBarTime = time[0];
|
||||
DrawDashboard();
|
||||
}
|
||||
|
||||
return rates_total;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void DrawDashboard()
|
||||
{
|
||||
double mv[8], vel[8];
|
||||
double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
|
||||
|
||||
for(int m=0;m<8;m++)
|
||||
{
|
||||
mv[m]=GetMA(0,m);
|
||||
double prv = (GetMA(1,m)>0) ? GetMA(1,m) : mv[m];
|
||||
vel[m]=mv[m]-prv;
|
||||
}
|
||||
|
||||
string tf = EnumToString((ENUM_TIMEFRAMES)_Period);
|
||||
int x=XPos, y=YPos, lh=FontSize+4;
|
||||
|
||||
//--- Title
|
||||
Lbl("T",_Symbol+" PaPP ["+tf+"] v2",x,y,FontSize+2,clrGold,true);
|
||||
y+=lh+4;
|
||||
|
||||
double c0=GetMA(0,7); // B1D[0] = SMA(1) = latest close
|
||||
double c1=GetMA(1,7);
|
||||
Lbl("P","Oggi: "+DTS(c0,_Digits)+" | Ieri: "+DTS(c1,_Digits),x,y,FontSize,clrWhite,false);
|
||||
y+=lh+2;
|
||||
|
||||
Lbl("S1","------------------------------",x,y,FontSize-1,clrGold,false);
|
||||
y+=lh;
|
||||
|
||||
string hdr = StringFormat("%-6s %-12s %-4s %-8s %-5s %-7s","Periodo","Media","Pos","Dist","Vol%","Veloc");
|
||||
Lbl("H",hdr,x,y,FontSize,clrGold,false);
|
||||
y+=lh;
|
||||
|
||||
for(int m=0;m<8;m++)
|
||||
{
|
||||
if(mv[m]<=0) continue;
|
||||
double dist = bid-mv[m];
|
||||
double absD = MathAbs(dist);
|
||||
|
||||
//--- Volatility % (rolling window)
|
||||
double vn=50.0;
|
||||
if(hMax[m]>hMin[m] && hMax[m]>0)
|
||||
{ vn=((absD-hMin[m])/(hMax[m]-hMin[m]))*100.0; vn=MathMax(0,MathMin(100,vn)); }
|
||||
|
||||
string row = StringFormat("%-6s %-12.*f %-4s %-+8.*f %-5.0f%% %-+7.*f",
|
||||
pN[m],_Digits,mv[m],
|
||||
(dist>0)?"SU":"GIU",
|
||||
_Digits,dist,vn,_Digits,vel[m]);
|
||||
Lbl("R"+(string)m,row,x,y,FontSize,(dist>0)?clrLimeGreen:clrRed,false);
|
||||
y+=lh;
|
||||
}
|
||||
|
||||
Lbl("S2","------------------------------",x,y,FontSize-1,clrGold,false);
|
||||
y+=lh;
|
||||
|
||||
//--- Score
|
||||
int sc = (int)BSc[0];
|
||||
string sS = StringFormat("SCORE: %+d/8",sc);
|
||||
string sD = " [LATERALE]";
|
||||
if(sc>=5) sD=" [IPERCOMPRATO]";
|
||||
else if(sc<=-5) sD=" [IPERVENDUTO]";
|
||||
else if(sc>=2) sD=" [RIALZO]";
|
||||
else if(sc<=-2) sD=" [RIBASSO]";
|
||||
Lbl("Sc",sS+sD,x,y,FontSize+1,(sc>=2)?clrLimeGreen:(sc<=-2)?clrRed:clrGray,true);
|
||||
y+=lh+2;
|
||||
|
||||
//--- Acceleration (threshold based on _Point)
|
||||
double acc = BAc[0];
|
||||
double accThresh = _Point * 10.0;
|
||||
string aS = StringFormat("ACCEL: %+.*f",_Digits+1,acc);
|
||||
string aD = " [STABILE/FRENATA]";
|
||||
if(acc>accThresh) aD=" [ACCELERAZIONE +]";
|
||||
else if(acc<-accThresh) aD=" [ACCELERAZIONE -]";
|
||||
Lbl("Ac",aS+aD,x,y,FontSize+1,(acc>accThresh)?clrLimeGreen:(acc<-accThresh)?clrRed:clrGray,true);
|
||||
y+=lh;
|
||||
|
||||
//--- Average volatility
|
||||
double vAvg=0; int vCnt=0;
|
||||
for(int m=0;m<8;m++)
|
||||
{
|
||||
if(mv[m]>0 && hMax[m]>hMin[m] && hMax[m]>0)
|
||||
{
|
||||
double ad=MathAbs(bid-mv[m]);
|
||||
double vn=((ad-hMin[m])/(hMax[m]-hMin[m]))*100.0;
|
||||
vAvg+=MathMax(0,MathMin(100,vn)); vCnt++;
|
||||
}
|
||||
}
|
||||
if(vCnt>0) vAvg/=vCnt;
|
||||
string vS = StringFormat("VOL: %.0f%%",vAvg);
|
||||
string vD = " [NORMALE]";
|
||||
if(vAvg>70) vD=" [ALTA - breakout in corso]";
|
||||
else if(vAvg<40) vD=" [BASSA - compressione]";
|
||||
Lbl("Vo",vS+vD,x,y,FontSize+1,(vAvg>70)?clrRed:(vAvg>40)?clrYellow:clrLimeGreen,true);
|
||||
y+=lh+2;
|
||||
Lbl("TPSL","TP: +"+string(TP_Points)+" pt ("+DTS(bid+TP_Points*_Point,_Digits)+
|
||||
") | SL: -"+string(SL_Points)+" pt ("+DTS(bid-SL_Points*_Point,_Digits)+")",
|
||||
x,y,FontSize,clrGray,false);
|
||||
y+=lh+6;
|
||||
|
||||
//--- TP/SL lines on chart
|
||||
if(ShowTPSL)
|
||||
{
|
||||
string tpName = _pfx+"TPLINE";
|
||||
string slName = _pfx+"SLLINE";
|
||||
double tpPrice = bid + TP_Points * _Point;
|
||||
double slPrice = bid - SL_Points * _Point;
|
||||
if(ObjectFind(0,tpName)<0) ObjectCreate(0,tpName,OBJ_HLINE,0,0,0);
|
||||
if(ObjectFind(0,slName)<0) ObjectCreate(0,slName,OBJ_HLINE,0,0,0);
|
||||
ObjectSetDouble(0,tpName,OBJPROP_PRICE,tpPrice);
|
||||
ObjectSetDouble(0,slName,OBJPROP_PRICE,slPrice);
|
||||
ObjectSetInteger(0,tpName,OBJPROP_COLOR,clrLimeGreen);
|
||||
ObjectSetInteger(0,slName,OBJPROP_COLOR,clrRed);
|
||||
ObjectSetInteger(0,tpName,OBJPROP_WIDTH,1);
|
||||
ObjectSetInteger(0,slName,OBJPROP_WIDTH,1);
|
||||
ObjectSetInteger(0,tpName,OBJPROP_STYLE,STYLE_DASHDOT);
|
||||
ObjectSetInteger(0,slName,OBJPROP_STYLE,STYLE_DASHDOT);
|
||||
ObjectSetString(0,tpName,OBJPROP_TEXT,"TP +"+string(TP_Points)+" ("+DTS(tpPrice,_Digits)+")");
|
||||
ObjectSetString(0,slName,OBJPROP_TEXT,"SL -"+string(SL_Points)+" ("+DTS(slPrice,_Digits)+")");
|
||||
ObjectSetInteger(0,tpName,OBJPROP_BACK,true);
|
||||
ObjectSetInteger(0,slName,OBJPROP_BACK,true);
|
||||
ObjectSetInteger(0,tpName,OBJPROP_SELECTABLE,false);
|
||||
ObjectSetInteger(0,slName,OBJPROP_SELECTABLE,false);
|
||||
}
|
||||
else
|
||||
{
|
||||
if(ObjectFind(0,_pfx+"TPLINE")>=0) ObjectDelete(0,_pfx+"TPLINE");
|
||||
if(ObjectFind(0,_pfx+"SLLINE")>=0) ObjectDelete(0,_pfx+"SLLINE");
|
||||
}
|
||||
|
||||
Lbl("L0","LEGENDA:",x,y,FontSize,clrGold,true);
|
||||
y+=lh;
|
||||
Lbl("L1","SU/GIU = prezzo sopra/sotto media | Vol% = 0(min)-100(max) rolling "+string(WINDOW),x,y,FontSize-1,clrWhite,false);
|
||||
y+=lh-2;
|
||||
Lbl("L2","Score +8=tutto rialzo -8=tutto ribasso ~0=laterale",x,y,FontSize-1,clrWhite,false);
|
||||
y+=lh-2;
|
||||
Lbl("L3","Accel +=forza in aumento -=forza in calo ~0=stabile/frenata",x,y,FontSize-1,clrWhite,false);
|
||||
y+=lh-2;
|
||||
Lbl("L4","Vol>70%=esplosione Vol<40%=compressione (molla)",x,y,FontSize-1,clrWhite,false);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void Lbl(string n,string t,int x,int y,int fs,color c,bool b)
|
||||
{
|
||||
string o=_pfx+n;
|
||||
if(ObjectFind(0,o)<0) ObjectCreate(0,o,OBJ_LABEL,0,0,0);
|
||||
ObjectSetInteger(0,o,OBJPROP_XDISTANCE,x);
|
||||
ObjectSetInteger(0,o,OBJPROP_YDISTANCE,y);
|
||||
ObjectSetInteger(0,o,OBJPROP_CORNER,CORNER_LEFT_UPPER);
|
||||
ObjectSetString(0,o,OBJPROP_TEXT,t);
|
||||
ObjectSetString(0,o,OBJPROP_FONT,b?"Lucida Console Bold":"Lucida Console");
|
||||
ObjectSetInteger(0,o,OBJPROP_FONTSIZE,fs);
|
||||
ObjectSetInteger(0,o,OBJPROP_COLOR,c);
|
||||
ObjectSetInteger(0,o,OBJPROP_BACK,false);
|
||||
ObjectSetInteger(0,o,OBJPROP_SELECTABLE,false);
|
||||
ObjectSetInteger(0,o,OBJPROP_HIDDEN,true);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
string DTS(double v,int d) { return DoubleToString(v,d); }
|
||||
//+------------------------------------------------------------------+
|
||||
@@ -0,0 +1,208 @@
|
||||
//+------------------------------------------------------------------+
|
||||
//| PaPP_Trading_EA.mq5 |
|
||||
//| PaPP Trading |
|
||||
//+------------------------------------------------------------------+
|
||||
#include <Trade/Trade.mqh>
|
||||
//+------------------------------------------------------------------+
|
||||
#property copyright "PaPP Trading"
|
||||
#property version "1.03"
|
||||
#property description "PaPP Trading EA - Mean Reversion su Score multi-TF"
|
||||
#property description "Compra quando Score <= BuyThresh (sotto media = ipervenduto)"
|
||||
#property description "Vende quando Score >= SellThresh (sopra media = ipercomprato)"
|
||||
|
||||
input double LotSize = 0.01;
|
||||
input int TP_Points = 100;
|
||||
input int SL_Points = 10000; // ~1000 pips, safety net largo
|
||||
input int BuyThresh = -3;
|
||||
input int SellThresh = 3;
|
||||
input bool UseAccel = false;
|
||||
input bool DebugPrint = true;
|
||||
input int MinValidMAs = 4;
|
||||
input int Magic = 2024001;
|
||||
input int Slippage = 30;
|
||||
|
||||
int hMA[8];
|
||||
int bars[8];
|
||||
string pN[8] = {"1Y","6M","4M","1M","2W","1W","3G","1G"};
|
||||
datetime lastBar = 0;
|
||||
ulong myTicket = 0;
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int TimeToBars(int days)
|
||||
{
|
||||
datetime now = TimeCurrent();
|
||||
if(now==0)
|
||||
{
|
||||
long s = (long)days*86400L;
|
||||
long p = PeriodSeconds((ENUM_TIMEFRAMES)_Period);
|
||||
return (int)MathMax(1,s/p);
|
||||
}
|
||||
datetime then = now - days*86400;
|
||||
int cnt = Bars(_Symbol,_Period,then,now);
|
||||
return MathMax(1,cnt);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int OnInit()
|
||||
{
|
||||
int days[8] = {365,182,121,30,14,7,3,1};
|
||||
for(int i=0;i<8;i++)
|
||||
{
|
||||
bars[i] = (i<7) ? TimeToBars(days[i]) : 1;
|
||||
hMA[i] = iMA(_Symbol,_Period,bars[i],0,MODE_SMA,PRICE_CLOSE);
|
||||
if(hMA[i]==INVALID_HANDLE) return INIT_FAILED;
|
||||
}
|
||||
myTicket = 0;
|
||||
Print("=== PaPP v1.03 INIT ===");
|
||||
for(int i=0;i<8;i++) Print(" MA[",i,"] ",pN[i]," bars=",bars[i]);
|
||||
return INIT_SUCCEEDED;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void OnDeinit(const int reason)
|
||||
{
|
||||
for(int i=0;i<8;i++)
|
||||
if(hMA[i]!=INVALID_HANDLE) IndicatorRelease(hMA[i]);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
double GetMA(int idx,int m)
|
||||
{
|
||||
double buf[1];
|
||||
// idx=0 -> last COMPLETED bar (start_pos=1)
|
||||
// idx=1 -> second-to-last (start_pos=2)
|
||||
if(CopyBuffer(hMA[m],0,idx+1,1,buf)==1) return buf[0];
|
||||
return 0;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void OnTick()
|
||||
{
|
||||
datetime curBar = iTime(_Symbol,_Period,0);
|
||||
if(curBar==lastBar) return;
|
||||
lastBar = curBar;
|
||||
|
||||
double close0 = iClose(_Symbol,_Period,0);
|
||||
if(close0<=0) return;
|
||||
|
||||
double mv[8], vel[8];
|
||||
int validMAs=0;
|
||||
for(int m=0;m<8;m++)
|
||||
{
|
||||
mv[m] = GetMA(0,m);
|
||||
if(mv[m]>0) validMAs++;
|
||||
double prv = GetMA(1,m);
|
||||
if(prv<=0) prv=mv[m];
|
||||
vel[m] = mv[m] - prv;
|
||||
}
|
||||
|
||||
if(DebugPrint)
|
||||
{
|
||||
Print("--- ",TimeToString(curBar)," Close=",DoubleToString(close0,_Digits)," Valid=",validMAs);
|
||||
for(int m=0;m<8;m++)
|
||||
if(mv[m]>0)
|
||||
Print(" ",pN[m],"=",DoubleToString(mv[m],_Digits),
|
||||
" diff=",DoubleToString(close0-mv[m],_Digits),
|
||||
" vel=",DoubleToString(vel[m],6));
|
||||
}
|
||||
|
||||
if(validMAs < MinValidMAs) return;
|
||||
|
||||
//--- Score (-validMAs .. +validMAs)
|
||||
int score = 0;
|
||||
for(int m=0;m<8;m++)
|
||||
if(mv[m]>0) score += (close0>mv[m]) ? 1 : -1;
|
||||
|
||||
//--- Acceleration
|
||||
double accel=0;
|
||||
int ac=0;
|
||||
for(int m=0;m<7;m++)
|
||||
{
|
||||
if(mv[m]>0 && mv[m+1]>0) { accel+=(vel[m]-vel[m+1]); ac++; }
|
||||
}
|
||||
if(ac>0) accel/=ac;
|
||||
|
||||
double point = SymbolInfoDouble(_Symbol,SYMBOL_POINT);
|
||||
|
||||
if(DebugPrint) Print("Score:",score," Entry:",BuyThresh,"/",SellThresh," Accel:",DoubleToString(accel,6));
|
||||
|
||||
//--- Position check
|
||||
bool hasPos = PositionSelectByTicket(myTicket);
|
||||
if(!hasPos) myTicket = 0;
|
||||
|
||||
//--- Exit
|
||||
if(hasPos)
|
||||
{
|
||||
bool isBuy = (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY);
|
||||
bool shouldClose = false;
|
||||
if(isBuy && score >= SellThresh) shouldClose = true;
|
||||
if(!isBuy && score <= BuyThresh) shouldClose = true;
|
||||
if(!shouldClose && score>=-1 && score<=1) shouldClose = true;
|
||||
if(shouldClose)
|
||||
{
|
||||
if(DebugPrint) Print(">>> CLOSE ",isBuy?"BUY":"SELL"," score=",score);
|
||||
CTrade trade;
|
||||
trade.PositionClose(myTicket,Slippage);
|
||||
myTicket = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
//--- BUY
|
||||
if(score <= BuyThresh)
|
||||
{
|
||||
if(!UseAccel || accel > -point*10)
|
||||
{
|
||||
if(DebugPrint) Print(">>> BUY score=",score);
|
||||
double tp = close0 + TP_Points*point;
|
||||
double sl = close0 - SL_Points*point;
|
||||
if(sl<0) sl = point;
|
||||
MqlTradeRequest req={};
|
||||
MqlTradeResult res={};
|
||||
req.action = TRADE_ACTION_DEAL;
|
||||
req.symbol = _Symbol;
|
||||
req.volume = LotSize;
|
||||
req.type = ORDER_TYPE_BUY;
|
||||
req.price = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
|
||||
req.tp = tp;
|
||||
req.sl = sl;
|
||||
req.deviation = Slippage;
|
||||
req.magic = Magic;
|
||||
req.comment = "PaPP B"+IntegerToString(score);
|
||||
if(OrderSend(req,res))
|
||||
{
|
||||
if(res.retcode==TRADE_RETCODE_DONE) myTicket = res.order;
|
||||
else if(DebugPrint) Print("BUY fail: c",res.retcode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//--- SELL
|
||||
if(score >= SellThresh)
|
||||
{
|
||||
if(!UseAccel || accel < point*10)
|
||||
{
|
||||
if(DebugPrint) Print(">>> SELL score=",score);
|
||||
double tp = close0 - TP_Points*point;
|
||||
double sl = close0 + SL_Points*point;
|
||||
MqlTradeRequest req={};
|
||||
MqlTradeResult res={};
|
||||
req.action = TRADE_ACTION_DEAL;
|
||||
req.symbol = _Symbol;
|
||||
req.volume = LotSize;
|
||||
req.type = ORDER_TYPE_SELL;
|
||||
req.price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
|
||||
req.tp = tp;
|
||||
req.sl = sl;
|
||||
req.deviation = Slippage;
|
||||
req.magic = Magic;
|
||||
req.comment = "PaPP S"+IntegerToString(score);
|
||||
if(OrderSend(req,res))
|
||||
{
|
||||
if(res.retcode==TRADE_RETCODE_DONE) myTicket = res.order;
|
||||
else if(DebugPrint) Print("SELL fail: c",res.retcode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
@@ -0,0 +1,241 @@
|
||||
//+------------------------------------------------------------------+
|
||||
//| PaPP_CrossExport.mq5 |
|
||||
//| PaPP v2 |
|
||||
//| Esporta in CSV TUTTI gli incroci tra le 9 linee (prezzo+Mediana |
|
||||
//| +7 MA), calcolati ANCORATI a D1 (come l'indicatore), con il |
|
||||
//| contesto di ogni incrocio e gli esiti futuri a 1/3/5/10/20 g. |
|
||||
//| Si puo' esportare un intervallo di date oppure tutto lo storico. |
|
||||
//+------------------------------------------------------------------+
|
||||
#property copyright "PaPP v2"
|
||||
#property version "1.00"
|
||||
#property script_show_inputs
|
||||
|
||||
//--- input
|
||||
input string InpSymbol = ""; // simbolo ("" = simbolo del grafico)
|
||||
input bool InpAllHistory = true; // true = tutto lo storico D1
|
||||
input datetime InpStart = D'2010.01.01'; // inizio intervallo (se AllHistory=false)
|
||||
input datetime InpEnd = D'2100.01.01'; // fine intervallo (se AllHistory=false)
|
||||
input string InpFileName = ""; // nome file ("" = automatico)
|
||||
|
||||
//--- costanti (stesse 7 MA dell'indicatore)
|
||||
#define ANCHOR_TF PERIOD_D1
|
||||
#define NSER 9 // PRICE, MED, MA365..MA3
|
||||
#define KSLOPE 5 // barre per pendenza / variazione cluster
|
||||
#define MAXH 20 // orizzonte massimo per gli esiti
|
||||
|
||||
int gDays[7] = {365,182,121,30,14,7,3};
|
||||
string SER[NSER]= {"PRICE","MED","MA365","MA182","MA121","MA30","MA14","MA7","MA3"};
|
||||
int gHor[5] = {1,3,5,10,20};
|
||||
|
||||
//--- contenitore per un buffer MA dinamico (MQL5 non permette double ma[7][])
|
||||
struct MABuf { double v[]; };
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int TimeToBarsD1(string sym,int d)
|
||||
{
|
||||
datetime n = TimeCurrent();
|
||||
if(n==0) return MathMax(1,(int)((long)d*86400L/PeriodSeconds(ANCHOR_TF)));
|
||||
return MathMax(1,Bars(sym,ANCHOR_TF,n-(long)d*86400,n));
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// valore valido = positivo e finito (MT5 usa EMPTY_VALUE=DBL_MAX nei warmup)
|
||||
bool IsVal(double v) { return (v>0.0 && v<1.0e12); }
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
double Median7(double &v[]) // mediana dei valori validi in v[0..6]
|
||||
{
|
||||
double a[]; int c=0; ArrayResize(a,7);
|
||||
for(int m=0;m<7;m++) if(IsVal(v[m])) { a[c]=v[m]; c++; }
|
||||
if(c==0) return 0;
|
||||
ArrayResize(a,c); ArraySort(a);
|
||||
if((c&1)==1) return a[c/2];
|
||||
return 0.5*(a[c/2-1]+a[c/2]);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void OnStart()
|
||||
{
|
||||
string sym = (InpSymbol=="") ? _Symbol : InpSymbol;
|
||||
if(!SymbolSelect(sym,true)) { Print("Simbolo non valido: ",sym); return; }
|
||||
int digits = (int)SymbolInfoInteger(sym,SYMBOL_DIGITS);
|
||||
|
||||
//--- handle delle 7 MA su D1 + ATR
|
||||
int hMA[7];
|
||||
for(int m=0;m<7;m++)
|
||||
{
|
||||
int per = TimeToBarsD1(sym,gDays[m]);
|
||||
hMA[m] = iMA(sym,ANCHOR_TF,per,0,MODE_SMA,PRICE_CLOSE);
|
||||
if(hMA[m]==INVALID_HANDLE) { Print("iMA fallita m=",m); return; }
|
||||
}
|
||||
int hATR = iATR(sym,ANCHOR_TF,14);
|
||||
if(hATR==INVALID_HANDLE) { Print("iATR fallita"); return; }
|
||||
|
||||
//--- attendo che lo storico D1 sia pronto
|
||||
int total=0;
|
||||
for(int t=0; t<100; t++)
|
||||
{
|
||||
total = Bars(sym,ANCHOR_TF);
|
||||
bool ok = (total>MAXH+KSLOPE+50);
|
||||
for(int m=0;m<7 && ok;m++) if(BarsCalculated(hMA[m])<total) ok=false;
|
||||
if(ok && BarsCalculated(hATR)>=total) break;
|
||||
Sleep(100);
|
||||
}
|
||||
total = Bars(sym,ANCHOR_TF);
|
||||
if(total<=MAXH+KSLOPE+50) { Print("Storico D1 insufficiente: ",total," barre"); return; }
|
||||
|
||||
//--- carico tutta la storia D1 (indice 0 = piu' vecchio)
|
||||
datetime tm[]; double cl[],hi[],lo[],atr[];
|
||||
MABuf ma[7];
|
||||
ArraySetAsSeries(tm,false); ArraySetAsSeries(cl,false);
|
||||
ArraySetAsSeries(hi,false); ArraySetAsSeries(lo,false);
|
||||
ArraySetAsSeries(atr,false);
|
||||
if(CopyTime(sym,ANCHOR_TF,0,total,tm)<=0) { Print("CopyTime KO"); return; }
|
||||
if(CopyClose(sym,ANCHOR_TF,0,total,cl)<=0) { Print("CopyClose KO"); return; }
|
||||
if(CopyHigh(sym,ANCHOR_TF,0,total,hi)<=0) { Print("CopyHigh KO"); return; }
|
||||
if(CopyLow(sym,ANCHOR_TF,0,total,lo)<=0) { Print("CopyLow KO"); return; }
|
||||
if(CopyBuffer(hATR,0,0,total,atr)<=0) { Print("CopyATR KO"); return; }
|
||||
for(int m=0;m<7;m++)
|
||||
{
|
||||
ArraySetAsSeries(ma[m].v,false);
|
||||
if(CopyBuffer(hMA[m],0,0,total,ma[m].v)<=0) { Print("CopyBuffer MA KO m=",m); return; }
|
||||
}
|
||||
int n = ArraySize(cl);
|
||||
|
||||
//--- costruisco le 9 serie allineate per barra: S[i][k]
|
||||
double S[][NSER];
|
||||
ArrayResize(S,n);
|
||||
for(int i=0;i<n;i++)
|
||||
{
|
||||
double mv[7];
|
||||
for(int m=0;m<7;m++) mv[m] = ma[m].v[i];
|
||||
S[i][0] = cl[i]; // PRICE
|
||||
S[i][1] = Median7(mv); // MED
|
||||
for(int m=0;m<7;m++) S[i][2+m] = mv[m]; // MA365..MA3
|
||||
}
|
||||
|
||||
//--- intervallo di scansione (eventi)
|
||||
datetime from = InpAllHistory ? 0 : InpStart;
|
||||
datetime to = InpAllHistory ? TimeCurrent(): InpEnd;
|
||||
int iStart = KSLOPE+1, iEnd = n-1;
|
||||
for(int i=KSLOPE+1;i<n;i++) if(tm[i]>=from) { iStart=i; break; }
|
||||
for(int i=n-1;i>=0;i--) if(tm[i]<=to) { iEnd=i; break; }
|
||||
|
||||
//--- apro il file CSV
|
||||
string fname = (InpFileName=="") ? ("PaPP_crosses_"+sym+"_D1.csv") : InpFileName;
|
||||
int fh = FileOpen(fname,FILE_WRITE|FILE_TXT|FILE_ANSI);
|
||||
if(fh==INVALID_HANDLE) { Print("FileOpen KO: ",fname," err=",GetLastError()); return; }
|
||||
|
||||
//--- header
|
||||
string head = "time,symbol,pair,a,b,dir,price,med,ma365,ma182,ma121,ma30,ma14,ma7,ma3,"
|
||||
"dist_med_pct,cluster_pct,cluster_exp,slope_a,slope_b,trend,atr_pct,dow,month";
|
||||
for(int hh=0;hh<5;hh++)
|
||||
{
|
||||
string s=IntegerToString(gHor[hh]);
|
||||
head += ",ret_"+s+",mfe_"+s+",mae_"+s+",dir_"+s+",rev_"+s;
|
||||
}
|
||||
for(int b=1;b<=MAXH;b++) head += ",cret_"+IntegerToString(b); // traiettoria forward bar-by-bar
|
||||
head += ",bars_to_revert,disc_max_pct";
|
||||
FileWriteString(fh,head+"\r\n");
|
||||
|
||||
//--- scansione incroci
|
||||
long rows=0;
|
||||
for(int i=iStart;i<=iEnd;i++)
|
||||
{
|
||||
if(i<KSLOPE+1) continue;
|
||||
|
||||
//--- esporto solo barre con TUTTE le 9 serie valide (cluster completo)
|
||||
bool allok=true;
|
||||
for(int k=0;k<NSER && allok;k++)
|
||||
if(!IsVal(S[i][k]) || !IsVal(S[i-1][k]) || !IsVal(S[i-KSLOPE][k])) allok=false;
|
||||
if(!allok) continue;
|
||||
|
||||
double price=S[i][0], med=S[i][1], ma365=S[i][2];
|
||||
|
||||
//--- feature comuni a tutti gli incroci di questa barra
|
||||
double dist_med = (price-med)/med*100.0;
|
||||
double cmax=-1, cmin=1e18;
|
||||
for(int k=2;k<NSER;k++){ double v=S[i][k]; if(v>cmax)cmax=v; if(v<cmin)cmin=v; }
|
||||
double cluster = (cmax-cmin)/price*100.0;
|
||||
double cmaxP=-1,cminP=1e18;
|
||||
for(int k=2;k<NSER;k++){ double v=S[i-KSLOPE][k]; if(v>cmaxP)cmaxP=v; if(v<cminP)cminP=v; }
|
||||
double clusterP = (cmaxP-cminP)/S[i-KSLOPE][0]*100.0;
|
||||
double cluster_exp = cluster-clusterP;
|
||||
int trend = (price>ma365)?1:-1;
|
||||
double atr_pct = atr[i]/price*100.0;
|
||||
MqlDateTime dt; TimeToStruct(tm[i],dt);
|
||||
|
||||
//--- esito globale: ritorno alla Mediana entro MAXH
|
||||
int side = (price>med)?1:-1;
|
||||
int b2rev=-1; double discMax=0;
|
||||
int jmax = MathMin(i+MAXH,n-1);
|
||||
for(int j=i+1;j<=jmax;j++)
|
||||
{
|
||||
if(!IsVal(S[j][0]) || !IsVal(S[j][1])) continue;
|
||||
int sj=(S[j][0]>S[j][1])?1:-1;
|
||||
if(b2rev<0 && sj!=side) b2rev=j-i;
|
||||
double d=(S[j][0]-S[j][1])/S[j][1]*100.0;
|
||||
if(MathAbs(d)>MathAbs(discMax)) discMax=d;
|
||||
}
|
||||
|
||||
//--- controllo ogni coppia (a,b)
|
||||
for(int a=0;a<NSER;a++)
|
||||
for(int b=a+1;b<NSER;b++)
|
||||
{
|
||||
double d0=S[i-1][a]-S[i-1][b];
|
||||
double d1=S[i][a]-S[i][b];
|
||||
int dir=0;
|
||||
if(d0<=0 && d1>0) dir=1; else if(d0>=0 && d1<0) dir=-1;
|
||||
if(dir==0) continue;
|
||||
|
||||
double slope_a = (S[i][a]-S[i-KSLOPE][a])/S[i-KSLOPE][a]*100.0;
|
||||
double slope_b = (S[i][b]-S[i-KSLOPE][b])/S[i-KSLOPE][b]*100.0;
|
||||
double thr = 0.25*atr_pct;
|
||||
|
||||
string row = StringFormat("%s,%s,%sx%s,%s,%s,%d,",
|
||||
TimeToString(tm[i],TIME_DATE),sym,SER[a],SER[b],SER[a],SER[b],dir);
|
||||
row += DoubleToString(price,digits)+","+DoubleToString(med,digits)+",";
|
||||
for(int k=2;k<NSER;k++) row += DoubleToString(S[i][k],digits)+",";
|
||||
row += DoubleToString(dist_med,5)+","+DoubleToString(cluster,5)+","
|
||||
+DoubleToString(cluster_exp,5)+","+DoubleToString(slope_a,5)+","
|
||||
+DoubleToString(slope_b,5)+","+IntegerToString(trend)+","
|
||||
+DoubleToString(atr_pct,5)+","+IntegerToString(dt.day_of_week)+","
|
||||
+IntegerToString(dt.mon);
|
||||
|
||||
//--- esiti per orizzonte
|
||||
for(int hh=0;hh<5;hh++)
|
||||
{
|
||||
int h=gHor[hh], iH=i+h;
|
||||
if(iH>n-1 || S[i][0]<=0) { row += ",,,,,"; continue; }
|
||||
double ret=(cl[iH]-cl[i])/cl[i]*100.0;
|
||||
double mxh=-1e18,mnl=1e18;
|
||||
for(int j=i+1;j<=iH;j++){ if(hi[j]>mxh)mxh=hi[j]; if(lo[j]<mnl)mnl=lo[j]; }
|
||||
double mfe=(mxh-cl[i])/cl[i]*100.0;
|
||||
double mae=(mnl-cl[i])/cl[i]*100.0;
|
||||
int dlab=(ret>thr)?1:((ret<-thr)?-1:0);
|
||||
int rev=(b2rev>0 && b2rev<=h)?1:0;
|
||||
row += ","+DoubleToString(ret,5)+","+DoubleToString(mfe,5)+","
|
||||
+DoubleToString(mae,5)+","+IntegerToString(dlab)+","+IntegerToString(rev);
|
||||
}
|
||||
//--- traiettoria: rendimento cumulato a +1..+MAXH barre
|
||||
for(int b=1;b<=MAXH;b++)
|
||||
{
|
||||
int iB=i+b;
|
||||
if(iB>n-1) { row += ","; continue; }
|
||||
row += ","+DoubleToString((cl[iB]-cl[i])/cl[i]*100.0,5);
|
||||
}
|
||||
row += ","+(b2rev>0?IntegerToString(b2rev):"")+","+DoubleToString(discMax,5);
|
||||
FileWriteString(fh,row+"\r\n");
|
||||
rows++;
|
||||
}
|
||||
if((i%200)==0) Comment(StringFormat("PaPP export: %d/%d barre, %d eventi",i-iStart,iEnd-iStart,(int)rows));
|
||||
}
|
||||
|
||||
FileClose(fh);
|
||||
for(int m=0;m<7;m++) IndicatorRelease(hMA[m]);
|
||||
IndicatorRelease(hATR);
|
||||
Comment("");
|
||||
PrintFormat("PaPP export COMPLETATO: %d incroci -> %s (cartella MQL5\\Files)",(int)rows,fname);
|
||||
Print("Periodo: ",TimeToString(tm[iStart])," -> ",TimeToString(tm[iEnd]));
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
@@ -0,0 +1,585 @@
|
||||
//+------------------------------------------------------------------+
|
||||
//| PaPP_Median.mq5 |
|
||||
//| PaPP v2 |
|
||||
//+------------------------------------------------------------------+
|
||||
#property copyright "PaPP v2"
|
||||
#property version "2.00"
|
||||
#property description "PaPP Median - Mediana 7 MA (3g-1y)"
|
||||
#property description "Calcolo ancorato a D1 = linea uguale su ogni timeframe"
|
||||
#property indicator_chart_window
|
||||
#property indicator_buffers 8
|
||||
#property indicator_plots 8
|
||||
|
||||
input int FontSize = 9;
|
||||
input bool Smooth = true; // interpola tra i valori D1 -> linea morbida
|
||||
input bool ShowMA = true; // mostra anche le 7 MA (oltre alla mediana)
|
||||
input bool ShowPanel = true; // box con sfondo dietro al pannello info
|
||||
input color PanelBg = C'20,20,25'; // colore sfondo del box
|
||||
|
||||
#define ANCHOR_TF PERIOD_D1 // calcolo ancorato a D1: linea identica su ogni TF
|
||||
#define KSLOPE 5 // barre D1 per velocita'/accelerazione
|
||||
#define NVOL 14 // barre D1 per la volatilita'
|
||||
#define CLWIN 252 // finestra D1 (~1 anno) per il percentile del cluster
|
||||
|
||||
double Buff_Median[];
|
||||
double B0[],B1[],B2[],B3[],B4[],B5[],B6[];
|
||||
|
||||
int gDays[7] = {365,182,121,30,14,7,3};
|
||||
color gCol[7] = {clrDodgerBlue,clrDeepSkyBlue,clrTurquoise,clrLimeGreen,clrOrange,clrTomato,clrRed};
|
||||
int hMA[7];
|
||||
int bars[7];
|
||||
struct PBuf { double v[]; }; // buffer dinamico per copiare una MA
|
||||
string _pfx = "PM_"; // oggetti pannello
|
||||
string _pfx2 = "PME_"; // etichette a fine linea
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// scrive il valore nel buffer della MA m
|
||||
void SetBuf(int m,int idx,double v)
|
||||
{
|
||||
switch(m)
|
||||
{
|
||||
case 0: B0[idx]=v; break;
|
||||
case 1: B1[idx]=v; break;
|
||||
case 2: B2[idx]=v; break;
|
||||
case 3: B3[idx]=v; break;
|
||||
case 4: B4[idx]=v; break;
|
||||
case 5: B5[idx]=v; break;
|
||||
case 6: B6[idx]=v; break;
|
||||
}
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// legge il valore corrente (barra 0) del buffer della MA m
|
||||
double GetBuf(int m)
|
||||
{
|
||||
switch(m)
|
||||
{
|
||||
case 0: return B0[0];
|
||||
case 1: return B1[0];
|
||||
case 2: return B2[0];
|
||||
case 3: return B3[0];
|
||||
case 4: return B4[0];
|
||||
case 5: return B5[0];
|
||||
case 6: return B6[0];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int TimeToBars(int d)
|
||||
{
|
||||
datetime n = TimeCurrent();
|
||||
if(n==0)
|
||||
{
|
||||
long s = (long)d*86400L, p = PeriodSeconds(ANCHOR_TF);
|
||||
return (int)MathMax(1,s/p);
|
||||
}
|
||||
return MathMax(1,Bars(_Symbol,ANCHOR_TF,n-d*86400,n));
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int OnInit()
|
||||
{
|
||||
for(int i=0;i<7;i++)
|
||||
{
|
||||
bars[i] = TimeToBars(gDays[i]);
|
||||
hMA[i] = iMA(_Symbol,ANCHOR_TF,bars[i],0,MODE_SMA,PRICE_CLOSE);
|
||||
if(hMA[i]==INVALID_HANDLE) return INIT_FAILED;
|
||||
}
|
||||
|
||||
SetIndexBuffer(0,Buff_Median,INDICATOR_DATA);
|
||||
SetIndexBuffer(1,B0,INDICATOR_DATA);
|
||||
SetIndexBuffer(2,B1,INDICATOR_DATA);
|
||||
SetIndexBuffer(3,B2,INDICATOR_DATA);
|
||||
SetIndexBuffer(4,B3,INDICATOR_DATA);
|
||||
SetIndexBuffer(5,B4,INDICATOR_DATA);
|
||||
SetIndexBuffer(6,B5,INDICATOR_DATA);
|
||||
SetIndexBuffer(7,B6,INDICATOR_DATA);
|
||||
ArraySetAsSeries(Buff_Median,true);
|
||||
ArraySetAsSeries(B0,true); ArraySetAsSeries(B1,true);
|
||||
ArraySetAsSeries(B2,true); ArraySetAsSeries(B3,true);
|
||||
ArraySetAsSeries(B4,true); ArraySetAsSeries(B5,true);
|
||||
ArraySetAsSeries(B6,true);
|
||||
|
||||
//--- plot 0 = mediana (linea principale)
|
||||
PlotIndexSetInteger(0,PLOT_DRAW_TYPE,DRAW_LINE);
|
||||
PlotIndexSetInteger(0,PLOT_LINE_COLOR,clrGold);
|
||||
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,2);
|
||||
PlotIndexSetString(0,PLOT_LABEL,"PaPP Median");
|
||||
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);
|
||||
|
||||
//--- plot 1..7 = le 7 MA
|
||||
for(int p=0;p<7;p++)
|
||||
{
|
||||
PlotIndexSetInteger(p+1,PLOT_DRAW_TYPE,ShowMA?DRAW_LINE:DRAW_NONE);
|
||||
PlotIndexSetInteger(p+1,PLOT_LINE_COLOR,gCol[p]);
|
||||
PlotIndexSetInteger(p+1,PLOT_LINE_WIDTH,1);
|
||||
PlotIndexSetString(p+1,PLOT_LABEL,"MA "+IntegerToString(gDays[p])+"g");
|
||||
PlotIndexSetDouble(p+1,PLOT_EMPTY_VALUE,0.0);
|
||||
}
|
||||
|
||||
IndicatorSetString(INDICATOR_SHORTNAME,"PaPP Median");
|
||||
return INIT_SUCCEEDED;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void OnDeinit(const int reason)
|
||||
{
|
||||
for(int i=0;i<7;i++) if(hMA[i]!=INVALID_HANDLE) IndicatorRelease(hMA[i]);
|
||||
ObjectsDeleteAll(0,_pfx);
|
||||
ObjectsDeleteAll(0,_pfx2);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// d1shift = indice (serie) della barra D1 da cui leggere la SMA
|
||||
double GetMA(int m,int d1shift)
|
||||
{
|
||||
if(d1shift<0) return 0;
|
||||
double buf[1];
|
||||
if(CopyBuffer(hMA[m],0,d1shift,1,buf)==1) return buf[0];
|
||||
return 0;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
double Median(double &a[],int n)
|
||||
{
|
||||
if(n<=0) return 0;
|
||||
ArraySort(a);
|
||||
if((n&1)==1) return a[n/2];
|
||||
return 0.5*(a[n/2-1]+a[n/2]);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// Mediana delle 7 MA su una specifica barra D1
|
||||
double MedianAtD1(int d1shift)
|
||||
{
|
||||
if(d1shift<0) return 0;
|
||||
double vals[]; int cnt=0; ArrayResize(vals,7);
|
||||
for(int m=0;m<7;m++) { double v=GetMA(m,d1shift); if(v>0) { vals[cnt]=v; cnt++; } }
|
||||
ArrayResize(vals,cnt);
|
||||
return Median(vals,cnt);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// valore valido = positivo e finito (esclude EMPTY_VALUE di warmup)
|
||||
bool IsVal(double v) { return (v>0.0 && v<1.0e12); }
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// mediana dei primi c valori di src
|
||||
double MedArr(double &src[],int c)
|
||||
{
|
||||
if(c<=0) return 0;
|
||||
double a[]; ArrayResize(a,c);
|
||||
for(int j=0;j<c;j++) a[j]=src[j];
|
||||
ArraySort(a);
|
||||
if((c&1)==1) return a[c/2];
|
||||
return 0.5*(a[c/2-1]+a[c/2]);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// Metriche a una specifica barra D1 (j), calcolate sui buffer gia' copiati mb[7]
|
||||
double ClusterAtJ(PBuf &mb[],int j)
|
||||
{
|
||||
double v[7]; int c=0;
|
||||
for(int m=0;m<7;m++){ double x=mb[m].v[j]; if(IsVal(x)) v[c++]=x; }
|
||||
if(c<2) return 0;
|
||||
double md=MedArr(v,c); if(md<=0) return 0;
|
||||
double ds=0; for(int m=0;m<c;m++) ds+=MathAbs(v[m]-md)/md*100.0;
|
||||
return ds/c;
|
||||
}
|
||||
double VelAtJ(PBuf &mb[],int j,int K)
|
||||
{
|
||||
double v[7]; int c=0;
|
||||
for(int m=0;m<7;m++){ double a=mb[m].v[j], b=mb[m].v[j+K]; if(IsVal(a)&&IsVal(b)) v[c++]=(a-b)/b*100.0; }
|
||||
return MedArr(v,c);
|
||||
}
|
||||
double AccAtJ(PBuf &mb[],int j,int K)
|
||||
{
|
||||
double v[7]; int c=0;
|
||||
for(int m=0;m<7;m++){ double a=mb[m].v[j], b=mb[m].v[j+K], d=mb[m].v[j+2*K];
|
||||
if(IsVal(a)&&IsVal(b)&&IsVal(d)) v[c++]=(a-2.0*b+d)/d*100.0; }
|
||||
return MedArr(v,c);
|
||||
}
|
||||
double VolAtJ(PBuf &mb[],int j,int N)
|
||||
{
|
||||
double v[7]; int c=0;
|
||||
for(int m=0;m<7;m++)
|
||||
{
|
||||
double r[]; int rc=0; ArrayResize(r,N);
|
||||
for(int t=j;t<j+N;t++){ double a=mb[m].v[t], b=mb[m].v[t+1]; if(IsVal(a)&&IsVal(b)) r[rc++]=(a-b)/b*100.0; }
|
||||
if(rc>=2)
|
||||
{
|
||||
double mn=0; for(int q=0;q<rc;q++) mn+=r[q]; mn/=rc;
|
||||
double s=0; for(int q=0;q<rc;q++){ double dd=r[q]-mn; s+=dd*dd; }
|
||||
v[c++]=MathSqrt(s/(rc-1));
|
||||
}
|
||||
}
|
||||
return MedArr(v,c);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// percentile (0..1) di cur fra i primi cc valori di arr
|
||||
double PctlOf(double &arr[],int cc,double cur)
|
||||
{
|
||||
if(cc<=0) return 0.5;
|
||||
int b=0; for(int k=0;k<cc;k++) if(arr[k]<=cur) b++;
|
||||
return (double)b/cc;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// Valori correnti + percentile storico (win giorni D1) di cluster/velocita'/accel/volatilita'
|
||||
// per i segnali con segno (vel/acc) il percentile e' calcolato sul VALORE ASSOLUTO (forza)
|
||||
void AllMetrics(int win,
|
||||
double &cluCur,double &cluPct,
|
||||
double &velCur,double &velPct,
|
||||
double &accCur,double &accPct,
|
||||
double &volCur,double &volPct)
|
||||
{
|
||||
cluCur=velCur=accCur=volCur=0; cluPct=volPct=0.5; velPct=accPct=0;
|
||||
int ext = MathMax(2*KSLOPE,NVOL+1);
|
||||
int need = win+ext+2;
|
||||
PBuf mb[7];
|
||||
for(int m=0;m<7;m++)
|
||||
{
|
||||
ArraySetAsSeries(mb[m].v,true);
|
||||
if(CopyBuffer(hMA[m],0,0,need,mb[m].v)!=need) return;
|
||||
}
|
||||
double cA[],vA[],aA[],oA[]; int cc=0,vc=0,ac=0,oc=0;
|
||||
ArrayResize(cA,win); ArrayResize(vA,win); ArrayResize(aA,win); ArrayResize(oA,win);
|
||||
for(int j=1;j<=win;j++)
|
||||
{
|
||||
double cv=ClusterAtJ(mb,j); if(cv>0) cA[cc++]=cv;
|
||||
vA[vc++]=MathAbs(VelAtJ(mb,j,KSLOPE));
|
||||
aA[ac++]=MathAbs(AccAtJ(mb,j,KSLOPE));
|
||||
double ov=VolAtJ(mb,j,NVOL); if(ov>0) oA[oc++]=ov;
|
||||
}
|
||||
cluCur=ClusterAtJ(mb,1); velCur=VelAtJ(mb,1,KSLOPE);
|
||||
accCur=AccAtJ(mb,1,KSLOPE); volCur=VolAtJ(mb,1,NVOL);
|
||||
cluPct=PctlOf(cA,cc,cluCur);
|
||||
volPct=PctlOf(oA,oc,volCur);
|
||||
velPct=PctlOf(vA,vc,MathAbs(velCur)); // forza (su |valore|)
|
||||
accPct=PctlOf(aA,ac,MathAbs(accCur));
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// descrizione a parole per una grandezza di sola ampiezza (cluster, volatilita')
|
||||
string MagWord(double pct,string w0,string w1,string w2,string w3,string w4)
|
||||
{
|
||||
if(pct<0.20) return w0;
|
||||
if(pct<0.40) return w1;
|
||||
if(pct<0.60) return w2;
|
||||
if(pct<0.80) return w3;
|
||||
return w4;
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
// descrizione a parole per un segnale con segno (velocita', accelerazione)
|
||||
string DirWord(double val,double absPct,string up,string down,string flat)
|
||||
{
|
||||
if(absPct<0.15) return flat;
|
||||
string forza = (absPct<0.40)?"lieve":((absPct<0.70)?"moderata":"forte");
|
||||
return (val>0?up:down)+" "+forza;
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
// descrizione a parole per la distanza prezzo-mediana (con segno)
|
||||
string DistWord(double val,double absPct)
|
||||
{
|
||||
if(absPct<0.15) return "sulla mediana";
|
||||
string q = (absPct<0.40)?"poco":((absPct<0.70)?"moderatamente":"molto");
|
||||
return q+(val>0?" sopra":" sotto");
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
// mediana delle 7 MA a barra j dai buffer mb
|
||||
double MedMAatJ(PBuf &mb[],int j)
|
||||
{
|
||||
double v[7]; int c=0;
|
||||
for(int m=0;m<7;m++){ double x=mb[m].v[j]; if(IsVal(x)) v[c++]=x; }
|
||||
return MedArr(v,c);
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
// distanza prezzo-mediana: percentile storico (su |valore|) sugli ultimi 'win' giorni D1
|
||||
void DistStats(int win,double curDist,double &absPct)
|
||||
{
|
||||
absPct=0.5;
|
||||
int need=win+2;
|
||||
double cl[]; ArraySetAsSeries(cl,true);
|
||||
if(CopyClose(_Symbol,ANCHOR_TF,0,need,cl)!=need) return;
|
||||
PBuf mb[7];
|
||||
for(int m=0;m<7;m++){ ArraySetAsSeries(mb[m].v,true); if(CopyBuffer(hMA[m],0,0,need,mb[m].v)!=need) return; }
|
||||
double dA[]; int dc=0; ArrayResize(dA,win);
|
||||
for(int j=1;j<=win;j++)
|
||||
{
|
||||
double md=MedMAatJ(mb,j); if(md<=0) continue;
|
||||
dA[dc++]=MathAbs((cl[j]-md)/md*100.0);
|
||||
}
|
||||
absPct=PctlOf(dA,dc,MathAbs(curDist));
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// interpolazione lineare con fallback se uno dei valori manca
|
||||
double Interp(double vStart,double vEnd,double frac)
|
||||
{
|
||||
if(vStart>0 && vEnd>0) return vStart+frac*(vEnd-vStart);
|
||||
if(vEnd>0) return vEnd;
|
||||
return vStart;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// Mediana dei primi n valori di src
|
||||
double MedianN(const double &src[],int n)
|
||||
{
|
||||
if(n<=0) return 0;
|
||||
double a[]; ArrayResize(a,n);
|
||||
for(int i=0;i<n;i++) a[i]=src[i];
|
||||
ArraySort(a);
|
||||
if((n&1)==1) return a[n/2];
|
||||
return 0.5*(a[n/2-1]+a[n/2]);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int OnCalculate(const int rates_total,
|
||||
const int prev_calculated,
|
||||
const datetime &time[],
|
||||
const double &open[],
|
||||
const double &high[],
|
||||
const double &low[],
|
||||
const double &close[],
|
||||
const long &tick_volume[],
|
||||
const long &volume[],
|
||||
const int &spread[])
|
||||
{
|
||||
if(rates_total<2) return 0;
|
||||
ArraySetAsSeries(close,true);
|
||||
ArraySetAsSeries(time,true);
|
||||
|
||||
//--- i dati D1 devono essere pronti, altrimenti ritenta al prossimo tick
|
||||
int d1bars = Bars(_Symbol,ANCHOR_TF);
|
||||
if(d1bars<2) return 0;
|
||||
if(BarsCalculated(hMA[0])<=0) return 0;
|
||||
|
||||
//--- carica le 7 MA D1 in blocco e calcola la mediana per ogni barra D1
|
||||
double med_d1[]; ArrayResize(med_d1,d1bars); ArraySetAsSeries(med_d1,true);
|
||||
double cols[][7]; ArrayResize(cols,d1bars);
|
||||
for(int m=0;m<7;m++)
|
||||
{
|
||||
double tmp[]; ArraySetAsSeries(tmp,true);
|
||||
int got = CopyBuffer(hMA[m],0,0,d1bars,tmp);
|
||||
if(got<=0) return 0; // non pronto: ritenta
|
||||
for(int s=0;s<d1bars;s++) cols[s][m] = (s<got) ? tmp[s] : 0.0;
|
||||
}
|
||||
for(int s=0;s<d1bars;s++)
|
||||
{
|
||||
double vv[7]; int c=0;
|
||||
for(int m=0;m<7;m++) if(cols[s][m]>0) { vv[c]=cols[s][m]; c++; }
|
||||
med_d1[s] = MedianN(vv,c);
|
||||
}
|
||||
|
||||
//--- range di barre grafico da (ri)calcolare:
|
||||
// tutto al primo load o quando nasce una nuova barra D1, altrimenti solo oggi
|
||||
static int s_lastD1 = -1;
|
||||
int recalcFrom;
|
||||
if(prev_calculated==0 || d1bars!=s_lastD1)
|
||||
recalcFrom = rates_total-1;
|
||||
else
|
||||
{
|
||||
datetime todayOpen = iTime(_Symbol,ANCHOR_TF,0);
|
||||
recalcFrom = 0;
|
||||
while(recalcFrom < rates_total-1 && time[recalcFrom] >= todayOpen) recalcFrom++;
|
||||
}
|
||||
s_lastD1 = d1bars;
|
||||
|
||||
for(int idx=recalcFrom; idx>=0; idx--)
|
||||
{
|
||||
int d1cur = iBarShift(_Symbol,ANCHOR_TF,time[idx],false);
|
||||
if(d1cur<0 || d1cur>=d1bars)
|
||||
{
|
||||
Buff_Median[idx]=0;
|
||||
for(int m=0;m<7;m++) SetBuf(m,idx,0.0);
|
||||
continue;
|
||||
}
|
||||
|
||||
int sj=d1cur+1; // barra D1 precedente (inizio giornata)
|
||||
|
||||
//--- frazione di giornata trascorsa (solo se Smooth)
|
||||
double frac=0.0;
|
||||
if(Smooth)
|
||||
{
|
||||
datetime t0 = iTime(_Symbol,ANCHOR_TF,d1cur);
|
||||
datetime t1 = (d1cur>0) ? iTime(_Symbol,ANCHOR_TF,d1cur-1)
|
||||
: t0 + PeriodSeconds(ANCHOR_TF);
|
||||
frac = (t1>t0) ? (double)(time[idx]-t0)/(double)(t1-t0) : 0.0;
|
||||
frac = MathMax(0.0,MathMin(1.0,frac));
|
||||
}
|
||||
|
||||
//--- mediana
|
||||
if(!Smooth)
|
||||
Buff_Median[idx] = (sj<d1bars) ? med_d1[sj] : 0.0;
|
||||
else
|
||||
{
|
||||
double vS = (sj<d1bars) ? med_d1[sj] : 0.0;
|
||||
Buff_Median[idx] = Interp(vS,med_d1[d1cur],frac);
|
||||
}
|
||||
|
||||
//--- le 7 MA
|
||||
for(int m=0;m<7;m++)
|
||||
{
|
||||
double val;
|
||||
if(!Smooth)
|
||||
val = (sj<d1bars) ? cols[sj][m] : 0.0;
|
||||
else
|
||||
{
|
||||
double vS2 = (sj<d1bars) ? cols[sj][m] : 0.0;
|
||||
val = Interp(vS2,cols[d1cur][m],frac);
|
||||
}
|
||||
SetBuf(m,idx,val);
|
||||
}
|
||||
}
|
||||
|
||||
DrawInfo();
|
||||
DrawTags(time[0]);
|
||||
return rates_total;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// larghezza in pixel di un testo nel font del pannello
|
||||
int TxtW(string s,int fs,bool bold)
|
||||
{
|
||||
TextSetFont(bold?"Consolas Bold":"Consolas",-fs*10);
|
||||
uint w=0,h=0;
|
||||
bool ok=TextGetSize(s,w,h);
|
||||
int est=(int)MathCeil(StringLen(s)*fs*0.62); // fallback se TextGetSize non disponibile
|
||||
if(!ok || (int)w<=0) return est;
|
||||
return MathMax((int)w,est); // mai meno della stima
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
void DrawInfo()
|
||||
{
|
||||
double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
|
||||
double median = MedianAtD1(1); // valore D1 chiuso (stabile, non-repaint)
|
||||
if(median<=0) return;
|
||||
|
||||
int x=10,y0=30,lh=FontSize+4;
|
||||
|
||||
//--- 1) calcolo metriche e preparo tutte le stringhe
|
||||
double distPct = (bid-median)/median*100;
|
||||
color distC = (distPct>0)?clrRed:clrLimeGreen;
|
||||
double distAbsPct; DistStats(CLWIN,distPct,distAbsPct);
|
||||
|
||||
double cluCur,cluPct,velCur,velPct,accCur,accPct,volCur,volPct;
|
||||
AllMetrics(CLWIN,cluCur,cluPct,velCur,velPct,accCur,accPct,volCur,volPct);
|
||||
|
||||
string sT = "PaPP Median ["+StringSubstr(EnumToString((ENUM_TIMEFRAMES)_Period),7)+"]";
|
||||
string sM = "Median: "+DoubleToString(median,_Digits);
|
||||
string sD = StringFormat("Dist: %+.2f%% - %s (P%.0f)",distPct,DistWord(distPct,distAbsPct),distAbsPct*100);
|
||||
string sV = StringFormat("Cluster %.3f%% - %s (P%.0f)",cluCur,MagWord(cluPct,"molto stretto","stretto","normale","largo","molto largo"),cluPct*100);
|
||||
string sVE = StringFormat("Velocita' %+.3f%% - %s",velCur,DirWord(velCur,velPct,"in salita","in discesa","quasi piatta"));
|
||||
string sAC = StringFormat("Accel %+.4f%% - %s",accCur,DirWord(accCur,accPct,"in accelerazione","in decelerazione","stabile"));
|
||||
string sVO = StringFormat("Volatilita' %.4f%% - %s (P%.0f)",volCur,MagWord(volPct,"molto bassa","bassa","normale","alta","molto alta"),volPct*100);
|
||||
string sMA[7];
|
||||
for(int m=0;m<7;m++) sMA[m]=StringFormat("MA %3dg: %s",gDays[m],DoubleToString(GetMA(m,1),_Digits));
|
||||
string sH = "Sopra=SELL | Sotto=BUY";
|
||||
|
||||
//--- 2) larghezza/altezza del box: misuro la larghezza REALE in pixel (TextGetSize)
|
||||
int maxw=0;
|
||||
maxw=MathMax(maxw,TxtW(sT,FontSize+2,true));
|
||||
maxw=MathMax(maxw,TxtW(sM,FontSize,false));
|
||||
maxw=MathMax(maxw,TxtW(sD,FontSize,true));
|
||||
maxw=MathMax(maxw,TxtW(sV,FontSize,false));
|
||||
maxw=MathMax(maxw,TxtW(sVE,FontSize,false));
|
||||
maxw=MathMax(maxw,TxtW(sAC,FontSize,false));
|
||||
maxw=MathMax(maxw,TxtW(sVO,FontSize,false));
|
||||
maxw=MathMax(maxw,TxtW(sH,FontSize-1,false));
|
||||
for(int m=0;m<7;m++) maxw=MathMax(maxw,TxtW(sMA[m],FontSize-1,false));
|
||||
int boxX=x-6, boxY=y0-6;
|
||||
int w=maxw+(x-boxX)+10; // padding sinistro (x-boxX) + destro 10
|
||||
int bodyH=15*lh+6; // 7 righe in alto + 7 MA + riga finale + padding
|
||||
PanelBox(boxX,boxY,w,bodyH);
|
||||
|
||||
//--- 3) scritte (aggiornate in-place: niente ObjectsDeleteAll -> niente lampeggio)
|
||||
int y=y0;
|
||||
Lbl("T",sT,x,y,FontSize+2,clrGold,true); y+=lh+4;
|
||||
Lbl("M",sM,x,y,FontSize,clrGold,false); y+=lh;
|
||||
Lbl("D",sD,x,y,FontSize,distC,true); y+=lh+2;
|
||||
Lbl("V",sV,x,y,FontSize,(cluPct<0.40)?clrLimeGreen:((cluPct>0.60)?clrTomato:clrSilver),false); y+=lh;
|
||||
Lbl("VEL",sVE,x,y,FontSize,(velCur>0)?clrLimeGreen:clrTomato,false); y+=lh;
|
||||
Lbl("ACC",sAC,x,y,FontSize,(accCur>0)?clrLimeGreen:clrTomato,false); y+=lh;
|
||||
Lbl("VOL",sVO,x,y,FontSize,(volPct<0.40)?clrLimeGreen:((volPct>0.60)?clrTomato:clrAqua),false); y+=lh+2;
|
||||
for(int m=0;m<7;m++)
|
||||
{
|
||||
double v=GetMA(m,1);
|
||||
Lbl("a"+IntegerToString(m),sMA[m],x,y,FontSize-1,(v>0)?gCol[m]:clrGray,false);
|
||||
y+=lh-2;
|
||||
}
|
||||
y+=2;
|
||||
Lbl("H",sH,x,y,FontSize-1,clrGray,false);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// etichetta di testo ancorata a (t,price); se price<=0 la rimuove
|
||||
void Tag(string n,datetime t,double price,string txt,color c)
|
||||
{
|
||||
string o=_pfx2+n;
|
||||
if(price<=0) { ObjectDelete(0,o); return; }
|
||||
if(ObjectFind(0,o)<0) ObjectCreate(0,o,OBJ_TEXT,0,0,0);
|
||||
ObjectSetInteger(0,o,OBJPROP_TIME,t);
|
||||
ObjectSetDouble(0,o,OBJPROP_PRICE,price);
|
||||
ObjectSetString(0,o,OBJPROP_TEXT," "+txt);
|
||||
ObjectSetString(0,o,OBJPROP_FONT,"Consolas");
|
||||
ObjectSetInteger(0,o,OBJPROP_FONTSIZE,FontSize);
|
||||
ObjectSetInteger(0,o,OBJPROP_COLOR,c);
|
||||
ObjectSetInteger(0,o,OBJPROP_ANCHOR,ANCHOR_LEFT);
|
||||
ObjectSetInteger(0,o,OBJPROP_BACK,false);
|
||||
ObjectSetInteger(0,o,OBJPROP_SELECTABLE,false);
|
||||
ObjectSetInteger(0,o,OBJPROP_HIDDEN,true);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// etichette a fine linea, nel margine vuoto a destra
|
||||
void DrawTags(datetime tlast)
|
||||
{
|
||||
datetime tfut = tlast + 2*PeriodSeconds(_Period);
|
||||
Tag("med",tfut,Buff_Median[0],"Mediana",clrGold);
|
||||
for(int m=0;m<7;m++)
|
||||
{
|
||||
double p = ShowMA ? GetBuf(m) : 0.0;
|
||||
Tag(IntegerToString(m),tfut,p,IntegerToString(gDays[m])+"g",gCol[m]);
|
||||
}
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void Lbl(string n,string t,int x,int y,int fs,color c,bool b)
|
||||
{
|
||||
string o=_pfx+n;
|
||||
if(ObjectFind(0,o)<0) ObjectCreate(0,o,OBJ_LABEL,0,0,0);
|
||||
ObjectSetInteger(0,o,OBJPROP_XDISTANCE,x);
|
||||
ObjectSetInteger(0,o,OBJPROP_YDISTANCE,y);
|
||||
ObjectSetInteger(0,o,OBJPROP_CORNER,CORNER_LEFT_UPPER);
|
||||
ObjectSetString(0,o,OBJPROP_TEXT,t);
|
||||
ObjectSetString(0,o,OBJPROP_FONT,b?"Consolas Bold":"Consolas");
|
||||
ObjectSetInteger(0,o,OBJPROP_FONTSIZE,fs);
|
||||
ObjectSetInteger(0,o,OBJPROP_COLOR,c);
|
||||
ObjectSetInteger(0,o,OBJPROP_BACK,false);
|
||||
ObjectSetInteger(0,o,OBJPROP_ZORDER,1); // sopra il box di sfondo
|
||||
ObjectSetInteger(0,o,OBJPROP_SELECTABLE,false);
|
||||
ObjectSetInteger(0,o,OBJPROP_HIDDEN,true);
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
// riquadro di sfondo del pannello (dietro alle scritte)
|
||||
void PanelBox(int px,int py,int w,int h)
|
||||
{
|
||||
string o=_pfx+"BOX";
|
||||
if(!ShowPanel) { ObjectDelete(0,o); return; }
|
||||
if(ObjectFind(0,o)<0) ObjectCreate(0,o,OBJ_RECTANGLE_LABEL,0,0,0);
|
||||
ObjectSetInteger(0,o,OBJPROP_CORNER,CORNER_LEFT_UPPER);
|
||||
ObjectSetInteger(0,o,OBJPROP_XDISTANCE,px);
|
||||
ObjectSetInteger(0,o,OBJPROP_YDISTANCE,py);
|
||||
ObjectSetInteger(0,o,OBJPROP_XSIZE,w);
|
||||
ObjectSetInteger(0,o,OBJPROP_YSIZE,h);
|
||||
ObjectSetInteger(0,o,OBJPROP_BGCOLOR,PanelBg);
|
||||
ObjectSetInteger(0,o,OBJPROP_BORDER_TYPE,BORDER_FLAT);
|
||||
ObjectSetInteger(0,o,OBJPROP_COLOR,clrDimGray); // bordo
|
||||
ObjectSetInteger(0,o,OBJPROP_BACK,false);
|
||||
ObjectSetInteger(0,o,OBJPROP_ZORDER,0); // dietro alle scritte
|
||||
ObjectSetInteger(0,o,OBJPROP_SELECTABLE,false);
|
||||
ObjectSetInteger(0,o,OBJPROP_HIDDEN,true);
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
@@ -0,0 +1,284 @@
|
||||
//+------------------------------------------------------------------+
|
||||
//| PaPP_Median_EA.mq5 |
|
||||
//| PaPP v2 |
|
||||
//+------------------------------------------------------------------+
|
||||
#include <Trade/Trade.mqh>
|
||||
//+------------------------------------------------------------------+
|
||||
#property copyright "PaPP v2"
|
||||
#property version "2.00"
|
||||
#property description "PaPP Median EA - Mean Reversion puro"
|
||||
#property description "Linea mediana (mediana 7 MA 3g-1y) = unico segnale"
|
||||
#property description "Sopra = SELL | Sotto = BUY"
|
||||
|
||||
input double LotSize = 0.01;
|
||||
input int TrailStart = 0;
|
||||
input int TrailStep = 0;
|
||||
input int MaxPosPerSide = 3;
|
||||
input bool DebugPrint = true;
|
||||
input int Magic = 2024002;
|
||||
input int Slippage = 30;
|
||||
|
||||
#define ANCHOR_TF PERIOD_D1 // calcolo ancorato a D1: stessa fair value su ogni TF
|
||||
|
||||
int hMA[7];
|
||||
int bars[7];
|
||||
datetime lastBar = 0;
|
||||
bool buyFired = false;
|
||||
bool sellFired = false;
|
||||
CTrade trade;
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int TimeToBars(int d)
|
||||
{
|
||||
datetime n = TimeCurrent();
|
||||
if(n==0)
|
||||
{
|
||||
long s = (long)d*86400L, p = PeriodSeconds(ANCHOR_TF);
|
||||
return (int)MathMax(1,s/p);
|
||||
}
|
||||
return MathMax(1,Bars(_Symbol,ANCHOR_TF,n-d*86400,n));
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int OnInit()
|
||||
{
|
||||
int days[7] = {365,182,121,30,14,7,3};
|
||||
for(int i=0;i<7;i++)
|
||||
{
|
||||
bars[i] = TimeToBars(days[i]);
|
||||
hMA[i] = iMA(_Symbol,ANCHOR_TF,bars[i],0,MODE_SMA,PRICE_CLOSE);
|
||||
if(hMA[i]==INVALID_HANDLE) return INIT_FAILED;
|
||||
}
|
||||
if(DebugPrint) Print("=== PaPP Median EA v2.00 INIT ===");
|
||||
Print(" Lot=",LotSize," Trail=",TrailStart,"/",TrailStep," MaxPos=",MaxPosPerSide);
|
||||
for(int i=0;i<7;i++) Print(" MA[",i,"] bars=",bars[i]);
|
||||
buyFired = (CountPos(POSITION_TYPE_BUY) > 0);
|
||||
sellFired = (CountPos(POSITION_TYPE_SELL) > 0);
|
||||
if(DebugPrint) Print(" Flags restored: buyFired=",buyFired," sellFired=",sellFired);
|
||||
return INIT_SUCCEEDED;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void OnDeinit(const int reason)
|
||||
{
|
||||
for(int i=0;i<7;i++) if(hMA[i]!=INVALID_HANDLE) IndicatorRelease(hMA[i]);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
// legge la SMA dall'ultima barra D1 chiusa (non-repaint)
|
||||
double GetMA(int m)
|
||||
{
|
||||
double buf[1];
|
||||
if(CopyBuffer(hMA[m],0,1,1,buf)==1) return buf[0];
|
||||
return 0;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
double Median(double &a[],int n)
|
||||
{
|
||||
if(n<=0) return 0;
|
||||
ArraySort(a);
|
||||
if((n&1)==1) return a[n/2];
|
||||
return 0.5*(a[n/2-1]+a[n/2]);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
int CountPos(int type)
|
||||
{
|
||||
int n=0;
|
||||
for(int i=PositionsTotal()-1; i>=0; i--)
|
||||
{
|
||||
ulong t=PositionGetTicket(i);
|
||||
if(t>0 && PositionSelectByTicket(t))
|
||||
if(PositionGetInteger(POSITION_MAGIC)==Magic && PositionGetString(POSITION_SYMBOL)==_Symbol)
|
||||
if(PositionGetInteger(POSITION_TYPE)==type) n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void TrailAll()
|
||||
{
|
||||
if(TrailStart<=0 || TrailStep<=0) return;
|
||||
double point = SymbolInfoDouble(_Symbol,SYMBOL_POINT);
|
||||
double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
|
||||
double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
|
||||
for(int i=PositionsTotal()-1; i>=0; i--)
|
||||
{
|
||||
ulong t=PositionGetTicket(i);
|
||||
if(t<=0 || !PositionSelectByTicket(t)) continue;
|
||||
if(PositionGetInteger(POSITION_MAGIC)!=Magic || PositionGetString(POSITION_SYMBOL)!=_Symbol) continue;
|
||||
|
||||
bool isBuy = (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY);
|
||||
double entry = PositionGetDouble(POSITION_PRICE_OPEN);
|
||||
double currSL = PositionGetDouble(POSITION_SL);
|
||||
double currTP = PositionGetDouble(POSITION_TP);
|
||||
double newSL=0;
|
||||
|
||||
if(isBuy && bid >= entry+TrailStart*point)
|
||||
{
|
||||
newSL = bid - TrailStep*point;
|
||||
if(newSL > currSL+point && trade.PositionModify(t,newSL,currTP))
|
||||
if(DebugPrint) Print(">>> TRAIL BUY t",t," SL->",DoubleToString(newSL,_Digits));
|
||||
}
|
||||
if(!isBuy && ask <= entry-TrailStart*point)
|
||||
{
|
||||
newSL = ask + TrailStep*point;
|
||||
if(currSL==0 || newSL < currSL-point)
|
||||
{
|
||||
if(trade.PositionModify(t,newSL,currTP))
|
||||
if(DebugPrint) Print(">>> TRAIL SELL t",t," SL->",DoubleToString(newSL,_Digits));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void UpdateTPSL(double median)
|
||||
{
|
||||
double point = SymbolInfoDouble(_Symbol,SYMBOL_POINT);
|
||||
for(int i=PositionsTotal()-1; i>=0; i--)
|
||||
{
|
||||
ulong t=PositionGetTicket(i);
|
||||
if(t<=0 || !PositionSelectByTicket(t)) continue;
|
||||
if(PositionGetInteger(POSITION_MAGIC)!=Magic || PositionGetString(POSITION_SYMBOL)!=_Symbol) continue;
|
||||
|
||||
bool isBuy = PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY;
|
||||
double entry = PositionGetDouble(POSITION_PRICE_OPEN);
|
||||
double currSL = PositionGetDouble(POSITION_SL);
|
||||
double currTP = PositionGetDouble(POSITION_TP);
|
||||
double tpDist = MathAbs(median-entry);
|
||||
if(tpDist<point) continue;
|
||||
|
||||
double newTP = NormalizeDouble(median,_Digits);
|
||||
double newSL = NormalizeDouble(isBuy ? entry-tpDist : entry+tpDist,_Digits);
|
||||
if(MathAbs(newTP-currTP)<=point && MathAbs(newSL-currSL)<=point) continue;
|
||||
if(isBuy && newSL <= currSL+point) continue;
|
||||
if(!isBuy && newSL >= currSL-point) continue;
|
||||
|
||||
if(DebugPrint) Print(">>> UPDATE t",t," TP=",DoubleToString(newTP,_Digits),
|
||||
" SL=",DoubleToString(newSL,_Digits));
|
||||
trade.PositionModify(t,newSL,newTP);
|
||||
}
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
void OnTick()
|
||||
{
|
||||
TrailAll();
|
||||
|
||||
datetime curBar = iTime(_Symbol,_Period,0);
|
||||
if(curBar==lastBar) return;
|
||||
lastBar = curBar;
|
||||
|
||||
double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
|
||||
double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
|
||||
double point = SymbolInfoDouble(_Symbol,SYMBOL_POINT);
|
||||
|
||||
//--- Leggi le 7 MA e calcola mediana
|
||||
double mv[7]; double vals[]; int valid=0; ArrayResize(vals,7);
|
||||
for(int m=0;m<7;m++) { mv[m]=GetMA(m); if(mv[m]>0) { vals[valid]=mv[m]; valid++; } }
|
||||
if(valid==0) { if(DebugPrint) Print("SKIP: valid=",valid); return; }
|
||||
ArrayResize(vals,valid);
|
||||
|
||||
double median = Median(vals,valid);
|
||||
|
||||
//--- Update TP/SL per tutte le posizioni con la mediana corrente
|
||||
UpdateTPSL(median);
|
||||
|
||||
//--- Banda = min/max delle 7 MA (1Y a 3G)
|
||||
double minMA=mv[0], maxMA=mv[0];
|
||||
for(int m=1;m<7;m++)
|
||||
if(mv[m]>0) {
|
||||
if(mv[m]<minMA) minMA=mv[m];
|
||||
if(mv[m]>maxMA) maxMA=mv[m]; }
|
||||
|
||||
double buyBand=minMA, sellBand=maxMA;
|
||||
double distPct = (bid-median)/median*100;
|
||||
|
||||
int nBuy = CountPos(POSITION_TYPE_BUY);
|
||||
int nSell = CountPos(POSITION_TYPE_SELL);
|
||||
|
||||
//--- Reset escursion flags solo quando price torna alla mediana
|
||||
if(bid>=median) buyFired=false;
|
||||
if(bid<=median) sellFired=false;
|
||||
|
||||
//--- MA alignment: se tutte monotone = trend, blocca mean reversion
|
||||
bool trendUp=true, trendDown=true;
|
||||
for(int m=2;m<6;m++)
|
||||
if(mv[m] > mv[m+1]) trendUp=false;
|
||||
else if(mv[m] < mv[m+1]) trendDown=false;
|
||||
else { trendUp=false; trendDown=false; }
|
||||
bool allowBuy = !buyFired && nBuy<MaxPosPerSide && !trendDown;
|
||||
bool allowSell = !sellFired && nSell<MaxPosPerSide && !trendUp;
|
||||
|
||||
//--- LOG
|
||||
if(DebugPrint)
|
||||
{
|
||||
Print("");
|
||||
Print("=== BAR: ",TimeToString(curBar)," ===");
|
||||
Print("Bid=",DoubleToString(bid,_Digits)," Median=",DoubleToString(median,_Digits));
|
||||
Print("Dist=",DoubleToString(distPct,3),"% Range=",DoubleToString((maxMA-minMA)/median*100,3),"%");
|
||||
Print("Trend: ",trendUp?"UP":trendDown?"DOWN":"MIX", " Allow: ",allowBuy?"B":"-",allowSell?"S":"-");
|
||||
Print("Band: [",DoubleToString(buyBand,_Digits)," <- ",DoubleToString(sellBand,_Digits)," ] Pos: ",nBuy,"B ",nSell,"S");
|
||||
for(int m=0;m<7;m++)
|
||||
if(mv[m]>0)
|
||||
Print(" MA",m,"=",DoubleToString(mv[m],_Digits),
|
||||
" diff=",DoubleToString(bid-mv[m],_Digits));
|
||||
Print("---");
|
||||
}
|
||||
|
||||
//--- Entry: fuori dal cluster, TP=mediana, SL simmetrico
|
||||
if(bid < buyBand && allowBuy)
|
||||
{
|
||||
double entry = ask;
|
||||
double tpDist = MathAbs(median-entry);
|
||||
double sl = NormalizeDouble(entry-tpDist,_Digits);
|
||||
double tp = NormalizeDouble(median,_Digits);
|
||||
if(tpDist>=point)
|
||||
{
|
||||
if(DebugPrint) Print(">>> BUY: bid=",DoubleToString(bid,_Digits),
|
||||
" < buyBand=",DoubleToString(buyBand,_Digits),
|
||||
" TP=",DoubleToString(tp,_Digits)," SL=",DoubleToString(sl,_Digits),
|
||||
" (",DoubleToString(tpDist/point,0),"pts)");
|
||||
MqlTradeRequest req={}; MqlTradeResult res={};
|
||||
req.action = TRADE_ACTION_DEAL; req.symbol = _Symbol;
|
||||
req.volume = LotSize; req.type = ORDER_TYPE_BUY; req.price = entry;
|
||||
req.sl = sl; req.tp = tp; req.deviation = Slippage; req.magic = Magic;
|
||||
req.comment = "Pv2B "+DoubleToString(distPct,1)+"%";
|
||||
if(OrderSend(req,res) && res.retcode==TRADE_RETCODE_DONE)
|
||||
{ if(DebugPrint) Print(">>> BUY OPENED t",res.order); buyFired=true; }
|
||||
else if(DebugPrint) Print("BUY fail: c",res.retcode);
|
||||
}
|
||||
else if(DebugPrint) Print("BUY SKIP: tpDist too small (",DoubleToString(tpDist/point,0),"pts)");
|
||||
}
|
||||
|
||||
if(bid > sellBand && allowSell)
|
||||
{
|
||||
double entry = bid;
|
||||
double tpDist = MathAbs(entry-median);
|
||||
double sl = NormalizeDouble(entry+tpDist,_Digits);
|
||||
double tp = NormalizeDouble(median,_Digits);
|
||||
if(tpDist>=point)
|
||||
{
|
||||
if(DebugPrint) Print(">>> SELL: bid=",DoubleToString(bid,_Digits),
|
||||
" > sellBand=",DoubleToString(sellBand,_Digits),
|
||||
" TP=",DoubleToString(tp,_Digits)," SL=",DoubleToString(sl,_Digits),
|
||||
" (",DoubleToString(tpDist/point,0),"pts)");
|
||||
MqlTradeRequest req={}; MqlTradeResult res={};
|
||||
req.action = TRADE_ACTION_DEAL; req.symbol = _Symbol;
|
||||
req.volume = LotSize; req.type = ORDER_TYPE_SELL; req.price = entry;
|
||||
req.sl = sl; req.tp = tp; req.deviation = Slippage; req.magic = Magic;
|
||||
req.comment = "Pv2S "+DoubleToString(distPct,1)+"%";
|
||||
if(OrderSend(req,res) && res.retcode==TRADE_RETCODE_DONE)
|
||||
{ if(DebugPrint) Print(">>> SELL OPENED t",res.order); sellFired=true; }
|
||||
else if(DebugPrint) Print("SELL fail: c",res.retcode);
|
||||
}
|
||||
else if(DebugPrint) Print("SELL SKIP: tpDist too small (",DoubleToString(tpDist/point,0),"pts)");
|
||||
}
|
||||
|
||||
if(DebugPrint && bid>=buyBand && bid<=sellBand)
|
||||
Print("NO ENTRY: inside cluster [",DoubleToString(buyBand,_Digits),
|
||||
" - ",DoubleToString(sellBand,_Digits),"]");
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
Reference in New Issue
Block a user