all in one afl

#1
please check the afl correct error error 42 message


// **************************
// BEING EXPLORATION CODE
// **************************

// -- what will be our lookback range for the hh and ll?
nBars = Param("Number of bars", 12, 5, 40);
bTrace = Param("Include trace output", 1, 0, 1);
nNoPivsInSetup = Param("No. Pivs in Setup", 4, 3, 4, 1);
bShowTCZ = Param("Show TCZ", 1, 0, 1);
nMinBarsBtwPivs = Param("Min. number of bars btw. pivots", 1, 1, 10, 1);
nMinPctBtwPivs = Param("Min. percent diff. btw. pivots", .05, .04, .2,
.01);
bLastBarCanBePiv = Param("Last bar can be a pivot", 1, 0, 1);
retrcTolerance = .01;
tczTolerance = .005;
nNumBarsToScan = 120;

// -- added from exploration version 20040204
nExploreBarIdx = 0;
nExploreDate = 0;
nCurDateNum = 0;
DN = DateNum();
DT = DateTime();

// -- key exploration variables
bTCZLong = Buy =False;
bTCZShort = Sell =False;
nAnchorPivIdx = 0;

ADX8 = ADX(8);

// 1 - INDICATOR, 2 - COMMENTARY, 3 - SCAN,
// 4 - EXPLORATION, 5 - BACKTEST / Optimize
if(Status("action")==1) {
bDraw = True;
bUseLastVis = Param("Use last visible bar", 1, 0, 1);
} else {
bDraw = False;
bUseLastVis = False;
bTrace = False;
nExploreDate = Status("rangetodate");
for (i=LastValue(BarIndex());i>=0;i--) {
nCurDateNum = DN;
if (nCurDateNum == nExploreDate) {
nExploreBarIdx = i;
}
}
// -- if(Status("action")==1...
}

GraphXSpace=7;

// -- basic candle chart
// -- if this appears inside if block, strange
// drawing results!
PlotOHLC(Open, High, Low, Close,
"BIdx = " + BarIndex() +
"\n" + "O = " + O + "\n"+"H = "+ H + "\n"+"L = " + L
+ "\n"+"C ",
colorBlack, styleCandle);

if (bDraw) {
Plot(MA(C, 21), "21 bar MA", colorAqua,
styleLine+styleNoRescale+styleNoLabel);
Plot(MA(C, 55), "55 bar MA", colorGreen,
styleLine+styleNoRescale+styleNoLabel);
//Plot(MA(C, 233), "233 bar MA", colorDarkRed,
// styleLine+styleNoRescale+styleNoLabel);
}

// -- Create 0-initialized arrays the size of barcount
aHPivs = H - H;
aLPivs = L - L;
aHPivHighs = H - H;
aLPivLows = L - L;
aHPivIdxs = H - H;
aLPivIdxs = L - L;
aAddedHPivs = H - H;
aAddedLPivs = L - L;
aLegVol = H - H;
aRetrcVol = H - H;

nHPivs = 0;
nLPivs = 0;

lastHPIdx = 0;
lastLPIdx = 0;
lastHPH = 0;
lastLPL = 0;
curPivBarIdx = 0;

// -- looking back from the current bar, how many bars
// back were the hhv and llv values of the previous
// n bars, etc.?
aHHVBars = HHVBars(H, nBars);
aLLVBars = LLVBars(L, nBars);
aHHV = HHV(H, nBars);
aLLV = LLV(L, nBars);

// -- Initialize value of curTrend
nLastVisBar = LastValue(
Highest(IIf(Status("barvisible"), BarIndex(), 0)));

curBar = IIf(nlastVisBar > 0 AND bUseLastVis, nlastVisBar,
IIf(Status("action")==4 AND nExploreBarIdx > 0, nExploreBarIdx,
LastValue(BarIndex())));

curTrend = "";
if (aLLVBars[curBar] < aHHVBars[curBar])
curTrend = "D";
else
curTrend = "U";

// -- Loop through bars. Search for
// entirely array-based approach
// in future version
/* *******************
Find main pivots
******************* */

// -- Make sure there are enough bars!
if (curBar >= nNumBarsToScan) {
for (i=0; i<nNumBarsToScan; i++) {

// -- value of curBar dependent on two parameters
curBar = IIf(nlastVisBar > 0 AND bUseLastVis,
nlastVisBar-i,
IIf(Status("action")==4 AND nExploreBarIdx > 0,
nExploreBarIdx-i,
LastValue(BarIndex())-i));

// -- Have we identified a pivot? If trend is down...
if (aLLVBars[curBar] < aHHVBars[curBar]) {

// ... and had been up, this is a trend change
if (curTrend == "U") {
curTrend = "D";
// -- Capture pivot information
curPivBarIdx = curBar - aLLVBars[curBar];
aLPivs[curPivBarIdx] = 1;
aLPivLows[nLPivs] = L[curPivBarIdx];
aLPivIdxs[nLPivs] = curPivBarIdx;
nLPivs++;
}
// -- or current trend is up
} else {
if (curTrend == "D") {
curTrend = "U";
curPivBarIdx = curBar - aHHVBars[curBar];
aHPivs[curPivBarIdx] = 1;
aHPivHighs[nHPivs] = H[curPivBarIdx];
aHPivIdxs[nHPivs] = curPivBarIdx;
nHPivs++;
}
// -- If curTrend is up...else...
}

// -- loop through bars
}
}
/* *******************
Found main pivots
******************* */

/* *************************
Finding missed pivot(s)
************************* */

// -- Start at last bar. Reestablish curBar
curBar =
IIf(nlastVisBar > 0 AND bUseLastVis,
nlastVisBar,
IIf(Status("action")==4 AND nExploreBarIdx > 0,
nExploreBarIdx,
LastValue(BarIndex()))
);

// -- Make sure I found at least two of each above.
if (nHPivs >= 2 AND nLPivs >= 2) {

lastLPIdx = aLPivIdxs[0];
lastLPL = aLPivLows[0];

lastHPIdx = aHPivIdxs[0];
lastHPH = aHPivHighs[0];

nLastHOrLPivIdx = Max(lastLPIdx, lastHPIdx);

nAddPivsRng = curBar - nLastHOrLPivIdx;
aLLVAfterLastPiv = LLV(L, nAddPivsRng);
nLLVAfterLastPiv = aLLVAfterLastPiv[curBar];
aLLVIdxAfterLastPiv = LLVBars(L, nAddPivsRng);
nLLVIdxAfterLastPiv = curBar - aLLVIdxAfterLastPiv[curBar];
aHHVAfterLastPiv = HHV(H, nAddPivsRng);
nHHVAfterLastPiv = aHHVAfterLastPiv[curBar];
aHHVIdxAfterLastPiv = HHVBars(H, nAddPivsRng);
nHHVIdxAfterLastPiv = curBar - aHHVIdxAfterLastPiv[curBar];

// -- Later want to add last high pivot only if
// not in buy mode from last and still in trade

/*
Note - I'm only interested in adding pivots if I'm in
a higher-highs or lower-lows scenario
*/


// -- OK, let's start where the last high pivot occurs after the
// last Low pivot
if (lastHPIdx > lastLPIdx) {

/* There are at least two possibilities here. One is that
the previous high was higher, indicating that this is a
possible short retracement or one in the making.
The other is that the previous high was lower, indicating
that this is a possible long retracement in the working.
However, both depend on opposing pivots. E.g., if I find
higher highs, what if I have lower lows?

If the highs are descending, then I can consider:
- a lower low, and leave it at that
- a higher high and higher low
- a lower low and another lower high
*/
if (aHPivHighs[0] < aHPivHighs[1]) {

if (nLLVAfterLastPiv < aLPivLows[0] AND
(nLLVIdxAfterLastPiv - lastHPIdx - 1) >= nMinBarsBtwPivs
AND nLLVIdxAfterLastPiv != curBar ) {

// -- OK, we'll add this as a pivot.
// Mark it for plotting...
aLPivs[nLLVIdxAfterLastPiv] = 1;
aAddedLPivs[nLLVIdxAfterLastPiv] = 1;

// ...and then rearrange elements in the
// pivot information arrays
for (j=0; j<nLPivs; j++) {
aLPivLows[nLPivs-j] = aLPivLows[nLPivs-(j+1)];
aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-(j+1)];
}
aLPivLows[0] = nLLVAfterLastPiv;
aLPivIdxs[0] = nLLVIdxAfterLastPiv;
nLPivs++;

// -- Test whether to add piv given last piv is high
// AND we have lower highs
}

// -- Here, the last piv is a high piv, and we have
// higher-highs. The most likely addition is a
// Low piv that is a retracement.
} else {

if (nLLVAfterLastPiv > aLPivLows[0] AND
(nLLVIdxAfterLastPiv - lastHPIdx - 1) >= nMinBarsBtwPivs
AND nLLVIdxAfterLastPiv != curBar ) {

// -- OK, we'll add this as a pivot.
// Mark it for plotting...
aLPivs[nLLVIdxAfterLastPiv] = 1;
aAddedLPivs[nLLVIdxAfterLastPiv] = 1;

// ...and then rearrange elements in the
// pivot information arrays
for (j=0; j<nLPivs; j++) {
aLPivLows[nLPivs-j] = aLPivLows[nLPivs-(j+1)];
aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-(j+1)];
}
aLPivLows[0] = nLLVAfterLastPiv;
aLPivIdxs[0] = nLLVIdxAfterLastPiv;
nLPivs++;

// -- Test whether to add piv given last piv is high
// AND we have lower highs
}
// -- The last piv is a high and we have higher highs
// OR lower highs
}

/* ****************************************************************
Still finding missed pivot(s). Here, the last piv is a low piv.
**************************************************************** */
} else {

// -- First case, lower highs
if (aHPivHighs[0] < aHPivHighs[1]) {

if (nHHVAfterLastPiv < aHPivHighs[0] AND
(nHHVIdxAfterLastPiv - lastLPIdx - 1) >= nMinBarsBtwPivs
AND nHHVIdxAfterLastPiv != curBar ) {

// -- OK, we'll add this as a pivot.
// Mark that for plotting
aHPivs[nHHVIdxAfterLastPiv] = 1;
aAddedHPivs[nHHVIdxAfterLastPiv] = 1;

// ...and then rearrange elements in the
// pivot information arrays
for (j=0; j<nHPivs; j++) {
aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs-(j+1)];
aHPivIdxs[nHPivs-j] = aHPivIdxs[nhPivs-(j+1)];
}
aHPivHighs[0] = nHHVAfterLastPiv;
aHPivIdxs[0] = nHHVIdxAfterLastPiv;
nHPivs++;

// -- Test whether to add piv given last piv is high
// AND we have lower highs
}

// -- Second case when last piv is a low piv, higher highs
// Most likely addition is high piv that is a retracement.
// Considering adding a high piv as long as it is higher
} else {

// -- Where I have higher highs,
if (nHHVAfterLastPiv > aHPivHighs[0] AND
(nHHVIdxAfterLastPiv - lastLPIdx - 1) >= nMinBarsBtwPivs
AND nHHVIdxAfterLastPiv != curBar ) {

// -- OK, we'll add this as a pivot.
// Mark it for plotting...
aHPivs[nHHVIdxAfterLastPiv] = 1;
aAddedHPivs[nHHVIdxAfterLastPiv] = 1;

// ...and then rearrange elements in the
// pivot information arrays
for (j=0; j<nHPivs; j++) {
aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs-(j+1)];
aHPivIdxs[nHPivs-j] = aHPivIdxs[nhPivs-(j+1)];
}
aHPivHighs[0] = nHHVAfterLastPiv;
aHPivIdxs[0] = nHHVIdxAfterLastPiv;
nHPivs++;

// -- Test whether to add piv given last piv is high
// AND we have lower highs
}

}

}

// -- If there are at least two of each
}

/* ****************************************
// -- Done with finding pivots
***************************************** */

if (bDraw) {

// -- OK, let's plot the pivots using arrows
PlotShapes(
IIf(aHPivs==1, shapeDownArrow, shapeNone),
colorRed, 0, High, Offset=-15);
PlotShapes(
IIf(aAddedHPivs==1, shapeDownArrow, shapeNone),
colorDarkRed, 0, High, Offset=-15);
PlotShapes(
IIf(aLPivs==1, shapeUpArrow , shapeNone),
colorGreen, 0, Low, Offset=-15);
PlotShapes(
IIf(aAddedLPivs==1, shapeUpArrow , shapeNone),
colorDarkGreen, 0, Low, Offset=-15);
}


/* ****************************************
// -- Done with discovering and plotting pivots
***************************************** */

// -- I'm going to want to look for possible retracement
risk = 0;
profInc = 0;
nLeg0Pts = 0;
nLeg0Bars = 0;
nLeg0Vol = 0;
nLeg1Pts = 0;
nLeg1Bars = 0;
nLeg1Vol = 0;
nLegBarsDiff = 0;
nRtrc0Pts = 0;
nRtrc0Bars = 0;
nRtrc0Vol = 0;
nRtrc1Pts = 0;
nRtrc1Bars = 0;
nRtrc1Vol = 0;

minRtrc = 0;
maxRtrc = 0;
minLine = 0;
maxLine = 0;
triggerLine = 0;
firstProfitLine = 0;
triggerInc = 0;
triggerPrc = 0;
firstProfitPrc = 0;
retrcPrc = 0;
retrcBar = 0;
retrcBarIdx = 0;
retrcRng = 0;
aRetrcPrc = H-H;
aRetrcPrcBars = H-H;
aRetrcClose = C;
retrcClose = 0;

// -- Do TCZ calcs. Arrangement of pivs very specific
// for this setup.
if (nHPivs >= 2 AND
nLPivs >=2 AND
aHPivHighs[0] > aHPivHighs[1] AND
aLPivLows[0] > aLPivLows[1]) {

tcz500 =
(aHPivHighs[0] -
(.5 * (aHPivHighs[0] - aLPivLows[1])));

tcz618 =
(aHPivHighs[0] -
(.618 * (aHPivHighs[0] - aLPivLows[1])));

tcz786 =
(aHPivHighs[0] -
(.786 * (aHPivHighs[0] - aLPivLows[0])));

retrcRng = curBar - aHPivIdxs[0];
aRetrcPrc = LLV(L, retrcRng);
retrcPrc = aRetrcPrc[curBar];
aRetrcPrcBars = LLVBars(L, retrcRng);
retrcBarIdx = curBar - aRetrcPrcBars[curBar];
retrcClose = aRetrcClose[retrcBarIdx];

// -- bTCZLong setup?
bTCZLong = (

// -- Are retracement levels arranged in
// tcz order?
tcz500 >= (tcz786 * (1 - tczTolerance))
AND
// .681 is below .786 for long setups
tcz618 <= (tcz786 * (1 + tczTolerance))
AND

// -- Is the low in the tcz range
// -- Is the close >= low of tcz range
// and low <= high of tcz range
retrcClose >= ((1 - retrcTolerance) * tcz618)
AND
retrcPrc <= ((1 + retrcTolerance) * tcz500)
);

// -- risk would be high of signal bar minus low of zone
//risk = 0;

// -- lower highs and lower lows
} else if (nHPivs >= 2 AND nLPivs >=2
AND aHPivHighs[0] < aHPivHighs[1]
AND aLPivLows[0] < aLPivLows[1]) {

tcz500 =
(aHPivHighs[1] -
(.5 * (aHPivHighs[1] - aLPivLows[0])));

tcz618 =
(aHPivHighs[0] -
(.618 * (aHPivHighs[1] - aLPivLows[0])));

tcz786 =
(aHPivHighs[0] -
(.786 * (aHPivHighs[0] - aLPivLows[0])));

retrcRng = curBar - aLPivIdxs[0];
aRetrcPrc = HHV(H, retrcRng);
retrcPrc = aRetrcPrc[curBar];
aRetrcPrcBars = HHVBars(H, retrcRng);
retrcBarIdx = curBar - aRetrcPrcBars[curBar];
retrcClose = aRetrcClose[retrcBarIdx];

bTCZShort = (
// -- Are retracement levels arranged in
// tcz order?

// .500 is below .786 for short setups
tcz500 <= (tcz786 * (1 + tczTolerance))
AND
// .681 is above .786 for short setups
tcz618 >= (tcz786 * (1 - tczTolerance))
AND

// -- Is the close <= high of tcz range
// and high >= low of tcz range
retrcClose <= ((1 + retrcTolerance) * tcz618)
AND
retrcPrc >= ((1 - retrcTolerance) * tcz500)
);

// -- Risk would be top of zone - low of signal bar
//risk = 0;
}

