AFL help needed to plot lines

KelvinHand

Well-Known Member
#81
Once again thank u Kelvinhand sir for pointing out to the right direction.
Nothing. Hope more people can do this simple Google RESEARCH. Then more and more expert in here.


Here the article: https://www.mail-archive.com/[email protected]/msg51063.html

1. data_import.py:this allows you to execute all AFL files in a directory (like the sample in the docs); it runs an Exploration on the last 30 days of data as well as a full Backtest on all of the data, saves both sets of results, and converts the Explore results to one HTML file.

PHP:
# Code adapted from TJ's sample in documentation by [email protected]
# File revision: $Revision: 203 $ 
import os
from win32com.client import Dispatch

# START MODIFY TO FIT YOUR SETUP
# These pairs (tuples) contain a data folder and a format file which defines
# how the data is stored
data_folders = (
                ("C:\\ua\\Files\\ForExport", "mycsinew.format"),
                ("C:\\ua\\Files\\Cash", "mycsinew.format")
               )
# END MODIFY TO FIT YOUR SETUP

# Create AmiBroker object 
ab = Dispatch("Broker.Application")
for (data_folder,format_file) in data_folders:
    for file in os.listdir(data_folder):
        if file[-3:].lower() == "csv":
            print "Importing:", file, "using:", format_file
            ab.Import(0, data_folder + "\\" + file, format_file)
ab.SaveDatabase()
2. run_production.py:this allows you to execute all AFL files in a directory (like the sample in the docs); it runs an Exploration on the last 30 days of data as well as a full Backtest on all of the data, saves both sets of results, and converts the Explore results to one HTML file.

PHP:
# Script modified and ported to Python from TJ's sample in the documentation by [email protected]
# File revision: $Revision: 205 $
import os
from datetime import date
from win32com.client import Dispatch

# START MODIFY TO FIT YOUR SETUP
AFLFolder = "C:\\Program Files (x86)\\AmiBroker\\Formulas\\Custom\\Strategies\\_Production"
ResultFolder = "C:\\Home\\Peter\\Documents\\Work\\Trading\\AmiBroker\\_Production"
# END MODIFY TO FIT YOUR SETUP

# Create AmiBroker object and get Analysis object
ab = Dispatch("Broker.Application")
aa = ab.Analysis 

# set apply to and range
aa.ClearFilters()
# MODIFY FOR YOUR SETUP: this runs against watchlist #8.  Note the VBScript/JScript
# syntax shown in the docs doesn't work in Python.
aa.Filter(0, "watchlist", 8)
aa.ApplyTo = 2     # use filters 

today = date.today()

# Open the HTML file we're going to write to and print the header
htmlfile = open(ResultFolder + "\\DailySignals.html", "w")
htmlfile.write("<html><head><title>Daily Signals</title></head><body><h1>Daily Signals:&nbsp;"+
                str(today)+"</h1><hr/>\n")

# Enumerate files.  Note: it's my understanding Python prefers to work with
# directories separated with the forward slash ('/') character.  However,
# since these paths are being passed over to AB, I'd prefer to just use the
# backslash ('\\').  This seems to work OK.
all_files = os.listdir(AFLFolder)
for file in all_files:
    fileparts = file.split(".")
    if len(fileparts) >= 2 and fileparts[1].lower() == "afl":
        basename = fileparts[0]
        if (aa.LoadFormula(AFLFolder + "\\" + file)):
            print "Successfully loaded AFL script:", file
            aa.RangeMode = 2    # last n days mode
            aa.RangeN = 30      # last 30 days

            # Run exploration first for signals
            aa.Explore()
            resultFile = ResultFolder + "\\" + basename + "_explore.csv"
            print "Explore file : " + resultFile
            aa.Export(resultFile)

            # Read the CSV file we just wrote and turn into HTML table.
            # No lectures about mixing data with logic please, yes, I know
            # how to use templating engines, not warranted here.  :-)
            with open(resultFile) as csv:
                first = True
                htmlfile.write("<h2>"+file+"</h2><table border=1>\n")
                for line in csv:
                    htmlfile.write("<tr>\n")
                    fields = line.split(',')
                    for field in fields:
                        if first:
                            htmlfile.write("<th bgcolor=eeeeee>"+field+"</th>")
                        else:
                            htmlfile.write("<td>"+field+"&nbsp;</td>")
                    htmlfile.write("\n</tr>\n")
                    first = False
                htmlfile.write("</table><p/>\n")

            # Full backtest, for verification and record-keeping
            aa.RangeMode = 0    # all data
            aa.Backtest(0)      # IMPORTANT: you need to specify parameter 0 to get PORTFOLIO backtest
            resultFile = ResultFolder + "\\" + basename + "_backtest.csv"
            print "Backtest file: " + resultFile
            aa.Export(resultFile)

