Stock Portfolio Organizer

The ultimate porfolio management solution.

Shares, Margin, CFD's, Futures and Forex
EOD and Realtime
Dividends and Trust Distributions
And Much More ....
For Portfolio Manager Click Here

WiseTrader Toolbox

#1 Selling Amibroker Plugin featuring:

Advanced Adaptive Indicators
Advanced Pattern Exploration
Neural Networks
And Much More ....
Find Out More Here

DoubleTop for Amibroker (AFL)

Copy & Paste Friendly
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
_SECTION_BEGIN("NICK MA Swing + heikin pivots");
SetBarsRequired(200,0);
 
GraphXSpace = 5;
SetChartOptions(0,chartShowArrows|chartShowDates);
k =  Optimize("K",Param("K",1,0.25,5,0.25),0.25,5,0.25);
Per= Optimize("atr",Param("atr",4,3,20,1),3,20,1);
HACLOSE=(O+H+L+C)/4;
HaOpen = AMA( Ref( HaClose,  -1 ),  0.5 );
HaHigh = Max( HMax( HaClose,  HaOpen ) );
HaLow = Min( LMin( HaClose,  HaOpen ) );
PlotOHLC( HaOpen, HaHigh, HaLow, HaClose, "" + Name(), colorWhite, styleCandle | styleNoLabel );
j=Haclose;
 
//=======================================================================================================================
//=========================Indicator==============================================================================================
f=ATR(14);
 
rfsctor = WMA(H-L, Per);
 
revers = k * rfsctor;
 
Trend = 1; 
NW[0] = 0; 
 
 
for(i = 1; i < BarCount; i++)
{
 if(Trend[i-1] == 1)               
 {
  if(j[i] < NW[i-1])                
  {
   Trend[i] = -1;                  
   NW[i] = j[i] + Revers[i];       
  }
  else                             
  {
   Trend[i] = 1;
   if((j[i] - Revers[i]) > NW[i-1])
   {
    NW[i] = j[i] - Revers[i];
   }
   else
   {
    NW[i] = NW[i-1];
   }
  }
 }
 if(Trend[i-1] == -1)              
 {
  if(j[i] > NW[i-1])               
  {
   Trend[i] = 1;                   
   NW[i] = j[i] - Revers[i];       
  }
  else                             
  {
   Trend[i] = -1;
   if((j[i] + Revers[i]) < NW[i-1])
   {
    NW[i] = j[i] + Revers[i];
   }
   else
   {
    NW[i] = NW[i-1];
   }
  }
 }
}
 
//===============system================
 
