27 August 2011

e-ratio

e-ratio: How to measure your trading edge in 4 easy steps

e-ratio is a metrics that measures the edge of a trading system component. For example, we could use it to quantify the edge gained from a donchian channel breakout entry signal.
The concept

The e-ratio quantifies the edge by calculating the overall amount trades go in your favor versus the overall amount trades go against you. The higher value the value of the e-ratio, the more trades move in your favor – giving you a good indication of the edge measured.

Take all the trades generated by the entry signal.
Close each trade after a given duration of n days.
Calculate the e-ratio based on data from all trades (formula detailed in 4 steps below). This gives you the e-ratio for a trade duration of n days.
Repeat the operation for various values of n to chart the e-ratio curve as a function of the number n of days – as illustrated below:



The e-ratio of the entry criteria is plotted above. The higher the value of the e-ratio, the better the edge. In the instance above the 45-day e-ratio is 1.21 but drops to 1.07 for day 68.


Step 1: Record MAE and MFE for each trade

For each trade, measure the Maximum Favorable Excursion and the Maximum Adverse Excursion.
Maximum Excursions are the maximum amount the price goes against you (Adverse) or in your favor (Favorable) during the trade. MAE is calculated between the entry price and the lowest price during the trade. MFE is calculated between the entry price and the highest price during the trade. Note that both values are positive.
Step 2: Normalise MAE and MFE values

To be able to compute the e-ratio across different markets, the Excursion values should be normalised to a common denominator – such as a unit of volatility. The Average True Range is a good measure of volatility. In many systems it is also used to drive the position sizing, making it really relevant.
Divide all MAE and MFE values by the ATR calculated at the beginning of the trade. In this example we use the same period for the ATR and the Donchian Channel.
This gives you comparable values across all markets and conditions.
Step 3: Average MAE and MFE values across all trades

Simple maths here: just add all normalised MAE values calculated in step 2 and divide by the number of trades. Repeat the operation for the MFE values.
Step 4: Final division = e-ratio

Simply divide the average MFE by the average MAE to give you the e-ratio. The higher the number, the better, with any values above 1 implying a positive edge.
Analysis

Plotting the e-ratio across different durations allows you to check the edge offered by the signal and what timeframe works best for the signal parameters.

You can also combine e-ratios for different parts of a system to see how they impact each other.
Another component of a trading system could be a trade filter, for example, trade with the main trend:

Only buy when the moving average (at a higher timeframe) is rising and below the price.
Only sell when the moving average (at a higher timeframe) is declining and above the price


http://www.automated-trading-system.com/e-ratio-trading-edge/






//----------------------------------------------------------------------
// e-ratio code aggregated by Jez Liberty
// http://www.automated-trading-system.com
//
// The code is largely inspired from the ASX Gorilla blog
// http://theasxgorilla.blogspot.com/2007/07/how-to-compute-edge-ratio-in-amibroker.html
//
// implementation of the Edge Ratio, included below, involves two profound Amibroker fudges.
// The first is the use of the AddToComposite function to create a composite ticker symbol
// in which to hold the ATR array of a given stock for later retrieval within the Custom Back Tester
// via the Foreign function.
// The second fudge is the use of the VarSet/VarGet function to create a quasi array.
// This was necessary to overcome the limitation where array elements cannot exceed in number the value of barcount-1.
//----------------------------------------------------------------------


//---------------------------------------------------------------------------------------------------------
// Options default reset (taken from boilerplate.afl on AmibrokerU.com
// Should be included on all code files
//---------------------------------------------------------------------------------------------------------

SetOption("InitialEquity",1000);
SetOption("MinShares", .0001);
SetOption("MinPosValue",0);
SetOption("FuturesMode", False);
SetOption("AllowPositionShrinking", True);
SetOption("ActivateStopsImmediately",False);
SetOption("ReverseSignalForcesExit", True);
SetOption("AllowSameBarExit",True);
SetOption("CommissionMode", 2);
SetOption("CommissionAmount", 0);
SetOption("InterestRate", 0);
SetOption("MarginRequirement", 100);
SetOption("PortfolioReportMode",0);
SetOption("MaxOpenPositions", 1);
SetOption("WorstRankHeld", 1);// Not in settings
SetOption("PriceBoundChecking",False);// Not in settings
SetOption("UsePrevBarEquityForPosSizing",True);
SetOption("UseCustomBacktestProc",False);

SetOption("DisableRuinStop",False);// Not in settings
SetOption("EveryBarNullCheck",False);// Not in settings

SetOption("HoldMinBars",0);// Not in settings
SetOption("HoldMinDays",0);// Not in settings
SetOption("EarlyExitBars",0);// Not in settings
SetOption("EarlyExitDays",0);// Not in settings
SetOption("EarlyExitFee",0);// Not in settings

SetOption("SeparateLongShortRank",False);// Not in settings
SetOption("MaxOpenLong",0);// Not in settings
SetOption("MaxOpenShort",0);// Not in settings

MaxPos= 100 * 100 / GetOption("MarginRequirement");
PositionSize = -MaxPos / GetOption("MaxOpenPositions");

RoundLotSize = 1; // 0 for Funds, 100 for Stocks
TickSize= 0; // 0 for no min. size
MarginDeposit = 10;
PointValue= 1;// For futures

ExitAtTradePrice = 0;
ExitAtStop= 1;
ExitNextBar= 2;

ReEntryDelay= 0;

//---------------------------------------------------------------------------------------------------------
// End of options reset - override options below
//---------------------------------------------------------------------------------------------------------

//Override of options to enable e-ratio calc and multiple simultaneous positions
PosQty = 5; // You can define here how many open positions you want
SetOption("MaxOpenPositions", PosQty );
PositionSize = -100/PosQty; // invest 100% of portfolio equity divided by max. position count
SetOption("InitialEquity",10000000);
SetOption("FuturesMode", True);

//-------------------------------------------------------------------------------
//Actual System/Signal tested goes below:
//-------------------------------------------------------------------------------

//BUY RULES: implemented with a Buy Stop based Upper Donchian Channel(20)
BuyStop = Ref(HHV(High, 20),-1);
Buy = Cross( High, BuyStop );
BuyPrice = Max( BuyStop, Low ); // make sure buy price not less than Low

//------------------------------------------------------------------------------
//e-ratio specific code
//------------------------------------------------------------------------------
//eratio is the variable that we "optimise" (step from 1 to 100)
eratio = Optimize("Eratio", 20, 1, 100, 1);

//Never Sell so that the position is stopped out after N bar instead
Sell = 3 > 5;
//Stop the positon and close it after N bars (eratio = N that we step from 1 to 100 in optimisation)
ApplyStop( stopTypeNBar, stopModeBars, eratio );

//AddToComposite function is used to create a composite ticker symbol.
//In it we hold the ATR array of a given instrument
//This is for later retrieval within the Custom Back Tester via the Foreign function
Normaliser = ATR(20);
AddToComposite(Normaliser, "~atr_"+Name(), "C", 1+2+8);