# Write footer and close file
htmlfile.write("</body></html>\n")
htmlfile.close()

<!-- neodl5.grp.bf1.yahoo.com Mon Dec 29 02:15:34 PST 2014 -->
 
Last edited:
#83
i still have to solve a few problems with this code. You have to fine tune it a bit for yourself. If you expect a gap zone and you do not see one then try to adjust the strength of the mini pivots to for instance 2 instead of 1 or adjust the Minimum gap factor to a lower number and see what works best

http://wisestocktrader.com/indicatorpasties/1428-gapfill3
casoni sir , edward sir , mastermind sir , rughaveer sir , amit sir ,
is it possible that we buy when price closes above blue pivot line with a sl of red pivot line and vice versa , i mean to buy above swing pivot high with sl below swing pivot low.
if it is possible than plz add buy sell arrows and other essential coding lines so that we can backtest it and add some filters to avoid whips .

thanx for all of u to create this wonderfull lines of code , i am searching this type of code from 6 months .:clap::clap:
 

casoni

Well-Known Member
#84
Hello SDL
First thing, please don't Use "SIR" with my name , i am just a copy-paster :)
and you are the first one , who comment on the concept , since the code was posted :)

and i am working on How to avoid whipsaws

Thank you
 

dell

Well-Known Member
#85
to avoid whips , we have to define condition's , about what a trend is , when it is changed , when smaller degree trend changes to secondary like things , we need a complete frame work of clear cut rules ,
also we can use other indi's , system's ,confluences for avoiding whips , yet we cannot eliminate it completely , but we can do it , by combined group effort .

we have great coder's like edward , casoni , mastermind , raguhveer ,extremist ,trash and many more .

plz put valuable idea's , so that we all try to implement it and test it to make a good system .

at starting point , @casoni ,
can u plz put multiple tf's pivot lines , like in 5m chart , 15m , 60m ad daily ? all should be visible in 5 m tf .
and what sdl suggest , can we backtest this idea , if it can be backtested than we will test and suggest some good filters definately ...
also thanx to all of u , in putting this afl upto to this stage .
 

amitrandive

Well-Known Member
#86
to avoid whips , we have to define condition's , about what a trend is , when it is changed , when smaller degree trend changes to secondary like things , we need a complete frame work of clear cut rules ,
also we can use other indi's , system's ,confluences for avoiding whips , yet we cannot eliminate it completely , but we can do it , by combined group effort .

we have great coder's like edward , casoni , mastermind , raguhveer ,extremist ,trash and many more .

plz put valuable idea's , so that we all try to implement it and test it to make a good system .

at starting point , @casoni ,
can u plz put multiple tf's pivot lines , like in 5m chart , 15m , 60m ad daily ? all should be visible in 5 m tf .
and what sdl suggest , can we backtest this idea , if it can be backtested than we will test and suggest some good filters definately ...
also thanx to all of u , in putting this afl upto to this stage .
Dell

Just my views on this

This AFL has been formed for identifying the trend strength.Let us not try to make it too complicated by inserting too many indicators.

We can have other AFL's for the different indicators.
Please remember that there cannot be any system which works well in both trending and sideways markets and is also able to avoid whipsaws.
 
#88
casoni sir , edward sir , mastermind sir , rughaveer sir , amit sir ,
is it possible that we buy when price closes above blue pivot line with a sl of red pivot line and vice versa , i mean to buy above swing pivot high with sl below swing pivot low.
if it is possible than plz add buy sell arrows and other essential coding lines so that we can backtest it and add some filters to avoid whips .

thanx for all of u to create this wonderfull lines of code , i am searching this type of code from 6 months .:clap::clap:
hi SDL,

i worked on ideas like you mention a lot and in volatile or strongly trending markets it works very good but in flat and non volatile markets it loses money. Trick is to recognize which market you are in but as we all know, that is very tough.

In some markets (e.g. with ES mini futures) just doing the opposite actually works better most of the times.

Below some code that does what you are looking for. Note1: slippageFactor should actually at least be 1 since I enter and exit at the breakout / stop lines. More realistic would be using a slip factor of 2. I like to use 0 so I can be in my dreamland some more. You can toggle between 2 different exits. Note2: if you do a backtest you need to set the parameters in the parameter window of the backtester which is separate from the chart parameters.

PHP:
// code by E.M.Pottasch, Jan 2015
SetBarsRequired(sbrAll,sbrAll);
xx=BarIndex();Lx=LastValue(xx); 
lvb=Min(Lx,Status("lastvisiblebarindex"));
rightStrength=Param("Right Strength (Major Pivot)",5,1,50,1);
leftStrength=Param("Left Strength (Major Pivot)",5,1,50,1);
rightStrength_mini=Param("Right Strength (Mini Pivot)",3,1,50,1);
leftStrength_mini=Param("Left Strength (Mini Pivot)",3,1,50,1);
tf=Param("Time Frame (Minutes)",5,1,1440,1);tfrm=in1Minute*tf;
slippageFactor=Param("Slippage Factor",0,0,10,1);
useMiniStop=ParamToggle("Exit Type","Major Pivot Stop and Reverse|Mini Pivot Stop",0);
fvb=0;lvb=BarCount;