_SECTION_BEGIN("ema5,13sound");
x = EMA(Close,5);
y = EMA(Close,13);
Plot(EMA(Close,5),"",colorBrightGreen,styleLine, styleThick);
Plot(EMA(Close,13),"",colorOrange,styleLine, styleThick);
XR=(EMA(Close,5) * (2 / 6 - 1) - EMA(Close,13) * (2 / 11 - 1)) / (2 / 6 - 2 / 11);
 
 
Buy=Cross(j,nw);
Cover=Cross(j,nw);
Sell=Cross(nw,j);
Short=Cross(nw,j);
SellPrice=ValueWhen(Sell,C,1);
BuyPrice=ValueWhen(Buy,C,1);
Long=Flip(Buy,Sell);
Shrt=Flip(Sell,Buy );
_SECTION_END();
//=================TITLE================================================================================================
_SECTION_BEGIN("Title");
if( Status("action") == actionIndicator )
(
Title = EncodeColor(colorWhite)+ "NICK MA Swing System" + " - " Name() + " - " + EncodeColor(colorRed)+ Interval(2) + EncodeColor(colorWhite) +
 "  - " + Date() +" - "+"\n" +EncodeColor(colorYellow) +"Op-"+O+"  "+"Hi-"+H+"  "+"Lo-"+L+"  "+
"Cl-"+C+"  "+ "Vol= "+ WriteVal(V)+"\n"+
EncodeColor(colorRed)+
WriteIf (Buy , " GO LONG / Reverse Signal at "+C+"  ","")+
WriteIf (Sell , " EXIT LONG / Reverse Signal at "+C+"  ","")+"\n"+EncodeColor(colorWhite)+
WriteIf(Sell , "Total Profit/Loss for the Last Trade Rs."+(C-BuyPrice)+"","")+
WriteIf(Buy  , "Total Profit/Loss for the Last trade Rs."+(SellPrice-C)+"","")+
WriteIf(Long AND NOT Buy, "Trade : Long - Entry price Rs."+(BuyPrice),"")+
WriteIf(shrt AND NOT Sell, "Trade : Short - Entry price Rs."+(SellPrice),"")+"\n"+
WriteIf(Long AND NOT Buy, "Current Profit/Loss Rs."+(C-BuyPrice)+"","")+
WriteIf(shrt AND NOT Sell, "Current Profit/Loss Rs."+(SellPrice-C)+"",""));
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-30);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-40);                     
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-35);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                     
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-30);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorLime, 0,L, Offset=-40);                     
PlotShapes(IIf(Cover, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-35);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                     
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
AlertIf( Ref(Buy,-1), "SOUND C:\\Windows\\Media\\Windows XP Startup.wav", "Nick MA Buy", 2 );
AlertIf( Ref(Sell,-1), "SOUND C:\\Windows\\Media\\Ringin.wav", "Nick MA Sell", 2 );
_SECTION_END();
 
_SECTION_BEGIN("MA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 8, 2, 200, 1 );
Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") | styleNoRescale );
_SECTION_END();
 
_SECTION_BEGIN("Mid MA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 34, 2, 300, 1 );
Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") | styleNoRescale );
_SECTION_END();
 
_SECTION_BEGIN("Long MA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 200, 2, 400, 1 );
Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") | styleNoRescale );
_SECTION_END();
_SECTION_END();
 
_SECTION_BEGIN("SAR");
acc = Param("Acceleration", 0.02, 0, 1, 0.001 );
accm = Param("Max. acceleration", 0.2, 0, 1, 0.001 );
Plot( SAR( acc, accm ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style", styleDots | styleNoLine, maskDefault | styleDots | styleNoLine ) );
_SECTION_END();
_SECTION_BEGIN("Sup / Res Lines");
RSIperiod   = 15;   // Param("RSI p",3,14,30,1);
Percent         = 5;    //  Param("ZIG %",8,9,15,1);
EMAperiod   = 2;    //Param("EMA p",4,5,10,1);
HHVperiod   = 8;    //Param("HHV p",3,5,10,1);
NumLine         = 2;    //Param("Num Lines",3,1,20,1);
 
Base = DEMA(RSI(RSIperiod),EMAperiod);
 
 
for( i = 1; i <= numline; i++ )
{
ResBase = LastValue(Peak(Base,Percent,i));
SupBase = LastValue(Trough(Base,Percent,i));
Plot(ValueWhen( ResBase==Base, HHV(H,HHVperiod) ), "Resist Level", colorRed, styleLine);
Plot(ValueWhen( supbase==Base, LLV(L,HHVperiod) ), "Support Level", colorGreen, styleLine);
 
}_SECTION_END();
 
 
_SECTION_BEGIN("heikin");
 
// Calculate Moving Average
MAPeriod = Param("MA Period", 15, 1, 100);
MAOpen = EMA(Open, MAPeriod);
MAHigh = EMA(High, MAPeriod);
MALow = EMA(Low, MAPeriod);
MAClose = EMA(Close, MAPeriod);
 
HaClose = (MAOpen + MAHigh + MALow + MAClose) / 4;
HaOpen = AMA(Ref(HaClose, -1), 0.5);
 
// for graph collapse
for(i = 0; i <= MAPeriod; i++)  {
 
HaClose[i] = Null;
/*
// same
// HaOpen = (Ref(HaOpen, -1) + Ref(HaClose, -1)) / 2;
HaOpen[ 0 ] = HaClose[ 0 ];
for(i = 1; i < BarCount; i++) {
    HaOpen[i] = (HaOpen[i - 1] + HaClose[i - 1]) / 2;
}
*/
 
HaHigh = Max(MAHigh, Max(HaClose, HaOpen));
HaLow = Min(MALow, Min(HaClose, HaOpen));
 
// outs comments
"BarIndex = " + BarIndex();
"Open = " + Open;
"High = " + High;
"Low = " + Low;
"Close = "+ Close;
"HaOpen = " + HaOpen;
"HaHigh = " + HaHigh;
"HaLow = " + HaLow;
"HaClose = "+ HaClose;
 
 
  /* **********************************
 
Code to automatically identify pivots
 
********************************** */
 
// -- what will be our lookback range for the hh and ll?
farback=Param("How Far back to go",100,50,5000,10);
nBars = Param("Number of bars", 12, 5, 40);
 
 
// -- Create 0-initialized arrays the size of barcount
 
aHPivs = H - H;
 
aLPivs = L - L;
 
// -- More for future use, not necessary for basic plotting
 
aHPivHighs = H - H;
 
aLPivLows = L - L;
 
aHPivIdxs = H - H;
 
aLPivIdxs = L - L;
 
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);
 
// -- Would like to set this up so pivots are calculated back from
 
// last visible bar to make it easy to "go back" and see the pivots
 
// this code would find. However, the first instance of
 
// _Trace output will show a value of 0
 
aVisBars = Status("barvisible");
 
nLastVisBar = LastValue(Highest(IIf(aVisBars, BarIndex(), 0)));
 
_TRACE("Last visible bar: " + nLastVisBar);
 
// -- Initialize value of curTrend
 
curBar = (BarCount-1);
 
curTrend = "";
 
if (aLLVBars[curBar] <
 
aHHVBars[curBar]) {
 
curTrend = "D";
 
}
 
else {
 
curTrend = "U";
 
}
 
// -- Loop through bars. Search for
 
// entirely array-based approach
 
// in future version
 
for (i=0; i<farback; i++) {
 
curBar = (BarCount - 1) - 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
 
}
 
// -- Basic attempt to add a pivot this logic may have missed
 
// -- OK, now I want to look at last two pivots. If the most
 
// recent low pivot is after the last high, I could
 
// still have a high pivot that I didn't catch
 
// -- Start at last bar
 
curBar = (BarCount-1);
 
candIdx = 0;
 
candPrc = 0;
 
lastLPIdx = aLPivIdxs[0];
 
lastLPL = aLPivLows[0];
 
lastHPIdx = aHPivIdxs[0];
 
lastHPH = aHPivHighs[0];
 
if (lastLPIdx > lastHPIdx) {
 
// -- Bar and price info for candidate pivot
 
candIdx = curBar - aHHVBars[curBar];
 
candPrc = aHHV[curBar];
 
if (
 
lastHPH < candPrc AND
 
candIdx > lastLPIdx AND
 
candIdx < curBar) {
 
 
// -- OK, we'll add this as a pivot...
 
aHPivs[candIdx] = 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] = candPrc ;
 
aHPivIdxs[0] = candIdx;
 
nHPivs++;
 
}
 
} else {
 
 
// -- Bar and price info for candidate pivot
 
candIdx = curBar - aLLVBars[curBar];
 
candPrc = aLLV[curBar];
 
if (
 
lastLPL > candPrc AND
 
candIdx > lastHPIdx AND
 
candIdx < curBar) {
 
 
// -- OK, we'll add this as a pivot...
 
aLPivs[candIdx] = 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] = candPrc;
 
aLPivIdxs[0] = candIdx;
 
nLPivs++;
 
}
 
}
 
// -- Dump inventory of high pivots for debugging
 
/*
 
for (k=0; k<nHPivs; k++) {
 
_TRACE("High pivot no. " + k
 
+ " at barindex: " + aHPivIdxs[k] + ", "
 
+ WriteVal(ValueWhen(BarIndex()==aHPivIdxs[k],
 
DateTime(), 1), formatDateTime)
 
+ ", " + aHPivHighs[k]);
 
}
 
*/
 
// -- OK, let's plot the pivots using arrows
 
PlotShapes(
 
IIf(aHPivs==1, shapeDownArrow, shapeNone), colorRed, 0,
 
High, Offset=-15);
 
PlotShapes(
 
IIf(aLPivs==1, shapeUpArrow , shapeNone), colorBrightGreen, 0,
 
Low, Offset=-15);
 
AlertIf( Ref(aLPivs==1,-1), "SOUND C:\\Windows\\Media\\Windows XP Startup.wav", "Heikin Buy ", 2 );
AlertIf( Ref(aHPivs==1,-1), "SOUND C:\\Windows\\Media\\Ringin.wav", "Heikin Sell", 2 );
 
 Buy=(aLPivs==1);
Cover=(aLPivs==1);
Sell=(aHPivs==1);
Short=(aHPivs==1);
SellPrice=ValueWhen(Sell,C,1);
BuyPrice=ValueWhen(Buy,C,1);
Long=Flip(Buy,Sell);
Shrt=Flip(Sell,Buy );
_SECTION_END();
//=================TITLE================================================================================================
_SECTION_BEGIN("Title");
if( Status("action") == actionIndicator )
(
Title = EncodeColor(colorLightBlue)+ "Heikin-Ashi pivot + NMA Swing system - Boxed arrows NMA buy-sell - Normal Arrows Heikin Pivot Buy-Sell" + " - " Name() + " - " + EncodeColor(colorRed)+ Interval(2) + EncodeColor(colorWhite) +
 "  - " + Date() +" - "+"\n" +EncodeColor(colorYellow) +"Op-"+O+"  "+"Hi-"+H+"  "+"Lo-"+L+"  "+
"Cl-"+C+"  "+ "Vol= "+ WriteVal(V)+"\n"+
EncodeColor(colorRed)+
WriteIf (Buy , " GO LONG / Reverse Signal at "+C+"  ","")+
WriteIf (Sell , " EXIT LONG / Reverse Signal at "+C+"  ","")+"\n"+EncodeColor(colorWhite)+
WriteIf(Sell , "Total Profit/Loss for the Last Trade Rs."+(C-BuyPrice)+"","")+
WriteIf(Buy  , "Total Profit/Loss for the Last trade Rs."+(SellPrice-C)+"","")+
WriteIf(Long AND NOT Buy, "Trade : Long - Entry price Rs."+(BuyPrice),"")+
WriteIf(shrt AND NOT Sell, "Trade : Short - Entry price Rs."+(SellPrice),"")+"\n"+
WriteIf(Long AND NOT Buy, "Current Profit/Loss Rs."+(C-BuyPrice)+"","")+
WriteIf(shrt AND NOT Sell, "Current Profit/Loss Rs."+(SellPrice-C)+"",""));
AlertIf( Ref(Buy, -1), "SOUND C:\\Windows\\Media\\Windows XP Startup.wav", "ActionIndicator Buy", 2 );
AlertIf( Ref(Sell, -1), "SOUND C:\\Windows\\Media\\Ringin.wav", "Action Indicator Sell", 2 );
_SECTION_END();
 
_SECTION_BEGIN("Shiree_Hanging Man bullish +bearish with volume");
 
BT = BBandTop( C, 20, 2 );
BB = BBandBot( C, 20, 2 );
X=(BT-BB);
 
RBuy=EMA(C,3)<EMA(C,10) AND C<EMA(C,3) AND ((O+C)/2)>L+0.7*(H-L) AND abs(O-C)<0.4*(H-L) AND V>MA(V,10) AND (H-L)>=0.8*MA((H-L),10) AND X>1.2*MA(X,10);
Rsell=EMA(C,3)>EMA(C,10) AND C>EMA(C,3) AND ((O+C)/2)<H-0.7*(H-L) AND abs(O-C)<0.4*(H-L) AND V>MA(V,10) AND (H-L)>=0.8*MA((H-L),10) AND X>1.2*MA(X,10);
 
 
PlotShapes(Rsell*shapeDownTriangle,colorCustom12, 0, High, Offset =-40);
PlotShapes(Rsell*shapeDigit5,colorCustom12, 0, High, Offset =55);
 
PlotShapes(RBuy*shapeDigit5,colorYellow, 0, High, Offset =-70);
PlotShapes(RBuy*shapeUpTriangle,colorYellow, 0, Low, Offset =-10);
 
 
Filter =Rbuy OR Rsell;
 
AddColumn( IIf(RBuy,1,IIf(Rsell,-1,Null)) ,"RBS",1.0,colorWhite,IIf(RBuy,colorDarkGreen,IIf( Rsell,colorRed,Null)));
 
_SECTION_END();
 
_SECTION_BEGIN("Double top detection");
//------------------------------------------------------------------------------
//
//  Formula Name:    Double top detection
//  Author/Uploader: Tomasz Janeczko
//  E-mail:          tj@amibroker.com
//  Date/Time Added: 2001-06-16 08:45:38
//  Origin:          Created by Tomasz Janeczko
//  Keywords:        pattern,recognition,top,bottom
//  Level:           semi-advanced
//  Flags:           commentary
//  Formula URL:     http://www.amibroker.com/library/formula.php?id=19
//  Details URL:     AmiBroker - AFL Library
//
//------------------------------------------------------------------------------
//
//  Detecting patterns is somewhat tricky thing mainly because you can be sure
//  about that only if the pattern is complete. This implies delay in detecting
//  patterns and/or formations and limits usefulness of automatic detection
//  formulas. Anyway I will try to show you how to write pattern recognition
//  formulas using AFL. In this article we will focus on detecting very well
//  known pattern - a double top / double bottom.
//
//  The double top is a major reversal pattern that forms after an extended
//  uptrend. As its name implies, the pattern is made up of two consecutive
//  peaks that are roughly equal, with a moderate trough in between. Although
//  there can be variations, the classic double top marks at least an
//  intermediate change, if not long-term change, in trend from bullish to
//  bearish. Many potential double tops can form along the way up, but until
//  key support is broken, a reversal cannot be confirmed. The whole formation
//  consists of the following parts: prior trend, first peak, trough, second
//  peak, decline from the peak, support break and then decline to the price
//  target. The pattern seems straightforward but there are many details to
//  watch out. For the purpose of this article I will use simplified model of
//  double top pattern that consists of double, roughly equal peaks and the
//  decline from the second peak. So, let's begin.
//
//  AmiBroker Formula Language provides built in functions for detecting peaks
//  and troughs. These functions are based on Zig( array, thresh ) function
//  which you can test by trying the follwing formula:
//
//  graph0 = close;
//
//  graph1= zig( close, 5 );
//
//  As you can see Zig() function determines major peaks and troughs using
//  percentage threshold given as a second parameter. The bigger threshold you
//  specify the more significant peaks and troughs are detected. The line
//  generated by Zig() function indentifies the main trend. There is one caveat
//  however: please take special attention using Zig() function in trading
//  systems because it looks in the future so you will get unrealistic system
//  test results. Zig() function and all function using it (Peak, Trough,
//  PeakBars, TroughBars) are intended for pattern recognition formulas only.
//
//  We will start wrting the formula for detecting double top pattern with
//  detecting peaks:
//
//  percdiff = 10; /* this defines percentage threshold for detecting peaks */
//
//  PK = Peak( H, percdiff, 1 ) == HIGH;
//
//  Now PK array will hold "1" for all bars when peaks occur and "0" elsewhere
//  because high price is equal to the peak value only on the day when this
//  peak occurs.
//
//  Now we want to know if two subsequent peaks are more or less the same:
//
//  peakdiff = ValueWhen( PK, H, 1 )/ValueWhen( PK, H, 2 );
//
//  The peakdiff variable holds now the high price of the most recent peak
//  divided by the high price of the second recent peak. Ideally this value
//  should be 1 - peaks are exactly the same but we will allow slight
//  differences. Let's say we allow the difference of one fourth of the
//  percentage threshold used for detecting peaks:
//
//  validdiff = percdiff/400;
//
//  doubletop = PK AND abs( peakdiff - 1 ) < validdiff;
//
//  Now doubletop variable is "1" if double peak occurred and the difference
//  between the peaks is less than one fourth of the threshold. In our example
//  the threshold in 10% and validdiff is 0.025 (2.5%).
//
//  Everything is fine but soon you find out that this formula is not too good.
//  It detects double tops much too often especially tops that are located to
//  close. For that reason we will add a check for distance between peaks:
//
//  percdiff = 10;
//
//  validdiff = percdiff/400;
//
//  mindistance = 10;
//
//  PK= Peak( H, percdiff, 1 ) == HIGH;
//
//  x = Cum( 1 );
//
//  XPK1 = ValueWhen( PK, x, 1 );
//
//  XPK2 = ValueWhen( PK, x, 2 );
//
//  peakdiff = ValueWhen( PK, H, 1 )/ValueWhen( PK, H, 2 );
//
//  doubletop = PK AND abs( peakdiff - 1 ) < validdiff AND (XPK1 - XPK2)>
//  mindistance;
//
//  The mindistance variable defines minimum number of bars between peaks
//  needed for valid double top formation. XPK1 and XPK2 variables hold the bar
//  number of the first and the second peak.
//
//  Now our formula does not detect peaks located to close but still generates
//  too much signals because it does not check for the validity of the second
//  peak. It just assumes too soon that the peak is valid. To be more sure we
//  need to wait for some days to find out that the second peak is important.
//  One idea is just to check for a couple of days if the price does not return
//  above the level of the peak. So our formula now will look like this:
//
//  percdiff = 10; /* peak detection threshold */
//
//  validdiff = percdiff/400;
//
//  fwdcheck = 4; /* how many days forward to check for valid second peak*/
//
//  mindistance = 10;
//
//  PK= Peak( H, percdiff, 1 ) == HIGH;
//
//  x = Cum( 1 );
//
//  XPK1 = ValueWhen( PK, x, 1 );
//
//  XPK2 = ValueWhen( PK, x, 2 );
//
//  peakdiff = ValueWhen( PK, H, 1 )/ValueWhen( PK, H, 2 );
//
//  doubletop = PK AND abs( peakdiff - 1 ) < validdiff
//
//  AND (XPK1 - XPK2) > mindistance
//
//  AND HIGH > HHV( Ref( H, fwdcheck ), fwdcheck - 1 );
//
//  Note that this formula now references the future ( look at the following
//  statement: Ref( H, fwdcheck ) ) - this means that it will not generate ANY
//  signals until fwdcheck bars pass after the second peak. So, for example, if
//  double top pattern has occured on Monday you will know about that on Friday
//  because four days (future quotes) are needed to confirm the pattern.
//
//  Now our formula for detecting double tops is much better, but still is
//  missing one imporant point - detecting prior trend. That is why it
//  sometimes generates false signals. I will not, however, go any further in
//  this article just to keep things simple. You can use the double top formula
//  in Automatic analysis/Scan function for screening the stocks for potential
//  reversal patterns or in Commentary. By adding buy=doubletop; sell=0;
//  statement to the formula you will be able to screen stocks for the
//  potential reversal patterns and see the arrows when the formula is used in
//  Commentary window.
//
//------------------------------------------------------------------------------
 
/* Detecting double tops */
percdiff = 5; /* peak detection threshold */
fwdcheck = 5; /* forward validity check */
mindistance = 10;
validdiff = percdiff/400;
PK= Peak( H, percdiff, 1 ) == High;
 
x = Cum( 1 );
XPK1 =  ValueWhen( PK, x, 1 );
XPK2 = ValueWhen( PK, x, 2 );
 
peakdiff = ValueWhen( PK, H, 1 )/ValueWhen( PK, H, 2 );
doubletop = PK AND abs( peakdiff - 1 ) < validdiff AND (XPK1 - XPK2)>mindistance
AND High > HHV( Ref( H, fwdcheck ), fwdcheck - 1 );
Buy = doubletop;
Sell = 0;
 
WriteIf( Highest( doubletop ) == 1, "AmiBroker has detected some possible double top patterns for " + Name() + "\nLook for green arrows on the price chart.", "There are no double top patterns for " + Name() );
_SECTION_END();
//_SECTION_BEGIN("foreign NMA");
//Vr=ParamList("Index",List = "^NSEI,^NSEBANK,RELIANCE.NS,SBIN.NS,EURUSD,XAUUSD",0);
//SetForeign(Vr);
//HaC =(O+H+L+C)/4;
//HaO = AMA( Ref( HaC, -1 ), 0.5 );
//HaH = Max( H, Max( HaC, HaO) );
//HaL = Min( L, Min( HaC, HaO) );
//BG3=HHV(LLV(HaL,4)+ATR(4),8);
//BR3=LLV(HHV(HaH ,4)-ATR(4),8);
//co = IIf(Hac>BG3 ,colorAqua,IIf(Hac < BR3,colorCustom12,colorGrey50));
//Plot(4, "", Co,styleArea+styleOwnScale | styleNoLabel, -1, 100);
//Comm2=("\n "+Vr+" Phase: ")+
//WriteIf(Hac>BG3,EncodeColor(colorLime)+"+Up",
//WriteIf(Hac<BR3,EncodeColor(colorRed)+"-Down",EncodeColor(colorLightYellow)+"< Flat >"));
//RestorePriceArrays();
//_SECTION_END();
//grid_day = IIf(Day()!=Ref(Day(),-1),1,0); 
//Plot(grid_day,"",colorDarkGrey,styleHistogram|styleDashed|styleNoLabel|styleOwnScale);
}
Back