SetCustomBacktestProc(""); //activate the custom backtester
if(Status("action") == actionPortfolio) //called when backtesting/optimising
{
bo = GetBacktesterObject();
bo.PreProcess(); // run default backtest procedure
TradeATR = NumTrades = ATRArr = 0; //init variables
for( bar=0; bar < BarCount-1; bar++) { bo.ProcessTradeSignals(bar); for ( sig=bo.GetFirstSignal(bar); sig; sig=bo.GetNextSignal(bar) ) { if (sig.isEntry()) { NumTrades++; ATRArr = Foreign("~atr_"+sig.Symbol, "C"); VarSet("TradeATR" + NumTrades, ATRArr[bar]); _TRACE("Symbol " + sig.Symbol + " ATR: " + VarGet("TradeATR" + NumTrades)); } } } AvgMAE = AccumMAE = AvgMFE = AccumMFE = NumTrades = 0; // iterate through closed trades for( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() ) { NumTrades++; EntryATR = VarGet ("TradeATR" + NumTrades); if ( EntryATR != 0 ) { _TRACE("EntryATR: " + WriteVal(EntryATR)); _TRACE("AccumMAE : " + WriteVal(AccumMAE)); AccumMAE = AccumMAE + (trade.GetMAE()*trade.EntryPrice/(100*EntryATR)); AccumMFE = AccumMFE + (trade.GetMFE()*trade.EntryPrice/(100*EntryATR)); } trade.AddCustomMetric("My MAE", trade.GetMAE()*trade.EntryPrice/100); trade.AddCustomMetric("My MFE", trade.GetMFE()*trade.EntryPrice/100); trade.AddCustomMetric("Entry ATR", EntryATR*10000); } AvgMAE = AccumMAE / NumTrades; AvgMFE = AccumMFE / NumTrades; _TRACE(WriteVal(AccumMAE )); _TRACE(WriteVal(NumTrades)); _TRACE(WriteVal(AvgMAE)); Eratio = abs(AvgMFE/AvgMAE); _TRACE(WriteVal(Eratio)); bo.AddCustomMetric( "Avg MAE", AvgMAE ); bo.AddCustomMetric( "Avg MFE", AvgMFE ); bo.AddCustomMetric( "Eratio", Eratio); bo.PostProcess(); } http://www.automated-trading-system.com/e-ratio-amibroker-code/

25 August 2011

Volume indi/ Oscillator for Amibroker

As volume levels are increasing, shorter-term volume moving averages will rise above longer-term volume moving averages. This is similar to how shorter-term price moving averages rise above longer-term price moving averages when prices are increasing. Thus, the difference between two volume moving averages of varying lengths (i.e., this indicator) can be used to see if overall volume trends are increasing or decreasing. When the Volume Oscillator rises above zero, it signifies that the shorter-term volume moving average has risen above the longer-term volume moving average, or that the short-term volume trend is higher (i.e., more volume) than the longer-term volume trend.

There are many ways to interpret changes in volume trends. One common belief is that rising prices coupled with increased volume, and falling prices coupled with decreased volume, is bullish. Conversely, if volume increases when prices fall, and volume decreases when prices rise, the market is showing signs of underlying weakness. The theory behind this is straight forward. Rising prices coupled with increased volume signifies increased upside participation (more buyers) that should lead to a continued move. Conversely, falling prices coupled with increased volume (more sellers signifies increased downside participation).

The above information is borrowed from the Metastock help files.

Place this indicator on the same chart as the DMI spread, Demand Index, and Cyclotron indicators. These provide some interesting supporting signals. Of couse, always have a price line somewhere.


http://www.wisestocktrader.com/indicators/123-volume-oscillator.txt





Time Segmented Volume for Amibroker (AFL)
TJ has helped me translate the metastock formula of TSV into AB language.

I thought I should share this formulas with other. This indicator uses volume and price, like OBV, but seems to be more reliable indicator then OBV.

In courtesy of The Wordens brothers I like to post the link for study on purpose and usage of this indicator. http://www.tc2000.com/privuser2/ii12118p.htm

By ntk98 – ntk98_2000 [at] yahoo.co.uk


// Time segment value

TSV=(Sum( IIf( C > Ref(C,-1), V * ( C-Ref(C,-1) ),
IIf( C < Ref(C,-1),-V * ( C-Ref(C,-1) ), 0 ) ) ,18)); Plot(TSV,"TSV",1,1); Stochastic %K & Volume for Amibroker (AFL) Quick solution to find Overbrought / Oversold Levels http://www.wisestocktrader.com/indicators/194-stochastic-k-volume


Pivots And Prices And Swing Volume for Amibroker (AFL)



Cumulate the volume for each swing

by Reinsley

Following the S&C "Price+Volume=Price movement by Tom ORD S&C’s document which is stored in Yahoo! Group files and posted in user’s list

Mod of Pivots And Prices formula




http://www.wisestocktrader.com/indicators/686-pivots-and-prices-and-swing-volume




Volume Analysis Studies for Amibroker (AFL)


This code studies price/volume based on information from

Master the Markets,
http://www.traderji.com/
http://www.traderslaboratory.com/


http://www.wisestocktrader.com/indicators/678-volume-analysis-studies



http://www.wisestocktrader.com/indicators/534-obtr-histogram




http://www.wisestocktrader.com/indicators/482-modified-volume-price-trend-indicator


http://www.wisestocktrader.com/indicators/472-klinger-volume-oscillator



http://www.wisestocktrader.com/indicators/1277-volume-delivery


http://www.wisestocktrader.com/indicators/1157-volume-price-analysis-v2


http://www.wisestocktrader.com/indicators/468-trendchart-v2-0-by-rmike



The Three Day Reversal Exploration for Amibroker (AFL)

The three day reversal is a very simple pattern. When the trend is Up or Long; The Three Day Drop and When the trend is Down or Short; The 3 Day Rise.

By Prashanth – prash454 [at] Rediffmail.com



http://www.wisestocktrader.com/indicators/187-the-three-day-reversal-exploration


Explo Vol Break out scan

http://www.wisestocktrader.com/indicators/786-exploration-formula-for-intraday


http://www.wisestocktrader.com/indicators/931-intraday-trend-break-system


http://www.wisestocktrader.com/indicators/1128-exploration-monthly-percent-change-table




http://www.wisestocktrader.com/indicators/1091-volume-spike-exploration


http://www.wisestocktrader.com/indicators/1415-volume-breakout-short.txt



BETTER VOLUME

http://emini-watch.com/free-stuff/volume-indicator/


Volume Spiker by Southwind for Amibroker (AFL)


This a very useful formula to detect volume breakout. As we know volume is a important thing to make a decision in trading. So with use this formula we can easily to find a volume breakout..


http://www.wisestocktrader.com/indicators/276-volume-spiker-by-southwind.txt

http://www.wisestocktrader.com/indicators/264-market-profile-with-volume-and-camarilla-pivots

http://www.wisestocktrader.com/indicators/453-strength-weakness.txt



Volume - compared with Moving Avg (100%) for Amibroker (AFL)

This is principle only another view of the volume. It shows you the difference from the current volume to the moving Volume in percent. I like it, because it is easier to analyze. you dont need to compare the volume with the moving, which has everyday another value. In this formula you see, for example, that sometimes the volume is 300% higher than the AVG. This makes it also easier to use in the exploration.

Set the scale to percent and automatic

//written by Thomas Zmuck
//Date: 15-07-02
//thomas.zm@aon.at

pds = 10;
V1 = V/MA(V,10); V2 = V/MA(V,20);
V3 = V/MA(V,50);

barcolor = IIf(V1 AND V2>1 AND V3>1;

Filter = unsure;
AddColumn(100*V/MA(V,10),"V/ma(V,10)",1.0);
AddColumn(100*V/MA(V,20),"V/ma(V,20)",1.0);
AddColumn(100*V/MA(V,50),"V/ma(V,50)",1.0);
AddColumn(ROC(C,1),"%today");

21 August 2011

Afl links

http://www.wisestocktrader.com/indicators/2023-auto-target

Z SCORE INDICATOR COLOR CODED TO IDENTIFY EASILY OVER BOUGHT AND OVER SOLD..


_SECTION_BEGIN("ZSCORE");
periods = 20;
ZScore = ( Close - MA( Close, periods ) ) / StDev( Close, periods );
color = IIf( ZSCORE >=3.0, ColorRGB(255,0,0),IIf( ZSCORE >=2.75, ColorRGB(0,255,0),IIf( ZSCORE >=2.5, ColorRGB(0,0,255),
IIf( ZSCORE >=2.25, ColorRGB(240,200,13),IIf( ZSCORE >=2,ColorRGB(255,22,160),IIf( ZSCORE >=0,ColorRGB(126,126,184),

IIf( ZSCORE <=-3.0, ColorRGB(255,0,0),IIf( ZSCORE <=-2.75, ColorRGB(0,255,0),IIf( ZSCORE <=-2.5, ColorRGB(0,0,255), IIf( ZSCORE <=-2.25, ColorRGB(240,200,13),IIf( ZSCORE <=-2,ColorRGB(255,22,160),ColorRGB(126,126,184)))))))))))); Plot( ZScore, "ZScore",color, ParamStyle("Style",styleHistogram |styleThick|styleNoTitle ,maskAll) ); Plot(2, "2", colorBlueGrey,4096); Plot(0, "0", colorBlueGrey,4096 ); Plot(-2, "-2", colorBlueGrey,4096); _SECTION_END(); Auto Target for Amibroker (AFL) I like to plot auto-target and see how far a price possibly up or down. You can set your own target. Pick the lowest and the highest of a trend, and this indicator will autocalculate the target. Enjoy. _SECTION_BEGIN("Auto Target Levels"); GraphXSpace=1; Plot(C,"", colorWhite,styleCandle); // Get values for target levels StartBar=SelectedValue(BarIndex()); FinishBar = EndValue( BarIndex() ); i = startbar; period = FinishBar - StartBar; Lo =LLV(L,period); Hi = HHV(H,period); Line0 = 0; Line1 = 0; //Target resisten 1 Line2 = 0; //Target resisten 2 Line3 = 0; //Target resisten 3 Line4 = 0; //Target support 1 Line5 = 0; //Target support 2 Line6 = 0; // Target support 3 Line100 = 0; for( i = startbar; i < finishbar; i++ ) { if(EndValue(C) Ref(C, -1);
DnTick = C < Ref(C, -1); SelBI = SelectedValue(BarIndex()) ; TotUpTick = 0; for(i = SelBI; i < BarCount; i++) { TotUpTick = TotUpTick + UpTick[i]; } ConsecCZ10UP = BarsSince(C <= Ref(C,-1)); ConsecCZ10Dn = BarsSince(C >= Ref(C,-1));
updncz10=(Conseccz10up-Conseccz10dn);
Plot(1,"",colorBlueGrey,styleLine|styleNoLabel|styleNoTitle);
Plot(0,"",ColorRGB(150,150,150),styleDashed|styleLine|styleNoLabel|styleNoTitle);
Plot(-1,"",colorBlueGrey,styleLine|styleNoLabel|styleNoTitle);

Plot(updncz10,"UptickDntick",IIf(updncz10>0,colorBlue,colorRed),styleHistogram|styleThick);
PlotOHLC(1,1,-1,-1,"",ColorRGB(20,20,25),styleCloud|styleNoLabel|styleNoTitle,Null,Null,0,-5);


Price Sup Res



_SECTION_BEGIN("Resistance");

HaClose =EMA((O+H+L+C)/4,3);
HaOpen = AMA( Ref( HaClose, -1 ), 0.5 );
HaHigh = Max( H, Max( HaClose, HaOpen ) );
HaLow = Min( L, Min( HaClose, HaOpen ) );
Temp = Max(High, HaOpen);
Temp = Min(Low,HaOpen);

supres=ParamToggle("Sup_Res","No|Yes",1);
if(supres)
{


Prd1=Param("Res_Period1",2,0,200,1);

test = TEMA ( High , Prd1 ) ;

PK = test > Ref(test,-1) AND Ref(test,1) < High;//Peak PKV0 = ValueWhen(PK,haHigh,0);//PeakValue0 PKV1 = ValueWhen(PK,haHigh,1);//PeakValue1 PKV2 = ValueWhen(PK,haHigh,2);//PeakValue2 MPK = PKV2 < PKV1 AND PKV1 > PKV0 ;//MajorPeak

MPKV = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, PKV1,1); //MajorPeakValue
MPKD = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, DateNum(),1); //MajorPeakDate
SD = IIf(DateNum() < LastValue(MPKD,lastmode = True ), Null, LastValue(MPKV,Lastmode = True));//SelectedDate Plot(SD, "Resist1", colorGreen,ParamStyle("ResStyle1",styleLine|styleNoTitle,maskAll)); MPKV2 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, PKV1,2); //MajorPeakValue MPKD2 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, DateNum(),2); //MajorPeakDate SD2 = IIf(DateNum() < LastValue(MPKD2,lastmode = True ), Null, LastValue(MPKV2,Lastmode = True));//SelectedDate Plot(SD2, "Resist2", colorGreen,ParamStyle("ResStyle2",styleLine|styleNoTitle,maskAll)); MPKV3 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, PKV1,3); //MajorPeakValue MPKD3 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, DateNum(),3); //MajorPeakDate SD3 = IIf(DateNum() < LastValue(MPKD3,lastmode = True ), Null, LastValue(MPKV3,Lastmode = True));//SelectedDate Plot(SD3, "Resist3", colorGreen,ParamStyle("ResStyle3",styleLine|styleNoTitle,maskAll)); MPKV4 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, PKV1,4); //MajorPeakValue MPKD4 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, DateNum(),4); //MajorPeakDate SD4 = IIf(DateNum() < LastValue(MPKD4,lastmode = True ), Null, LastValue(MPKV4,Lastmode = True));//SelectedDate Plot(SD4, "Resist4", colorGreen,ParamStyle("ResStyle4",styleLine|styleNoTitle,maskAll)); MPKV5 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, PKV1,5); //MajorPeakValue MPKD5 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, DateNum(),5); //MajorPeakDate SD5 = IIf(DateNum() < LastValue(MPKD5,lastmode = True ), Null, LastValue(MPKV5,Lastmode = True));//SelectedDate Plot(SD5, "Resist5", colorGreen,ParamStyle("ResStyle5",styleLine|styleNoTitle,maskAll)); MPKV6 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, PKV1,6); //MajorPeakValue MPKD6 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, DateNum(),6); //MajorPeakDate SD6 = IIf(DateNum() < LastValue(MPKD6,lastmode = True ), Null, LastValue(MPKV6,Lastmode = True));//SelectedDate Plot(SD6, "Resist6", colorGreen ,ParamStyle("ResStyle6",styleLine|styleNoTitle,maskAll)); _SECTION_END(); HaClose =EMA((O+H+L+C)/4,3); HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); Temp = Max(High, HaOpen); Temp = Min(Low,HaOpen); _SECTION_BEGIN("Support"); //SP=L > Ref(L,-1) AND Ref(L,1) < L;//Peak Prd2=Param("Sup_Period1",2,0,200,1); test2 = TEMA ( Low , Prd2 ) ; SP = Ref(test2,1) > Low AND test2 < Ref(test2,-1);//Peak SPV0 = ValueWhen(SP,haLow,0);//PeakValue0 SPV1 = ValueWhen(SP,haLow,1);//PeakValue1 SPV2 = ValueWhen(SP,haLow,2);//PeakValue2 //PKV5 = ValueWhen(PK,haHigh,5);//PeakValue5 //PKV6 = ValueWhen(PK,haHigh,6);//PeakValue6 MSP = SPV2 > SPV1 AND SPV1 < SPV0 ;//MajorPeak MSPV = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, SPV1,1); MSPD = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, DateNum(),1); SD = IIf(DateNum() < LastValue(MSPD,lastmode = True ), Null, LastValue(MSPV,Lastmode = True)); Plot(SD,"Support1", colorBrown,ParamStyle("SupportLine1",styleLine|styleNoTitle,maskAll)); MSPV2 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, SPV1,2); MSPD2 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, DateNum(),2); SD2 = IIf(DateNum() < LastValue(MSPD2,lastmode = True ), Null, LastValue(MSPV2,Lastmode = True)); Plot(SD2,"Support2", colorBrown,ParamStyle("SupportLine2",styleLine|styleNoTitle,maskAll)); MSPV3 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, SPV1,3); MSPD3 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, DateNum(),3); SD3 = IIf(DateNum() < LastValue(MSPD3,lastmode = True ), Null, LastValue(MSPV3,Lastmode = True)); Plot(SD3,"Support3", colorBrown,ParamStyle("SupportLine3",styleLine|styleNoTitle,maskAll)); MSPV4 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, SPV1,4); MSPD4 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, DateNum(),4); SD4 = IIf(DateNum() < LastValue(MSPD4,lastmode = True ), Null, LastValue(MSPV4,Lastmode = True)); Plot(SD4,"Support4", colorBrown,ParamStyle("SupportLine4",styleLine|styleNoTitle,maskAll)); MSPV5 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, SPV1,5); MSPD5 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, DateNum(),5); SD5 = IIf(DateNum() < LastValue(MSPD5,lastmode = True ), Null, LastValue(MSPV5,Lastmode = True)); Plot(SD5,"Support5", colorBrown,ParamStyle("SupportLine5",styleLine|styleNoTitle,maskAll)); MSPV6 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, SPV1,6); MSPD6 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, DateNum(),6); SD6 = IIf(DateNum() < LastValue(MSPD6,lastmode = True ), Null, LastValue(MSPV6,Lastmode = True)); Plot(SD6,"Support6", colorBrown,ParamStyle("SupportLine6",styleLine|stylehidden|styleNoTitle,maskAll)); } _SECTION_BEGIN("Price"); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) )); Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 10 % return by 15 day uptrend exploration for Amibroker (AFL) This is very simple formula for finding up trending stocks. Here one can take entry in a stock when It crosses 15 day sma and trades above it for at least 13 days. After taking entry on 13 days hold it for 1 to 1.5 week and will get 10% return here use upper bollinger band as exit and 15 day sma as stoploss. _SECTION_BEGIN("seasionality"); // Define label bar (x) position location #pragma nocache blankRightBars = 5; //insert actual blank right bars specified in Preferences barsInView = Status("lastvisiblebarindex") - Status("firstvisiblebarindex") - blankRightBars; Offset = Param("Offset Bar", 0.95, 0, 1, 0.01); textOffset = BarCount - (Offset * barsInView); TimeFrameSet( inDaily) ; HaClose =EMA((O+H+L+C)/4,3); HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); X=Haopen Haclose, colorRed, IIf( X,7,14));
Plot(20,"", Color,styleHistogram|styleOwnScale|styleNoLabel, 0, 100 );
Plot( 21,"",colorBlack,styleOwnScale|styleArea|styleNoLabel,0, 100 );
PlotText("DAILY TREND", textoffset, 81.05, colorWhite);
CondB=Haopen > Haclose;CONDS=Haopen < Haclose; event1=condS; PlotShapes( IIf(event1 ,shapeDigit1,0) ,5, 0,81.0); event2=CondB; PlotShapes( IIf(event2 ,shapeDigit1,0) , 4, 0,81.0); TimeFrameRestore(); TimeFrameSet( inWeekly) ; HaClose =EMA((O+H+L+C)/4,3); HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); X=HaOpen Haclose, colorRed, IIf( X,7,14));
Plot(40,"", Color, styleHistogram|styleOwnScale|styleNoLabel, 0, 100 );
Plot( 41,"",colorBlack,styleOwnScale|styleArea|styleNoLabel,0, 100 );
PlotText(" WEEKLY TREND", textoffset, 81.20, colorWhite);
CondB1=Haopen > Haclose;CONDS1=Haopen < Haclose; event3=condS1; PlotShapes( IIf(event3 ,shapeDigit2,0) ,5, 0,81.20); event4=CondB1; PlotShapes( IIf(event4 ,shapeDigit2,0) , 4, 0,81.2); TimeFrameRestore(); TimeFrameSet( 10*inDaily) ; HaClose =EMA((O+H+L+C)/4,3); HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); X=Haopen Haclose, colorRed, IIf( X,7,14));
Plot(60,"", Color2, styleHistogram|styleOwnScale|styleNoLabel, 0, 100 );
Plot( 61,"",colorBlack,styleOwnScale|styleArea|styleNoLabel,0, 100 );
PlotText("2 WEEK TREND", textoffset, 81.40, colorWhite);
CondB2=Haopen > Haclose;CONDS2=Haopen < Haclose; event4=condS2; PlotShapes( IIf(event4 ,shapeDigit3,0) ,5, 0,81.40); event5=CondB2; PlotShapes( IIf(event5 ,shapeDigit3,0) , 4, 0,81.4); TimeFrameRestore(); TimeFrameSet(20*inDaily) ; HaClose =EMA((O+H+L+C)/4,3); HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); X=Haopen Haclose, colorRed, IIf( X,7,14));
Plot(80,"", Color4, styleHistogram|styleOwnScale|styleNoLabel, 0, 100 );
Plot( 81,"",colorBlack,styleOwnScale|styleArea|styleNoLabel,0, 100 );
PlotText("MONTHLY TREND", textoffset, 81.55, colorWhite);
CondB3=Haopen > Haclose;CONDS3=Haopen < Haclose; event6=condS3; PlotShapes( IIf(event6 ,shapeDigit4,0) ,5, 0,81.65); event7=CondB3; PlotShapes( IIf(event7 ,shapeDigit4,0) , 4, 0,81.65); TimeFrameRestore(); Sell=CondB AND CondB1 AND CondB2 OR Condb3; Buy= CondS AND CondS1 AND CondS2 OR Conds3; //Cover= Cond1 AND Cond2 OR Cond2 AND Cond3 OR Cond1 AND Cond3 ; //Sell= Cond4 AND Cond5 OR Cond5 AND Cond6 OR Cond4 AND Cond6; Buy=ExRem (Buy,Sell);Sell=ExRem(Sell,Buy); PlotShapes(shapeCircle*Buy, colorGreen,0,81.85); PlotShapes(shapeCircle*Sell, colorRed,0,81.85); GraphXSpace = 15; //...................................... _SECTION_END(); _SECTION_END(); If stocks continue to trade above 15 day sma ones you get 10% return then second entry possible on 21 day. Seasionality for Amibroker (AFL) I have collect it from my friend. It can identify monthly, weekly and daily trend. _SECTION_BEGIN("seasionality"); // Define label bar (x) position location #pragma nocache blankRightBars = 5; //insert actual blank right bars specified in Preferences barsInView = Status("lastvisiblebarindex") - Status("firstvisiblebarindex") - blankRightBars; Offset = Param("Offset Bar", 0.95, 0, 1, 0.01); textOffset = BarCount - (Offset * barsInView); TimeFrameSet( inDaily) ; HaClose =EMA((O+H+L+C)/4,3); HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); X=Haopen Haclose, colorRed, IIf( X,7,14));
Plot(20,"", Color,styleHistogram|styleOwnScale|styleNoLabel, 0, 100 );
Plot( 21,"",colorBlack,styleOwnScale|styleArea|styleNoLabel,0, 100 );
PlotText("DAILY TREND", textoffset, 81.05, colorWhite);
CondB=Haopen > Haclose;CONDS=Haopen < Haclose; event1=condS; PlotShapes( IIf(event1 ,shapeDigit1,0) ,5, 0,81.0); event2=CondB; PlotShapes( IIf(event2 ,shapeDigit1,0) , 4, 0,81.0); TimeFrameRestore(); TimeFrameSet( inWeekly) ; HaClose =EMA((O+H+L+C)/4,3); HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); X=HaOpen Haclose, colorRed, IIf( X,7,14));
Plot(40,"", Color, styleHistogram|styleOwnScale|styleNoLabel, 0, 100 );
Plot( 41,"",colorBlack,styleOwnScale|styleArea|styleNoLabel,0, 100 );
PlotText(" WEEKLY TREND", textoffset, 81.20, colorWhite);
CondB1=Haopen > Haclose;CONDS1=Haopen < Haclose; event3=condS1; PlotShapes( IIf(event3 ,shapeDigit2,0) ,5, 0,81.20); event4=CondB1; PlotShapes( IIf(event4 ,shapeDigit2,0) , 4, 0,81.2); TimeFrameRestore(); TimeFrameSet( 10*inDaily) ; HaClose =EMA((O+H+L+C)/4,3); HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); X=Haopen Haclose, colorRed, IIf( X,7,14));
Plot(60,"", Color2, styleHistogram|styleOwnScale|styleNoLabel, 0, 100 );
Plot( 61,"",colorBlack,styleOwnScale|styleArea|styleNoLabel,0, 100 );
PlotText("2 WEEK TREND", textoffset, 81.40, colorWhite);
CondB2=Haopen > Haclose;CONDS2=Haopen < Haclose; event4=condS2; PlotShapes( IIf(event4 ,shapeDigit3,0) ,5, 0,81.40); event5=CondB2; PlotShapes( IIf(event5 ,shapeDigit3,0) , 4, 0,81.4); TimeFrameRestore(); TimeFrameSet(20*inDaily) ; HaClose =EMA((O+H+L+C)/4,3); HaOpen = AMA( Ref( HaClose, -1 ), 0.5 ); HaHigh = Max( H, Max( HaClose, HaOpen ) ); HaLow = Min( L, Min( HaClose, HaOpen ) ); X=Haopen Haclose, colorRed, IIf( X,7,14));
Plot(80,"", Color4, styleHistogram|styleOwnScale|styleNoLabel, 0, 100 );
Plot( 81,"",colorBlack,styleOwnScale|styleArea|styleNoLabel,0, 100 );
PlotText("MONTHLY TREND", textoffset, 81.55, colorWhite);
CondB3=Haopen > Haclose;CONDS3=Haopen < Haclose; event6=condS3; PlotShapes( IIf(event6 ,shapeDigit4,0) ,5, 0,81.65); event7=CondB3; PlotShapes( IIf(event7 ,shapeDigit4,0) , 4, 0,81.65); TimeFrameRestore(); Sell=CondB AND CondB1 AND CondB2 OR Condb3; Buy= CondS AND CondS1 AND CondS2 OR Conds3; //Cover= Cond1 AND Cond2 OR Cond2 AND Cond3 OR Cond1 AND Cond3 ; //Sell= Cond4 AND Cond5 OR Cond5 AND Cond6 OR Cond4 AND Cond6; Buy=ExRem (Buy,Sell);Sell=ExRem(Sell,Buy); PlotShapes(shapeCircle*Buy, colorGreen,0,81.85); PlotShapes(shapeCircle*Sell, colorRed,0,81.85); GraphXSpace = 15; //...................................... _SECTION_END(); _SECTION_END(); OBV in isolation may not make much sense intraday, All this simple but effective indicator does is to create the shadows of the OBV in the form of 9 WMA and 21 WMA and the crossover of the OBV and shadows tells you to go long or short.As they say “Coming events cast their shadows before” _SECTION_BEGIN("OBV"); Plot( OBV(), _DEFAULT_NAME(), IIf( C > O, ParamColor("Up Color", colorGreen ), ParamColor("Down Color", colorRed ) ), ParamStyle( "Style") );
SetChartBkGradientFill( ParamColor("BgTop",colorBlack),ParamColor("BgBottom",colorBlack),ParamColor("Titleblock",colorLightGrey));