Filter = (bTCZShort OR bTCZLong);
AddColumn(C, "Close");
AddColumn(IIf(bTCZLong, 76, 83), "L/S", formatChar);

// **************************
// END EXPLORATION CODE
// **************************

// **************************
// BEGIN INDICATOR CODE
// **************************

// -- what will be our lookback range for the hh and ll?
nBars = Param("Number of bars", 12, 5, 40);
bTrace = Param("Include trace output", 1, 0, 1);
nNoPivsInSetup = Param("No. Pivs in Setup", 4, 3, 4, 1);
bShowTCZ = Param("Show TCZ", 1, 0, 1);
nMinBarsBtwPivs = Param("Min. number of bars btw. pivots", 1, 1, 10, 1);
nMinPctBtwPivs = Param("Min. percent diff. btw. pivots", .05, .04, .2,
.01);
bLastBarCanBePiv = Param("Last bar can be a pivot", 1, 0, 1);
retrcTolerance = .01;
tczTolerance = .005;
nNumBarsToScan = 120;

// -- added from exploration version 20040204
nExploreBarIdx = 0;
nExploreDate = 0;
nCurDateNum = 0;
DN = DateNum();
DT = DateTime();

// -- key exploration variables
bTCZLong = Buy = False;
bTCZShort = Sell = False;
nAnchorPivIdx = 0;

ADX8 = ADX(8);

// 1 - INDICATOR, 2 - COMMENTARY, 3 - SCAN,
// 4 - EXPLORATION, 5 - BACKTEST / Optimize
if(Status("action")==1) {
bDraw = True;
bUseLastVis = Param("Use last visible bar", 1, 0, 1);
} else {
bDraw = False;
bUseLastVis = False;
bTrace = False;
nExploreDate = Status("rangetodate");
for (i=LastValue(BarIndex());i>=0;i--) {
nCurDateNum = DN;
if (nCurDateNum == nExploreDate) {
nExploreBarIdx = i;
}
}
// -- if(Status("action")==1...
}

GraphXSpace=7;

// -- basic candle chart
// -- if this appears inside if block, strange
// drawing results!
PlotOHLC(Open, High, Low, Close,
"BIdx = " + BarIndex() +
"\n" + "O = " + O + "\n"+"H = "+ H + "\n"+"L = " + L
+ "\n"+"C ",
colorBlack, styleCandle);

if (bDraw) {
Plot(MA(C, 21), "21 bar MA", colorAqua,
styleLine+styleNoRescale+styleNoLabel);
Plot(MA(C, 55), "55 bar MA", colorGreen,
styleLine+styleNoRescale+styleNoLabel);
//Plot(MA(C, 233), "233 bar MA", colorDarkRed,
// styleLine+styleNoRescale+styleNoLabel);
}

// -- Create 0-initialized arrays the size of barcount
aHPivs = H - H;
aLPivs = L - L;
aHPivHighs = H - H;
aLPivLows = L - L;
aHPivIdxs = H - H;
aLPivIdxs = L - L;
aAddedHPivs = H - H;
aAddedLPivs = L - L;
aLegVol = H - H;
aRetrcVol = H - H;

nHPivs = 0;
nLPivs = 0;

lastHPIdx = 0;
lastLPIdx = 0;
lastHPH = 0;
lastLPL = 0;
curPivBarIdx = 0;

// -- looking back from the current bar, how many bars
// back were the hhv and llv values of the previous
// n bars, etc.?
aHHVBars = HHVBars(H, nBars);
aLLVBars = LLVBars(L, nBars);
aHHV = HHV(H, nBars);
aLLV = LLV(L, nBars);

// -- Initialize value of curTrend
nLastVisBar = LastValue(
Highest(IIf(Status("barvisible"), BarIndex(), 0)));

curBar = IIf(nlastVisBar > 0 AND bUseLastVis, nlastVisBar,
IIf(Status("action")==4 AND nExploreBarIdx > 0, nExploreBarIdx,
LastValue(BarIndex())));

curTrend = "";
if (aLLVBars[curBar] < aHHVBars[curBar])
curTrend = "D";
else
curTrend = "U";

// -- Loop through bars. Search for
// entirely array-based approach
// in future version
/* *******************
Find main pivots
******************* */

// -- Make sure there are enough bars!
if (curBar >= nNumBarsToScan) {
for (i=0; i<nNumBarsToScan; i++) {

// -- value of curBar dependent on two parameters
curBar = IIf(nlastVisBar > 0 AND bUseLastVis,
nlastVisBar-i,
IIf(Status("action")==4 AND nExploreBarIdx > 0,
nExploreBarIdx-i,
LastValue(BarIndex())-i));

// -- Have we identified a pivot? If trend is down...
if (aLLVBars[curBar] < aHHVBars[curBar]) {

// ... and had been up, this is a trend change
if (curTrend == "U") {
curTrend = "D";
// -- Capture pivot information
curPivBarIdx = curBar - aLLVBars[curBar];
aLPivs[curPivBarIdx] = 1;
aLPivLows[nLPivs] = L[curPivBarIdx];
aLPivIdxs[nLPivs] = curPivBarIdx;
nLPivs++;
}
// -- or current trend is up
} else {
if (curTrend == "D") {
curTrend = "U";
curPivBarIdx = curBar - aHHVBars[curBar];
aHPivs[curPivBarIdx] = 1;
aHPivHighs[nHPivs] = H[curPivBarIdx];
aHPivIdxs[nHPivs] = curPivBarIdx;
nHPivs++;
}
// -- If curTrend is up...else...
}

// -- loop through bars
}
}
/* *******************
Found main pivots
******************* */

/* *************************
Finding missed pivot(s)
************************* */

// -- Start at last bar. Reestablish curBar
curBar =
IIf(nlastVisBar > 0 AND bUseLastVis,
nlastVisBar,
IIf(Status("action")==4 AND nExploreBarIdx > 0,
nExploreBarIdx,
LastValue(BarIndex()))
);

// -- Make sure I found at least two of each above.
if (nHPivs >= 2 AND nLPivs >= 2) {

lastLPIdx = aLPivIdxs[0];
lastLPL = aLPivLows[0];

lastHPIdx = aHPivIdxs[0];
lastHPH = aHPivHighs[0];

nLastHOrLPivIdx = Max(lastLPIdx, lastHPIdx);

nAddPivsRng = curBar - nLastHOrLPivIdx;
aLLVAfterLastPiv = LLV(L, nAddPivsRng);
nLLVAfterLastPiv = aLLVAfterLastPiv[curBar];
aLLVIdxAfterLastPiv = LLVBars(L, nAddPivsRng);
nLLVIdxAfterLastPiv = curBar - aLLVIdxAfterLastPiv[curBar];
aHHVAfterLastPiv = HHV(H, nAddPivsRng);
nHHVAfterLastPiv = aHHVAfterLastPiv[curBar];
aHHVIdxAfterLastPiv = HHVBars(H, nAddPivsRng);
nHHVIdxAfterLastPiv = curBar - aHHVIdxAfterLastPiv[curBar];

// -- Later want to add last high pivot only if
// not in buy mode from last and still in trade

/*
Note - I'm only interested in adding pivots if I'm in
a higher-highs or lower-lows scenario
*/


// -- OK, let's start where the last high pivot occurs after the
// last Low pivot
if (lastHPIdx > lastLPIdx) {

/* There are at least two possibilities here. One is that
the previous high was higher, indicating that this is a
possible short retracement or one in the making.
The other is that the previous high was lower, indicating
that this is a possible long retracement in the working.
However, both depend on opposing pivots. E.g., if I find
higher highs, what if I have lower lows?

If the highs are descending, then I can consider:
- a lower low, and leave it at that
- a higher high and higher low
- a lower low and another lower high
*/
if (aHPivHighs[0] < aHPivHighs[1]) {

if (nLLVAfterLastPiv < aLPivLows[0] AND
(nLLVIdxAfterLastPiv - lastHPIdx - 1) >= nMinBarsBtwPivs
AND nLLVIdxAfterLastPiv != curBar ) {

// -- OK, we'll add this as a pivot.
// Mark it for plotting...
aLPivs[nLLVIdxAfterLastPiv] = 1;
aAddedLPivs[nLLVIdxAfterLastPiv] = 1;

// ...and then rearrange elements in the
// pivot information arrays
for (j=0; j<nLPivs; j++) {
aLPivLows[nLPivs-j] = aLPivLows[nLPivs-(j+1)];
aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-(j+1)];
}
aLPivLows[0] = nLLVAfterLastPiv;
aLPivIdxs[0] = nLLVIdxAfterLastPiv;
nLPivs++;

// -- Test whether to add piv given last piv is high
// AND we have lower highs
}

// -- Here, the last piv is a high piv, and we have
// higher-highs. The most likely addition is a
// Low piv that is a retracement.
} else {

if (nLLVAfterLastPiv > aLPivLows[0] AND
(nLLVIdxAfterLastPiv - lastHPIdx - 1) >= nMinBarsBtwPivs
AND nLLVIdxAfterLastPiv != curBar ) {

// -- OK, we'll add this as a pivot.
// Mark it for plotting...
aLPivs[nLLVIdxAfterLastPiv] = 1;
aAddedLPivs[nLLVIdxAfterLastPiv] = 1;

// ...and then rearrange elements in the
// pivot information arrays
for (j=0; j<nLPivs; j++) {
aLPivLows[nLPivs-j] = aLPivLows[nLPivs-(j+1)];
aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-(j+1)];
}
aLPivLows[0] = nLLVAfterLastPiv;
aLPivIdxs[0] = nLLVIdxAfterLastPiv;
nLPivs++;

// -- Test whether to add piv given last piv is high
// AND we have lower highs
}
// -- The last piv is a high and we have higher highs
// OR lower highs
}

/* ****************************************************************
Still finding missed pivot(s). Here, the last piv is a low piv.
**************************************************************** */
} else {

// -- First case, lower highs
if (aHPivHighs[0] < aHPivHighs[1]) {

if (nHHVAfterLastPiv < aHPivHighs[0] AND
(nHHVIdxAfterLastPiv - lastLPIdx - 1) >= nMinBarsBtwPivs
AND nHHVIdxAfterLastPiv != curBar ) {

// -- OK, we'll add this as a pivot.
// Mark that for plotting
aHPivs[nHHVIdxAfterLastPiv] = 1;
aAddedHPivs[nHHVIdxAfterLastPiv] = 1;

// ...and then rearrange elements in the
// pivot information arrays
for (j=0; j<nHPivs; j++) {
aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs-(j+1)];
aHPivIdxs[nHPivs-j] = aHPivIdxs[nhPivs-(j+1)];
}
aHPivHighs[0] = nHHVAfterLastPiv;
aHPivIdxs[0] = nHHVIdxAfterLastPiv;
nHPivs++;

// -- Test whether to add piv given last piv is high
// AND we have lower highs
}

// -- Second case when last piv is a low piv, higher highs
// Most likely addition is high piv that is a retracement.
// Considering adding a high piv as long as it is higher
} else {

// -- Where I have higher highs,
if (nHHVAfterLastPiv > aHPivHighs[0] AND
(nHHVIdxAfterLastPiv - lastLPIdx - 1) >= nMinBarsBtwPivs
AND nHHVIdxAfterLastPiv != curBar ) {

// -- OK, we'll add this as a pivot.
// Mark it for plotting...
aHPivs[nHHVIdxAfterLastPiv] = 1;
aAddedHPivs[nHHVIdxAfterLastPiv] = 1;

// ...and then rearrange elements in the
// pivot information arrays
for (j=0; j<nHPivs; j++) {
aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs-(j+1)];
aHPivIdxs[nHPivs-j] = aHPivIdxs[nhPivs-(j+1)];
}
aHPivHighs[0] = nHHVAfterLastPiv;
aHPivIdxs[0] = nHHVIdxAfterLastPiv;
nHPivs++;

// -- Test whether to add piv given last piv is high
// AND we have lower highs
}

}

}

// -- If there are at least two of each
}

/* ****************************************
// -- Done with finding pivots
***************************************** */

if (bDraw) {

// -- OK, let's plot the pivots using arrows
PlotShapes(
IIf(aHPivs==1, shapeDownArrow, shapeNone),
colorRed, 0, High, Offset=-15);
PlotShapes(
IIf(aAddedHPivs==1, shapeDownArrow, shapeNone),
colorDarkRed, 0, High, Offset=-15);
PlotShapes(
IIf(aLPivs==1, shapeUpArrow , shapeNone),
colorGreen, 0, Low, Offset=-15);
PlotShapes(
IIf(aAddedLPivs==1, shapeUpArrow , shapeNone),
colorDarkGreen, 0, Low, Offset=-15);
}


/* ****************************************
// -- Done with discovering and plotting pivots
***************************************** */

// -- I'm going to want to look for possible retracement
risk = 0;
profInc = 0;
nLeg0Pts = 0;
nLeg0Bars = 0;
nLeg0Vol = 0;
nLeg1Pts = 0;
nLeg1Bars = 0;
nLeg1Vol = 0;
nLegBarsDiff = 0;
nRtrc0Pts = 0;
nRtrc0Bars = 0;
nRtrc0Vol = 0;
nRtrc1Pts = 0;
nRtrc1Bars = 0;
nRtrc1Vol = 0;

minRtrc = 0;
maxRtrc = 0;
minLine = 0;
maxLine = 0;
triggerLine = 0;
firstProfitLine = 0;
triggerInc = 0;
triggerPrc = 0;
firstProfitPrc = 0;
retrcPrc = 0;
retrcBar = 0;
retrcBarIdx = 0;
retrcRng = 0;
aRetrcPrc = H-H;
aRetrcPrcBars = H-H;
aRetrcClose = C;
retrcClose = 0;