SetTradeDelays(0,0,0,0);
SetOption("CommissionMode",3);
SetOption("CommissionAmount",2.01);
SetOption("FuturesMode",True);
NumContracts=1;//StaticVarGet("NumContractsSV");
PositionSize=NumContracts*MarginDeposit;
SetOption("MaxOpenPositions",4);

slip=TickSize*slippageFactor;

function handleSignals(Buy,BuyPrice,Sell,SellPrice,Short,ShortPrice,Cover,CoverPrice)
{
global BuyAdjusted;
global BuyPriceAdjusted;
global ShortAdjusted;
global ShortPriceAdjusted;
global SellAdjusted;
global SellPriceAdjusted;
global CoverAdjusted;
global CoverPriceAdjusted;
global longTarget;
global shortTarget;

BuyAdjusted=0;
BuyPriceAdjusted=0;
ShortAdjusted=0;
ShortPriceAdjusted=0;
SellAdjusted=0;
SellPriceAdjusted=0;
CoverAdjusted=0;
CoverPriceAdjusted=0;

for(i=fvb;i<lvb;i++) 
{
	if(Buy[i])
	{
		BuyAdjusted[i]=1;
		BuypriceAdjusted[i]=Min(BuyPrice[i]+slip,H[i]);
		
		for(j=i+1;j<BarCount;j++) 
		{					
			if(Sell[j])
			{
				SellAdjusted[j]=1;
				SellPriceAdjusted[j]=Max(SellPrice[j]-slip,L[j]);
				i=j-1;
				break;				
			}
			else if(Short[j])
			{
				SellAdjusted[j]=1;
				SellPriceAdjusted[j]=Max(ShortPrice[j]-slip,L[j]);
				i=j-1;
				break;				
			}
			else if(j==BarCount-1)
			{
				i=j;
				break;
			}						
		}
	}
	else if(Short[i])
	{
		ShortAdjusted[i]=1;
		ShortPriceAdjusted[i]=Max(ShortPrice[i]-slip,L[i]);
		
		for(j=i+1;j<BarCount;j++) 
		{					
			if(Cover[j])
			{
				CoverAdjusted[j]=1;
				CoverPriceAdjusted[j]=Min(CoverPrice[j]+slip,H[j]);
				i=j-1;
				break;				
			}
			else if(Buy[j])
			{
				CoverAdjusted[j]=1;
				CoverPriceAdjusted[j]=Min(BuyPrice[j]+slip,H[j]);
				i=j-1;
				break;				
			}
			else if(j==BarCount-1)
			{
				i=j;
				break;
			}										
		}
	}

}
}
function pkID(rightStrength,leftStrength)
{
	pk=H>Ref(HHV(H,leftStrength),-1) AND H>=Ref(HHV(H,rightStrength),rightStrength);
	return pk;
}
function trID(rightStrength,leftStrength)
{
	tr=L<Ref(LLV(L,leftStrength),-1) AND L<=Ref(LLV(L,rightStrength),rightStrength);
	return tr;
}

TimeFrameSet(tfrm); 
	pk=pkID(rightStrength,leftStrength);
	tr=trID(rightStrength,leftStrength);
	pkh=IIf(pk,H,Null);
	trl=IIf(tr,L,Null);
TimeFrameRestore();
fact=Nz(Max(tfrm/60,Interval()/60)/(Interval()/60));
if(fact==0)fact=1;
Lkbk=Nz(tfrm/Interval());
if(Lkbk>1)
{
	pk=TimeFrameExpand(pk,tfrm,expandFirst);
	pkh=TimeFrameExpand(pkh,tfrm,expandFirst);
	pkhs=IIf(!IsEmpty(pkh),1,0);pkhs=pkhs-Ref(pkhs,-1);
	pk=pk AND H==pkh;
	cond1=Sum(pk,BarsSince(pkhs==1)+1)==1 AND pk;
	pk=pk AND cond1;
	
	tr=TimeFrameExpand(tr,tfrm,expandFirst);	
	trl=TimeFrameExpand(trl,tfrm,expandFirst);
	trls=IIf(!IsEmpty(trl),1,0);trls=trls-Ref(trls,-1);
	tr=tr AND L==trl;
	cond1=Sum(tr,BarsSince(trls==1)+1)==1 AND tr;
	tr=tr AND cond1;
}