_SECTION_END();

_SECTION_BEGIN("WMA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 300, 1, 10 );
Plot( WMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );
_SECTION_END();

_SECTION_BEGIN("OBV1");
Plot( OBV(), _DEFAULT_NAME(), IIf( C > O, ParamColor("Up Color", colorGreen ), ParamColor("Down Color", colorBlue ) ), ParamStyle( "Style") );
_SECTION_END();

Buy = Cross(OBV(),WMA(OBV(),9));
Sell = Cross(WMA(OBV(),9),OBV());

Short = Sell;
Cover = Buy;
PlotShapes(shapeUpArrow*Buy,colorGreen);

PlotShapes(shapeDownArrow*Sell,colorRed);


_SECTION_BEGIN("WMA1");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 300, 1, 10 );
Plot( WMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );
_SECTION_END();




Trade Entry with Bollinger Bands in down-market for Amibroker (AFL)


Bollinger bands are really fantastic in providing with a limiting value or a standard deviation of the price-hikes. It is also found that if two Bollinger Bands of different parameters are overlapped over one another than it gives a finer edge for the trade entry.

There are actually two Bollingers used in the formula, but only the bottom part is drawn as this formula depicts the entries in the down trend of the market only. It possibly can well be extended for the upmarket. If anyone can do that addition it’ll be appreciated to have it here too :)

I have tried to mimic that in the formula below. Please do feel free to change the formula or comment your findings and pitfalls or benefits of this indicator in your trade.

Enjoy the indicator.

Disclaimer: The author and the site do not guarantee any accuracy of this indicator as well as any loss or profit incurring from using it. Please use only for study and entertainment purpose.


SetFormulaName( "NMN Bollinger Entry" );
SetChartOptions( 1, chartShowDates | chartWrapTitle );

_SECTION_BEGIN( "Bollinger Parameters" );
P = ParamField( "Bollinger Band on", 3 );
Pd1 = Param( "BB 1 Period", 10, 3, 100, 1 );
W1 = Param( "BB 1 Width", 1.35, 0, 50, 0.01 );
Pd2 = Param( "BB 2 Period", 15, 3, 100, 1 );
W2 = Param( "BB 2 Width", 2, 0, 50, 0.01 );

Plot( P, "Price Chart", IIf( O < C, colorBrightGreen, colorRed ), styleCandle ); Plot( bb1 = BBandBot( P, Pd1, W1 ), "Inner/Top Bollinger", colorLightOrange, styleLine ); Plot( bb2 = BBandBot( P, Pd2, W2 ), "Outer/Btm Bollinger", colorLightGrey, styleLine ); _SECTION_END(); _SECTION_BEGIN( "Candle-Bollinger positions" ); DCT = Param( "Down Candle triggger", 1.5, 0.01, 10, 0.01 ); UCT = Param( "Up Candle triggger", 1.5, 0.01, 10, 0.01 ); DnCandle = ( O >= C );
UpCandle = NOT DnCandle; // ( O < C ) // Signals OpenAboveBB1 = O > bb1;
OpenBelowBB1 = O < bb1; CloseAboveBB1 = C > bb1;
CloseBelowBB1 = C < bb1; CloseBelowBB2 = C < bb2; CloseAboveBB2 = C > bb2;

OpenBelowBB2 = O < bb2; OpenAboveBB2 = O > bb2;

OpenBetweenBB = ( bb1 > O ) AND ( bb2 < O ); CloseBetweenBB = ( bb1 > C ) AND ( bb2 < C ); CandleBetweenBB = OpenBetweenBB AND CloseBetweenBB ; DnCandleAcrossBB = ( O > bb1 ) AND ( bb2 > C ) ;
UpCandleAcrossBB = ( C > bb1 ) AND ( bb2 > O ) ;

CandleBelowBB2 = OpenBelowBB2 AND CloseBelowBB2 ;

TotallyBelowBB1 = ( H < bb1 ) AND ( H > bb2 ) ; // without the 2nd condn. its same as 'TotallyBelowBB2'
TotallyBelowBB2 = ( H < bb2 ); TotallyBetweenBB = ( H < bb1 ) AND ( L > bb2 );

CandleBody = IIf( DnCandle, ( O - C ), ( C - O ) ); //CandleBody = IIf(CandleBody==0,0.000001,CandleBody);
FullCandle = ( H - L );
CandleWick = FullCandle - CandleBody;
TopWick = H - IIf( DnCandle, O, C ) ;
BtmWick = IIf( DnCandle, C, O ) - L ;

LastIsDnCandle = Ref( DnCandle, -1 );
LastIsUpCandle = Ref( UpCandle, -1 );

BBGap = ( bb1 - bb2 ); // Gap between the overlapping bollinger-bands

BB_Candle_ratio = BBGap / CandleBody ;
Candle_BB_ratio = CandleBody / BBGap ;
WickCandleRatio = CandleWick / CandleBody ;
CandleWickRatio = CandleBody / CandleWick ;
WickTopBtmRatio = TopWick / BtmWick ;

bb1topcut = IIf( DnCandle, ( O - bb1 ), ( C - bb1 ) );
bb2topcut = IIf( DnCandle, ( O - bb2 ), ( C - bb2 ) );

bb1cut = bb1topcut / CandleBody ;
CandleCutByBB1 = IIf( DnCandle, ( bb1 > C ) AND ( bb1 < O ), ( bb1 > O ) AND ( bb1 < C ) ) ; bb1cutHi = ( abs( bb1cut ) <= ( Param( "High cut by BB1 (in %)", 30, 1, 100, 1 ) / 100 ) ) AND CandleCutByBB1 ; bb1cutLo = ( abs( bb1cut ) >= ( Param( "Low cut by BB1 (in %)", 50, 1, 100, 1 ) / 100 ) ) AND CandleCutByBB1 ;

bb2cut = bb2topcut / CandleBody ;
CandleCutByBB2 = IIf( DnCandle, ( bb2 > C ) AND ( bb2 < O ), ( bb2 > O ) AND ( bb2 < C ) ); bb2cutHi = abs( bb2cut ) <= ( Param( "High cut by BB2 (in %)", 50, 1, 100, 1 ) / 100 ) AND CandleCutByBB2 ; bb2cutLo = abs( bb2cut ) >= ( Param( "Low cut by BB2 (in %)", 60, 1, 100, 1 ) / 100 ) AND CandleCutByBB2 ;

// Down candle 'buy' logic-parts
DnCandle_below_both_BB = DnCandle AND OpenBelowBB2 AND CloseBelowBB2 ;
DnCandle_above_both_BB = DnCandle AND CloseAboveBB1 AND OpenAboveBB1 ;
DnCandle_between_BB = DnCandle AND CandleBetweenBB ;
DnCandle_Across_BB = DnCandleAcrossBB AND ( CandleBody > ( BBGap * DCT ) ) ;
//DnCandleSpansBB = ( O > bb1 ) AND ( C < bb2 ) ; // Up Candle 'buy' logic-parts UpCandleBelowBothBB = UpCandle AND OpenBelowBB2 ; UpCandleAboveBothBB = UpCandle AND OpenAboveBB1 ; UpCandle_between_BB = UpCandle AND ( ( bb1 > C ) AND ( bb2 < C ) ) AND ( ( bb1 > O ) AND ( bb2 < O ) ); UpCandleBetweenBB = UpCandle AND ( bb1 > O ) AND ( bb2 < O ) AND ( bb2 > C );
UpCandle_Across_BB = UpCandleAcrossBB AND ( CandleBody > ( BBGap * UCT ) ) ;

/*--------------------------------------------
TRADE LOGICS
---------------------------------------------*/

Buy0 = ( DnCandle AND bb1cut < 0.7 AND bb1cut > 0.0 AND WickCandleRatio > 0.75 AND WickCandleRatio < 1.0 ) OR ( ( CandleBetweenBB OR CandleBelowBB2 ) AND ( CandleBody > 1 ) AND ( BBGap < 100 ) AND ( IIf( DnCandle, TopWick CandleBody * 2, TopWick > BtmWick AND TopWick > CandleBody * 2 ) ) ) OR
( UpCandle AND ( TopWick > BtmWick ) AND ( TopWick > CandleBody * 2 ) AND ( ( CandleCutByBB1 AND C > bb2 ) OR CandleBetweenBB OR CandleBelowBB2 ) ) OR
( UpCandle AND bb1cutHi AND bb2cutHi );

Buy1 = DnCandle AND bb1cutHi AND BBGap <= CandleBody ; Buy2 = OpenBelowBB1 AND DnCandle_Across_BB ; Buy3 = DnCandle_Across_BB AND ( ( bb1cut < .5 ) AND ( bb2cut > .5 ) ) ;
Buy4 = DnCandle AND bb2cutHi ;

Buy5 = TotallyBelowBB2 AND ( BBGap >= 30 ) AND GapDown();
Buy6 = ( TotallyBelowBB2 OR ( UpCandle AND CloseBelowBB2 ) ) AND ( BBGap <= CandleBody ); Buy7 = ( bb1cut < 0 AND bb2cut > 0 AND bb2cut <= 1.0 ) OR ( UpCandle_Across_BB AND bb2cut > 0.6 ) ;
Buy8 = DnCandle_below_both_BB AND ( ( BBGap <= CandleBody ) OR ( CandleBody == 0 ) ); Buy = Buy0 OR Buy1 OR Buy2 OR Buy3 OR Buy4 OR Buy5 OR Buy6 OR Buy7 OR Buy8; Sell = IIf( GroupID( 1 ) == "Z", Ref( Buy, -10 ), Ref( Buy, -3 ) );//( Ref( Buy, -10 ) AND (GroupID(1)== "Z") ) OR Ref( Buy, -3 ); // back log : 4 day maturity profit/loss : it is a requirement in BD-DSE market Clog = ( 100 * ( C - Ref( C, -3 ) ) / Ref( C, -3 ) ); MaturedSince = IIf( GroupID( 1 ) == "Z", Ref( C, -10 ), Ref( C, -3 ) ); sYield = IIf( Buy, C - HHV( O, 15 ), C - MaturedSince ); Ypercent = ( sYield / MaturedSince ) * 100 ; YpcStr = NumToStr( Ypercent, 12.2 ) + " %"; Yrate = Ypercent / IIf( GroupID( 1 ) == "Z", 11, 4 ); YrateStr = NumToStr( Yrate, 12.2 ) + " %" ; Strength = Buy0 + Buy1 + Buy2 + Buy3 + Buy4 + Buy5 + Buy6 + Buy7 + Buy8; // - Sell; Trade = WriteIf( Buy == True, "Buy", WriteIf( Sell == True, "Sell", "N" ) ); // [Indicator] shape0 = Buy0 * shapeUpTriangle ; shape1 = Buy1 * shapeSmallUpTriangle ; shape2 = Buy2 * shapeSmallUpTriangle ; shape3 = Buy3 * shapeSmallUpTriangle ; shape4 = Buy4 * shapeSmallUpTriangle ; shape5 = Buy5 * shapeSmallUpTriangle ; shape6 = Buy6 * shapeSmallUpTriangle ; shape7 = Buy7 * shapeSmallUpTriangle ; shape8 = Buy8 * shapeSmallUpTriangle ; sellshape = Sell * shapeDownArrow ; shape0color = colorViolet; shape1color = colorBrightGreen; shape2color = colorViolet; shape3color = colorGreen; shape4color = colorRed; shape5color = colorPink; shape6color = colorLavender; shape7color = colorAqua; shape8color = colorDarkRed; sellshapecolor = colorRose; BuySellLetter = IIf( Buy, colorDarkGreen, IIf( Sell, colorRed, colorDefault ) ); BuySellBG = IIf( Buy, colorPaleGreen, IIf( Sell, colorDarkRed, colorDefault ) ); /*------------------------------------------ Automatic Analysis -------------------------------------------*/ TransmitOrder = False; // Set to True to really trade! bi = BarIndex(); cid = ( SelectedValue( bi ) - bi[ 0 ] ); // candle identification Filter = ( Buy OR Sell ) ;//AND Status( "lastbarinrange" ) ; // chooses only the last bar i.e., day or period AASettings = Status( "action" ); if ( AASettings == actionIndicator ) { // [Indicator] PlotShapes( shape0, shape0color, 0, L, -42 ); PlotShapes( shape1, shape1color, 0, L, -12 ); PlotShapes( shape2, shape2color, 0, L, -16 ); PlotShapes( shape3, shape3color, 0, L, -20 ); PlotShapes( shape4, shape4color, 0, L, -24 ); PlotShapes( shape5, shape5color, 0, L, -28 ); PlotShapes( shape6, shape6color, 0, L, -32 ); PlotShapes( shape7, shape7color, 0, L, -34 ); PlotShapes( shape8, shape8color, 0, L, -38 ); PlotShapes( sellshape, sellshapecolor, 0, H, -24 ); } else if ( AASettings == actionCommentary ) { // [Commentary] printf( "Study of parameters.\n---------------------------\n" ); printf( "High @ = %g\n", H ) ; if ( DnCandle[cid] ) { printf( "Open @ = %g\n", O ) ; printf( "Close @ = %g (4dM %g)\n", C, sYield ) ; } else { printf( "Close @ = %g (4dM %g)\n", C, sYield ) ; printf( "Open @ = %g\n", O ) ; } printf( "Low @ = %g\n\n", L ) ; printf( "Volume = %g\n\n", V ) ; printf( "Body of the candle = %g\n", CandleBody ); printf( "Top Wick Size = %g\n", TopWick ); printf( "Bottom Wick Size = %g\n", BtmWick ); printf( "Wick Size = %g\n", CandleWick ); printf( "Full-candle Size = %g\n\n", FullCandle ); printf( "..........................\nCandle type = " + WriteIf( DnCandle, "Down / Red / Black\n\n", "Up / Green / White\n\n" ) ); printf( "Candle:wick ratio = 1 : %g\n", CandleWickRatio ); printf( "Wick:candle ratio = 1 : %g\n\n", WickCandleRatio ); printf( "TopWick:BtmWick ratio = 1 : %g\n\n", WickTopBtmRatio ); printf( "Gap between Bollingers = %g\n\n", BBGap ); printf( "Candle:BBGap ratio = 1 : %g\n", round( Candle_BB_ratio * 100 ) / 100 ); printf( "BBGap:Candle ratio = 1 : %g\n\n", round( BB_Candle_ratio * 100 ) / 100 ) ; printf( WriteIf( Candle_BB_ratio > 1.0, "The 'candle is larger' than the bollinger gap.\n", "" ) +
WriteIf( BB_Candle_ratio < 0, "Candle is away from the Bollinger-gap\n", "" ) + WriteIf( BB_Candle_ratio > 1.00, "The Bollinger gap is wide enough to hold the candle in.\n", "" ) +
WriteIf( CandleBetweenBB, "Candle is inside the bollinger band.\n", "" ) +
WriteIf( ( DnCandle AND OpenBelowBB2 ) OR ( UpCandle AND CloseBelowBB2 ), "The 'candle is outside' and 'below' the bollinger gap.\n", "" ) +
WriteIf( ( DnCandle AND CloseAboveBB1 ) OR ( UpCandle AND OpenAboveBB1 ), "The 'candle is outside' and 'above' the bollinger gap.\n", "" ) +
"..........................\n"
);