// -- Do TCZ calcs. Arrangement of pivs very specific
// for this setup.
if (nHPivs >= 2 AND
nLPivs >=2 AND
aHPivHighs[0] > aHPivHighs[1] AND
aLPivLows[0] > aLPivLows[1]) {

tcz500 =
(aHPivHighs[0] -
(.5 * (aHPivHighs[0] - aLPivLows[1])));

tcz618 =
(aHPivHighs[0] -
(.618 * (aHPivHighs[0] - aLPivLows[1])));

tcz786 =
(aHPivHighs[0] -
(.786 * (aHPivHighs[0] - aLPivLows[0])));

retrcRng = curBar - aHPivIdxs[0];
aRetrcPrc = LLV(L, retrcRng);
aRetrcPrcBars = LLVBars(L, retrcRng);

retrcPrc = aRetrcPrc[curBar];
retrcBarIdx = curBar - aRetrcPrcBars[curBar];
retrcClose = aRetrcClose[retrcBarIdx];

// -- bTCZLong setup?
bTCZLong = (

// -- Are retracement levels arranged in
// tcz order?

// .500 is above .786 for long setups
tcz500 >= (tcz786 * (1 - tczTolerance))
AND
// .681 is below .786 for long setups
tcz618 <= (tcz786 * (1 + tczTolerance))
AND

// -- Is the low in the tcz range
// -- Is the close >= low of tcz range
// and low <= high of tcz range
retrcClose >= ((1 - retrcTolerance) * tcz618)
AND
retrcPrc <= ((1 + retrcTolerance) * tcz500)
);

// -- risk would be high of signal bar minus low of zone
//risk = 0;

// -- lower highs and lower lows
} else if (nHPivs >= 2 AND nLPivs >=2
AND aHPivHighs[0] < aHPivHighs[1]
AND aLPivLows[0] < aLPivLows[1]) {

tcz500 =
(aHPivHighs[1] -
(.5 * (aHPivHighs[1] - aLPivLows[0])));

tcz618 =
(aHPivHighs[0] -
(.618 * (aHPivHighs[1] - aLPivLows[0])));

tcz786 =
(aHPivHighs[0] -
(.786 * (aHPivHighs[0] - aLPivLows[0])));

retrcRng = curBar - aLPivIdxs[0];
aRetrcPrc = HHV(H, retrcRng);
retrcPrc = aRetrcPrc[curBar];
aRetrcPrcBars = HHVBars(H, retrcRng);
retrcBarIdx = curBar - aRetrcPrcBars[curBar];
retrcClose = aRetrcClose[retrcBarIdx];

bTCZShort = (
// -- Are retracement levels arranged in
// tcz order?

// .500 is below .786 for short setups
tcz500 <= (tcz786 * (1 + tczTolerance))
AND
// .681 is above .786 for short setups
tcz618 >= (tcz786 * (1 - tczTolerance))
AND

// -- Is the close <= high of tcz range
// and high >= low of tcz range
retrcClose <= ((1 + retrcTolerance) * tcz618)
AND
retrcPrc >= ((1 - retrcTolerance) * tcz500)
);

// -- Risk would be top of zone - low of signal bar
//risk = 0;
}

// -- Show zone if present
if (bTCZShort OR bTCZLong) {

// -- Be prepared to see symmetry
if (bTCZShort) {
if (aLPivIdxs[0] > aHPivIdxs[0]) {
// -- Valuable, useful symmetry information
nRtrc0Pts = aHPivHighs[0] - aLPivLows[1];
nRtrc0Bars = aHPivIdxs[0] - aLPivIdxs[1] + 1;
nRtrc1Pts = retrcPrc - aLPivLows[0];
nRtrc1Bars = retrcBarIdx - aLPivIdxs[0] + 1;
} else {
nRtrc0Pts = aHPivHighs[1] - aLPivLows[1];
nRtrc0Bars = aHPivIdxs[1] - aLPivIdxs[1] + 1;
nRtrc1Pts = aHPivHighs[0] - aLPivLows[0];
nRtrc1Bars = aHPivIdxs[0] - aLPivIdxs[0] + 1;
}
} else { // bLongSetup
if (aLPivIdxs[0] > aHPivIdxs[0]) {
nRtrc0Pts = aHPivHighs[0] - aLPivLows[1];
nRtrc0Bars = aHPivIdxs[0] - aLPivIdxs[1] + 1;
nRtrc1Pts = retrcPrc - aLPivLows[0];
nRtrc1Bars = retrcBarIdx - aLPivIdxs[0] + 1;
} else {
nRtrc0Pts = aHPivHighs[1] - aLPivLows[0];
nRtrc0Bars = aLPivIdxs[0] - aHPivIdxs[1] + 1;
nRtrc1Pts = aHPivHighs[0] - aLPivLows[0];
nRtrc1Bars = aLPivIdxs[0] - aHPivIdxs[0] + 1;
}
}

if (bShowTCZ) {
Plot(
LineArray( IIf(bTCZLong, aHPivIdxs[0], aLPivIdxs[0]),
tcz500, curBar, tcz500 , 0),
"tcz500", colorPaleBlue, styleLine);
Plot(
LineArray( IIf(bTCZLong, aHPivIdxs[0], aLPivIdxs[0]),
tcz618, curBar, tcz618, 0),
"tcz618", colorPaleBlue, styleLine);
Plot(
LineArray( IIf(bTCZLong, aHPivIdxs[0], aLPivIdxs[0]),
tcz786, curBar, tcz786, 0),
"tcz786", colorTurquoise, styleLine);
}

// -- if (bShowTCZ)
}

if (bDraw) {
Title = Name() + " (" + StrLeft(FullName(), 10) +
") ATR: " + NumToStr(ATR(1), 4.2) + " ( " +
NumToStr((C - Ref(C, -1)), 4.2) + " / " +
NumToStr((((C - Ref(C, -1)) / Ref(C, -1)) * 100), 2.1) + "% ) " +
WriteVal( SelectedValue( DateTime() ), formatDateTime) +
" \nO: " + Open +
", \nH: " + High +
", \nL: " + Low +
", \nC: " + Close + ", \n" +
// "Risk: " + WriteVal(risk, 2.1) + "% \n" +
"Rtrc 0/1 Pts: " + WriteVal(nRtrc0Pts, 2.1) + "/" +
WriteVal(nRtrc1Pts, 2.1) + " \n" +
"Rtrc 0/1 Bars: " + WriteVal(nRtrc0Bars, 2.0) + "/" +
WriteVal(nRtrc1Bars, 2.0);
}

// **************************
// END INDICATOR CODE
// **************************

//Filter = (bTCZShort OR bTCZLong) AND C > $2 AND C < $20;

Buy = Cover = Filter ;
Sell = Short = aAddedHPivs;
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
AddColumn(C, "Close");
//AddColumn(IIf(bTCZLong, 76, 83), "L/S", formatChar);

////////////////////////
num = Param("trend",3,1,6,1);

FirstVisibleBar = Status( "FirstVisibleBar" );
Lastvisiblebar = Status("LastVisibleBar");

for( b = Firstvisiblebar + num; b <= Lastvisiblebar AND b < BarCount -
num; b++)
{
i = num;
ml = 0;
mu = 0;
while( i > 0 )
{
if (L <= L[b-i] && L <= L[b+i] )
{
ml++;
}
if (H >= H[b-i] && H >= H[b+i] )
{
mu++;
}
i--;
}
if ( ml == num )
{
PlotText("\n***\n",b,L,colorGreen);
}
if ( mu == num )
{
PlotText("***\n",b,H,colorRed);
}
}

_SECTION_BEGIN("Alert Output As Quick Rewiev");
//========================= QUICK VIEW [alert]
=============================
//==============================================================================
// Period at finding changes at stocks price

x =-90;
eDay =-1;
eWeek =-5;
eMonth =-20;
eQTR =-60;
eYEAR =-260;
user =x;
// HLEDAN DLKA

qvCAS = eDay; // There enter lenght period
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// PODMNKY

qvCE =C;
qvHLEDANE =Ref(C,qvCAS);
qvBODY =qvCE-qvHLEDANE;
qvPROCENTA =100*(qvCE-qvHLEDANE)/qvHLEDANE;
// EXPLORE

Filter = C;
AddTextColumn(Name(),"Ticker",2, IIf( MarketID()==0,5,4));
AddColumn(qvHLEDANE,"Prev.Price",1.2);
AddColumn(C,"Price",1.2,IIf(C<1,11,IIf(C>=1 AND C<3,12,IIf(C>=3 AND
C<20,1,0))));
;
AddColumn(qvBODY,"Change in $",1.2,2
,IIf(qvBODY>=0.001,5,IIf(qvBODY==0,9,4 )));
AddColumn(qvPROCENTA,"Change in %",1.2,2
,IIf(qvPROCENTA>=0.001,5,IIf(qvPROCENTA==0,9,4 )));// ALERT

Buy = qvPROCENTA>0;
Cover= qvProcenta==0;
Sell = qvPROCENTA<0;
AlertIf( Buy,"",WriteVal(qvPROCENTA,1.2),1,1,0 );
AlertIf( Sell,"",WriteVal(qvPROCENTA,1.2),2,1,0 );
AlertIf( Cover,"",WriteVal(qvPROCENTA,1.2),0,1,0 );
//

_SECTION_END();

_SECTION_BEGIN("Application of Ehler filter");
// ehler filter based on acclerartion and speed
// x - input
// n - length of FIR
// w - exponential weight of passed acceleration and speed
// f - weighting factor between acceleration and speed
function Ehler1( x, V, n, w,f)
{y=x;
// acceleration + speed
a = x-2*Ref(x,-1) + Ref(x,-2);
s = f*(x-Ref(x,-1));
q=AMA(V*(abs(a)+abs(s))/x,w);

for( i = n-1; i < BarCount; i++ )
{
sy=0;sw=0;
for (j=i-n+1; j<i+1; j++)
{sy = sy + q[j]*x[j];
sw = sw + q[j];
}
y=sy/sw;
}
return y;
}
w=Param("w",0.62,0.05,0.99,0.01);
n=Param("n",8,1,42,1);
f=Param("f",-0.3,-10,10,0.1);
f=10^f;
eh=Ehler1(C,V,n,w,f);
Plot( Close, "Price", colorBlack, styleCandle );
Plot( eh, "Ehler", colorBlack );
Plot( MA(C,n), "MA", colorBlue );

_SECTION_END();

_SECTION_BEGIN("ATR Study");
//* ATR Study: */

Exclude = MA(V,50)<200 ;
MaxGraph = 12;
Graph0 = C;
Graph0Color = 1;
Graph0Style = 64;

BuyOffSet = 18;//Optimize("BuyOffSet",18,15,20,1);
SellOffset = BuyOffSet;//Optimize("SellOffset",2,2,14,2);
RegLength = 5;//Optimize("RegLength",5, 2,11,2);
BuyATRPeriod = 2;//Optimize("BuyATRPeriod",2,2,5,1);
SellATRPeriod = BuyATRPeriod;//Optimize("SellATRPeriod",4,2,11,2);
ATRMultiplier = 1;//Optimize("ATRMultiplier",1,0.7,1.25,.05);


Graph8 = HHV(H-ATRMultiplier*ATR(BuyATRPeriod),BuyOffset); /* RED */
Graph9 = LLV(L+ATRMultiplier*ATR(SellATRPeriod),SellOffset); /* GREEN */

Graph8Style=Graph9Style = 5;
Graph9Color= 5; /* 5 is green */
Graph8Color = 4; /* 4 is red */

ticker = 0.0;//Optimize("Tickerk",0,0,1,0.125);

Buy = Cover = Cross(C,Graph8) AND C>Graph9 AND LinRegSlope(EMA(C,17),2)>0;
Sell = Short = Cross(Graph8,C) AND LinRegSlope(C,2)<0;
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
BuyStop = Ref(Graph8,-1)+ ticker;
BuyPrice = Max(BuyStop,Low);
SellStop= Ref(Graph8,-1); //IIf(Cross(Graph8,C),Ref(Graph8,-1),0);
SellPrice = Min( SellStop, High )- ticker;

//ApplyStop(2,3,Optimize("TrailingStop",15,0,20,5),1);

Filter= (Buy OR Sell) ;
NumColumns = 8;
Column0 = IIf(Buy==1,1,IIf(Sell==1,-1,0) );
Column0Format = 1.0;
Column0Name = "Long/Sell";
Column1 = C;
Column1Name = "Close ";
Column1Format = 1.2;
Column2 = MA(V,17);
Column2Name = "17 Ma Vol ";
Column2Format = 1.0;
Column3 = MA(C,17)/MA(C,50);
Column3Name = "% 17/50 ";
Column3Format = 1.2;
Column3Format = 1.2;
Column4= MA(C,17);
Column4Name="17 C ma";
Column4Format = 1.2;
Column5= MA(C,50);
Column5Name="50 C ma";
Column5Format = 1.2;

Column6= BuyPrice;
Column6Name="BuyPrice";
Column6Format = 1.2;
Column7= SellPrice;
Column7Name="Sellprice";
Column7Format = 1.2;
_SECTION_END();

_SECTION_BEGIN("Bull Fear _ Bear Fear");
// BBFEAR.AFL v 0.001 24/01/2002
// Bull Fear / Bear Fear with DX Trading System
// Developed by Jef
// Published in http://www.nt-tech.com.au/guppy/
// Coded by Marek Chlopek, January 2002


//
********************************************************************************\
********
// INITIALIZATION OF EXPLORATION IN AMIBROKER
//
********************************************************************************\
********
Filter = 1;
NumColumns = 5;
Column0 = O; Column0Name = "O"; Column0Format = 1.2;
Column1 = H; Column1Name = "H"; Column1Format = 1.2;
Column2 = L; Column2Name = "L"; Column2Format = 1.2;
Column3 = C; Column3Name = "C"; Column3Format = 1.2;
Column4 = V; Column4Name = "V"; Column4Format = 1.0;

// END OF "INITIALIZATION OF EXPLORATION IN AMIBROKER" SECTION


//
********************************************************************************\
********
// MAIN CODE
//
********************************************************************************\
********
Opt1 = Optimize("DX Level", 16, 10, 30, 1);
Opt2 = Optimize("Period", 15, 10, 50, 1); // n

n = Opt2;
BullFear = (HHV(High,n) - LLV(High,n))/2 + LLV(High,n);
BearFear = (HHV(Low,n) - LLV(Low,n))/2 + LLV(Low,n);

// Exploration in Amibroker
AddColumn(BullFear, "BullFear", format=1.2);
AddColumn(BearFear, "BearFear", format=1.2);

// END OF "MAIN CODE" SECTION


//
********************************************************************************\
********
// TRADING SYSTEM ENTRY FORMULAS
//
********************************************************************************\
********
Buy = Cover = Cross(Close, BullFear) AND ADX(10) > Opt1;
Short = Sell = Cross(BearFear, Close);

// Exploration in Amibroker
AddColumn(Buy, "Buy", format=1.0);
AddColumn(Short, "Short", format=1.0);
//AddColumn(BuyPrice, "BuyPrice", format=1.2);
//AddColumn(ShortPrice, "ShortPrice", format=1.2);

// END OF "TRADING SYSTEM ENTRY FORMULAS" SECTION


//
********************************************************************************\
********
// TRADING SYSTEM EXIT FORMULAS
//
********************************************************************************\
********
Sell = Short;
Cover = Buy;

// Exploration in Amibroker
AddColumn(Sell, "Sell", format=1.0);
AddColumn(Cover, "Cover", format=1.0);
//AddColumn(SellPrice, "SellPrice", format=1.2);
//AddColumn(CoverPrice, "CoverPrice", format=1.2);

// END OF "TRADING SYSTEM EXIT FORMULAS" SECTION


//
********************************************************************************\
********
// TRADING SYSTEM EXCESSIVE ENTRY/EXIT SIGNALS REMOVING FORMULAS
//
********************************************************************************\
********
Buy = ExRem(Buy, Sell);
Sell = ExRem(Sell, Buy);
Short = ExRem(Short, Cover);
Cover = ExRem(Cover, Short);

// END OF "TRADING SYSTEM EXCESSIVE ENTRY/EXIT SIGNALS REMOVING
FORMULAS" SECTION