pkm=pkID(rightStrength_mini,leftStrength_mini);
trm=trID(rightStrength_mini,leftStrength_mini);

pkHigh1=Ref(ValueWhen(pk,H,1),-(rightStrength*fact+fact));
trLow1=Ref(ValueWhen(tr,L,1),-(rightStrength*fact+fact));
pkmHigh1=Ref(ValueWhen(pkm,H,1),-(rightStrength_mini+1));
trmLow1=Ref(ValueWhen(trm,L,1),-(rightStrength_mini+1));
pkHigh0=ValueWhen(pkm,H,0);
trLow0=ValueWhen(trm,L,0);
		
SetChartBkColor(ColorRGB(0,0,0));SetChartOptions(0,chartShowDates);
SetBarFillColor(IIf(C>O,colorGreen,IIf(C<=O,colorRed,colorLightGrey)));
Plot(C,"Price",IIf(C>O,colorDarkGreen,IIf(C<=O,colorDarkRed,colorLightGrey)),64,null,null,0,0,1);
PlotShapes(shapeCircle*tr,IIf(Lx-ValueWhen(tr,xx)>rightStrength*fact+fact,ColorRGB(0,255,0),colorWhite),0,L,-10);
PlotShapes(shapeCircle*pk,IIf(Lx-ValueWhen(pk,xx)>rightStrength*fact+fact,ColorRGB(255,0,0),colorWhite),0,H,10);
PlotShapes(shapeSmallCircle*trm,IIf(Lx-ValueWhen(tr,xx)>rightStrength_mini,ColorRGB(0,70,0),colorWhite),0,L,-10);
PlotShapes(shapeSmallCircle*pkm,IIf(Lx-ValueWhen(pk,xx)>rightStrength_mini,ColorRGB(70,0,0),colorWhite),0,H,10);

Plot(pkHigh1,"",colorBlue,1,Null,Null,0,0,1);
Plot(trLow1,"",colorRed,1,Null,Null,0,0,1);

Buy=Cross(H,pkHigh1);BuyPrice=Max(O,pkHigh1);
Short=Cross(trLow1,L);ShortPrice=Min(O,trLow1);

if(useMiniStop)
{
	Sell=Cross(trmLow1,L);SellPrice=Min(O,trmLow1);
	Cover=Cross(H,pkmHigh1);CoverPrice=Max(O,pkmHigh1);
	Plot(pkmHigh1,"",colorBlue,styledashed,Null,Null,0,0,1);
	Plot(trmLow1,"",colorRed,styledashed,Null,Null,0,0,1);
}
else
{
	Sell=Cross(trLow1,L);SellPrice=Min(O,trLow1);
	Cover=Cross(H,pkHigh1);CoverPrice=Max(O,pkHigh1);
}

handleSignals(Buy,BuyPrice,Sell,SellPrice,Short,ShortPrice,Cover,CoverPrice);
Buy=BuyAdjusted;
BuyPrice=BuyPriceAdjusted;
Short=ShortAdjusted;
ShortPrice=ShortPriceAdjusted;
Sell=SellAdjusted;
SellPrice=SellPriceAdjusted;
Cover=CoverAdjusted;
CoverPrice=CoverPriceAdjusted;

PlotShapes(IIf(Buy,shapeUpArrow,shapeNone),colorDarkGreen,0,L,-15);
PlotShapes(IIf(Buy,shapeSmallCircle,shapeNone),colorWhite,0,BuyPrice,0);
PlotShapes(IIf(Sell,shapeDownArrow,shapeNone),colorRed,0,H,-15);
PlotShapes(IIf(Sell,shapeSmallCircle,shapeNone),colorWhite,0,SellPrice,0);
PlotShapes(IIf(Short,shapeSmallDownTriangle,shapeNone),colorRed,0,H,IIf(Short AND Sell,-30,-15));
PlotShapes(IIf(Short,shapeSmallCircle,shapeNone),colorWhite,0,ShortPrice,0);
PlotShapes(IIf(Cover,shapeSmallUpTriangle,shapeNone),colorDarkGreen,0,L,IIf(Cover AND Buy,-30,-15));
Plotshapes(IIf(Cover,shapeSmallCircle,shapeNone),colorWhite,0,CoverPrice,0);
 

casoni

Well-Known Member
#89
Thank you Edward sir,
This code will keep me Busy for 2-3 days :)
 
#90
Thank you Edward sir,
This code will keep me Busy for 2-3 days :)
hi Cas, the idea is pretty simple. If you backtest a single future using "Exit Type" set on "Mini Pivot Stop" you will get pretty good results when the slippagefactor=0.

In many cases you will be able to enter/exit the trade at the price shown in the chart but in some cases you will not and that will kill the system.

I have some ideas to "solve" this but new ideas are welcome.
 

Similar threads