if ( DnCandle[cid] )
{
Commentary = "\nBlack / Red / Down Candle :\n~~~~~~~~~~~~~~~~~~" ;

if ( CloseAboveBB1[cid] )
Commentary += "\nCandle closed above Top bollinger." ;
else
if ( OpenBelowBB2[cid] )
Commentary += "\nCandle opens below Bottom Bollinger,\nthus a 'below bollinger candle'.";
else
if ( CloseBetweenBB[cid] AND OpenAboveBB1[cid] )
Commentary += "\nCandle is cut by the top bollinger\nand resides above bottom bollinger.";
else
if ( OpenBetweenBB[cid] AND CloseBelowBB2[cid] )
Commentary += "\nCandle is cut by the bottom bollinger\nand resides below top bollinger.";
else
if ( OpenAboveBB1[cid] AND CloseBelowBB2[cid] )
Commentary += "\nCandle cut by both bollingers.";
else
Commentary += "\nCandle is lying between the bollingers.";
}
else
{
Commentary = "\nWhite / Green / Up Candle :\n~~~~~~~~~~~~~~~~~~" ;

if ( OpenAboveBB1[cid] )
Commentary += "\nCandle started above Top bollinger." ;
else
if ( CloseBelowBB2[cid] )
Commentary += "\nCandle closed below Bottom Bollinger.";
else
if ( OpenBetweenBB[cid] AND CloseAboveBB1[cid] )
Commentary += "\nCandle is cut by the top bollinger\nand starts above bottom bollinger.";
else
if ( CloseBetweenBB[cid] AND OpenBelowBB2[cid] )
Commentary += "\nCandle is cut by the bottom bollinger\nand ends below top bollinger.";
else
if ( CloseAboveBB1[cid] AND OpenBelowBB2[cid] )
Commentary += "\nCandle cut by both bollingers.";
else
Commentary += "\nCandle is lying between the bollingers.";
}

if ( DnCandle_between_BB[cid] )
Commentary += "\nCandle enclosed inside the Bollingers!";
else
if ( DnCandleAcrossBB[cid] OR UpCandleAcrossBB[cid] )
Commentary += "\nCandle spans across the Bollingers.";

printf( "\nbb1cut = %g%% (O - bb1) = %g", /**/bb1cut , bb1topcut );/** /round( bb1cut*10000 ) / 100, bb1topcut );/**/

printf( "\nbb2cut = %g%% (O - bb2) = %g\n", /**/bb2cut, bb2topcut );/** /round( bb2cut*10000 ) / 100, bb2topcut );/**/

printf( Commentary + "\n\n" );
}
else
if ( AASettings == actionScan )
{
// Scan
}
else
if ( AASettings == actionExplore )
{
// Exploration
AddTextColumn( GroupID( 1 ), "Cat", formatChar, IIf( GroupID( 1 ) == "Z", colorWhite, colorDefault ), IIf( GroupID( 1 ) == "Z", colorRed, colorDefault ), 30 );

AddColumn( IIf( GroupID( 1 ) == "Z", Ref( C, -10 ), Ref( C, -3 ) ), "Start Price", 3.2, colorBlue, colorDefault, -1 );
AddColumn( C, "Close", 3.2, colorBlue, colorDefault, -1 );

AddColumn( V, "Total Vol.", 8 ) ;

AddColumn( Strength, "Strength", 1, colorRed, colorDefault, 40 );
// AddTextColumn( Trade, "Trade", 1, BuySellLetter, BuySellBG, -1 );
AddTextColumn( WriteIf( Buy, "Buy", "" ), "Buy", 1, BuySellLetter, IIf( Buy, colorPaleGreen, colorDefault ), -1 );
AddTextColumn( WriteIf( Sell, "Sell", "" ), "Sell", 1, BuySellLetter, IIf( Sell, colorDarkRed, colorDefault ), -1 );

AddColumn( sYield, "Avg.Yield", 1.2, IIf( Buy, colorLightGrey, IIf( sYield < 0, colorRed, colorGreen ) ), colorDefault, -1 );
AddTextColumn( YpcStr, "Yield %", 1, IIf( Buy, colorLightGrey, IIf( Ypercent < 0, colorRed, colorGreen ) ), colorDefault, -1 );
AddTextColumn( YrateStr, "Yield rate", 1, IIf( Buy, colorLightGrey, IIf( Yrate < 0, colorRed, colorGreen ) ), colorDefault, -1 );

AddColumn( round( ROC( Close, 4 )*100 ) / 100, "ROC(4)", 1.2, colorDefault, colorDefault, -1 );

}
else
if ( AASettings == actionBacktest )
{
// Backtest
}

_SECTION_END();

Title = "{{NAME}} - {{INTERVAL}} - {{DATE}} - {{VALUES}}" + "\n";

03 August 2011

Z-Score Indicator

Z-Score Indicator
The Z-Score indicator is used in statistics to determine how far a data element is from the mean.

68% of a given dataset will be 1 standard deviation from the mean or +-1 from the mean. 94% of a given dataset will be +-2 standard deviations from the mean.

This would tell us that if a value in a sample (stock price in for this discussion) is beyond +-2 standard deviations from the mean it would be considered an anomaly or to use other stock technical analysis terms overbought or oversold. This would also tell use that typically 68% of the data should fall within +-1 standard deviation from the mean, in other words moving beyond +-1 standard deviation can prove to be the acceleration of a trend (or jump in price) that may soon reverse.

Z-Score

The chart of the S&P 500 below shows when the Z-Score indicator could have been applied to determine if the trend was about to change.
Z-Score Indicator

How to Plot: Select the Z-Score indicator from the drop down box as shown below. Enter the number of days in the parameter box to the right of the indicator.
Z-Score Indicator

How To Use: Use the Z-Score indicator with indicators such as Momentum and RSI to confirm the turning point in stock prices based on a +-1 or +-2 standard deviations.

If you are an AMIBroker user you can download this formula from the AMIBroker site.




/*-----------------------------------------------------------
MTR Investors Group - www.MTRIG.com

Statistical Z-Score Indicator: Tracks how many standard
deviations the price is from the mean.

For more information on this indicator see the links below.

MTRIG - Reference
http://blog.mtrig.com/mtrig/blog/page/Z-Score-Indicator.aspx

Z-Score Trader's Notebook Article
http://premium.working-money.com/wm/display.asp?art=344

AMIBroker forumula on Traders.com
http://www.traders.com/Documentation/FEEDbk_docs/Archive/022003/TradersTips/TradersTips.html

Z-Score in Wikipedia
http://en.wikipedia.org/wiki/Standard_score
-------------------------------------------------------------*/

periods = Param( "Period", 20, 1,3, 1);

ZScore = ( Close - MA( Close, periods ) ) / StDev( Close, periods );

Plot(ZScore, "Z-Score", colorDarkGrey );
Plot(2, "2", colorBlueGrey);
Plot(0, "0", colorBlueGrey );
Plot(-2, "-2", colorBlueGrey);

//3 Gradient Color

_SECTION_BEGIN("3 color gradient");

priceAxesWidth=0;
dateAxesHeight=0;
TitleHeight=0;

pxwidth = Status("pxwidth");
pxheight = Status("pxheight");

chartwidth = pxwidth-priceAxesWidth;
chartheight = pxheight-dateAxesHeight;

topColor=ParamColor("topColor",ColorRGB(207,254,240) );
centerColor=ParamColor("centerColor", ColorRGB(249,236,164));
botColor=ParamColor("BottomColor", ColorRGB( 253,223,196));
priceAxesColor=ParamColor("priceAxesColor", colorWhite );
dateAxesColor=ParamColor("dateAxesColor", colorWhite);

relPos=Param("centerPosition%",50,0,100,1)/100;
centerHeight=chartheight*Param("centerHeight%",10,0,100,1)/100;
x0=0;
y0=Max(TitleHeight,chartheight*relPos-centerHeight/2);
x1=chartwidth;
y1=Min(chartheight,chartheight*relPos+centerHeight/2);

GfxSetBkMode( 1 );
GfxSetOverlayMode(1);
GfxGradientRect(0,0,chartwidth,TitleHeight, colorWhite ,colorWhite);
GfxGradientRect(chartwidth,0,pxwidth,pxheight, priceAxesColor
,priceAxesColor);
GfxGradientRect(0,chartheight,chartwidth,pxheight, dateAxesColor
,dateAxesColor);
GfxGradientRect(x0,y0,x1,y1, CenterColor ,CenterColor );
GfxGradientRect(0,TitleHeight,chartwidth, y0,topColor, CenterColor );
GfxGradientRect(0,y1,chartwidth, chartheight, CenterColor ,botColor);

_SECTION_END();

29 July 2011

csv

SUCCESS!!!???

Success demands you stay focused. Going on tilt over losses due to small stop losses, bad timing, having full time job, etc. – are excuses to humans seeking excuses. True professionals understand stalking currency pairs and managing risk management until finding Zero Risk trades that run.
Do you spend quality time sulking over bad trades for an extended period?
History and many in-house surveys suggest students that experience at least three consecutive bad trades begin to seriously doubt their abilities. Reader’s Digest version: They FREAK out and start to revert back to old habits, due to inexperience.
Humans revert back to old habits, a comfort zone when times go bad learning a new craft. I’m amazed at amount of people throwing money around for software searching for easy access to profits. Most never withstand the onslaught of understanding how to deal with losses.
Without learning how to deal with losses, traders will never fully grasp or understand the wins. Risk management is vital to one’s continued success. Embrace losses. Don’t accept them, but embrace losses as part of the journey.
This will be a key to those trading live accounts. Learning to accept losses without fear, self-doubt, regret and knowing your trading plan will produce over the long haul. Another term I use is called the Laws of Probability. My strength is in using numbers where I have the edge in advance.
This brings calm and confidence to seasoned traders.
How can you make the best of a setback?
First, identify what you did right and what you did wrong. Sometimes a trade goes wrong because you were in a bad mood. Perhaps you were stressed out or tried to risk too much money. Perhaps you didn’t prepare far enough in advance for a trade. Maybe your trading approach was inappropriate for current market conditions. You may had a small stop loss and bad timing caused a reversal to take you out before the pair turned around and went in direction you thought.
Things may have not gone your way because you did not trade under optimal conditions. It’s necessary, however, to identify those conditions where you trade at your best and to trade under those conditions
Second, don’t be afraid to identify what you did wrong and admit it. The biggest obstacle to improving your trading approach is to deny you have limitations and to try to cover them up. We usually engage in such deceptions because we believe that we cannot overcome our limitations. If we have the courage to admit what we did wrong, however, we can be more open to change.
Third, it’s vital to be committed to making a change. You must be willing to do whatever it takes to change. Making a change is difficult, and if your heart isn’t it in, you will find a variety of reasons to not change. In the end, you must make the decision to change in order to actually change. You cannot just think, “I would like to change or it would be advantages to change,” but you must think, “I am determined to make a change.”
Finally, you must maintain optimism. You must believe that change is possible and that if you work hard enough, you will achieve the change you desire.
When searching for success as a trader, it’s vital to continue to improve. You must pick yourself up after a setback. When your ego is hurt, you cannot wallow in self-pity. You must get up and fight. Losses are only setbacks if you think of them that way. Rather than see a loss as a tragedy, look at it as a stepping stone on the path to more profitable trading.
Success is a lousy teacher. It seduces smart people into thinking they can’t lose.
–Bill Gates

28 July 2011

example afl write

_SECTION_BEGIN("AFL Example");
/*
This is an attempt to provide a basic trading system AFL. The system is purely
imaginary
AND NOT provided as one that would make money. This is just to provide a guide
to learners
on the common components of writing AFL.


When you copy/paste ensure the existing continuous lines have not been wrapped.
This wrapping
can create error signals when you try to use the code. Click on the check afl
button in the
editor before trying to apply or scan.
I have used slash-asterisk /* */ /* for my comments to get around the problem
of wrapping,
which could happen if you used double slash //

I hope this helps the beginners in creating AFL code

*/

/*firstly some basics common*/
SetBarsRequired(10000,10000); /* this ensures that the charts include all bars
AND NOT just those on screen */
SetFormulaName("Sample System"); /*name it for backtest report identification
*/
SetTradeDelays( 1, 1, 1, 1 ); /* delay entry/exit by one bar */
SetOption( "initialequity", 100000 ); /* starting capital */
PositionSize = -10; /* trade size will be 10% of available equty */
SetOption( "MaxOpenPositions", 6 ); /* I don't want to comit more than 60% of
Equity at any one time */
SetOption( "PriceBoundChecking", 1 ); /* trade only within the chart bar's
price range */
SetOption( "CommissionMode", 2 ); /* set commissions AND costs as $ per trade
*/
SetOption( "CommissionAmount", 32.95 ); /* commissions AND cost */
SetOption( "UsePrevBarEquityForPosSizing", 1 ); /*set the use of last bars
equity for trade size*/
PositionScore = 100/C; /*Set the order for which stock trades when get mulitple
signals in one bar in backtesting */

//Trade system
/*
Buy when exp mov avg crosses and the high is highest for 50 bars
Sell when exp mov avg crosses back
Cross is first variable moves to above the second variable
*/

LongPer = Param("Long Period", 50, 30, 100, 5 ); /* select periods with
parameter window */
ShortPer = Param("Short Period", 5, 3, 10, 1 );

LongMA = EMA( C, LongPer );
ShortMA = EMA( C, ShortPer );
LastHigh = HHV( H, LongPer );

Buy = Cross( ShortMA, LongMA ) AND H > Ref( LastHigh, -1 );
/* ref,-1 is used for the high to have todays high greater than the previous 50
bar high.
To just use H==LastHigh couold mean a previous high was equal to current
high */
Sell = Cross( LongMA, ShortMA );
/* exrem is one method to remove surplus strade signals*/
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);


/* Now for exploration results.
Will restrict results of exploration to when the Buy AND Sell signals occur

You can use Filter=1; to display every bar result */

Filter = Buy OR Sell;
AddTextColumn( FullName(), "Company Name" );
AddColumn( Buy, "Buy", 1 );
AddColumn( Sell, "Sell", 1 );
AddColumn( C, "Close", 1.3 );
AddColumn( H, "High", 1.3 );
AddColumn( LastHigh, "HHV", 1.3 );
AddColumn( LongMA, "Long MA", 1,3 );
AddColumn( ShortMA, "Short MA", 1,3 );


/* Now to show this on a chart */
/* I use WriteVal to limit the values to the wanted number of decimal places,
seeing a value of 5 decimal places can be frustrating.
I have included additional information in the plot title sections to add
some
information to the title block */

GraphXSpace = 10; /* create empty space of 10% top and bottom of chart */

Plot( C, " Close Price", colorGrey50, styleBar );
Plot( LongMA, " EMA(C,"+WriteVal(LongPer,1)+")", colorRed,
styleLine|styleNoRescale );
Plot( ShortMA, " EMA(C,"+WriteVal(ShortPer,1)+")", colorGreen,
styleLine|styleNoRescale );
Plot( Ref(Lasthigh,-1), " HHV(H,"+WriteVal(LongPer,1)+")", colorBlue,
styleNoLine|styleDots|styleNoRescale );

/* styleNoRescale in the plots stops the added plots from compressing the
original bar chart to the middle of the pane */

PlotShapes( shapeUpArrow*Buy, colorGreen, 0, L, -10 );
PlotShapes( shapeDownArrow*Sell, colorRed, 0, H, -10 );

Title = " {{NAME}} {{DATE}} {{INTERVAL}} "+_DEFAULT_NAME()+" Chart values :
{{VALUES}} ";
/* _DEFAULT_NAME() shows the section name or, if not present, the file name
the items in {{}} are short cuts for the title block. It can be done long hand

Title = Name() +" "+ Date() +" "+ "{{INTERVAL}}"+_DEFAULT_NAME()+" Chart values
: " +
" Close Price = " + C +
" EMA(C,"+WriteVal(LongPer,1)+") = "+WriteVal(LongMA,1.3) +
" EMA(C,"+WriteVal(ShortPer,1)+") = "+WriteVal(ShortMA,1.3) +
" HHV(H,"+WriteVal(LongPer,1)+") = "+WriteVal(Ref(LastHigh,-1),1.3) ;

*/

_SECTION_END();

example afl write

_SECTION_BEGIN("AFL Example");
/*
This is an attempt to provide a basic trading system AFL. The system is purely
imaginary
AND NOT provided as one that would make money. This is just to provide a guide
to learners
on the common components of writing AFL.


When you copy/paste ensure the existing continuous lines have not been wrapped.
This wrapping
can create error signals when you try to use the code. Click on the check afl
button in the
editor before trying to apply or scan.
I have used slash-asterisk /* */ /* for my comments to get around the problem
of wrapping,
which could happen if you used double slash //

I hope this helps the beginners in creating AFL code

*/