//
********************************************************************************\
********
// GRAPHIC PRESENTATION IN AMIBROKER
//
********************************************************************************\
********
MaxGraph = 3;
Graph0 = C; Graph0Style = 4; Graph0Color = 1;
Graph1 = BullFear; Graph1Style = 1; Graph1Color = 5;
Graph2 = BearFear; Graph2Style = 1; Graph2Color = 4;

Title = Name()
+ " - C (Black) = " + WriteVal(Graph0, 1.2)
+ ", BullFear (Green) = " + WriteVal(Graph1, 1.2)
+ ", BearFear (Red) = " + WriteVal(Graph2, 1.2);

// END OF "GRAPHIC PRESENTATION IN AMIBROKER" SECTION


//
********************************************************************************\
********
// END OF CODE (BBFEAR.AFL)
//
********************************************************************************\
********
/**/
_SECTION_END();

_SECTION_BEGIN("Pivot Point and Support and Resistance Points");
//------------------------------------------------------------------------------
//
// Formula Name: Pivot Point and Support and Resistance Points
// Author/Uploader: Anthony Faragasso
// E-mail: ajf1111@...
// Date/Time Added: 2002-04-25 09:04:53
// Origin:
// Keywords:
// Level: basic
// Flags: commentary
// Formula URL: http://www.amibroker.com/library/formula.php?id=186
// Details URL: http://www.amibroker.com/library/detail.php?id=186
//
//------------------------------------------------------------------------------
//
// Guru Commentary, provides Pivot and support and resistance
//
// points for the Next trading day.
//
//------------------------------------------------------------------------------

/* Pivot points and Support and Resistance Points*/
/* for next day trading*/
/* coded by Anthony Faragasso */


MaxGraph =8;

p = (H+L+C)/3;
r1 = (2*p)-L;
s1 = (2*p)-H;
r2 = p +(r1 - s1);
s2 = p -(r2 - s1);

Graph0=p;
Graph1=r1;
Graph2 = s1;
Graph3= r2;
Graph4 = s2;

Graph0Style = Graph1Style = Graph2Style = Graph3Style = Graph4Style =
16 + 8;
Graph0Color = 2;
Graph1Color = Graph2Color = 8;
Graph3Color = Graph4Color = 6;

Graph5 = Close;
Graph5Color = 3;
Graph5Style = 128;
"";
"-------------------------------------------------------------------------------\
-----------------------------";
" PIVOT POINTS AND SUPPORT AND RESISTANCE POINTS ";
"-------------------------------------------------------------------------------\
-----------------------------";
"";
"MARKET BEING EVALUATED : " + Title = Name() + " DATE : " + Date();
"";
"TODAY'S CLOSE WAS : "+"( " +WriteVal(Close,format=1.2)+" )";
"-------------------------------------------------------------------------------\
---------------------------------------";
" ******* THESE POINTS ARE VALID FOR NEXT TRADING DAY ******";
"-------------------------------------------------------------------------------\
----------------------------------------";
"RESISTENCE POINT 2 : ----------------" +WriteVal(Graph3,format=1.2);
"";
"RESISTENCE POINT 1 : ----------------" +WriteVal(Graph1,format=1.2);
"";
" --------------------------------------------------------"+
"("+WriteVal(Graph0,format=1.2)+")" +" PIVOT POINT--------";
"";
"SUPPORT POINT 1 : ----------------------" +WriteVal(Graph2,format=1.2);
"";
"SUPPORT POINT 2 : ----------------------" +WriteVal(Graph4,format=1.2);
_SECTION_END();

_SECTION_BEGIN("Auto Analysis Key Reversal");
//------------------------------------------------------------------------------
//
// Formula Name: Auto Analysis Key Reversal
// Author/Uploader: Larry Lovrencic
// E-mail: lvl@...
// Date/Time Added: 2001-09-04 01:51:44
// Origin:
// Keywords: key reversal automatic analysis
// Level: basic
// Flags: exploration
// Formula URL: http://www.amibroker.com/library/formula.php?id=109
// Details URL: http://www.amibroker.com/library/detail.php?id=109
//
//------------------------------------------------------------------------------
//
// Find Key Reversals using automatic analysis
//
//------------------------------------------------------------------------------

/*Key Reversals Automatic Analysis
by Larry Lovrencic*/

Buy=O<Ref(C,-1) AND L<Ref(L,-1) AND C>Ref(H,-1);
Sell=O>Ref(C,-1) AND H>Ref(H,-1) AND C<Ref(L,-1);
_SECTION_END();

_SECTION_BEGIN("Positive ROC Exploration");
//------------------------------------------------------------------------------
//
// Formula Name: Positive ROC Exploration
// Author/Uploader: Mubashar Virk
// E-mail: mavirk@...
// Date/Time Added: 2006-10-03 14:36:47
// Origin: ROC
// Keywords: ROC
// Level: basic
// Flags: exploration
// Formula URL: http://www.amibroker.com/library/formula.php?id=730
// Details URL: http://www.amibroker.com/library/detail.php?id=730
//
//------------------------------------------------------------------------------
//
// Hi there guys and ladies, I have a Positive ROC exploration for
all you
// tight-traders and beginners. It may give you some good picks for
the next
// day. Needless to say you must study the securities by using William,
// Chaikin, and Bollinger's. Also try to put your own filtration
values for
// ROC and Volume as mine are too tight. May the Profit be with you all.
//
//------------------------------------------------------------------------------

P = ((H + L + C) / 3);
R1 = ((2 * P) - L);
S1 = ((2 * P) - H);
R2 = ((P - S1) + R1);
S2 = (P - (R1 - S1));

Filter = ROC( C, 1 ) > 0.25 AND V > 29999;

AddColumn( V, "Volume",1 );
AddColumn( C, "Close" );
AddColumn( Ref (C, -1), "Last Close");
AddColumn( C - Ref( C, -1), "Change");
AddColumn( ROC( C, 1 ), "ROC" );
AddColumn (RSI(), "RSI",1.2);
AddColumn( r2, "R 2", 1.2);
AddColumn( r1, "R 1", 1.2);
AddColumn( P, "Pivot", 1.2);
AddColumn( S1, "S 1", 1.2);
AddColumn( S2, "S 2", 1.2);
_SECTION_END();

_SECTION_BEGIN("Price Persistency");
//------------------------------------------------------------------------------
//
// Formula Name: Price Persistency
// Author/Uploader: Anthony Faragasso
// E-mail: ajf1111@...
// Date/Time Added: 2002-12-29 18:20:39
// Origin:
// Keywords:
// Level: basic
// Flags: exploration
// Formula URL: http://www.amibroker.com/library/formula.php?id=245
// Details URL: http://www.amibroker.com/library/detail.php?id=245
//
//------------------------------------------------------------------------------
//
// Interested in measuring a short-term Trend ?
//
// Price persistency is the number of days that a market continues to
Close
// either up or down. It's another term for a market run. The
usefulness of
// Price Persistency is based on the theory of runs..It is the idea that,
// given the market has moved in a particular direction for ( n )
days, the
// likelihood it will either continue..or not...can be estimated and
used in a
// profitable trading system....
//
//------------------------------------------------------------------------------

//Price Persistency Exploration
//Interpreted from January,2002, TASC, page 44
//article by Gordon Gustafson on Price Persistency
//Coded by Anthony Faragasso, 12/31/01
//Version 1.00

/*****Bars in the test*****************/
bars=Cum(1);
/**************************************/
Day1up=C > Ref(C,-1);
Day1Dn=C < Ref(C,-1);
/**************************************/

Day2up=C > Ref(C,-1) AND Ref(C,-1) > Ref(C,-2);
Day2Dn=C < Ref(C,-1) AND Ref(C,-1) < Ref(C,-2);

/***********************************************/
Day3up=C > Ref(C,-1) AND Ref(C,-1) > Ref(C,-2) AND Ref(C,-2) > Ref(C,-3);
Day3Dn=C < Ref(C,-1) AND Ref(C,-1) < Ref(C,-2) AND Ref(C,-2) < Ref(C,-3);
/**********************************************/

Day4up=C > Ref(C,-1) AND Ref(C,-1)>Ref(C,-2)AND Ref(C,-2)>Ref(C,-3)
AND Ref(C,-3) > Ref(C,-4);
Day4Dn=C < Ref(C,-1) AND Ref(C,-1)<Ref(C,-2)AND Ref(C,-2)<Ref(C,-3)
AND Ref(C,-3) < Ref(C,-4);
/**********************************************/

Day5up=C > Ref(C,-1) AND Ref(C,-1)>Ref(C,-2)AND Ref(C,-2)>Ref(C,-3)AND
Ref(C,-3) > Ref(C,-4) AND Ref(C,-4) > Ref(C,-5);
Day5Dn=C < Ref(C,-1) AND Ref(C,-1)<Ref(C,-2)AND Ref(C,-2)<Ref(C,-3)AND
Ref(C,-3) < Ref(C,-4) AND Ref(C,-4) < Ref(C,-5);
/************************************************/

Day6up=C > Ref(C,-1) AND Ref(C,-1)> Ref(C,-2)AND
Ref(C,-2)>Ref(C,-3)AND Ref(C,-3) > Ref(C,-4) AND Ref(C,-4) > Ref(C,-5)
AND Ref(C,-5) > Ref(C,-6);
Day6Dn=C < Ref(C,-1) AND Ref(C,-1)< Ref(C,-2)AND Ref(C,-2)<
Ref(C,-3)AND Ref(C,-3) < Ref(C,-4)AND Ref(C,-4) < Ref(C,-5) AND
Ref(C,-5) < Ref(C,-6);
/***********************************************/

Day7up=C > Ref(C,-1) AND Ref(C,-1)> Ref(C,-2)AND
Ref(C,-2)>Ref(C,-3)AND Ref(C,-3) > Ref(C,-4) AND Ref(C,-4) >
Ref(C,-5)AND Ref(C,-5)>Ref(C,-6) AND Ref(C,-6) > Ref(C,-7);
Day7Dn=C < Ref(C,-1) AND Ref(C,-1)< Ref(C,-2)AND Ref(C,-2)<
Ref(C,-3)AND Ref(C,-3) < Ref(C,-4)AND Ref(C,-4) < Ref(C,-5)AND
Ref(C,-5)< Ref(C,-6)AND Ref(C,-6) < Ref(C,-7);
/*********************************************/

Day8up=C > Ref(C,-1) AND Ref(C,-1)> Ref(C,-2)AND
Ref(C,-2)>Ref(C,-3)AND Ref(C,-3) > Ref(C,-4) AND Ref(C,-4) >
Ref(C,-5)AND Ref(C,-5)>Ref(C,-6)AND Ref(C,-6) > Ref(C,-7) AND
Ref(C,-7) > Ref(C,-8);
Day8Dn=C < Ref(C,-1) AND Ref(C,-1)< Ref(C,-2)AND Ref(C,-2)<
Ref(C,-3)AND Ref(C,-3) < Ref(C,-4)AND Ref(C,-4) < Ref(C,-5)AND
Ref(C,-5)< Ref(C,-6)AND Ref(C,-6) < Ref(C,-7)AND Ref(C,-7) < Ref(C,-8);
/**********************************************/

Day9up=C > Ref(C,-1) AND Ref(C,-1)> Ref(C,-2)AND
Ref(C,-2)>Ref(C,-3)AND Ref(C,-3) > Ref(C,-4) AND Ref(C,-4) >
Ref(C,-5)AND Ref(C,-5)>Ref(C,-6)AND Ref(C,-6) > Ref(C,-7)AND Ref(C,-7)
> Ref(C,-8) AND Ref(C,-8) > Ref(C,-9);
Day9Dn=C < Ref(C,-1) AND Ref(C,-1)< Ref(C,-2)AND Ref(C,-2)<
Ref(C,-3)AND Ref(C,-3) < Ref(C,-4)AND Ref(C,-4) < Ref(C,-5)AND
Ref(C,-5)< Ref(C,-6)AND Ref(C,-6) < Ref(C,-7)AND Ref(C,-7) < Ref(C,-8)
AND Ref(C,-8) < Ref(C,-9);
/**********************************************/

Day10up=C > Ref(C,-1) AND Ref(C,-1)> Ref(C,-2)AND
Ref(C,-2)>Ref(C,-3)AND Ref(C,-3) > Ref(C,-4) AND Ref(C,-4) >
Ref(C,-5)AND Ref(C,-5)>Ref(C,-6)AND Ref(C,-6) > Ref(C,-7)AND Ref(C,-7)
> Ref(C,-8)AND Ref(C,-8)> Ref(C,-9) AND Ref(C,-9) > Ref(C,-10);
Day10Dn=C < Ref(C,-1) AND Ref(C,-1)< Ref(C,-2)AND Ref(C,-2)<
Ref(C,-3)AND Ref(C,-3) < Ref(C,-4)AND Ref(C,-4) < Ref(C,-5)AND
Ref(C,-5)< Ref(C,-6)AND Ref(C,-6) < Ref(C,-7)AND Ref(C,-7) <
Ref(C,-8)AND Ref(C,-8) < Ref(C,-9) AND Ref(C,-9) < Ref(C,-10);
/************************************************/

tot1dayUp=LastValue(Cum(Day1up));tot1dayDn=LastValue(Cum(Day1Dn));
tot2dayUp=LastValue(Cum(Day2up));tot2dayDn=LastValue(Cum(Day2Dn));
tot3dayUp=LastValue(Cum(Day3up));tot3dayDn=LastValue(Cum(Day3Dn));
tot4dayUp=LastValue(Cum(Day4up));tot4dayDn=LastValue(Cum(Day4Dn));
tot5dayUp=LastValue(Cum(Day5up));tot5dayDn=LastValue(Cum(Day5Dn));
tot6dayUp=LastValue(Cum(Day6up));tot6dayDn=LastValue(Cum(Day6Dn));
tot7dayUp=LastValue(Cum(Day7up));tot7dayDn=LastValue(Cum(Day7Dn));
tot8dayUp=LastValue(Cum(Day8up));tot8dayDn=LastValue(Cum(Day8Dn));
tot9dayUp=LastValue(Cum(Day9up));tot9dayDn=LastValue(Cum(Day9Dn));
tot10dayUp=LastValue(Cum(Day10up));tot10dayDn=LastValue(Cum(Day10Dn));

/*********Percentages for Up or Down as a % of total bars *************/
totpct1dayup=tot1dayUp/(Cum(1))*100;
totpct1dayDn=tot1dayDn/(Cum(1))*100;
totpct2dayUp=tot2dayUp/(Cum(1))*100;
totpct2dayDn=tot2dayDn/(Cum(1))*100;
totpct3dayUp=tot3dayUp/(Cum(1))*100;
totpct3dayDn=tot3dayDn/(Cum(1))*100;
totpct4dayUp=tot4dayUp/(Cum(1))*100;
totpct4dayDn=tot4dayDn/(Cum(1))*100;
totpct5dayUp=tot5dayUp/(Cum(1))*100;
totpct5dayDn=tot5dayDn/(Cum(1))*100;
totpct6dayUp=tot6dayUp/(Cum(1))*100;
totpct6dayDn=tot6dayDn/(Cum(1))*100;
totpct7dayUp=tot7dayUp/(Cum(1))*100;
totpct7dayDn=tot7dayDn/(Cum(1))*100;
totpct8dayUp=tot8dayUp/(Cum(1))*100;
totpct8dayDn=tot8dayDn/(Cum(1))*100;
totpct9dayUp=tot9dayUp/(Cum(1))*100;
totpct9dayDn=tot9dayDn/(Cum(1))*100;
totpct10dayUp=tot10dayUp/(Cum(1))*100;
totpct10dayDn=tot10dayDn/(Cum(1))*100;