/*firstly some basics common*/
SetBarsRequired(10000,10000); /* this ensures that the charts include all bars
AND NOT just those on screen */
SetFormulaName("Sample System"); /*name it for backtest report identification
*/
SetTradeDelays( 1, 1, 1, 1 ); /* delay entry/exit by one bar */
SetOption( "initialequity", 100000 ); /* starting capital */
PositionSize = -10; /* trade size will be 10% of available equty */
SetOption( "MaxOpenPositions", 6 ); /* I don't want to comit more than 60% of
Equity at any one time */
SetOption( "PriceBoundChecking", 1 ); /* trade only within the chart bar's
price range */
SetOption( "CommissionMode", 2 ); /* set commissions AND costs as $ per trade
*/
SetOption( "CommissionAmount", 32.95 ); /* commissions AND cost */
SetOption( "UsePrevBarEquityForPosSizing", 1 ); /*set the use of last bars
equity for trade size*/
PositionScore = 100/C; /*Set the order for which stock trades when get mulitple
signals in one bar in backtesting */

//Trade system
/*
Buy when exp mov avg crosses and the high is highest for 50 bars
Sell when exp mov avg crosses back
Cross is first variable moves to above the second variable
*/

LongPer = Param("Long Period", 50, 30, 100, 5 ); /* select periods with
parameter window */
ShortPer = Param("Short Period", 5, 3, 10, 1 );

LongMA = EMA( C, LongPer );
ShortMA = EMA( C, ShortPer );
LastHigh = HHV( H, LongPer );

Buy = Cross( ShortMA, LongMA ) AND H > Ref( LastHigh, -1 );
/* ref,-1 is used for the high to have todays high greater than the previous 50
bar high.
To just use H==LastHigh couold mean a previous high was equal to current
high */
Sell = Cross( LongMA, ShortMA );
/* exrem is one method to remove surplus strade signals*/
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);


/* Now for exploration results.
Will restrict results of exploration to when the Buy AND Sell signals occur

You can use Filter=1; to display every bar result */

Filter = Buy OR Sell;
AddTextColumn( FullName(), "Company Name" );
AddColumn( Buy, "Buy", 1 );
AddColumn( Sell, "Sell", 1 );
AddColumn( C, "Close", 1.3 );
AddColumn( H, "High", 1.3 );
AddColumn( LastHigh, "HHV", 1.3 );
AddColumn( LongMA, "Long MA", 1,3 );
AddColumn( ShortMA, "Short MA", 1,3 );


/* Now to show this on a chart */
/* I use WriteVal to limit the values to the wanted number of decimal places,
seeing a value of 5 decimal places can be frustrating.
I have included additional information in the plot title sections to add
some
information to the title block */

GraphXSpace = 10; /* create empty space of 10% top and bottom of chart */

Plot( C, " Close Price", colorGrey50, styleBar );
Plot( LongMA, " EMA(C,"+WriteVal(LongPer,1)+")", colorRed,
styleLine|styleNoRescale );
Plot( ShortMA, " EMA(C,"+WriteVal(ShortPer,1)+")", colorGreen,
styleLine|styleNoRescale );
Plot( Ref(Lasthigh,-1), " HHV(H,"+WriteVal(LongPer,1)+")", colorBlue,
styleNoLine|styleDots|styleNoRescale );

/* styleNoRescale in the plots stops the added plots from compressing the
original bar chart to the middle of the pane */

PlotShapes( shapeUpArrow*Buy, colorGreen, 0, L, -10 );
PlotShapes( shapeDownArrow*Sell, colorRed, 0, H, -10 );

Title = " {{NAME}} {{DATE}} {{INTERVAL}} "+_DEFAULT_NAME()+" Chart values :
{{VALUES}} ";
/* _DEFAULT_NAME() shows the section name or, if not present, the file name
the items in {{}} are short cuts for the title block. It can be done long hand

Title = Name() +" "+ Date() +" "+ "{{INTERVAL}}"+_DEFAULT_NAME()+" Chart values
: " +
" Close Price = " + C +
" EMA(C,"+WriteVal(LongPer,1)+") = "+WriteVal(LongMA,1.3) +
" EMA(C,"+WriteVal(ShortPer,1)+") = "+WriteVal(ShortMA,1.3) +
" HHV(H,"+WriteVal(LongPer,1)+") = "+WriteVal(Ref(LastHigh,-1),1.3) ;

*/

_SECTION_END();

example afl write

_SECTION_BEGIN("AFL Example");
/*
This is an attempt to provide a basic trading system AFL. The system is purely
imaginary
AND NOT provided as one that would make money. This is just to provide a guide
to learners
on the common components of writing AFL.


When you copy/paste ensure the existing continuous lines have not been wrapped.
This wrapping
can create error signals when you try to use the code. Click on the check afl
button in the
editor before trying to apply or scan.
I have used slash-asterisk /* */ /* for my comments to get around the problem
of wrapping,
which could happen if you used double slash //

I hope this helps the beginners in creating AFL code

*/

/*firstly some basics common*/
SetBarsRequired(10000,10000); /* this ensures that the charts include all bars
AND NOT just those on screen */
SetFormulaName("Sample System"); /*name it for backtest report identification
*/
SetTradeDelays( 1, 1, 1, 1 ); /* delay entry/exit by one bar */
SetOption( "initialequity", 100000 ); /* starting capital */
PositionSize = -10; /* trade size will be 10% of available equty */
SetOption( "MaxOpenPositions", 6 ); /* I don't want to comit more than 60% of
Equity at any one time */
SetOption( "PriceBoundChecking", 1 ); /* trade only within the chart bar's
price range */
SetOption( "CommissionMode", 2 ); /* set commissions AND costs as $ per trade
*/
SetOption( "CommissionAmount", 32.95 ); /* commissions AND cost */
SetOption( "UsePrevBarEquityForPosSizing", 1 ); /*set the use of last bars
equity for trade size*/
PositionScore = 100/C; /*Set the order for which stock trades when get mulitple
signals in one bar in backtesting */

//Trade system
/*
Buy when exp mov avg crosses and the high is highest for 50 bars
Sell when exp mov avg crosses back
Cross is first variable moves to above the second variable
*/

LongPer = Param("Long Period", 50, 30, 100, 5 ); /* select periods with
parameter window */
ShortPer = Param("Short Period", 5, 3, 10, 1 );

LongMA = EMA( C, LongPer );
ShortMA = EMA( C, ShortPer );
LastHigh = HHV( H, LongPer );

Buy = Cross( ShortMA, LongMA ) AND H > Ref( LastHigh, -1 );
/* ref,-1 is used for the high to have todays high greater than the previous 50
bar high.
To just use H==LastHigh couold mean a previous high was equal to current
high */
Sell = Cross( LongMA, ShortMA );
/* exrem is one method to remove surplus strade signals*/
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);


/* Now for exploration results.
Will restrict results of exploration to when the Buy AND Sell signals occur

You can use Filter=1; to display every bar result */

Filter = Buy OR Sell;
AddTextColumn( FullName(), "Company Name" );
AddColumn( Buy, "Buy", 1 );
AddColumn( Sell, "Sell", 1 );
AddColumn( C, "Close", 1.3 );
AddColumn( H, "High", 1.3 );
AddColumn( LastHigh, "HHV", 1.3 );
AddColumn( LongMA, "Long MA", 1,3 );
AddColumn( ShortMA, "Short MA", 1,3 );


/* Now to show this on a chart */
/* I use WriteVal to limit the values to the wanted number of decimal places,
seeing a value of 5 decimal places can be frustrating.
I have included additional information in the plot title sections to add
some
information to the title block */

GraphXSpace = 10; /* create empty space of 10% top and bottom of chart */

Plot( C, " Close Price", colorGrey50, styleBar );
Plot( LongMA, " EMA(C,"+WriteVal(LongPer,1)+")", colorRed,
styleLine|styleNoRescale );
Plot( ShortMA, " EMA(C,"+WriteVal(ShortPer,1)+")", colorGreen,
styleLine|styleNoRescale );
Plot( Ref(Lasthigh,-1), " HHV(H,"+WriteVal(LongPer,1)+")", colorBlue,
styleNoLine|styleDots|styleNoRescale );

/* styleNoRescale in the plots stops the added plots from compressing the
original bar chart to the middle of the pane */

PlotShapes( shapeUpArrow*Buy, colorGreen, 0, L, -10 );
PlotShapes( shapeDownArrow*Sell, colorRed, 0, H, -10 );

Title = " {{NAME}} {{DATE}} {{INTERVAL}} "+_DEFAULT_NAME()+" Chart values :
{{VALUES}} ";
/* _DEFAULT_NAME() shows the section name or, if not present, the file name
the items in {{}} are short cuts for the title block. It can be done long hand

Title = Name() +" "+ Date() +" "+ "{{INTERVAL}}"+_DEFAULT_NAME()+" Chart values
: " +
" Close Price = " + C +
" EMA(C,"+WriteVal(LongPer,1)+") = "+WriteVal(LongMA,1.3) +
" EMA(C,"+WriteVal(ShortPer,1)+") = "+WriteVal(ShortMA,1.3) +
" HHV(H,"+WriteVal(LongPer,1)+") = "+WriteVal(Ref(LastHigh,-1),1.3) ;

*/

_SECTION_END();

BASIC AFL

The indicator logic is described in the January issue of TASC and sounds intriguing. Without rehashing the details of the indicator calculation, it is very similar to Welles Wilder’s Directional Movement Index Calculation (DMI) except that Wilder’s Directional Movement (largest part of today’s range outside of yesterday’s range) is replaced by calculating the differences between today’s High and yesterday’s Low (positive Vortex Movement) and today’s Low and yesterday’s High (negative Vortex Movement).

Go long when the VI (or Dmi) goes from less than zero to greater than zero.
Go short when the VI (or Dmi) goes from above zero to less than zero.

period = Param("Period", 14, 2 );

VMP = Sum( abs( H - Ref( L, -1 ) ), period );
VMM = Sum( abs( L - Ref( H, -1 ) ), period );
STR = Sum( ATR( 1 ), period );

VIP = VMP / STR;
VIM = VMM / STR;

Plot( VIP, "VI"+period+"+", colorBlue);
Plot( VIM, "VI"+period+"-", colorRed );



SIMPLE TREND

_SECTION_BEGIN("StockManiacs Trendline - www.stockmaniacs.net");
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
THIS SECTION DRAWS TD TREND LINES */

percent = 0.01 * 1; /* Adjust this percent as necessary, */
firstpointL = 2;
firstpointH = 2;

y0=LastValue(Trough(L,percent,firstpointL));
y1=LastValue(Trough(Ref(L,-1),percent,1));

for( i = 1; i < BarCount AND y0 >= y1; i++ )
{

firstpointL++;
y0=LastValue(Trough(L,percent,firstpointL));
}

x0=BarCount - 1 - LastValue(TroughBars(L,percent,firstpointL));
x1=BarCount - 1 - LastValue(TroughBars(Ref(L,-1),percent,1));
LineL = LineArray( x0, y0, x1, y1, 1 );
/*
Plot(C, "C", colorBlack, styleCandle);
*/
Plot( LineL, " Support Trend line", colorGreen,4 +8 );


yt0=LastValue(Peak(H,percent,firstpointH));
yt1=LastValue(Peak(Ref(H,-1),percent,1));

for(i = 1; i < BarCount AND yt0 <= yt1; i++ ) { firstpointH++; yt0=LastValue(Peak(H,percent,firstpointH)); } xt0=BarCount - 1 - LastValue(PeakBars(H,percent,firstpointH)); xt1=BarCount - 1 - LastValue(PeakBars(Ref(H,-1),percent,1)); LineH = LineArray( xt0, yt0, xt1, yt1, 1 ); Plot( LineH, "Resistance Trend line", colorRed,4 + 8 ); /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ _SECTION_END(); _SECTION_BEGIN("Price"); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) )); Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); _SECTION_END(); CANDLE PATTERN HAMMER /******************************************************* Candlestick Commentary Load this file into the Commentary Option of the Analysis tab. Green arrows indicate bullish candles. Red arrows indicate bearish candles. Scroll down the commentary for comments. This is a work in progress. Thanks to all on this forum whose code I may have incorporated into this file. Comments are from Steve Nison "Japanese Candlestick Charting Techniques" and the LitWick web site. **********************************************************/ /*Body Colors*/ whiteBody=C>=O;
blackBody=O>C;

/*Body Size*/
smallBodyMaximum=0.0025;//less than 0.25%
LargeBodyMinimum=0.01;//greater than 1.0%
smallBody=(O>=C*(1-smallBodyMaximum) AND whiteBody)
OR (C>=O*(1-smallBodyMaximum) AND blackBody);
largeBody=(C>=O*(1+largeBodyMinimum) AND whiteBody)
OR C<=O*(1-largeBodyMinimum) AND blackBody; mediumBody=NOT LargeBody AND NOT smallBody; identicalBodies=abs(abs(Ref(O,-1)-Ref(C,-1))-abs(O-C)) < abs(O-C)*smallBodyMaximum; realBodySize=abs(O-C); /*Shadows*/ smallUpperShadow=(whiteBody AND H<=C*(1+smallBodyMaximum)) OR (blackBody AND H<=O*(1+smallBodyMaximum)); smallLowerShadow=(whiteBody AND L>=O*(1-smallBodyMaximum))
OR (blackBody AND L>=C*(1-smallBodyMaximum));
largeUpperShadow=(whiteBody AND H>=C*(1+largeBodyMinimum))
OR (blackBody AND H>=O*(1+largeBodyMinimum));
largeLowerShadow=(whiteBody AND L<=O*(1-largeBodyMinimum)) OR (blackBody AND L<=C*(1-largeBodyMinimum)); /*Gaps*/ upGap= IIf(Ref(blackBody,-1)AND whiteBody AND O>Ref(O,-1),1,
IIf(Ref(blackbody,-1) AND blackBody AND C>Ref(O,-1),1,
IIf(Ref(whiteBody,-1) AND whiteBody AND O>Ref(C,-1),1,
IIf(Ref(whiteBody,-1) AND blackBody AND C>Ref(C,-1),1,0))));

downGap=IIf(Ref(blackBody,-1)AND whiteBody AND C2*realBodySize) OR
(whiteBody AND abs(H-C)>2*realBodySize));
Hammer = (((H-L)>3*(O-C)) AND ((C-L)/(0.001+H-L)>0.6) AND ((O-L)/(0.001+H-L)>0.6));
InvertedHammer = (((H-L)>3*(O-C)) AND ((H-C)/(0.001+H-L)>0.6) AND ((H-O)/(0.001+H-L)>0.6));
//Hammer=smallUpperShadow AND NOT doji AND
// ((blackBody AND abs(C-L)>2*realBodySize) OR
// (whiteBody AND abs(L-O)>2*realBodySize));

tweezerTop=abs(H-Ref(H,-1))<=H*0.0025; tweezerBottom=abs(L-Ref(L,-1))<=L*0.0025; engulfing= IIf(blackBody AND Ref(blackbody,-1) AND CRef(O,-1),1,
IIf(blackBody AND Ref(whiteBody,-1) AND O>Ref(C,-1) AND CRef(C,-1) AND ORef(O,-1)AND ORef(L,-1),1,
IIf(blackBody AND Ref(whiteBody,-1) AND C>Ref(L,-1) AND ORef(L,-1),1,
IIf(whiteBody AND Ref(blackBody,-1) AND O>Ref(L,-1) AND
CRef(C,-1),1,
IIf(blackBody AND Ref(whiteBody,-1) AND C>Ref(O,-1) AND ORef(O,-1),1,
IIf(whiteBody AND Ref(blackBody,-1) AND O>Ref(C,-1) AND
C Ref( High , -1 ) OR Ref(x1, -2) AND Close > Ref( High , -2 )OR Ref(x1, -3) AND Close > Ref( High , -3 );
GetreadyBuy1=((NOT Ref(GetreadyBuy,-1)) AND (NOT Ref(GetreadyBuy,-2)));
GetreadyBuy3=GetreadyBuy1 AND GetReadyBuy;
Buy=Ref(GetreadyBuy, -1) AND C>Ref(L,-1);
Buy1=(NOT Ref(Buy,-1));
Buy3=Buy1 AND Buy;
BuyStop=Ref(GetreadyBuy,-1) AND (Ref(L,-1));
x2=InvertedHammerSpecial;
GetreadySell=Ref(x2, -1) AND Close < Ref( Low , -1 ) OR Ref(x2, -2) AND Close < Ref( Low , -2 )OR Ref(x2, -3) AND Close < Ref( Low , -3 ); GetreadySell1=((NOT Ref(GetreadySell,-1)) AND (NOT Ref(GetreadySell,-2))); GetreadySell3=GetreadySell1 AND GetReadySell; Short=Ref(GetreadySell, -1) AND CRef(L,-2);



Sell1=((NOT Ref(Sell,-1)) AND (NOT Ref(Sell,-2)));
Sell2=Sell1 AND Sell;

Cover1=((NOT Ref(Cover,-1)) AND (NOT Ref(Cover,-2)));
Cover2=Cover1 AND Cover;




_SECTION_BEGIN("Title");
if( Status("action") == actionIndicator )
(
Title = EncodeColor(colorYellow)+ "Winston system - 1-hammer, 2-getready, up/down arrow=Enter position, Orange colour short and white colour long, white dot trailing profit exit long and orange dot trailing profit exit short, triangles are pivot markers" + " - " + Name() + " - " + EncodeColor(colorYellow)+ Interval(2) + EncodeColor(colorWhite) +
" - " + Date() +" - "+"\n" +EncodeColor(colorYellow) + "Vol= "+ WriteVal(V)+"\n"+ EncodeColor(colorYellow)+
WriteIf(x1, "1-Hammer Special"+C+" ","")+
WriteIf(GetreadyBuy3, "2-Get Ready to Buy"+C+" ","")+
WriteIf(Buy3, "BUY AT "+C+" ","")+
WriteIf(BuyStop, "BUYSTOP AT"+Ref(L,-2)+" ","")+
WriteIf(Sell2, "Exit Buy at "+C+" ","")+




WriteIf(x2, "1-Inverted Hammer Special"+C+" ","")+
WriteIf(GetreadySell3, "2-Get Ready to Short"+C+" ","")+
WriteIf(Short3, " SHORT AT "+C+" ","")+
WriteIf(ShortStop, "SHORTSTOP AT "+Ref(H,-2)+" ","")+
WriteIf(Cover2, "Exit short at "+C+" ",""));


Plot(C,"Close",colorWhite,64);
PlotShapes(x1*shapeDigit1,colorWhite,0,L);
PlotShapes(GetreadyBuy3*shapeDigit2,colorWhite,0,L);
PlotShapes(Buy3*shapeUpArrow,colorWhite,0,L,Offset=-45);
PlotShapes(Sell2*shapeSmallCircle,colorWhite,0,H,Offset=45);

PlotShapes(x2*shapeDigit1,colorOrange,0,H,Offset=25);
PlotShapes(GetreadySell3*shapeDigit2,colorOrange,0,H,Offset=25);
PlotShapes(Short3*shapeDownArrow,colorOrange,0,H,Offset=-45);
PlotShapes(Cover2*shapeSmallCircle,colorOrange,0,L,Offset=-45);

AlertIf( Ref(GetreadyBuy3, -1), "SOUND C:\\Windows\\Media\\Ringin.wav", "Get Ready To Buy", 2 );
AlertIf( Ref(Buy3, -1), "SOUND C:\\Windows\\Media\\Ringin.wav", "Buy Now", 2 );
AlertIf( Ref(GetreadySell3, -1), "SOUND C:\\Windows\\Media\\Ringin.wav", "Get Ready To Short", 2 );
AlertIf( Ref(Short3, -1), "SOUND C:\\Windows\\Media\\Ringin.wav", "Short Now", 2 );

RSIperiod = 14; // Param("RSI p",3,14,30,1);
Percent = 5; // Param("ZIG %",8,9,15,1);
EMAperiod = 9; //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", colorDarkRed, styleLine); Plot(ValueWhen( supbase==Base, LLV(L,HHVperiod) ), "Support Level", colorDarkGreen, styleLine); } //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 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 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; jendR AND medR>startR AND abs(startR-endR)<0.02*(startR+endR) AND dt1LastValue(x)-back;
MaxGraph = 10;
Graph1 = C;
Graph1Style=64;
GraphXSpace=5;

/*H&S Neck Line*/

Aper = medt1-startt1;
bper = endt1-medt1;
La = LastValue(ValueWhen(x==medt1,LLV(L,Aper)));
Lb = LastValue(ValueWhen(x==-1+endt1,LLV(L,bper)));
Fa=L==La AND x>startt1 AND xmedt1 AND xstartt-5,trendlineS,-1e10);Graph3BarColor=5;
//-------------------------------------------------------------------------------------------------
/*Inverted H & S*/

tpR = TroughBars( s12, per, 1 ) == 0;
tendt1 = LastValue(ValueWhen(tpr,x,1));
tmedt1 = LastValue(ValueWhen(tpr,x,2));
tstartt1 = LastValue(ValueWhen(tpr,x,3));
tdt1 = tendt1-tstartt1;
C2 = x==tendt1 OR x==tmedt1 OR x==tstartt1;
tendR = LastValue(ValueWhen( tpR, s12, 1 ) );
tmedR = LastValue(ValueWhen( tpR, s12, 2 ) );
tstartR = LastValue( ValueWhen( tpR, s12, 3 ));
//
Filter2=tmedRLastValue(x)-back;
Graph1BarColor=IIf(C1 AND Filter1,colorWhite,IIf(C2 AND Filter2,10,1));

/*Inverted H&S Neck Line*/

tAper = tmedt1-tstartt1;tbper=tendt1-tmedt1;
Ha = LastValue(ValueWhen(x==tmedt1,HHV(H,tAper)));
Hb = LastValue(ValueWhen(x==-1+tendt1,HHV(H,tbper)));
tFa = H==Ha AND x>tstartt1 AND xtmedt1 AND xRstartt-5,trendlineR,-1e10);Graph4BarColor=10;
Filter = Filter1 OR Filter2;
//
NumColumns= 2;/*Graph2=x==-1+tendt1;*/
Column0 = Filter1;
Column1 = Filter2;
Column0Format=Column1Format=1.0;
Column0Name="H&S";
Column1Name="inv H&S";
//-------------------------------------------------------------------------------------------------
Title = EncodeColor(colorGold)+Name()+" - "+EncodeColor(colorBrightGreen)+FullName()+"\n "+
EncodeColor(colorGold)+StrFormat(" - Open %g, Hi %g, Lo %g, Close %g ",O,H,L,C )+EncodeColor(colorRed)+" - "+Date()+
" - Volume :"+WriteVal(V,1.0);
_SECTION_END();


ELLIOTT FRACTAL


//ELLIOT Fractals
_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleCandle
| ParamStyle("Style") | GetPriceStyle() );
// Paste the code below to your price chart somewhere and green ribbon means both
// both MACD and ADX trending up so if the red ribbon shows up the MACD and the ADX
// are both trending down.

_SECTION_BEGIN("trending ribbon");
uptrend=PDI()>MDI()AND Signal()PDI()AND Signal()>MACD();


Plot( 2, /* defines the height of the ribbon in percent of pane width */"ribbon",
IIf( uptrend, colorGreen, IIf( downtrend, colorRed, 0 )), /* choose color */
styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );

_SECTION_END();

_SECTION_END();

_SECTION_BEGIN("LEMA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 20, 2, 200, 1, 10 );
lema = EMA (Close,Periods)+ EMA((Close-EMA(Close,Periods)),Periods);
Plot( lEMA, _DEFAULT_NAME(), ParamColor( "Color", colorCycle ),
ParamStyle("Style") );
_SECTION_END();

_SECTION_BEGIN("ELLIOTT Fractals");
/*
The basic definition of an 'up' fractal is a bar high that is both higher than the two bars immediately preceding it
and higher than the two bars immediately following it.
The lows of the bars are NOT considered in determining the up fractal progression.

If two bars in the progression have equal highs followed by two consecutive bars with lower highs,
then a total of six bars rather than the usual five bars will make up the progression.
The first High becomes the counting fractal. Reverse for 'down' fractals.

The 5 bar formation works best on Daily or longer time frame charts.For intraday data charts we often use 9 bar, 13 bar and 21 bar formations for fractal counting
*/
Up5BarFractal = Ref(H,-2) < H AND Ref(H,-1) < H AND Ref(H,1) < H AND Ref(H,2) < H; Up6BarFractal = Ref(H,-2) < H AND Ref(H,-1) < H AND (H == Ref(H,1)) AND Ref(H,2) < H AND Ref(H,3) < H; Down5BarFractal = Ref(L,-2) > L AND Ref(L,-1) > L AND Ref(L,1) > L AND Ref(L,2) > L;
Down6BarFractal = Ref(L,-2) > L AND Ref(L,-1) > L AND (L == Ref(L,1)) AND Ref(L,2) > L AND Ref(L,3) > L;

//TODO: More filtering: Show only troughs that are around atrough in trix(9).

PlotShapes( IIf(Down5BarFractal ,shapeSmallUpTriangle,0) ,colorBlack, 0, L,-12);
PlotShapes( IIf(Down6BarFractal ,shapeSmallUpTriangle,0) ,colorBlack, 0, L,-12);

PlotShapes( IIf(Up5BarFractal ,shapeSmallDownTriangle,0) ,colorBlack, 0, H,-12);
PlotShapes( IIf(Up6BarFractal ,shapeSmallDownTriangle,0) ,colorBlack, 0, H,-12);

Up = (Up5BarFractal OR Up6BarFractal);
Down = (Down5BarFractal OR Down6BarFractal);
//Removing false fractals:
DownSignal = Flip(Ref(Up,-1), Ref(Down,-1));
UpSignal = Flip(Ref(Down,-1), Ref(Up,-1));

LastHigh[0] = H[0];
LastLow[0] = L[0];

LastLowIndex = 0;
LastHighIndex = 0;
Valid = 0;
for (i=1; i < BarCount; i++) { LastHigh[i] = LastHigh[i-1]; LastLow[i] = LastLow[i-1]; if (Up[i]) { Valid[i] = True; if (DownSignal[i]) { //Sequence of 2 Up Fractals. Validate only the higher one. Valid[i] = H[i] >= H[LastHighIndex];
Valid[LastHighIndex] = H[LastHighIndex] > H[i];
}
LastHigh[i] = Max(H[i], H[LastHighIndex ]);
LastHighIndex = i;
}

if (Down[i])
{
Valid[i] = True;
if (UpSignal[i])
{
//Sequence of 2 Down Fractals. Validate only the lower one.
Valid[i] = L[i] <= L[LastLowIndex]; Valid[LastLowIndex] = L[LastLowIndex] < L[i]; } LastLow[i] = Min(L[i], L[LastLowIndex]); LastLowIndex = i; } } TrixN = Trix(9); TroughLow = Ref(TrixN, -3) > TrixN AND Ref(TrixN, -2) > TrixN AND Ref(TrixN, -1) > TrixN AND Ref(TrixN, 1) > TrixN AND Ref(TrixN, 2) > TrixN AND Ref(TrixN, 3) > TrixN;
TroughHigh = Ref(TrixN, -3) < TrixN AND Ref(TrixN, -2) < TrixN AND Ref(TrixN, -1) < TrixN AND Ref(TrixN, 1) < TrixN AND Ref(TrixN, 2) < TrixN AND Ref(TrixN, 3) < TrixN; //TroughLow = Ref(TrixN, -2) > TrixN AND Ref(TrixN, -1) > TrixN AND Ref(TrixN, 1) > TrixN AND Ref(TrixN, 2) > TrixN;
//TroughHigh = Ref(TrixN, -2) < TrixN AND Ref(TrixN, -1) < TrixN AND Ref(TrixN, 1) < TrixN AND Ref(TrixN, 2) < TrixN; ZeroValid = Cross(TrixN, 0) OR Cross(0, TrixN) OR Ref(Cross(TrixN, 0),1) OR Ref(Cross(0, TrixN),1); ValidLow = TroughLow OR Ref(TroughLow, 1) OR Ref(TroughLow, 2) OR Ref(TroughLow, 3) OR Ref(TroughLow, 4);// OR Ref(TroughLow, 5)); ValidHigh = TroughHigh OR Ref(TroughHigh, 1) OR Ref(TroughHigh, 2) OR Ref(TroughHigh, 3) OR Ref(TroughHigh, 4);// OR Ref(TroughHigh, 5)); //Plot(LastHigh-10 ,"LastHigh", colorBlue, styleLine); //Plot(LastLow-10 ,"LastLow ", colorRed, styleLine); //Plot(Valid*5 + 10 ,"LastLow ", colorGreen, styleLine | styleThick); //PlotShapes( IIf(Down AND Valid,shapeSmallUpTriangle,0) ,colorGreen, 0, L,-12); //PlotShapes( IIf(Up AND Valid,shapeSmallDownTriangle,0) ,colorRed, 0, H,-12); Maxi = Up AND (ValidHigh OR ZeroValid); Mini = Down AND (ValidLow OR ZeroValid); PlotShapes( IIf(Down AND (ValidLow OR ZeroValid),shapeSmallUpTriangle,0) ,colorBlue, 0, L,-12); PlotShapes( IIf(Up AND (ValidHigh OR ZeroValid),shapeSmallDownTriangle,0) ,colorOrange, 0, H,-12); AlertIf(Down AND (ValidLow OR ZeroValid), "SOUND C:\\Windows\\Media\\Chord.wav", "Audio alert", 2); AlertIf(Up AND (ValidHigh OR ZeroValid), "SOUND C:\\Windows\\Media\\Ding.wav", "Audio alert", 2); //Plot(UpSignal*3+5,"UpSignal", colorBlue, styleLine| styleThick); //Plot(DownSignal*3 ,"DownSignal", colorRed, styleLine| styleThick); /* LastMaxi = 0; LastMini = 0; ElliotLines = 0; State = 0; for (i=1; i < BarCount; i++) { State[i] = State[i-1]; if (Maxi[i]) { State[i] = 1;//down } if (Mini[i]) { State[i] = 2; } } PlotShapes(IIf(State > 0, shapeSmallCircle, 0), IIf(State == 1, colorRed, colorBlue), 0, IIf(State == 1, H, L), -5);
*/
//Line = LineArray( x0, y0, x1, y1, 1 );
//Plot( Line, "Trend line", colorBlue );

/*
Wave B
Usually 50% of Wave A
Should not exceed 75% of Wave A
Wave C
either 1 x Wave A
or 1.62 x Wave A
or 2.62 x Wave A
*/
function CorrectiveRatios(StartPrice, A, B, C, RatioDelta, Delta)
{

ALength = abs(startPrice - A); BLength = abs(A-B);
CLength = abs(B-C);

Ratio1 = BLength / CLength ;
Cond1 = Ration1 >= 0.5 - RatioDelta AND ratio1 <= 0.75 + RatioDelta; Cond2 = abs(Clength - ALength) < Delta OR abs(Clength - 1.62 * ALength) < Delta OR abs(CLength - 2.62 * ALength) < Delta; return Cond1 AND Cond2; } function ImpulseRules(StartPrice, One, Two, Three, Four, Five) { //Wave 2 should be beneath wave 1 start: Cond1 = Two > StartPrice AND Two < One; //Wave 4 - the same: Cond2 = Four > Two AND Four < Three; //Wave 5 should be <= wave 3 Cond3 = abs(Three-Two) >= abs(Five - Four);
//Wave 1 should be smaller than wave five, making wave 3 the biggest:
Cond4 = abs(StartPrice - One) < abs(Five - Four); return Cond1 AND Cond2 AND Cond3 AND Cond4; } _SECTION_END(); //3 Gradient Color _SECTION_BEGIN("3 color gradient"); priceAxesWidth=0; dateAxesHeight=0; TitleHeight=0; pxwidth = Status("pxwidth"); pxheight = Status("pxheight"); chartwidth = pxwidth-priceAxesWidth; chartheight = pxheight-dateAxesHeight; topColor=ParamColor("topColor",ColorRGB(207,254,240) ); centerColor=ParamColor("centerColor", ColorRGB(249,236,164)); botColor=ParamColor("BottomColor", ColorRGB( 253,223,196)); priceAxesColor=ParamColor("priceAxesColor", colorWhite ); dateAxesColor=ParamColor("dateAxesColor", colorWhite); relPos=Param("centerPosition%",50,0,100,1)/100; centerHeight=chartheight*Param("centerHeight%",10,0,100,1)/100; x0=0; y0=Max(TitleHeight,chartheight*relPos-centerHeight/2); x1=chartwidth; y1=Min(chartheight,chartheight*relPos+centerHeight/2); GfxSetBkMode( 1 ); GfxSetOverlayMode(1); GfxGradientRect(0,0,chartwidth,TitleHeight, colorWhite ,colorWhite); GfxGradientRect(chartwidth,0,pxwidth,pxheight, priceAxesColor ,priceAxesColor); GfxGradientRect(0,chartheight,chartwidth,pxheight, dateAxesColor ,dateAxesColor); GfxGradientRect(x0,y0,x1,y1, CenterColor ,CenterColor ); GfxGradientRect(0,TitleHeight,chartwidth, y0,topColor, CenterColor ); GfxGradientRect(0,y1,chartwidth, chartheight, CenterColor ,botColor); _SECTION_END(); BEAST BSA _SECTION_BEGIN("Background_Setting"); SetChartBkGradientFill( ParamColor("BgTop", colorBlack), ParamColor("BgBottom", colorBlack),ParamColor("titleblock",colorDarkTeal )); _SECTION_END(); _SECTION_BEGIN("The_Beast_2"); SetBarsRequired(10000,10000); /* this ensures that the charts include all bars AND NOT just those on screen */ Prd1=Param("ATR Period 1-20",4,1,20,1);//{Default = 4 Because most traders use 5} Prd2=Param("LookBack Period 1-20",7,1,20,1);//{Default = 11 Because most traders use 10} //{Green} {Start Long position when Close>Green}
Green=HHV(LLV(L,Prd1)+ATR(Prd1),Prd2);
//{Red} {Stop loss when CloseGreen ,colorBrightGreen,IIf(C < RED,colorRed,colorWhite)); PlotOHLC( HaOpen, HaHigh, HaLow, HaClose, "", color, styleCandle,styleThick ); SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) Vol " +WriteVal( V, 1.0 ) +" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 )) )); _SECTION_END(); _SECTION_BEGIN("Trailing_Stop_Short"); stoplossPercentage = Param("Stoploss Percentage", 5, 2, 10); lookbackPeriod = Param("Lookback period", 10, 5, 30); Plot(HHV(C,lookbackPeriod) - HHV(C,lookbackPeriod) * (stoplossPercentage / 100), "Trailing stoploss", ParamColor( "Color", colorCycle ),ParamStyle("Style",styleLine|Stylehidden ,maskAll)); _SECTION_END(); _SECTION_BEGIN("Trailing_Stop_Long"); //ATR values can be changed from 1 to 3 multiplications in steps of 0.25 //ATR value or the last low pivot value can be selected. This feature can be overridden from the parameter window. It is recommended to use only ATR Value //Choice of plots line or just dots from the parameter window is also possible mf = Param("ATR multiplier",3,1,3,0.25); ap=Param("ATR Period",10,5,30,1); Lb=Param("Lookback Period",20,10,40,1); ps=ParamToggle("Use last low pivot","Use,Dont",1); //Thick = Param("Thick" , 0.02, 0.01, 0.2, 0.01); t1=HHV(C,Lb); t2=(mf*ATR(ap)); t3=Trough(C,2,1); t4=t1-t2; t5=Min(t4,t3); if(ps) { t6 = t1-t2; } else { t6=t5; } initial=t6; stop[ 0 ] = Close[ 0 ]; for( i = 1 ; i < BarCount; i++) { if( Close[ i ] > stop[ i - 1])
{
temp = t6[ i ];
if( temp > stop[ i - 1 ] ) stop[ i ] = temp;
else stop[ i ] = stop[ i - 1 ];
}
else
stop[ i ] = initial[ i ];

}

Plot(stop,"ATR Stop",ParamColor( "Color", colorSeaGreen ),ParamStyle("Style",styleLine|Stylehidden,maskAll));

_SECTION_END();

_SECTION_BEGIN("Trailing_Lines");
Plot(LLV(HHV(H,5)-ATR(5),8),"",ParamColor( "Color Line 0", colorDarkGreen ),ParamStyle("Style Line 0",styleLine,maskAll));
Plot(LLV(HHV(H,5)-ATR(5),7),"",ParamColor( "Color Line 1", colorDarkGrey),ParamStyle("styleLine 1",styleLine,maskAll));
Plot(LLV(HHV(H,5)-ATR(5),6),"",ParamColor( "Color Line 2", colorDarkGrey ),ParamStyle("Style Line 2",styleLine,maskAll));
Plot(LLV(HHV(H,5)-ATR(5),5),"",ParamColor( "Color Line 3", colorDarkGrey),ParamStyle("Style Line 3",styleLine,maskAll));
Plot(LLV(HHV(H,5)-ATR(5),4),"",ParamColor( "Color Line 4", colorDarkGrey ),ParamStyle("Style Line 4",styleLine,maskAll));
Plot(LLV(HHV(H,5)-ATR(5),3),"",ParamColor( "Color Line 5", colorDarkYellow ),ParamStyle("Style Line 5",styleLine,maskAll));

_SECTION_END();




/*_SECTION_BEGIN("Stop_loss");

lookbackPeriod = Param("Lookback period", 10, 5, 30);
stoplossPercentage = Param("Stoploss Percentage", 5, 2, 10);
Thick = Param("Thick" , 0.02, 0.01, 0.2, 0.01);


StopLoss=(HHV(C,lookbackPeriod) - HHV(C,lookbackPeriod) * (stoplossPercentage / 100));
function SPlot( Pr, Txt, Co, St )
{
PlotOHLC(Pr, Pr,Pr+Thick, Pr+Thick, "",Co,styleCloud );
}
SPlot(StopLoss,"" ,ParamColor( "Color", colorCycle ), 2) ;

_SECTION_END();*/





_SECTION_BEGIN("Pivot_Finder");
/* **********************************

Code to automatically identify pivots

********************************** */

// -- what will be our lookback range for the hh and ll?
farback=Param("How Far back to go",100,0,5000,10);
nBars = Param("Number of bars", 12, 5, 40);


GraphXSpace=7;

// -- 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 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 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 M2, colorLime, colorRed);
shape = Buy * shapeUpArrow + Sell * shapeDownArrow ;


PlotShapes( shape, IIf( Buy, colorGreen, colorRed ),0, IIf( Buy, Low, High ) );
dist = 1.5*ATR(20);
for( i = 0; i < BarCount; i++ ) { if( Buy[i] ) PlotText( "Buy\n@" + Close[i], i, Low[i] - dist[i], colorGreen ); if( Sell[i] ) PlotText( "sell\n@" + Close[i], i, Low[i] + dist[i], colorRed ); } Plot( Close, "Close", mycolor, styleNoTitle ); _SECTION_END(); PH PL LINEAR REGRESSION _SECTION_BEGIN(""); SetBarsRequired(350, -0); parmPlotScoreCard = ParamToggle("Plot KPScoreCard", "No|Yes", 1); parmPlotA900AutoStop = ParamToggle("Plot A900/AutoStop", "No|Yes", 0); parmA900Color = ParamColor("A900 Color", colorWhite); parmA900Style = ParamStyle("A900 Style", styleLine, maskAll); parmAutoStopColor = ParamColor("AutoStop Color", colorYellow); parmAutoStopStyle = ParamStyle("AutoStop Style", styleLine, maskAll); parmPPTextColor = ParamColor("PP Text color", colorBlue); parmPPTrndColorUp = ParamColor("PP Trend Up color", ColorRGB(167,224,243) ); parmPPTrndColorDn = ParamColor("PP Trend Dwn color", ColorRGB(255,192,203) ); parmPPTextOffSet = Param("PP OffSet", 0.60, 0.40, 1.5, 0.1); parmTickMultipler = Param("M/W tick allowance", 1, 0, 10, 1); parmA900AutoStopX = ParamToggle("Plot A900/AutoStop Cross", "No|Yes"); parmA900AutoStopColorX = ParamColor("A900/AutoStop Cross Color", colorBlue); ParmSCThreshold = Param("ScoreCard Threshold", 3, 1, 9, 1); parmVoice = ParamToggle("Voice 123 Setups", "No|Yes", 0); parmAlert = ParamToggle("Alert 123 Setups", "No|Yes", 0); parmPivotPop = ParamToggle("PivotPop", "No|Yes", 1); parmBarCancel = Param("Bar Cancel", 7, 1, 20, 1); parmWaterLevelColor = ParamColor("WalterLevel Color", ColorRGB(127,255,212)); parmWaterLevelStyle = ParamStyle("WaterLevel Style", styleLine, maskAll); parmBBPeriod = Param("Bollinger Band Period", 10, 2, 30, 1); parmBBSD = Param("bollinger Band SD", 0.8, 0.2, 3.0); ParmPlotPPIndicators = ParamToggle("Plot Pivot Pop indicators", "No|Yes", 0); parmBBColor = ParamColor("BBands Color", colorWhite); parmBBStyle = ParamStyle("BBands Style", styleLine, maskAll); ParmDebug = ParamToggle("Debug", "No|Yes", 0); _N(PaneName = Name() + Interval(2)+ _SECTION_NAME()); _N(NewBarName = "NewBar" + PaneName); function NewBarP() { PrevDT = StaticVarGet( NewBarName); DT = LastValue(DateTime()); StaticVarSet( NewBarName,DT); return DT != PrevDT; } function MRoundP(Number, Multiple ) { if(Multiple == 0 ) { xMultiple = 0.01; } else { xMultiple = Multiple; } Divided = Number / xMultiple; intDivided = int(Divided); intDivided = intDivided + round(Divided - intDivided); return intDivided * xMultiple; } ObjAB = CreateObject("Broker.Application"); ticker = objAB.Stocks(Name() ); if(ticker.TickSize == 0) { TickValue = 0.01; } else { TickValue = ticker.TickSize; } NewBarSignal = NewBarP(); KPA900 = E_TSKPA900(Close); KPAutoStop = E_TSKPAUTOSTOP(High,Low,Close); Ctmpl = E_TSKPCOLORTMPL(Open,High,Low,Close,Volume); //ScoreCard KPScoreCard = 0; KPScoreCard = KPScoreCard + IIf(tskp_colortmplcnd0 > 0, 1, -1);
KPScoreCard = KPScoreCard + IIf(tskp_colortmplcnd1 > 0, 1, -1);
KPScoreCard = KPScoreCard + IIf(tskp_colortmplcnd2 > 0, 1, -1);
KPScoreCard = KPScoreCard + IIf(tskp_colortmplcnd3 > 0, 1, -1);
KPScoreCard = KPScoreCard + IIf(tskp_colortmplcnd4 > 0, 1, -1);
KPScoreCard = KPScoreCard + IIf(tskp_colortmplcnd5 > 0, 1, -1);
KPScoreCard = KPScoreCard + IIf(tskp_colortmplcnd6 > 0, 1, -1);
KPScoreCard = KPScoreCard + IIf(tskp_colortmplcnd7 > 0, 1, -1);
KPScoreCard = KPScoreCard + IIf(tskp_colortmplcnd8 > 0, 1, -1);

if(parmDebug == 1)
{
// printf("a900: %0.6f% \nAutoStop: %0.6f%\nScoreCard: %0.0f%\n", KPA900, KPAutoStop, KPScoreCard);
}
if(parmPlotScoreCard == 1)
{
//_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g% (%0.4f%) {{VALUES}}", O, H, L, C, SelectedValue( C - Ref(C, -1)) ));
if( ParamToggle("Tooltip shows", "All Values|Only Prices" ) )
{
// ToolTip=StrFormat("Open: %g\nHigh: %g\nLow: %g\nClose: %g (%.2f%%)\nVolume: "+NumToStr( V, 1 ), O, H, L, C, SelectedValue( ROC( C, 1 )));
}
//Color = IIf(KPScoreCard >= parmSCThreshold, colorBlue, IIf(KPScoreCard <= -parmSCThreshold, colorRed, colorYellow) ); //Plot( C, "Close", Color , styleNoTitle | ParamStyle("OHLC Style") | GetPriceStyle() ); } //user want A900/AutoStop plotted if(parmPlotA900AutoStop == 1) { // Plot(KPA900, "A900", parmA900Color, parmA900Style); // Plot(KPAutoStop, "AutoStop", parmAutoStopColor, parmAutoStopStyle); } // find A900/AutoStop cross over/under with ScoreCard confirmation. XOUp = (KPA900 > KPAutoStop) AND (KPScoreCard >= parmSCThreshold); // New Pivot Low
XODn = (KPA900 < KPAutoStop) AND (KPScoreCard <= -parmSCThreshold); // New Pivot High if(parmDebug == 1) { // printf(WriteIf(XOUp, "before= XOUp: True", "before= XOUp: False") + WriteIf(XODn, " XODn: True\n", " XODn: False\n") ); } //remove duplicate signals XOUp = ExRem(XOUp, XODn); XODn = ExRem(XODn, XOUp); if(parmDebug == 1) { // printf(WriteIf(XOUp, "after= XOUp: True", "after= XOUp: False") + WriteIf(XODn, " XODn: True\n", " XODn: False\n") ); } //find the current Pivot Points - PL and PH //remember XOUp = 1 means a PL and XODn =1 means a PH PLBars = IIf(XOUp, LowestSinceBars(XODn, L ,1), 0); //find the bar that produced the Lowest Low PHBars = IIf(XODn, HighestSinceBars(XOUp, H, 1),0); //find the bar that produced the Highest High //PLPrice = IIf(XOUp, Ref(L, -PLBars), 0); //PHPrice = IIf(XODn, Ref(H, -PHBars),0); PLPrice = Ref(L, -PLBars); PHPrice = Ref(H, -PHBars); //keep track of the previous Pivot Points PrevPLBars = Ref(BarsSince(XOUp), -1) +1; PrevPHBars = Ref(BarsSince(XODn), -1) +1; PrevPLPrice = Ref(PLPrice, -prevPLBars); PrevPHPrice = Ref(PHPrice, -PrevPHBars ); PivotsCloseEnough = TickValue * parmTickMultipler; PLDifference = MroundP(PLPrice - PRevPLPrice, ticker.TickSize); PHDifference = MroundP(PHPrice - PrevPHPrice, ticker.TickSize); PPTrend = IIf(XOUp AND (PLDifference > PivotsCloseEnough) AND PrevPHPrice > PrevPLPrice AND PRevPHPrice > PLPrice, 1,
IIf(XOUp AND (PLDifference < - PivotsCloseEnough) AND PRevPHPrice > PrevPLPrice AND PrevPHPrice > PLPrice, -1,
IIf(XODn AND (PHDifference > PivotsCloseEnough) AND PrevPLPrice < PrevPHprice AND PrevPLPrice < PHPrice, 1, IIf(XODn AND (PHDifference < -PivotsCloseEnough) AND PrevPLPrice < PrevPHPrice AND PrevPLPrice < PHPrice, -1, IIf(XOUp AND (abs(PLDifference) <= PivotsCloseEnough) AND PrevPHPrice > PrevPLPrice AND PRevPHPrice > PLPrice, 2,
IIf(XODn AND (abs(PHDifference) <= PivotsCloseEnough) AND PrevPLPrice < PrevPHPrice AND PrevPLPrice < PHPrice, -2, 0)))) )); if(ParmDebug) { //printf("Current PH Bar: %g% /Price: %g%\n", PHBars, PHPrice); //printf("Current PL Bar: %g% /Price: %g%\n", PLBars, PLPrice); //printf("Previous PH Bar: %g% /Price: %g%\n", PrevPHBars, PrevPHPrice); //printf("Previous PL Bar: %g% /Price: %g%\n", PrevPLBars, PrevPLPrice) ; //printf("PP Trend: %g%\n", PPTrend); //printf("PHPrice - PrevPHPrice: %g%\nPLPrice - PrevPLPrice: %g%\nPivotsCloseEnough: %g%", PHDifference, PLDifference, PivotsCloseEnough); } //PLot pivots as text dist = parmPPTextOffSet * ATR(10); //for( i = 0; i < BarCount -1; i++) for( i = 0; i < BarCount ; i++) { if(XOUp[i ] == 1 AND abs(PPTrend[i]) != 2) //cross up -plot the Pivot Low { PlotText("PL", i - PLBars[i], PLPrice[i] - dist[i] , parmPPTextColor, IIf(PPTrend[i] == 1, parmPPTrndColorUp, IIf(PPTrend[i] == -1, parmPPTrndColorDn, colorYellow) )); } if(XODn[i ] == 1 AND abs(PPTrend[i]) != 2) //cross down - plot the pivot high { PlotText("PH", i - PHBars[i], PHPrice[i] + dist[i], parmPPTextColor, IIf(PPTrend[i] == 1, parmPPTrndColorUp, IIf(PPTrend[i] == -1, parmPPTrndColorDn, colorYellow) )); } if(XOUp[i ] == 1 AND (PPTrend[i]) == 2) // the Pivot Low is a W Bottom { PlotText("PW", i - PLBars[i], PLPrice[i] - dist[i] , parmPPTextColor, colorYellow) ; } if(XODn[i ] == 1 AND PPTrend[i] == -2) //cross down - pivot high is a M Top { PlotText("PM", i - PHBars[i], PHPrice[i] + dist[i], parmPPTextColor, colorYellow) ; } } //end For // Plot A900/AutoStop cross over/under if(parmA900AutoStopX == 1) { PlotShapes(IIf(Cross(KPA900, KPAutoStop), shapeUpTriangle, shapeNone),colorYellow, 0, L, -30); PlotShapes(IIf(Cross(KPAutoStop, KPA900), shapeDownTriangle, shapeNone), colorRed, 0, H , -30); } if(parmPivotPop == 1) { //Kp indicators for Pivot Pop dummy = E_TSKPFAST2(Open, High, Low, Close, Volume); KPFast2 = IIf(tskp_fast2val1 > 0, 1, -1);
//calculations
BarsSinceXOUp =BarsSince(XOUp);
BarsSinceXODn = BarsSince(XODn);
UBB = BBandTop(C, parmBBPeriod, parmBBSD);
LBB = BBandBot(C, parmBBPeriod, parmBBSD);
PopFilter = True;
if(parmDebug == 1)
{
//printf("\nFast2: %1.0f% \nUBB: %0.6f%\nLBB: %0.6f%\nC: %g%\n", KPFast2, UBB, LBB, C);
//printf("Bars since Last XOUp: %1.0f%\nBars since last XODn: %1.0f%\n", BarsSinceXOUp, BarsSinceXODn );
//printf("Bars since PPTrnd =1: %1.0f%\nBars since PPTrnd = -1: %1.0f%\n", BarsSince(PPTrend ==1), BarsSince(PPTrend == -1) );

}
PPopUp = (BarsSince(PPTrend >= 1) < BarsSince(PPTrend <= -1)) AND (BarsSince(XOUp) <= parmBarCancel) AND (KPA900 >= KPAutoStop) AND(KPFast2 == 1) AND (KPScoreCard >= 5)
AND PopFilter AND (C > UBB) AND (C > O) ;
PPopUp = IIf( PPopUp AND Sum(PPopUP, BarsSince(XOUp)+1) == 1, True, False ); //keep only the 1st signal
PPopDn = (BarsSince(PPTrend <= -1) < BarsSince(PPTrend >= 1)) AND (BarsSince(XODn) <= parmBarCancel) AND (KPA900 <= KPAutoStop) AND(KPFast2 == -1) AND (KPScoreCard <= -5) AND PopFilter AND (C < LBB) AND (C < O) ; PPopDn = IIf( PPopDn AND Sum(PPopDn, BarsSince(XODn) + 1) == 1, True, False); //keep only the first signal if(parmDebug == 1) { //printf(WriteIf(PPopUp,"PPopUp: True", "PPopUp: False") + WriteIf(PPopDn, " PPopDn: True\n", " PPopDn: False\n") ); //printf("PPopUp sum: %1.0f% \nPPopDn sum: %1.0f%\n", Sum(PPopUP, BarsSince(XOUp)) , Sum(PPopDn, BarsSince(XODn)) ); } // Plots PlotShapes(IIf(PPopUp, shapeHollowUpArrow, shapeNone), colorYellow, 0, L, -25); PlotShapes(IIf(PPopDn, shapeHollowDownArrow, shapeNone), colorRed, 0, H, -25); if(ParmPlotPPIndicators == 1) //plot the Pivot Pop Indicators { //Plot(UBB, "Upper BB", colorYellow, parmBBStyle); //Plot(LBB, "Lower BB", colorRed, parmBBStyle); if(parmPlotA900AutoStop == 1) { // Plot(KPA900, "A900", parmA900Color, parmA900Style); // Plot(KPAutoStop, "AutoStop", parmAutoStopColor, parmAutoStopStyle); } //Plot( 0.5, "Fast2", IIf(tskp_fast2val1 > 0, parmPPTrndColorUp, parmPPTrndColorDn) , styleArea | styleNoLabel | styleOwnScale , 0, 10);
} //endif parmPlotPPIndicators
} // end if parmPivotPop
// Type 1, 2 or 3 setups
// kp indicators
KPWaterlevel = E_TSKPWATERLEVEL(Open,High,Low,Close,Volume);
dummy = E_TSKPMEDIUM(Close);
KPMediumUp = tskp_mediumup;
KPMediumDn = tskp_mediumdown;
KPMediumMA = tskp_mediumma;
KPMedium = KPMediumUp + KPMediumDn;
//calculations
PLBars = IIf(XOUp, LowestSince(XODn, KPMedium ,1), 0); //find the Lowest Low
PHBars = IIf(XODn, HighestSinceBars(XOUp, KPMedium, 1),0); //find the bar that produced the Highest High
PrevPLMedium = Ref(KPMedium, -prevPLBars);
PrevPHMedium = Ref(KPMEdium, -PrevPHBars );

Type1Filter = IIf(PPopUp AND (LowestSince(XODn, KPMedium, 1) > 0 ) AND (HighestSince(XODn, KPMedium, 1) > 0 ), True, IIf(PPopDn AND (HighestSince(XOUp, KPMedium ,1) < 0) AND (LowestSince(XOUp, KPMedium ,1) < 0), True, False)); Type2Filter = IIf(PPopUp AND LowestSince(XODn, KPMedium, 1) < 0 AND KPMedium > 0, True, IIf(PPopDn AND (HighestSince(XOUp, KPMedium ,1) > 0) AND KPMEdium < 0, True, False)); Type3Filter = IIf(PPopUp AND LowestSince(XODn, KPMedium, 1) < 0 AND KPMedium < 0 AND (KPMedium > KPMediumMA), True, IIf(PPopDn AND (HighestSince(XOUp, KPMedium ,1) > 0) AND KPMEdium > 0 AND(KPMedium < KPMediumMA), True, False)); Type1Buy = PPopUp AND ((Close - Open) >= 0) AND (KPScoreCard >= ParmSCThreshold) AND Type1Filter;
Type1Sell = PPopDn AND ((Close - Open) <= 0) AND (KPScoreCard <= -ParmSCThreshold) AND Type1Filter; Type2Buy = PPopUp AND ((Close - Open) >= 0) AND (KPScoreCard >= ParmSCThreshold) AND Type2Filter AND C > KPWaterLevel;
Type2Sell = PPopDn AND ((Close - Open) <= 0) AND (KPScoreCard <= -ParmSCThreshold) AND Type2Filter AND C < KPWaterLevel; Type3Buy = PPopUp AND ((Close - Open) >= 0) AND (KPScoreCard >= ParmSCThreshold) AND Type3Filter AND C > KPWaterLevel;
Type3Sell = PPopDn AND ((Close - Open) <= 0) AND (KPScoreCard <= -ParmSCThreshold) AND Type3Filter AND C < KPWaterLevel; if(parmDebug == 1) { //printf("Type1Filter: %g%\nType2Filter: %g%\nType3Filter: %g%\n", Type1Filter, Type2Filter, Type3Filter); //printf("KPWaterlevel: %g%\n", KPWaterLevel); //printf("KPMedium: %g%\nKPMediumMA: %g%\n", KPMedium, KPMediumMA); //printf("Highest XOUp Medium: %g%\nLowest XOUp Medium: %g%\n", HighestSince(XOUp, KPMedium, 1), LowestSince(XOUp, KPMedium ,1) ); //printf("Highest XODn Medium: %g%\nLowest XODn Medium: %g%\n", HighestSince(XODn, KPMedium, 1), LowestSince(XODn, KPMedium ,1) ); //printf("Prev PH Medium: %g%:Prev PL Medium: %g%\n", PrevPHMedium, PrevPLMedium); //printf("Type1Buy: %g%:Type1Sell: %g%\n", Type1Buy, Type1Sell); //printf("Type2Buy: %g%:Type2Sell: %g%\n", Type2Buy, Type2Sell); //printf("Type3Buy: %g%:Type3Sell: %g%\n", Type3Buy, Type3Sell); } // Plots PlotShapes(IIf(Type1Buy, shapeDigit1 , IIf(Type1Sell, shapeDigit1, shapeNone)), IIf(Type1Buy, colorBlue, IIf(Type1Sell, colorRed, Null)), 0, IIf(Type1Buy, High, IIf(Type1Sell, L, O)), IIf(Type1Buy, 30, IIf(Type1Sell, -30, 0)) ); PlotShapes(IIf(Type2Buy, shapeDigit2 , IIf(Type2Sell, shapeDigit2, shapeNone)), IIf(Type2Buy, colorBlue, IIf(Type2Sell, colorRed, Null)), 0, IIf(Type2Buy, High, IIf(Type2Sell, L, O)), IIf(Type2Buy, 30, IIf(Type2Sell, -30, 0)) ); PlotShapes(IIf(Type3Buy, shapeDigit3 , IIf(Type3Sell, shapeDigit3, shapeNone)), IIf(Type3Buy, colorBlue, IIf(Type3Sell, colorRed, Null)), 0, IIf(Type3Buy, High, IIf(Type3Sell, L, O)), IIf(Type3Buy, 30, IIf(Type3Sell, -30, 0)) ); //Plot(KPWaterLevel, "KPWaterLevel", parmWaterLevelColor, parmWaterLevelStyle); // HMM how to print Medium on a price chart //voice if(parmVoice ==1) { if(NewBarSignal) { if( LastValue(Ref(Type1Buy, -1)) == 1) Say(Interval(2) + " New Type one buy."); if( LastValue(Ref(Type2Buy, -1)) == 1) Say(Interval(2) + " New Type two buy"); if( LastValue(Ref(Type3Buy, -1)) == 1) Say(Interval(2) + " New Type three buy."); if( LastValue(Ref(Type1Sell,-1)) ==1) Say(Interval(2) + " New Type one sell."); if( LastValue(Ref(Type2Sell,-1)) ==1) Say(Interval(2) + " New Type two sell."); if( LastValue(Ref(Type3Sell,-1)) ==1) Say(Interval(2) + " New Type three sell."); } } //alerts if(parmAlert ==1) { AlertIf(NewbarSignal AND Ref(Type1Buy, -1), "", "Type 1 Buy.", 1, 15, 0); AlertIf(NewbarSignal AND Ref(Type2Buy, -1), "", "Type 2 Buy.", 1, 15, 0); AlertIf(NewbarSignal AND Ref(Type3Buy, -1), "", "Type 3 Buy.", 1, 15, 0); AlertIf(NewbarSignal AND Ref(Type1Sell, -1), "", "Type 1 Sell.", 2, 15, 0); AlertIf(NewbarSignal AND Ref(Type2Sell, -1), "", "Type 2 Sell.", 2, 15, 0); AlertIf(NewbarSignal AND Ref(Type3Sell, -1), "", "Type 3 Sell.", 2, 15, 0); } _SECTION_END(); //********************************* //********************************* _SECTION_BEGIN("Chart Settings"); SetChartOptions(0,chartShowArrows|chartShowDates); SetChartBkColor(ParamColor("Outer Panel",colorPaleBlue)); SetChartBkGradientFill(ParamColor("Upper Chart",1),ParamColor("Lower Chart",23)); _SECTION_END(); //================================================Start Chart Configuration============================================================================ _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) Vol " +WriteVal( V, 1.0 ) +" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 )) )); Plot( C, "Close", colorBlue, styleCandle, Zorder = 1); //================================================End Chart Configuration=============================================================================== //====================================Start of Linear Regression Code================================================================================== P = ParamField("Price field",-1); Length = 150; Daysback = Param("Period for Liner Regression Line",Length,1,240,1); shift = Param("Look back period",0,0,240,1); //=============================== Math Formula ======================================================================================================== x = Cum(1); lastx = LastValue( x ) - shift; aa = LastValue( Ref(LinRegIntercept( p, Daysback), -shift) ); bb = LastValue( Ref(LinRegSlope( p, Daysback ), -shift) ); y = Aa + bb * ( x - (Lastx - DaysBack +1 ) ); //==================Plot the Linear Regression Line ==================================================================================================== LRColor = ParamColor("LR Color", colorCycle ); LRStyle = ParamStyle("LR Style"); LRLine = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y, Null ); LRStyle = ParamStyle("LR Style"); Angle = Param("Angle", 0.05, 0, 1.5, 0.01);// A slope higher than 0.05 radians will turn green, less than -0.05 will turn red and anything in between will be white. LRLine = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y, Null ); Pi = 3.14159265 * atan(1); // Pi SlopeAngle = atan(bb)*(180/Pi); LineUp = SlopeAngle > Angle;
LineDn = SlopeAngle < - Angle; if(LineUp) { Plot(LRLine, "Lin. Reg. Line Up", IIf(LineUp, colorBrightGreen, colorWhite), LRStyle); } else { Plot(LRLine, "Lin. Reg. Line Down", IIf(LineDn, colorDarkRed, colorWhite), LRStyle); } //========================== Plot 1st SD Channel ====================================================================================================== SDP = Param("Standard Deviation", 1.5, 0, 6, 0.1); SD = SDP/2; width = LastValue( Ref(SD*StDev(p, Daysback),-shift) ); //Set width of inside chanels here. SDU = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y+width , Null ) ; SDL = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y-width , Null ) ; SDColor = ParamColor("SD Color", colorCycle ); SDStyle = ParamStyle("SD Style"); Plot( SDU , "Upper Lin Reg", colorBrown,SDStyle ); //Inside Regression Lines Plot( SDL , "Lower Lin Reg", colorLime,SDStyle ); //Inside Regression Lines //========================== Plot 2d SD Channel ======================================================================================================== SDP2 = Param("2d Standard Deviation", 2.0, 0, 6, 0.1); SD2 = SDP2/2; width2 = LastValue( Ref(SD2*StDev(p, Daysback),-shift) ); //Set width of outside chanels here. SDU2 = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y+width2 , Null ) ; SDL2 = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y-width2 , Null ) ; SDColor2 = ParamColor("2 SD Color", colorCycle ); SDStyle2 = ParamStyle("2 SD Style"); Plot( SDU2 , "Upper Lin Reg", colorRed,SDStyle2 ); //OutSide Regression Lines Plot( SDL2 , "Lower Lin Reg", colorLime,SDStyle2 ); //OutSide Regression Lines Trend = IIf(LRLine > Ref(LRLine,-1),colorGreen,colorRed);//Changes LR line to green if sloping up and red if sloping down.

Plot( LRLine , "LinReg", Trend, LRSTYLE );
PlotOHLC(SDU,SDL2,SDU2,SDL,"",colorYellow,styleNoLabel | styleCloud);
//============================ End Indicator Code ========================================================================================================



_SECTION_BEGIN(" ");
farback=Param("How Far back to go",100,50,5000,10);
nBars = Param("Number of bars", 12, 5, 40);


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 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 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
aLPivLows[nLPivs-j] = aLPivLows[nLPivs-(j+1)];

aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-(j+1)];

}

aLPivLows[0] = candPrc;

aLPivIdxs[0] = candIdx;

nLPivs++;

}

}