/*******************************************************/
/**********Percent up or down / previous up or
down***********************/

Pct2dayUp=(tot2dayUp/tot1dayup)*100;
Pct2dayDn=(tot2dayDn/tot1dayDn)*100;
pct3dayUp=(tot3dayUp/tot2dayup)*100;
pct3dayDn=(tot3dayDn/tot2dayDn)*100;
pct4dayUp=(tot4dayUp/tot3dayUp)*100;
pct4dayDn=(tot4dayDn/tot3dayDn)*100;
pct5dayUp=(tot5dayUp/tot4dayUp)*100;
pct5dayDn=(tot5dayDn/tot4dayDn)*100;
pct6dayUp=(tot6dayUp/tot5dayUp)*100;
pct6dayDn=(tot6dayDn/tot5dayDn)*100;
pct7dayUp=(tot7dayUp/tot6dayUp)*100;
pct7dayDn=(tot7dayDn/tot6dayDn)*100;
pct8dayUp=(tot8dayUp/tot7dayUp)*100;
pct8dayDn=(tot8dayDn/tot7dayDn)*100;
pct9dayUp=(tot9dayUp/tot8dayUp)*100;
pct9dayDn=(tot9dayDn/tot8dayDn)*100;
pct10dayUp=(tot10dayUp/tot9dayUp)*100;
pct10dayDn=(tot10dayDn/tot9dayDn)*100;


Filter=1;
/***Current State of the Closes******/
stateUp=BarsSince(C < Ref(C,-1));
stateDown=BarsSince(C > Ref(C,-1));
AddColumn(stateUp,"currentUp");
AddColumn(statedown,"CurrentDown");

/***Close is equal to previous close*****/
AddColumn(Cum(C == Ref(C,-1)),"Close==PrevClose",1);

/***Days in a row ,whether up or down ( A Run )********/
//1 day

AddColumn(tot1dayUp,"1dayUp",1);AddColumn(tot1dayDn,"1dayDn",1);AddColumn(0,"%Up\
/PrevUp");AddColumn(0,"%Dn/PrevDn");AddColumn(totpct1dayUp,"%Up[bars]");AddColum\
n(totpct1dayDn,"%Dn[bars]");
//2 days
AddColumn(tot2dayUp,"2dayUp",1);AddColumn(tot2dayDn,"2dayDn",1);AddColumn(pct2da\
yUp,"%Up/prevUp");AddColumn(pct2dayDn,"%Dn/prevDn");AddColumn(totpct2dayUp,"%Up[\
bars]");AddColumn(totpct2dayDn,"%Dn[bars]");
//3 days
AddColumn(tot3dayUp,"3dayUp",1);AddColumn(tot3dayDn,"3dayDn",1);AddColumn(pct3da\
yUp,"%Up/prevUp");AddColumn(pct3dayDn,"%Dn/prevDn");AddColumn(totpct3dayUp,"%Up[\
bars]");AddColumn(totpct3dayDn,"%Dn[bars]");
//4 days
AddColumn(tot4dayUp,"4dayUp",1);AddColumn(tot4dayDn,"4dayDn",1);AddColumn(pct4da\
yup,"%Up/prevUp");AddColumn(pct4dayDn,"%Dn/prevDn");AddColumn(totpct4dayUp,"%Up[\
bars]");AddColumn(totpct4dayDn,"%Dn[bars]");
//5 days
AddColumn(tot5dayUp,"5dayUp",1);AddColumn(tot5dayDn,"5dayDn",1);AddColumn(pct5da\
yup,"%Up/prevUp");AddColumn(pct5dayDn,"%Dn/prevDn");AddColumn(totpct5dayUp,"%Up[\
bars]");AddColumn(totpct5dayDn,"%Dn[bars]");
//6 days
AddColumn(tot6dayUp,"6dayUp",1);AddColumn(tot6dayDn,"6dayDn",1);AddColumn(pct6da\
yUp,"%Up/prevUp");AddColumn(pct6dayDn,"%Dn/prevDn");AddColumn(totpct6dayUp,"%Up[\
bars]");AddColumn(totpct6dayDn,"%Dn[bars]");
//7 days
AddColumn(tot7dayUp,"7dayUp",1);AddColumn(tot7dayDn,"7dayDn",1);AddColumn(pct7da\
yUp,"%Up/prevUp");AddColumn(pct7dayDn,"%Dn/prevDn");AddColumn(totpct7dayUp,"%Up[\
bars]");AddColumn(totpct7dayDn,"%Dn[bars]");
//8 days
AddColumn(tot8dayUp,"8dayUp",1);AddColumn(tot8dayDn,"8dayDn",1);AddColumn(pct8da\
yUp,"%Up/prevUp");AddColumn(pct8dayDn,"%Dn/PrevDn");AddColumn(totpct8dayUp,"%Up[\
bars]");AddColumn(totpct8dayDn,"%Dn[bars]");
//9 days
AddColumn(tot9dayUp,"9dayUp",1);AddColumn(tot9dayDn,"9dayDn",1);AddColumn(pct9da\
yUp,"%Up/prevUp");AddColumn(pct9dayDn,"%Dn/prevDn");AddColumn(totpct9dayUp,"%Up[\
bars]");AddColumn(totpct9dayDn,"%Dn[bars]");
//10 days
AddColumn(tot10dayUp,"10dayUp",1);AddColumn(tot10dayDn,"10dayDn",1);AddColumn(pc\
t10dayUp,"%Up/prevUp");AddColumn(pct10dayDn,"%Dn/prevDn");AddColumn(totpct10dayU\
p,"%Up[bars]");AddColumn(totpct10dayDn,"%Dn[bars]");

AddColumn(bars,"bars",1);
_SECTION_END();

_SECTION_BEGIN("Trend exploration with multiple timeframes");
//------------------------------------------------------------------------------
//
// Formula Name: Trend exploration with multiple timeframes
// Author/Uploader: Marcus Davidsson
// E-mail: davidsson_marcus@...
// Date/Time Added: 2006-09-30 20:31:21
// Origin:
// Keywords: exploration, trend, moving average
// Level: medium
// Flags: exploration
// Formula URL: http://www.amibroker.com/library/formula.php?id=724
// Details URL: http://www.amibroker.com/library/detail.php?id=724
//
//------------------------------------------------------------------------------
//
// I started experimenting with Tradestations Radarscreen
//
// when it struck me that Amibroker have the same function
"Exploration" but
// 100000$ much cheaper.
//
// The formula is quite simple just load it in to Amibroker
//
// and go to automatic analysis and push explore.
//
// The formula will scan multiple moving averages and draw conclusions
// regarding overall trend phase, strenght etc. Enjoy!
//
//------------------------------------------------------------------------------

/*Use daily data! You could use data with
higher time resolution but then you have
to include a timeframe parameters
since 10 periods will become
10 minutes (if you have one Minute data)*/

//////////////////////////////////////////////////////////////

Filter = 1; // all symbols and quotes accepted.
DTL=140; // DTL = Define Trend Long
DTM=60; // DTM = Define Trend Medium
DTS=8; // DTS = Define Trend Short

//////////////////////////////////////////////////////////////

TL=LinRegSlope(MA(C, DTL),2); // TL = Trend Long
TM=LinRegSlope(MA(C, DTM),2); // TM = Trend Medium
TS=LinRegSlope(MA(C, DTS),2); // TS = Trend Short

TLL=IIf(LinRegSlope(MA(C, DTL),2) > 0,True, False);
TMM=IIf(LinRegSlope(MA(C, DTM),2) > 0,True, False);
TSS=IIf(LinRegSlope(MA(C, DTS),2) > 0,True, False);

TLLL=
WriteIf(TL>0 AND TL<0.3,"+",
WriteIf(TL>=0.3 AND TL<0.6 ,"+ +",
WriteIf(TL>=0.6,"+ + +",
WriteIf(TL<0 AND TL>-0.3,"-",
WriteIf(TL<=-0.3 AND TL>-0.6 ,"- -",
WriteIf(TL<=-0.6,"- - -",""))))));

TMMM=
WriteIf(TM>0 AND TM<0.3,"+",
WriteIf(TM>=0.3 AND TM<0.6 ,"+ +",
WriteIf(TM>=0.6,"+ + +",
WriteIf(TM<0 AND TM>-0.3,"-",
WriteIf(TM<=-0.3 AND TM>-0.6 ,"- -",
WriteIf(TM<=-0.6,"- - -",""))))));

TSSS=
WriteIf(TS>0 AND TS<0.3,"+",
WriteIf(TS>=0.3 AND TS<0.6 ,"+ +",
WriteIf(TS>=0.6,"+ + +",
WriteIf(TS<0 AND TS>-0.3,"-",
WriteIf(TS<=-0.3 AND TS>-0.6 ,"- -",
WriteIf(TS<=-0.6,"- - -",""))))));

//////////////////////////////////////////////////////////////

AddTextColumn( TLLL, "MA"+-DTL, 1 , colorDefault,
IIf( TLL==True, colorGreen, colorRed ),-1 );
AddTextColumn( TMMM, "MA"+-DTM, 1 , colorDefault,
IIf( TMM==True, colorGreen, colorRed ),-1 );
AddTextColumn( TSSS, "MA"+-DTS, 1 , colorDefault,
IIf( TSS==True, colorGreen, colorRed ),-1 );

//////////////////////////////////////////////////////////////
message=
WriteIf(TL>=0.3 AND TM>=0.3 AND
TS>=0.3, "Strong Up Trend",
WriteIf(TL<=-0.3 AND TM<=-0.3 AND
TS<=-0.3, "Strong Down Trend",
WriteIf(TLL==True AND TMM==True AND
TSS==True,"Up Trend",
WriteIf(TLL==False AND TMM==False AND
TSS==False,"Down Trend", "No Trend"))));


AddTextColumn( message, "Overall Trend", 1 ,
colorDefault,IIf(TLL==True AND TMM==True AND
TSS==True, colorGreen,
IIf(TLL==False AND TMM==False AND
TSS==False, colorRed, colorDefault )),-1 );

//////////////////////////////////////////////////////////////

x = IIf(Cross(LinRegSlope(MA(C, DTL),2),0) OR
Cross(0, LinRegSlope(MA(C, DTL),2) ), True, False);
y = BarIndex()-ValueWhen(x==True, BarIndex(),1);

Phase=WriteIf(Y>=400,"Mature",WriteIf(Y>100 AND
Y<400, "Progress", WriteIf(Y<=100, "Initial", "")));
//AddColumn( y, "Trend Phase", 1 , colorDefault, -1);
AddTextColumn( Phase, "Trend Phase", 1 , colorDefault, -1);

//////////////////////////////////////////////////////////////
Comments=
WriteIf(Y>=400,"Mature trend with risk of bubble",
WriteIf(y<400 AND TLL==True AND TMM==True AND TSS==True,
"Keep on coming baby $",
WriteIf(y<15 AND TLL==True AND TMM==True AND TSS==True OR
TLL==False AND TMM==False AND TSS==False,
"Are you going to grow up and become a big boy?",
WriteIf(y<400 AND TLL==False AND TMM==False AND TSS==False,
"Keep on coming baby $$",
WriteIf(TLL==True AND TMM==True AND TSS==False OR
TLL==False AND TMM==False AND TSS==True,
"Risk for short term reversal",
WriteIf(TLL==True AND TMM==False AND TSS==True OR
TLL==False AND TMM==True AND TSS==False,
"trading range-avoid",
"live to trade another day"))))));

AddTextColumn( Comments, "Comments", 1 ,
colorDefault,colorDefault,-1 );


//////////////////////////////////////////////////////////////
_SECTION_END();

//------------------------------------------------------------------------------
//
// Formula Name: Auto-Optimization Framework
// Author/Uploader: Dave Merrill
// E-mail:
// Date/Time Added: 2003-10-22 11:58:47
// Origin:
// Keywords: optimize,auto-optimize,backtest
// Level: advanced
// Flags: system,exploration,function
// Formula URL: http://www.amibroker.com/library/formula.php?id=304
// Details URL: http://www.amibroker.com/library/detail.php?id=304
//
//------------------------------------------------------------------------------
//
// this is a backtest framework that continously and automatically
optimizes
// settings for a trading rule you provide. it chooses settings that
measure
// best over a selectable lookback period. this re-optimization can
be done
// every bar, at a user-definable interval, or once at the start of
trading.
// it requires AFL editing to use; instructions are provided.
//
//------------------------------------------------------------------------------

//////////////////////////////////////////////////////////////////////////
// INTRO
//////////////////////////////////////////////////////////////////////////
/*

------------------------------------------------------------------------
Auto-Optimization Framework
v 1.0 (hah) 10/20/03 Dave Merrill (email: dmerrill at usa dot net)
thanks to Tomasz Janeczko for AmiBroker, and everyone in the AmiBroker
groups at Yahoo
comments, suggestions, bug reports etc are most welcome
------------------------------------------------------------------------


WHAT DOES THIS DO?

you've probably done walk-forward optimizations, where you optimize a
trading system over some time period, then trade with those settings
for a while, optimize again at some later date, trade on, etc.. in
fact, this is like real life, unless you assume your initial settings
will be optimal forever and you'll never change them.

this code is a backtest framework that does this continously and
automatically. you provide a trading rule, and it constantly optimizes
the parameters for it, always using the settings that measure best
over a selectable lookback period. this re-optimization can be done
every bar, at a user-definable interval, or once at the start of trading.

one interesting fact is that so far, almost no trading rules I've
tested are very profitable when managed this way, with any framework
settings I've tried. the ones that are are far from universally
successful over various stocks and time frames. I find this very
interesting and quite puzzling, as is well documented on the AB group.
maybe there are bugs that cause this; please let me know about any you
find. maybe the equity evaluation function or other framework
behaviors could be improved; please let me know if you come up with
great changes. maybe it's just not a very effective method; if you can
explain to me why this is so, please do!

and lastly, if you find any hugely profitable uses for this thing, or
other interesting insights from poking around with it, PLEASE let me
in on 'em! :)-)


IMPORTANT USAGE NOTE!!!!

parts of this code belong to the framework itself, and shouldn't be
modified in normal use. other parts you need to edit, to select the
specific trading rule you want to test, and establish settings for how
the framework will operate.

all sections are clearly labelled as editable or not. it's in your
best interest not to change the ones that say NOT EDITABLE, at least
to start with.


DON'T BE IMTIMIDATED

though this is pretty long, it's actually not that complicated, either
to use or in its internals. it's broken down into sections, most of
which you don't need to even look at. if I could hide the no-touchy
bits away I would :)-). also, a lot of it is explanation, not code,
and a lot of the code is a collection of sample trading rules.


INSTRUCTIONS

1) add trading rule(s) you want to test to the CUSTOM TRADING RULES
section. see comments there for how your rules will be called, and
what they need to do. some examples are provided. you can have as many
rules here as you want, but only one can be in use at a time. step 3
below controls which one is active.

2) if those rules require other custom functions, add them to the
CUSTOM UTILITY FUNCTIONS section.

3) edit the framework function BuySellRule(), at the start of the
FRAMEWORK CONFIGURATION section, to call the trading rule you want to
test now.

4) edit the SetParameterRanges() call, next in the FRAMEWORK
CONFIGURATION section, to set the ranges over which you want to test
each of the two optimization parameters. some examples are provided;
comment out all but the one you want to use.

5) if desired, edit the rest of the FRAMEWORK CONFIGURATION section,
to control various aspects of how the framework itself behaves.

6) set the AA range, stock universes you want to test, and other AA
settings, then run a Backtest or Portfolio Backtest.

7) if you want to see the parameters selected and other decisions
being made under the hood, you can Explore instead of backtest. if
desired, edit the EXPLORATION section at the end to change the columns
and bars displayed; some possible extensions and modifications are
provided. note that exploring doesn't actually trade, it's only a
readout for your interest.


GETTING STARTED

this comes set up to run the included trading rule 'BuySellCCI'.
backtest it on, say, the NASDAQ Composite Index, to get an idea of how
it performs (nothing great). explore it to see the parameter values
the framework selected (the best_p1 column). try changing the
parameter ranges tested, as described in the instructions above.

BuySellCCI uses a single parameter, requiring only 40 tests to
optimize. this makes it quicker to run than most two-parameter
systems, which typically need about 40 x 40 tests or more, depending
on the number of values you want to test. performance can definitely
be an issue as the number of tests goes up, and even single parameter
systems can be pretty slow with a large number of stocks.

in the FRAMEWORK CONFIGURATION section, try changing
equity_lookback_bars (how far back performance is evaluated during
optimization) and equity_lookback_frequency (how often optimization is
done). if you want, you can actually optimize these; possible
optimization settings are provided. be cautious in interpreting those
results though. I'd do it more for a quick sense of how things behave
than to necessarily choose the highest performing settings. at the
very least, test a variety of stocks and time frames with any settings
you arrive at, to make sure they're not a fluke.

try some of the other included trading rules, maybe starting with the
MA/EMA/DEMA/TEMA cross rules. hook them up and select parameter ranges
to test as described in the instructions above.

try adding your own trading rules, and experiment with optimization
ranges and equity feedback parameters.

try modifying the performance scoring methods, and adding your own.

*/