PlotShapes(

IIf(aHPivs==1, shapeDownArrow, shapeNone), colorRed, 0,

High, Offset=-15);

PlotShapes(
IIf(aLPivs==1, shapeUpArrow , shapeNone), colorGreen, 0,

Low, Offset=-15);

AlertIf( aHPivs==1, "SOUND C:\\Windows\\Media\\Ding.wav", "Sell " + C,2,1+2,1);
AlertIf( aLPivs==1, "SOUND C:\\Windows\\Media\\Ding.wav","Buy " + C,1,1+2,1);

_SECTION_END();


_SECTION_BEGIN("");


n=25; Av=12; Av1=16; Av2=2; stp=2;

Var1= TEMA(Close,n);
Var2= TEMA(var1,av);
Var3= (var1-var2)+var1;
Var1= TEMA(var3,av1);
Var4= MA((var1-var2)+var1,av2);
Var5=(Var1-Var2)+Var1;

//Buy=Cover=Cross(Var5,Var4);
//Sell=Short=Cross(Var4,VAR5);

Buy=Cover=Cross(Var5,Ref(Var5,-1));
Sell=Short=Cross(Ref(Var5,-1),VAR5);
Filter =Buy OR Sell;

Plot( Flip( Buy, Sell ), "Trade", 9, styleArea | styleOwnScale, 0, 1 );
_SECTION_END();

My Blog List

Total Pageviews

Search This Blog

Followers