//////////////////////////////////////////////////////////////////////////
// FRAMEWORK INIT - NOT EDITABLE
//////////////////////////////////////////////////////////////////////////

Buy = Sell = Short = Cover = 0;
equity_lookback_bars = equity_lookback_frequency =
equity_lookback_smoothing = equity_drawdown_discount_pct = 0;
e = best_e = best_perf_score = best_p1 = best_p2 = 0;
p1_start = p2_start = 2;
p1_end = p2_end = 20;
p1_step = p2_step = 1;
bar_index = BarIndex();


//////////////////////////////////////////////////////////////////////////
// FRAMEWORK FUNCTIONS - NOT EDITABLE
//////////////////////////////////////////////////////////////////////////

function SetParameterRanges(p1_start_p, p1_end_p, p1_step_p,
p2_start_p, p2_end_p, p2_step_p) {
if(p1_step_p != 0) {
p1_start = p1_start_p;
p1_end = p1_end_p;
p1_step = p1_step_p;
} else {
p1_start = p1_end = p1_step = 1;
}
if(p2_step_p != 0) {
p2_start = p2_start_p;
p2_end = p2_end_p;
p2_step = p2_step_p;
} else {
p2_start = p2_end = p2_step = 1;
}
}
function PerformanceScoreMDDDiscount(e, perf_score) {
e_max = Highest(e); // peak equity so far
mdd = Highest(e_max - e); // max drawdown so far
mdd_fraction = Highest(mdd / e_max); // fraction max drawdown is of
Peak Equity
perf_score = perf_score - (perf_score * mdd_fraction *
(equity_drawdown_discount_pct/100)); // reduce score by mdd fraction
scaled by drawdown discount
return perf_score;
}


//////////////////////////////////////////////////////////////////////////
// CUSTOM UTILITY FUNCTIONS - EDITABLE
//////////////////////////////////////////////////////////////////////////

function EMAx(array, period) { // use in place of AB EMA function when
period needs to be an array
return AMA(array, 1 / (period + 2));
}
function StochTransform(array, period) {
return
100*(array-LLV(array,period))/(HHV(array,period)-LLV(array,period));
}
function MeanDev(array, mean, range) {
result = 0;
for(i = LastValue(Highest(range)); i < BarCount; i++) {
result = 0; // the mean is not 'moving' over the range (outside
the loop)
tm = mean;
for(j = 0; j < range; j++) {
result = result + abs(array[i - j] - tm);
}
result = result / range;
}
return result;
}
function CCIx(period) { // use in place of AB CCI function when period
needs to be an array
// CCI = (TypicalPrice - MA(TypicalPrice, 20)) / (.015 x MeanDeviation)
SMATP = MA(Avg, period);
MD = MeanDev(Avg, SMATP, period);
result = (Avg - SMATP) / (0.015 * MD);
return result;
}
function TradeDivergences(array1, array2) {
dir1 = IIf(array1 > Ref(array1, -1), 1, IIf(array1 < Ref(array1, -1),
-1, 0));
dir2 = IIf(array2 > Ref(array2, -1), 1, IIf(array2 < Ref(array2, -1),
-1, 0));
Buy = Cover = (dir1 == 1) AND (dir2 == -1);
Sell = Short = (dir1 == -1) AND (dir2 == 1);
}
function TradeReversalsArith(array, threshold) {
array = last_hi = last_lo = IIf(IsNull(array), -1, array);
last_signal[0] = 0;
Buy = Sell = 0;
for(i = 1; i < BarCount; i++) {
Buy = array >= last_lo[i-1] + threshold AND
last_signal[i-1] != 1 AND array[i-1] != -1;
Sell = array <= last_hi[i-1] - threshold AND
last_signal[i-1] != -1 AND array[i-1] != -1;
last_signal = IIf(Buy, 1, IIf(Sell, -1, last_signal[i-1]));
always_track = array[i-1] == -1 OR Buy OR Sell;
last_lo = IIf(always_track OR array < last_lo[i-1], array,
last_lo[i-1]);
last_hi = IIf(always_track OR array > last_hi[i-1], array,
last_hi[i-1]);
}
Short = Sell;
Cover = Buy;
}


/////////////////////////////////////////////////////////////////////////
// CUSTOM TRADING RULES - EDITABLE
/////////////////////////////////////////////////////////////////////////

/*

this is where you put the various trading rules you may want to test.
only one rule can be in use at a time. select which one actually gets
used by editing the framework function BuySellRule(), at the start of
the FRAMEWORK CONFIGURATION section.

all rules should set buy, sell, short and cover, in response to the
parameters passed to it and whatever logic you want.

your rule will be passed 3 parameters:
dynamic (true/false) : true if parameters are arrays, not just single
values; see ABOUT THE 'DYNAMIC' PARAMETER, below
p1 (number/array) : first optimization parameter
p2 (number/array) : second optimization parameter

p1 and p2 are the values being optimized on. trading rules can use
them for any optimizable purpose, MA periods or crossover thresholds
for example.

during optimization, the rule in use will be called multiple times,
once with each combination of p1 and p2 being tested. at this time, p1
and p2 will be simple numeric values, not arrays. once optimal
settings have been determined for every bar, the rule will be called
once more, to generate actual trading signals. this time, p1 and p2
will be arrays, each bar containing the optimal p1 and p2 value for
that bar.

ABOUT THE 'DYNAMIC' PARAMETER

not all AB functions can take arrays as inputs. for example, MA, TEMA
and DEMA can use an array as their period, but EMA can't. it's usually
possible to code an equivalent that can in AFL, but it may be slower,
or in a DLL, which I didn't want to depend on for this. this speed
difference can be big, since the trading rule is called many times
during optimization.

if desired, your rule can include both slower array-capable code for
use in the final signal-generation phase, and faster,
non-array-capable code for use during the many optimization tries. if
you do this, use the 'dynamic' parameter to know which to call. see
BuySellCCI, below, for an example.

*/

function BuySellEMACrossPrice(dynamic, p1, p2) { // p1 = EMA period
m = EMAx(C, p1);
Buy = Cover = Cross(C, m);
Sell = Short = Cross(m, C);
}
function BuySellMACross(dynamic, p1, p2) { // p1 = MA1 period, p2 =
MA2 period increase over MA1 period
m1 = MA(C, p1);
m2 = MA(C, p1 + p2);
Buy = Cover = Cross(m1, m2);
Sell = Short = Cross(m2, m1);
}
function BuySellEMACross(dynamic, p1, p2) { // p1 = MA1 period, p2 =
MA2 period increase over MA1 period
m1 = EMAx(C, p1);
m2 = EMAx(C, p2);
Buy = Cover = Cross(m1, m2);
Sell = Short = Cross(m2, m1);
}
function BuySellDEMACross(dynamic, p1, p2) { // p1 = MA1 period, p2 =
MA2 period increase over MA1 period
m1 = DEMA(C, p1);
m2 = DEMA(C, p1 + p2);
Buy = Cover = Cross(m1, m2);
Sell = Short = Cross(m2, m1);
}
function BuySellTEMACross(dynamic, p1, p2) { // p1 = MA1 period, p2 =
MA2 period increase over MA1 period
m1 = TEMA(C, p1);
m2 = TEMA(C, p1 + p2);
Buy = Cover = Cross(m1, m2);
Sell = Short = Cross(m2, m1);
//short = cover = 0; // at least sometimes, short is perf_scoreable,
but only barely, so RAR drops
}
function BuySellCCI(dynamic, p1, p2) { // p1 = CCI period; fixed
threshold of zero
if(dynamic) {
cc = CCIx(p1);
} else {
cc = CCI(p1);
}
Buy = Cover = Cross(cc, 0);
Sell = Short = Cross(0, cc);
}
function BuySellCCI2(dynamic, p1, p2) { // p1 = CCI period; moveable
symetrical thresholds, mirrored above AND below zero for long AND Short
if(dynamic) {
cc = CCIx(p1);
} else {
cc = CCI(p1);
}
Buy = Cover = Cross(cc, p2);
Sell = Short = Cross(-p2, cc);
}
function BuySellCCI3(dynamic, p1, p2) { // p1 = CCI period; moveable
absolute threshold, same numeric level for long AND Short
if(dynamic) {
cc = CCIx(p1);
} else {
cc = CCI(p1);
}
Buy = Cover = Cross(cc, p2);
Sell = Short = Cross(p2, cc);
}
function BuySellStochCCI(dynamic, p1, p2) { // p1 = CCI period
cc = CCIx(period);
cc = StochTransform(cc, period);
Buy = Cover = Cross(cc, 50);
Sell = Short = Cross(50, cc);
}
function BuySellStoch(dynamic, p1, p2) { // p1 = range, p2 = K & D
smoothing
if(dynamic) {
stoK =
MA(100*(C-LLV(L,best_p1))/(HHV(H,best_p1)-LLV(L,best_p1)),best_p2);
stoD = MA(stoK, best_p2);
} else {
stoD = StochD(p1, p2, p2);
stoK = StochK(p1, p2);
}
sig = stoD - stoK;
Buy = Cover = Cross(sig, 0);;
Sell = Short = Cross(0, sig);
}
function BuySellStochDivergence(dynamic, p1, p2) { // p1 = range, p2 =
K & D smoothing
if(dynamic) {
stoK =
MA(100*(C-LLV(L,best_p1))/(HHV(H,best_p1)-LLV(L,best_p1)),best_p2);
stoD = MA(stoK, best_p2);
} else {
stoD = StochD(p1, p2, p2);
stoK = StochK(p1, p2);
}
TradeDivergences(stoD, stoK);
}
function BuySellROC(dynamic, p1, p2) { // p1 = range, p2 = threshold
sig = ROC(MA(C, p1), 1);
Buy = Cover = Cross(sig, p2);
Sell = Short = Cross(p2, sig);
}
function BuySellDemandIndex(dynamic, p1, p2) { // p1 = DI & TEMA
period, p2 = EMA period
period = 21; //p1; // 21
period2 = 30; //p2; // 30
A=(H+L+2*C);
B=EMAx((HHV(H,2)-LLV(L,2)),21);
BuyP= /*{BuyPower}*/
V/EMAx(V,21) * ((A>=Ref(A,-1)) +(A<Ref(A,-1)) / exp((0.375 *
(A+Ref(A,-1)) /B ) *(Ref(A,-1)-A) / A));
SellP = /*{SellPressure}*/
V/EMAx(V,21) * ((A<=Ref(A,-1)) + (A>Ref(A,-1)) / exp((0.375 *
(A+Ref(A,-1)) / B ) * (A-Ref(A,-1)) / Ref(A,-1)));
mabp=EMAx(BuyP,period);
masp=EMAx(SellP,period); // {smooth Selling Pressure}
divsor=IIf(mabp>masp,mabp,masp); // {BP:SP ratio}
divend=IIf(mabp<masp,mabp,masp); // {biggest=divisor}
var2=1-(divend/divsor); // {adjust ratio to plot in}
var3=IIf((masp>mabp), -var2, var2); // {range -100 to 100}
var4=var3*100;
DI = var4;
DI_TEMA = TEMA(DI, period);
DI_TEMA_MA = EMAx(DI_TEMA, period2);
Buy = Cover = Cross(DI_TEMA, 0); // try various crosses of DI,
DI_TEMA, DI_TEMA_MA AND zero
Sell = Short = Cross(0, DI_TEMA);
Short = Cover = 0; // improves performance sometimes
}
function BuySellMTIReversals(dyanamic, p1, p2) { // p1 = reversal
threshold; .12 for San Diego Wave timing
// requires MTI in ticker !!MTI;
// note that MTI data doesn't go back very far, and was calculated
differently before some time in early '00
// adjust test period and keep results in perspective accordingly
MTI = Foreign("!!MTI", "C", True);
TradeReversalsArith(MTI, p1);
}


//////////////////////////////////////////////////////////////////////////
// PERFORMANCE SCORING METHODS - EDITABLE
//////////////////////////////////////////////////////////////////////////
// one of these functions will be called to evaluate the performance
of each parameter combination tried
// select the one that will be active by editing the framework
function PerformanceScore
// it's at the beginning of EQUITY FEEDBACK BEHAVIOR, in the
FRAMEWORK CONFIGURATION section
// you can edit these or add your own
function PerformanceScore1() { // profit per bar
e = Equity(0, 0);
if(equity_lookback_bars == 0) { // test all performance to date
e_ref = e[0];
} else { // test performance back spec'd number of bars
e_ref = Ref(e, -equity_lookback_bars);
}
perf_score = (e - e_ref) / e_ref; // growth over lookback period
perf_score = MA(perf_score, IIf(equity_lookback_smoothing >= 1,
equity_lookback_smoothing, 1)) * 100; // smoothed pct
perf_score = perf_score * 100 / IIf(equity_lookback_bars == 0,
Cum(1), equity_lookback_bars); // per 100 bars
perf_score = PerformanceScoreMDDDiscount(e, perf_score);
return perf_score;
}
function PerformanceScore2() { // net of right-sided bars per bar
e = Equity(0, 0);
e_ref = Ref(e, -1);
e_delta = e - e_ref;
last_buy_bar = ValueWhen(Buy, bar_index);
last_sell_bar = ValueWhen(Sell, bar_index);
last_short_bar = ValueWhen(Short, bar_index);
last_cover_bar = ValueWhen(Cover, bar_index);
entry_status = IIf(last_buy_bar > last_sell_bar, 1,
IIf(last_short_bar > last_cover_bar, -1, 0));
bar_is_right = IIf(entry_status == 1, e_delta > 0, IIf(entry_status
== -1, e_delta < 0, 0));
bar_is_wrong = IIf(entry_status == 1, e_delta < 0, IIf(entry_status
== -1, e_delta < 0, 0));
if(equity_lookback_bars == 0) { // test all performance to date
bars_right = Cum(bar_is_right); // bars long and rising or short and
falling
bars_wrong = Cum(bar_is_wrong); // bars long and falling or short
AND rising
} else { // test performance back spec'd number of bars
bars_right = Sum(bar_is_right, equity_lookback_bars); // bars long
AND rising OR Short AND falling
bars_wrong = Sum(bar_is_wrong, equity_lookback_bars); // bars long
AND falling OR Short AND rising
}
perf_score = (bars_right - bars_wrong) / bar_index; // net bars
right per bar
perf_score = MA(perf_score, IIf(equity_lookback_smoothing >= 1,
equity_lookback_smoothing, 1)) * 100; // smoothed pct
perf_score = PerformanceScoreMDDDiscount(e, perf_score);
return perf_score;
}


//////////////////////////////////////////////////////////////////////////
// FRAMEWORK CONFIGURATION - EDITABLE
//////////////////////////////////////////////////////////////////////////

// TRADING RULE: EDIT TO CALL THE CUSTOM RULE YOU WANT TO TEST
function BuySellRule(dynamic, p1, p2) {
BuySellCCI(dynamic, p1, p2);
}

// PARAMETER RANGES TO TEST
// each of the two parameters, p1 and p2, has start, end and step
values that control the values tried during optimization
// you'll probably need to adjust these to the ranges that are useful
for the active trading rule
// to set them all at once, call SetParameterRanges(p1_start, p1_end,
p1_step, p2_start, p2_end, p2_step)
// if your rule doesn't use p2, use p2_step = 0 to speed up optimization
// some typical settings are provided below; uncomment and edit the
one you want to use
SetParameterRanges(2, 40, 1, 1, 1, 0); // basic single parameter range
//SetParameterRanges(2, 40, 1, 2, 40, 1); // basic two parameter ranges
//SetParameterRanges(2, 40, 1, 0, 100, 10); // 2-40 period, 0-100
threshold
//SetParameterRanges(.01, .5, .01, 1, 1, 0); // for MTI reversals

// EQUITY FEEDBACK BEHAVIOR
// parameter values selected by the framework are the ones that
performed best over a specified time in the past
// this section controls how this is done
// two performance metrics are provided, and you can add your own
// only one can be active at a time
// edit the function PerformanceScore to call the one you want to use
// equity_lookback_bars controls how many bars worth of history will
be examined
// 0 = examine all performance to date
// equity_lookback_frequency is the number of bars between optimizations
// 0 = optimize every bar, -1 = first bar only
// equity_lookback_smoothing applies an MA to the equity curve before
picking optimum values
// minimizes the effect of daily price fluctuations on optimization;
only matters much when pretty High, multiple months
// equity_drawdown_discount_pct reduces the performance score by the
maximum drawdown amount * this percentage
// at zero, MDD has no effect; at 100, 20% MDD reduces the score by 20%
function PerformanceScore() {
return PerformanceScore2();
}
equity_lookback_bars = 0; // 126 * Optimize("Equity Lookback", 0, 0,
5*2, 1);
equity_lookback_frequency = 0; //21 * Optimize("Equity Lookback
Frequency", 0, 0, 12*2, 1);
equity_lookback_smoothing = 0; //21*6;
equity_drawdown_discount_pct = 0; //100;

// TRADE ENTRY RESTRICTIONS
// edit to set minimum price, volume and length of history required to
enter a trade
// note that the volume requirement is ignored for mutual funds and
tickers starting w '!' OR '~'
has_min_vol = (MA(V, 100) > 1000000) OR True;
is_min_price_long = C > 1;
is_min_price_short = C > 5;
has_min_history = bar_index >= (252 * 3); // require 3 years of
history before trading

// PORTFOLIO MANAGEMENT
// these settings aren't well tested :)-)
max_positions = 0; // number of simultaneous positions to hold; zero
for no portfolio management
use_ranking = False; // true to rank simultaneous entry signals by
backtest return in portfolio mode


//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////// FRAMEWORK ENGINE - NOT EDITABLE //////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////

// tweak volume entry requirements for things with no volume data
has_min_vol = has_min_vol
OR (MarketID(1) == "Mutual funds") OR (StrLeft(Name(), 1) == "!") OR
(StrLeft(Name(), 1) == "~");

// loop through requested parameter ranges, calculating signals and
choosing parameter values that score best
first_bar_index = ValueWhen(Status("FirstBarInRange"), bar_index);
for(p1 = p1_start; p1 <= p1_end; p1 = p1 + p1_step) {
for(p2 = p2_start; p2 <= p2_end; p2 = p2 + p2_step) {

// calc buy/sell/short/cover w those settings
BuySellRule(False, p1, p2);

// apply overall entry restrictions
Buy = Buy AND is_min_price_long AND has_min_vol;
Short = Short AND is_min_price_short AND has_min_vol;

// calc performance score w those settings
perf_score = PerformanceScore();

// track settings w best performance and resulting equity
if(equity_lookback_frequency == 0) {
optimize_this_bar = 1;
} else if(equity_lookback_frequency == -1) {
optimize_this_bar = Status("FirstBarInRange");
} else {
optimize_this_bar = (first_bar_index - bar_index) %
equity_lookback_frequency == 0;
}
is_new_best = IIf(optimize_this_bar AND perf_score >
best_perf_score, 1, 0);
best_perf_score = IIf(is_new_best, perf_score, best_perf_score);
best_p1 = IIf(is_new_best, p1, best_p1);
best_p2 = IIf(is_new_best, p2, best_p2);
best_e = IIf(is_new_best, e, best_e);
best_perf_score = IIf(optimize_this_bar, best_perf_score,
ValueWhen(optimize_this_bar, best_perf_score));
best_p1 = IIf(optimize_this_bar, best_p1,
ValueWhen(optimize_this_bar, best_p1));
best_p2 = IIf(optimize_this_bar, best_p2,
ValueWhen(optimize_this_bar, best_p2));
best_e = IIf(optimize_this_bar, best_e, ValueWhen(optimize_this_bar,
best_e));
}
}

// calc real buy/sell/short/cover w optimal settings
BuySellRule(True, best_p1, best_p2);

// apply overall entry restrictions
Buy = Buy AND is_min_price_long AND has_min_vol AND has_min_history;
Short = Short AND is_min_price_short AND has_min_vol AND has_min_history;

// don't enter, exit now, unless lookback was perf_scoreable
Buy = Buy AND best_perf_score > 0;
Short = Short AND best_perf_score > 0;
Sell = Sell OR best_perf_score <= 0;
Cover = Cover OR best_perf_score <= 0;

// kill sells and covers before respective entries; cleans up exploration
Sell = Sell AND Cum(Buy);
Cover = Cover AND Cum(Short);

// kill dupe signals, for exploration
Sell = ExRem(Sell, Buy);
Cover = ExRem(Cover, Short);

// set PostionSize and PositionScore if requested
if(max_positions > 0) {
PositionSize = -((100 / max_positions) - 1);
}
if(use_ranking) {
PositionScore = IIf(Buy, best_perf_score, IIf(Short,
-best_perf_score, 0));
}


//////////////////////////////////////////////////////////////////////////
// EXPLORATION - EDITABLE IF YOU WANT, BUT USUALLY NOT NECCESSARY
//////////////////////////////////////////////////////////////////////////

Filter = Buy OR Sell OR Short OR Cover;
//filter = optimize_this_bar; // to show every bar where optimization
was done
//filter = filter or Ref(filter, 1); // to show the day before each
Signal too
//filter = 1; //to show all bars

AddColumn(bar_index, "Bar Index", 1.0);
AddColumn(Buy, "buy", 1);
AddColumn(Sell, "sell", 1);
AddColumn(Short, "short", 1);
AddColumn(Cover, "cover", 1);
AddColumn(optimize_this_bar, "optimize_this_bar", 1.0);
AddColumn(best_perf_score, "best_perf_score", 1.4);
AddColumn(best_e, "best_e", 1.0);
AddColumn(((ValueWhen(Filter OR Status("LastBarInTest"), best_e, 0) -
best_e) / best_e) * 100, "best_e_pct_change", 1.2);
AddColumn(best_p1, "best_p1");
AddColumn(best_p2, "best_p2");
AddColumn(BarsSince(best_p1 != Ref(best_p1, -1) OR best_p2 !=
Ref(best_p2, -1)) + 1, "bars_since_settings", 1.0);
AddColumn(ValueWhen(Filter OR Status("LastBarInTest"), bar_index, 0) -
bar_index, "bars", 1.0);
AddColumn(has_min_history, "has_min_vol", 1.0);
AddColumn(has_min_history, "has_min_history", 1.0);
AddColumn(C, "price");
AddColumn(equity_lookback_bars, "equity_lookback_bars");
AddColumn(equity_lookback_frequency, "equity_lookback_frequency");

// enable next lines to see more optimization details; note that only
the last parameter set tried will show
//AddColumn(e, "e");
//AddColumn(e_ref, "e_ref");
//AddColumn(perf_score, "perf_score", 1.4);

// TRADING THE MACD Ver 1.0 by Karthik Marar. AFL provided as a part
of the Discussion on trading the MACD in the Thread " Experiments in
Technical Analysis"
// Afl provided to learn and get an insight for trading using the
MACD. The AFL can be freely distributed except for commercial purpose.

_SECTION_BEGIN("MACD optimize");
//------------------------------------------------------------------------------
//
// Formula Name: MACD optimize
// Author/Uploader: Grayesso
// E-mail: grayesso@...
// Date/Time Added: 2003-12-10 14:12:39
// Origin:
// Keywords:
// Level: advanced
// Flags: showemail,function
// Formula URL: http://www.amibroker.com/library/formula.php?id=313
// Details URL: http://www.amibroker.com/library/detail.php?id=313
//
//------------------------------------------------------------------------------
//
// MACD (12,26,9 - 5,34,5 <==> by default - by Bill Williams
//
//------------------------------------------------------------------------------

/* Project: AmiBroker
** File: MACD_optimize.afl
** Title: MACD Optimize for Automatic Analysis (English)
** Date: Dec 10th, 2003
** Written by: Grayesso (grayesso dog rambler dot ru)
*/

/*After entering the formula just click on Optimize button in
"Automatic Analysis" window. AmiBroker will start testing all possible
combinations of optimization variables and report the results in the
list. After optimization is done the list of result is presented
sorted by the Net % profit. As you can sort the results by any column
in the result list it is easy to get the optimal values of parameters
for the lowest drawdown, lowest number of trades, largest profit
factor, lowest market exposure and highest risk adjusted annual %
return. The last three columns of result list present the values of
optimization variables for given test.


When you decide which combination of parameters suits your needs the
best all you need to do is to replace the default values in optimize
function calls with the optimal values. At current stage you need to
type them by hand in the formula edit window (the second parameter of
optimize function call). */

/* MACD (12,26,9 - 5,34,5 <==> by default - by Bill Williams */

/* variable = optimize( "Description", default, min, max, step ) */


fa = Optimize( "MACD Fast", 5, 5, 12, 1 );
sa = Optimize("MACD Slow", 34, 26, 34, 1 );
sig = Optimize( "Signal average", 5, 5, 9, 1 );

Buy = Cross( MACD( fa, sa ) , Signal( fa, sa, sig ) );
Sell = Cross( Signal( fa, sa, sig ), MACD( fa, sa ) );
_SECTION_END();


_SECTION_BEGIN("Randomize");
//------------------------------------------------------------------------------
//
// Formula Name: Randomize()
// Author/Uploader: Antonio Marra
// E-mail: ant.marra@...
// Date/Time Added: 2004-07-20 06:40:47
// Origin:
// Keywords: Random interval
// Level: basic
// Flags: showemail,function
// Formula URL: http://www.amibroker.com/library/formula.php?id=365
// Details URL: http://www.amibroker.com/library/detail.php?id=365
//
//------------------------------------------------------------------------------
//
// This function will generate random numbers included in a given numeric
// interval.
//
//------------------------------------------------------------------------------

/*______________________________________________________________________________\
___________


SYNTAX:
Randomize(a,b)

PURPOSE:
This function will generate random numbers included in a
given numeric interval.

HOW TO USE:
Copy this file in your include directory or append it to
another file that You
use as "functions database".
"a" is the lowest value, "b" is the highest value.

EXAMPLE:
1. if you want to generate random between 1 e 100 (with
decimal values):

RandomNumber = Randomize(1,100);

2. if you want to generate random between 1 e 100 (with only
integer values):

RandomNumber = int( Randomize(1,100) ) ;


________________________________________________________________________________\
________


*/


function Randomize(a,b)
{
result = Random()*(b-a)+a;
return result;
}
_SECTION_END();

_SECTION_BEGIN("sort function");
//------------------------------------------------------------------------------
//
// Formula Name: sort function
// Author/Uploader: walt schwarz
// E-mail: wschwarz@...
// Date/Time Added: 2003-05-26 17:11:16
// Origin:
// Keywords: sort array function
// Level: medium
// Flags: showemail,function
// Formula URL: http://www.amibroker.com/library/formula.php?id=283
// Details URL: http://www.amibroker.com/library/detail.php?id=283
//
//------------------------------------------------------------------------------
//
// will return the passed array in sorted order
//
//------------------------------------------------------------------------------

function sort(inlist)

{

//sort inlist

temp=0;

for(i = BarCount-1; i>=0; i--)

{

for (j = 1; j <= i; j++)

{

if (inlist[j-1] > inlist[j])

{

temp = inlist[j-1];

inlist[j-1] = inlist[j];

inlist[j] = temp;

}

}

}

//inlist now sorted

return inlist;

}

_SECTION_END();

SetCustomBacktestProc("");
if( Status("action") == actionPortfolio )
{
bo = GetBacktesterObject();
bo.Backtest();
Buy = 0;
Sell= 0;
PosTradePos = 0;
NegTradePos = 0;
}

_SECTION_BEGIN("EOD v1.1 Mod");
#include <T3_include.AFL>;
//WAD
TrueRangeHigh=Max( Ref(Close,-1), High );
TrueRangeLow=Min( Ref(Close,-1), Low );
WAD = Cum(IIf(C > Ref(C,-1),C-TrueRangeLow, IIf(C <
Ref(C,-1),C-TrueRangeHigh,0)));
wadup = WAD > EMA (WAD,20);
waddn = WAD < EMA (WAd,20);
wadbl = Cross(WAD, EMA(WAD,20));
wadbr = Cross(EMA(WAD,20), WAD);
wad_status= WriteIf(wadup, "Bullish Zone", WriteIf(waddn, "Bearish
Zone", WriteIf(wadbl, "Bullish Cross", WriteIf(wadbr, "Bearish Cross",
"Zilch"))));
wad_Col=IIf(wadup OR wadbl, colorGreen, IIf(waddn OR wadbr, colorRed,
colorLightGrey));


//Trend Strength
up = ADX(10) > 20;
down = ADX(10) < 20;
choppy = ADX(10) < PDI(10) AND ADX(10) < MDI(10);
adx_status= WriteIf(up, "Strong Trend", WriteIf(down, "Weak Trend",
WriteIf( choppy, "Choppy", "Zilch")));
adx_Col=IIf(up, colorGreen, IIf(down, colorRed, IIf(Choppy, colorPink,
colorLightGrey)));

// Coppock
r1=ROC(C,14);
r2=ROC(C,11);
ck=EMA((r1+r2),10);
upt=IIf(ck>0 AND ROC(ck,1)>0,ck,0);
ups=IIf(ck>0 AND ROC(ck,1)<0,ck,0);
downs=IIf(ck<0 AND ROC(ck,1)>0,ck,0);
down=IIf(ck<0 AND ROC(ck,1)<0,ck,0);
cop_status= WriteIf(upt, "Uptrend", WriteIf(ups, "Uptrend Sidways",
WriteIf(downs, "Downtrend Sideways", WriteIf(down, "Downtrend",
"Zilch"))));
cop_Col=IIf(upt, colorDarkGreen, IIf(ups, colorGreen, IIf(downs,
colorOrange, IIf(down, colorRed, colorLightGrey))));

//Initial Buy Signal
Ibuy = Cross(RSI(14), EMA(RSI(14),9));
Isell = Cross(EMA(RSI(14),9), RSI(14));
Ibuy = ExRem(Ibuy, ISell);
Isell = ExRem(ISell, Ibuy);
BlRSI = RSI(14) > EMA(RSI(14),9);
BrRSI = RSI(14) < EMA(RSI(14),9);
Ibuy_status= WriteIf(Ibuy, "Buy Warning", WriteIf(Isell, "Sell
Warning", WriteIf(BlRSI, "Bullish Zone", WriteIf(BrRSI, "Breaish
Zone", "Zilch"))));
I_Col=IIf(Ibuy OR BlRSI, colorGreen, IIf(Isell OR BrRSI, colorRed,
colorLightGrey));

//BB Breakout
bbk2 = Cross(RSI(14),30) AND
RSI(14) > Ref(RSI(14),-1);
bbk_status= WriteIf(bbk2, "Break RSI", "Zilch" );
bbk_Col=IIf(bbk2, colorGreen, colorLightGrey);


//Price Smoothing
TBuy = Cross (T3(C,3), T3(C,5));
TSell = Cross (T3(C,5), T3(C,3));
TBuy = ExRem(TBuy, TSell);
TSell = ExRem(TSell, TBuy);
Tbuy_status= WriteIf(TBuy, "Buy", WriteIf(TSell, "Sell", "Zilch"));
T_Col=IIf(TBuy, colorGreen, IIf(TSell, colorRed, colorLightGrey));

//Guppy MMA
P1 = EMA(C,3);
P2 = EMA(C,5);
P3 = EMA(C,8);
P4 = EMA(C,10);
P5 = EMA(C,12);
P6 = EMA(C,15);
P7 = EMA(C,30);
P8 = EMA(C,35);
P9 = EMA(C,40);
P10 = EMA(C,45);
P11 = EMA(C,50);
P12 = EMA(C,55);
P13 = EMA(C,60);
GBuy = Cross (P1,P8);
GSell = Cross(P8,P1);
GBuy = ExRem(GBuy, GSell);
GSell = ExRem(GSell, GBuy);
Gbuy_status= WriteIf(GBuy, "Buy", WriteIf(GSell, "Sell", "Zilch"));
G_Col=IIf(GBuy, colorGreen, IIf(GSell, colorRed, colorLightGrey));

//EMA-9
MAbuy = Cross(C, EMA(C,9));
MAsell= Cross(EMA(C,9),C);
MAbuy = ExRem(MAbuy, MAsell);
MAsell = ExRem(MAsell, MAbuy);
MA1 = C > EMA(C,9);
MA11 = C < EMA(C,9);
MA_status= WriteIf(MAbuy, "Buy", WriteIf(MAsell, "Sell", WriteIf(MA1,
"Bullish", WriteIf(MA11, "Bearish","Zilch"))));
MA_Col=IIf(MAbuy OR MA1, colorGreen, IIf(MAsell OR MA11, colorRed,
colorLightGrey));

//EMA-20
MA2buy = Cross(C, EMA(C,20));
MA2sell= Cross(EMA(C,20),C);
MA2buy = ExRem(MA2buy, MA2sell);
MA2sell = ExRem(MA2sell, MA2buy);
MA2 = C > EMA(C,20);
MA22 = C < EMA(C,20);
MA2_status= WriteIf(MA2buy, "Buy", WriteIf(MA2sell, "Sell",
WriteIf(MA2, "Bullish", WriteIf(MA22, "Bearish","Zilch"))));
MA2_Col=IIf(MA2buy OR MA2, colorGreen, IIf(MA2sell OR MA22, colorRed,
colorLightGrey));

//EMA-9 x 20
MA3buy = Cross(EMA(C,9), EMA(C,20));
MA3sell= Cross(EMA(C,20),EMA(C,9));
MA3buy = ExRem(MA3buy, MA3sell);
MA3sell = ExRem(MA3sell, MA3buy);
MA3 = EMA(C,9) > EMA(C,20);
MA33 = EMA(C,9) < EMA(C,20);
MA3_status= WriteIf(MA3buy, "Buy", WriteIf(MA3sell, "Sell",
WriteIf(MA3, "Bullish", WriteIf(MA33, "Bearish","Zilch"))));
MA3_Col=IIf(MA3buy OR MA3, colorGreen, IIf(MA3sell OR MA33, colorRed,
colorLightGrey));

//Midterm Bullish or Bearish
mBull = C > EMA(C,50);
mBear= C < EMA(C,50);
mt_status= WriteIf(mBull, "Bullish", WriteIf(mBear, "Bearish", "Zilch"));
mt_Col=IIf(mBull, colorGreen, IIf(mbear, colorRed, colorLightGrey));

//Longterm Bullish or Bearish
Bull = C > EMA(C,200);
Bear= C < EMA(C,200);
lt_status= WriteIf(Bull, "Bullish", WriteIf(Bear, "Bearish", "Zilch"));
lt_Col=IIf(Bull, colorGreen, IIf(bear, colorRed, colorLightGrey));

//Long-term Price Trend
rc= C > EMA (C,50) AND C < EMA(C,200) AND EMA(C,50) < EMA(C,200);
ac= C > EMA (C,50) AND C > EMA(C,200) AND EMA(C,50) < EMA(C,200);
bl= C > EMA (C,50) AND C > EMA(C,200) AND EMA(C,50) > EMA(C,200);
wr= C < EMA (C,50) AND C > EMA(C,200) AND EMA(C,50) > EMA(C,200);
ds= C < EMA (C,50) AND C < EMA(C,200) AND EMA(C,50) > EMA(C,200);
br= C < EMA (C,50) AND C < EMA(C,200) AND EMA(C,50) < EMA(C,200);

ltp=WriteIf(rc, "RECOVERY", WriteIf(ac, "ACCUMULATION", WriteIf(bl,
"BULLISH", WriteIf(wr, "WARNING",WriteIf(ds,
"DISTRIBUTION",WriteIf(br, "BEARISH", "Zilch"))))));
ltp_col=IIf( rc, colorBlue, IIf( ac, colorGreen, IIf(bl,
colorDarkGreen, IIf(wr, colorOrange, IIf(ds, colorRed, IIf(br,
colorDarkRed, colorLightGrey ))))));

G=((O-Ref(L,-1))/Ref(L,-1))*100;
F=((C-Ref(C,-1))/Ref(C,-1))*100;

//T-3 Delta
T3Day = T3(Close, 3);
T5Day = T3(Close, 5);
Delta = T3Day - T5Day;


Filter=O<Ref(L,-1) AND C>Ref(C,-1)|C>Ref(O,-1)
AND L<Ref(L,-1) AND Ref(L,-1)<Ref(L,-2) AND Ref(L,-2)<Ref(L,-3)
AND V>Ref(V,-1) AND V>(MA(Ref(V,-1),5)+(MA(Ref(V,-1),5)*0.3)) AND
MA(V,21)>50000;

Buy=Filter;

AddColumn(V, "Volome", 1, IIf(V > Ref(V,-1), colorGreen, colorRed),-1);
AddColumn(((V/EMA(Ref(V,-1),10)))*100, "VolSpike %", 1.2, IIf(V>
EMA(Ref(V,-1),10), colorBlue, colorRed),-1);
AddColumn(Delta, "Delta",1.2, IIf(delta < 0, colorRed, colorGreen),-1);
AddColumn(C, "Close", 1.2, IIf(C > Ref(C,-1), colorGreen, colorRed),-1);
AddColumn(G,"O Low%",1.2,-1);
AddColumn(F,"C High%",1.2,-1);
AddColumn(RSI(14),"RSI-14",1.2, IIf(RSI(14) > Ref(RSI(14),-1),
colorGreen, colorRed),-1);
AddColumn(ADX(10),"ADX-10",1.2,IIf(ADX(10) > Ref(ADX(10),-1),
colorGreen, colorRed),-1);
AddTextColumn(bbk_status, "Breaks", 1.6, colorWhite, bbk_Col,-1);
AddTextColumn(Tbuy_status, "T3-Signal", 1.6, colorWhite, T_Col,-1);
AddTextColumn(Gbuy_status, "Guppy", 1.6, colorWhite, G_Col,-1);
AddTextColumn(MA_status, "EMA-9", 1.6, colorWhite, MA_Col,-1);
AddTextColumn(MA2_status, "EMA-20", 1.6, colorWhite, MA2_Col,-1);
AddTextColumn(MA3_status, "EMA-9x20", 1.6, colorWhite, MA3_Col,-1);
AddTextColumn(Ibuy_status, "RSI signal", 1.6, colorWhite, I_Col,-1);
AddTextColumn(adx_status, "Trend", 1.6, colorWhite, adx_Col,-1);
AddTextColumn(cop_status, "Coppock", 1.6, colorWhite, cop_Col,-1);
AddTextColumn(mt_status, "Mid Term", 1, colorWhite, mt_Col);
AddTextColumn(lt_status, "Long Term", 1, colorWhite, lt_Col);
//AddTextColumn(wad_status, "WAD", 1.6, colorWhite, WAD_Col,-1);
//AddTextColumn(mt_status, "EMA-50", 1.6, colorWhite, mt_Col,-1);
//AddTextColumn(lt_status, "EMA-200", 1.6, colorWhite, lt_Col,-1);
AddTextColumn(ltp, "Phase", 1.6, colorWhite, ltp_Col,-1);


_SECTION_END();

_SECTION_BEGIN("All in One EOD Explorer");
//52 Week New High-New Low
HI = High > Ref(HHV(High,260),-1);
LI = Low < Ref(LLV(Low,260),-1);
W_status= WriteIf(HI, "High", WriteIf(LI, "Low", "Neutral"));
W_Col=IIf(HI, colorGreen, IIf(LI, colorRed, colorLightGrey));


//Price Volume Breakout
HIV = C > Ref (C,-1) AND V > (MA(V,50)*2);
LIV = C < Ref (C,-1) AND V < (MA(V,50)*2);
V_status= WriteIf(HIV, "Gainer", WriteIf(LIV, "Loser", "Neutral"));
V_Col=IIf(HIV, colorGreen, IIf(LIV, colorRed, colorLightGrey));


//50/200 Crosses
BC= Cross(MA(C,50),MA(C,200));
BR= Cross(MA(C,200),MA(C,50));
B_status= WriteIf(BC, "Bullish", WriteIf(BR, "Bearish", "Neutral"));
B_Col=IIf(BC, colorGreen, IIf(BR, colorRed, colorLightGrey));

//MACD Crosses
MB= Cross (MACD(), Signal());
MS = Cross( Signal(), MACD());
MB_status= WriteIf(MB, "Bullish", WriteIf(MS, "Bearish", "Neutral"));
MS_Col=IIf(MB, colorGreen, IIf(MS, colorRed, colorLightGrey));

//RSI Status
r=RSI(14) < 70 AND Ref (RSI(14),-1) > 70 AND Ref (RSI(14),-2) > 70;
r2= RSI(14) > 70 AND Ref (RSI(14),-1) < 70 AND Ref (RSI(14),-2) < 70;
r_status= WriteIf(r, "Declining", WriteIf(r2, "Improving", "Neutral"));
r_Col=IIf(r, colorGreen, IIf(r2, colorRed, colorLightGrey));

//Bollinger Bands
bb= C > BBandTop( C, 20, 2) AND Ref (C,-1) < Ref(BBandTop( C, 20, 2),-1);
bb1= C < BBandBot( C, 20, 2) AND Ref (C,-1) > Ref(BBandBot( C, 20, 2),-1);
bb_status= WriteIf(BB, "AboveTop", WriteIf(r2, "BelowBottom", "Neutral"));
bb_Col=IIf(r, colorGreen, IIf(r2, colorRed, colorLightGrey));

//Daily Acc/Dist Status
acc = AccDist() > Ref (AccDist(),-1);
dist = AccDist() < Ref (AccDist(),-1);
ad_status= WriteIf(acc, "Accumulation", WriteIf(dist, "Distribution",
"Neutral"));
ad_Col=IIf(acc, colorGreen, IIf(dist, colorRed, colorLightGrey));

//Midterm Bullish or Bearish
mBull = C > EMA(C,50);
mBear= C < EMA(C,50);
mt_status= WriteIf(mBull, "Bullish", WriteIf(mBear, "Bearish", "Zilch"));
mt_Col=IIf(mBull, colorGreen, IIf(mbear, colorRed, colorLightGrey));

//Longterm Bullish or Bearish
Bull = C > MA(C,200);
Bear= C < MA(C,200);
lt_status= WriteIf(Bull, "Bullish", WriteIf(Bear, "Bearish", "Neutral"));
lt_Col=IIf(Bull, colorGreen, IIf(bear, colorRed, colorLightGrey));

//Median Price
mp=(H+L)/2;

Filter = HI OR LI OR HIV OR LIV OR BC OR BR OR MB OR MS OR acc OR dist
OR bull OR bear;

AddColumn(C, "Close", 1.2, IIf(C > Ref(C,-1), colorGreen, colorRed));
AddColumn(ROC(C,1), "ROC Price", 1.2, IIf(ROC(C,1) > 0, colorGreen,
colorRed));
AddColumn(mp, "Median Price", 1.2, IIf(mp > Ref(mp,-1), colorGreen,
colorRed));
AddColumn(V, "Volume", 1, IIf(V > Ref(V,-1), colorGreen, colorRed));
AddColumn(ROC(V,1), "ROC Volume", 1.2, IIf(ROC(V,1) > 0, colorGreen,
colorRed));
AddTextColumn(V_status, "Price Volume Breakout", 1, colorWhite, V_Col);
AddTextColumn(ad_status, "Acc/Dist", 1, colorWhite, ad_Col);
AddColumn(NVI(), "NVI", 1, IIf(NVI() > Ref(NVI(),-1), colorGreen,
colorRed));
AddColumn(MFI(21),"MFI-21",1.2, IIf(MFI(21) > Ref(MFI(21),-1),
colorGreen, colorRed));
AddColumn(RSI(14),"RSI-14",1.2, IIf(RSI(14) > Ref(RSI(14),-1),
colorGreen, colorRed));
AddColumn(ADX(14),"ADX-14",1.2,IIf(ADX(14) > Ref(ADX(14),-1),
colorGreen, colorRed));
AddTextColumn(bb_status, "BBand", 1, colorWhite, bb_Col);
AddTextColumn(MB_status, "MACDX", 1, colorWhite, MS_Col);
AddTextColumn(W_status, "52-Week", 1, colorWhite, W_Col);
AddTextColumn(B_status, "50/200", 1, colorWhite, B_Col);
AddTextColumn(mt_status, "Mid Term", 1, colorWhite, mt_Col);
AddTextColumn(lt_status, "Long Term", 1, colorWhite, lt_Col);
_SECTION_END();

Buy = Cover =Cross( MACD(), 0 );
Sell = Short =Cross( 0, MACD() );

Filter = Cross( MACD(), 0 );

Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

a=EMA(C,30)-EMA(C,200);
b=EMA(a,20);


Buy = Cross( a,b );
Sell = Cross( b,a );
//Short = Sell;
//Cover = Buy;

AlertIf( Buy, "", "MACD BUY", 1,1+2 );

AlertIf( Sell, "", "MACD SELL", 2 ,1+2);
 

Similar threads