Simple Coding Help - No Promise.

Actually, it didnt work. Let me show:



That's the code I made:

_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", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();

_SECTION_BEGIN("MA BackTest");
ArrayMA = ParamField( "Array" , 3 );
PeriodosMA = Param( "Períodos" , 28 , 2 , 100 , 1 );
ProjectedMA_Period = PeriodosMA - 1;

OriginalMA = MA( ArrayMA , PeriodosMA );
//MA where i want to enter as the price touch it

ProjectedMA = Ref ( MA( ArrayMA , ProjectedMa_Period ) , -1 );
//this will show the exacly point where the MA will be when prices touch it



Plot( OriginalMA , "Média " + PeriodosMA + ")" , colorRed ) ;
Plot( ProjectedMA , "Buy/Sell Point" , colorWhite , styleDots | styleNoLine);




/*I activated the option: ACTIVATE STOPS IMMEDIATELY. I understood that after entering the trade, it checks:

1 - if the low activate the stop loss. If not...
2 - it checks if the high activate the take profit.

Actually, is there a way to make only the first check true? I mean:

1 - check if the low activate the stop loss in the entry bar...
2 - check if the high activate the take profit only on the next candle (the one after the entry bar).

What do you think? The reason I want it like this is because I want the backtest to assume the
worst possible scenario. Since its EOD data, I can't know for certain if the high of the
candle was achieved after I entered in the trade. So I want to assume it made the
high (takeprofit) before the entry signal (but I want to assume, also, that
the StopLoss was achieved after the entry signal). */

//Delay set by Mr. Trash Example:

tradedelay = 0;

if ( tradedelay > 0 )
{
entryprice = Open;
immediatestop = 1;
}
else
{
entryprice = Close;
immediatestop = 0;
}

SetOption( "ActivateStopsImmediately", immediatestop );


//Now the Buy Signal

BuySetup = (Ref( Low , -1 ) > Ref( OriginalMA , -1 )) AND (Low <= ProjectedMA);
//the prices must be above the MA for a buysetup

BuyPrice = ProjectedMA;
//I want to enter at the exact point of touch

Buy = Ref( BuySetup, -tradedelay );

Sell = 0;

StopGain_Multiplicator = Optimize( "StopGain_Mult" , 10 , 10 , 40 , 1 );
StopLoss_Multiplicator = Optimize( "StopLoss_Mult" , 10 , 10 , 40 , 1 );


StopLoss = StopLoss_Multiplicator * TickSize;
StopGain = StopGain_Multiplicator * TickSize;


ApplyStop(stopTypeLoss , stopModePoint , stoploss , 1 , False , 0 ) ;
ApplyStop( stopTypeProfit , stopModePoint , stopgain , 1 , False , 0 );


//I want to sell by stop loss of 100 points or take profit of 100 points




_SECTION_END();

What did I do wrong, Mr. Trash?

My best regards.
 

trash

Well-Known Member
As I have already mentioned I've posted two/three links. Two of those links will guide you on how to plot any Applystop. Also read my post again, carefully (also the links of course). All together you just need to adjust a bit here and there. Yes, it may sound evil because I'm not spoon feeding but that's the way it is. And it is quite simple really. Just some reading and logical thinking is needed.
 

josh1

Well-Known Member
Hi Happy,

Below AFL export exports entire intra-day data of a ticker into Ascii format when I click on Explore or Scan.
However, I want it to export for given date range only. Though it shows data for given date range only in New Analysis window. The date and time format is not proper.
Can You help.
Code:
//Filter=1;// By Barry Scarborough 7/14/2008, updated to handle large files 8/30/08
Filter=Status("rangetodate");
// #### READ THIS FIRST #### READ THIS FIRST #### READ THIS FIRST #### READ THIS FIRST #### READ THIS FIRST ####
// Export intraday and EOD data to .csv files 
// One file for each stock but the symbol name must be a valid Microsoft file Name OR you will have to modify it, see code below to change Name
// if the data exceeds 65500 lines it will be broken into separate files up to 327,500 lines OR about 227 days of 24 Hour, one Minute data
// This will create a directory H:\AmiBackup
// Select your symbols to export with the "Apply to" filter in AA window, to save data base use all symbols AND all quotes 
// Make sure the chart is on the period you want to save 
// Select the same timeframe period you want to save as using the AA "Settings"
// Press Scan button
// 

// created a directory on your C drive named AmiBroker data backup
dayhours = ParamToggle("Day hours only", "No|Yes");
fmkdir("H:\\AmiBackup\\");
SetBarsRequired(100000,100000);
Rfd = Status("rangefromdate");
Rtd = Status("rangetodate");
lname = Name(); // gets the name of the symbol
// note: if you have names with invalid characters like / you must rename the file before you try to create a Name 
// add an IF line for each symbol you need to rename
if (lname == "ER2U8-GLOBEX-FUT") lname = "ER2U8";
if (lname == " ") lname = "NSEI";

//Added by Josh1
//AddColumn(DateTime(), "Date", formatDateTime, FG, BG, 100);
AddColumn(DateTimeConvert( 0, DateTime() ), "Date");
AddColumn(DateTimeConvert( 1, DateTime() ), "Time");
//AddColumn(TimeNum() ,"Time",1);
AddColumn( O, "Open", 1.3 );
AddColumn( H, "High", 1.3 );
AddColumn( L, "Low", 1.3 );
AddColumn( C, "Close", 1.3 );
AddColumn(V, "Volume");
AddColumn(OpenInt,"OpenInt");
//AddColumn( Buy, "Buy", 1 );
//End - Added by Josh1

fh = fopen( "H:\\AmiBackup\\" + lname + ".csv", "w"); 
if( fh ) 
{ 
	if(Interval() == inDaily OR Interval() == inMonthly OR Interval() ==
inWeekly)
	{
		fputs( "Ticker,Date,Open,High,Low,Close,Volume,OpenInt \n", fh ); 
	   	for( i = 0; i < BarCount; i++ ) 
		{ 
//			zdate =DateNum();
//			if (zdate >= Rfd AND zdate<=Rtd)  {
 		  	y = Year(); 
 		  	m = Month(); 
		   	d = Day(); 
			fputs( Name() + "," , fh );
   		   	ds = StrFormat("%02.0f-%02.0f-%02.0f,", m[ i ], d[ i ], y[ i ] ); 
   	   		fputs( ds, fh ); 
      		qs = StrFormat("%.4f,%.4f,%.4f,%.4f,%.0f,%.0f\n", O[ i ],H[ i ],L[ i ],C[ i],V[ i ], OpenInt[i] ); 
      		fputs( qs, fh );
//			} 
/*
			if(i == 65500 OR i == 130000 OR i == 196500 OR i == 262000)
			{
				fclose( fh ); 
				if(i == 65500  ) fh = fopen( "H:\\AmiBackup\\" + lname + " A.csv", "w"); 
				if(i == 130000 ) fh = fopen( "H:\\AmiBackup\\" + lname + " B.csv", "w"); 
				if(i == 196500 ) fh = fopen( "H:\\AmiBackup\\" + lname + " C.csv", "w"); 
				if(i == 262000 ) fh = fopen( "H:\\AmiBackup\\" + lname + " D.csv", "w"); 
			}
*/
		}
	}
	else // intraday so add time field
	{
		fputs( "Ticker,Date,Time,Open,High,Low,Close,Volume,OpenInt \n", fh ); 
 	  	y = Year(); 
 	  	m = Month(); 
	   	d = Day(); 
	   	r = Hour();
	   	e = Minute();
	   	n = Second();
   		
	   	for( i = 0; i < BarCount; i++ ) 
		{ 
//			zdate =DateNum();
//			if (zdate >= Rfd AND zdate <= Rtd)   {
			if (dayhours AND LastValue(TimeNum()) >= 91500 AND LastValue(TimeNum()) <=153100)
			{ 
				fputs( Name() + "," , fh );
 		     	ds = StrFormat("%02.0f-%02.0f-%02.0f,", m[ i ], d[ i ], y[ i ] ); 
   			   	fputs( ds, fh ); 
 
  	    		ts = StrFormat("%02.0f:%02.0f:%02.0f,", r[ i ],e[ i ],n[ i ] ); 
  	    		fputs( ts, fh ); 

	 	     	qs = StrFormat("%.4f,%.4f,%.4f,%.4f,%.0f,%.0f\n", O[ i ],H[ i ],L[ i ],C[ i],V[ i ],OpenInt[ i ] ); 
		      	fputs( qs, fh ); 
			}
			else
			{ 
				fputs( Name() + "," , fh );
 		     	ds = StrFormat("%02.0f-%02.0f-%02.0f,", m[ i ], d[ i ], y[ i ] ); 
   			   	fputs( ds, fh ); 
 
  	    		ts = StrFormat("%02.0f:%02.0f:%02.0f,", r[ i ],e[ i ],n[ i ] ); 
  	    		fputs( ts, fh ); 

	 	     	qs = StrFormat("%.4f,%.4f,%.4f,%.4f,%.0f,%.0f\n", O[ i ],H[ i ],L[ i ],C[ i],V[ i ],OpenInt[ i ] ); 
		      	fputs( qs, fh ); 
			}
//		}
/*
			if(i == 65500 OR i == 130000 OR i == 196500 OR i == 262000)
			{
				fclose( fh ); 
				if(i == 65500  ) fh = fopen( "c:\\AmiBackup\\" + lname + " A.csv", "w"); 
				if(i == 130000 ) fh = fopen( "c:\\AmiBackup\\" + lname + " B.csv", "w"); 
				if(i == 196500 ) fh = fopen( "c:\\AmiBackup\\" + lname + " C.csv", "w"); 
				if(i == 262000 ) fh = fopen( "c:\\AmiBackup\\" + lname + " D.csv", "w"); 
			}
*/
 	  	} 
	}
   	fclose( fh ); 
} 

//Buy = Sell = 1;
Buy=((DateNum()>=1130101) AND (DateNum()<=1140227) );
//Buy = ( (TimeNum()>=190000 AND DateNum()==1050315) OR (TimeNum()<=030000 AND DateNum()==1050316) ) AND V>0;
 

trash

Well-Known Member
Hi Happy,

Below AFL export exports entire intra-day data of a ticker into Ascii format when I click on Explore or Scan.
However, I want it to export for given date range only. Though it shows data for given date range only in New Analysis window. The date and time format is not proper.
Can You help.
Search my name and keyword "barinrange", then you will find at least one example.
 
Last edited:

trash

Well-Known Member
Search my name and keyword "barinrange", then you will find at least one example.
Anyway here is another example outputting OHLCV


Code:
// Exploration code to export to CSV (intra-day or EOD, any chosen Range output possible)
// minimum Amibroker 5.50 required
// by trash

// Usage:
// 1. open AFL in Analysis,
// 2. choose Apply to:
// 3. choose Range
// 4. choose Periodicity in backtest settings
// 5. check two settings below
// 6. click Explore

separatefiles = 1; // true or false to export to separate files (1) or all to one file (0)
destination = "C:\\#ABexport\\"; // location of exported files

fmkdir( destination ); // Create export folder


// critical section functions by AmiBroker start ###########################
function _TryEnterCS( secname )
{
    global _cursec;
    _cursec = "";

    // try obtaining semaphore for 1000 ms
    for ( i = 0; i < 1000; i++ )
        if ( StaticVarCompareExchange( secname, 1, 0 ) == 0 )
        {
            _cursec = secname;
            break;
        }
        else
            ThreadSleep( 1 ); //sleep one millisecond

    return _cursec != "";
}

// call it ONLY when _TryEnterCS returned TRUE!
function _LeaveCS()
{
    global _cursec;
    if ( _cursec != "" )
    {
        StaticVarSet( _cursec, 0 );
        _cursec = "";
    }
}
// critical section functions by AmiBroker end ############################


nm      = Name();
dt      = DateTime();
bi      = BarIndex();
bir     = Status( "BarInRange" );
fbr     = Status( "FirstBarInRange" );
lbr     = Status( "LastBarInRange" );
bars    = ValueWhen( lbr, bi ) - ValueWhen( fbr, bi ) + 1;

if ( Status( "actionex" ) == actionExplore )
{
    if ( _TryEnterCS( "myexportsemaphore" ) )
    {
        if ( separatefiles )
            fh = fopen( destination + nm + ".csv", "w" ); // each symbol to separate files !!!!!!!!!!!!!!!!
        else
            fh = fopen( destination + "AllToOne.csv", "a" ); // all symbols to one file    !!!!!!!!!!!!!!!!

        if ( fh )
        {
            if ( Status( "stocknum" ) == 0 )
                fputs( "Symbol,DateTime,Open,High,Low,Close,Volume,OpenInt\n", fh );

            for ( i = 0; i < BarCount; i++ )
            {
                if ( bir[i] ) // check date range
                {
                    dtstring = DateTimeToStr( dt[i] ); // Datetime to string conversion

                    Line = nm + "," + dtstring + StrFormat( ",%g,%g,%g,%g,%g,%g\n",
                                                            O[ i ],
                                                            H[ i ],
                                                            L[ i ],
                                                            C[ i ],
                                                            V[ i ],
                                                            OI[ i ] );
                    fputs( Line, fh );
                }
            }

            fclose( fh );
        }

        _LeaveCS();
    }
    else
        _TRACE( "Unable to enter CS" );
}

// Exploration info output ############################
Filter  = lbr;

SetOption( "NoDefaultColumns", True );

AddTextColumn( "Export finished", "Status", 1, colorWhite, colorDarkGreen, 90 );
AddTextColumn( nm, "Ticker", 1, colorWhite, colorDarkGrey, 80 );
AddColumn( ValueWhen( fbr, dt ), "Start Date/Time", formatDateTime, colorWhite, colorDarkGrey, 120 );
AddColumn( ValueWhen( lbr, dt ), "End Date/Time", formatDateTime, colorWhite, colorDarkGrey, 120 );
AddColumn( bars, "Bars in Range", 1.0, colorWhite, colorDarkGrey, 80 );
 
Dear All,
I want to modify this afl which scans for Gap Up/Down.
I want to explore for scrips where the stocks have Gapped Up/Down
and then the Gap has not been closed in subsequent days.

Thanks and regards.

bi=BarIndex();
f=(100+Param("gap up factor",2,0,50,1))/100;//guf
g=(100-Param("gap down factor",2,0,50,1))/100;//gdf

bbc= Ref(C,-1)>=Ref(O,-1) && C>=O;
brc= Ref(C,-1)>=Ref(O,-1) && O>=C ;
rbc= Ref (C,-1)<=Ref(O,-1) && C>=O;
rrc= Ref (C,-1)<=Ref(O,-1) && O>=C;

guo= (bbc && O> f*Ref(C,-1)) || ( brc && C>f*Ref(C,-1) ) || ( rbc && O>f*Ref(O,-1) ) || (rrc && C >f*Ref (O,-1) ) ;
gdo= ( bbc && C<g*Ref(O,-1)) || (brc && O<g*Ref (O,-1) )|| ( rbc && C< g*Ref (C,-1) ) || (rrc && O <g*Ref(C,-1));

Filter = (guo OR gdo )AND C > 10 AND V > 10000;
AddColumn(C,"close",1.2);
AddTextColumn(WriteIf(guo,"gap up opening ",WriteIf(gdo,"gape down opening","")),"gap up/ gap down",1.2,colorBlack,IIf(guo,colorGreen,IIf(gdo,colorRed,Null)));



PlotShapes(IIf(bi>=LastValue(bi)-100,guo*shapeSmallUpTriangle+gdo*shapeSmallDownTriangle,Null),IIf(guo,colorGreen,IIf(gdo,colorRed, Null)))
;
 
Hello, guys.

How do we tell to the formula if the linear regression channel is upward or downward? Something that make possible a condition like this:

if linear regression is pointing up, buy mode.
if linear regression is pointing down, short mode.

Thanks! :D

EDIT: Nevermind. Just got the solution. If anyone wants to know, too, here's the code I used - text in red is what I added (it changes the color of the central channel line to blue (upward) or red (downward)):

/*

trend channel development
Edward Pottasch, nov 2004

*/


//per = 15;
per = Param( "period", 15, 1, 500, 1);

mm = C;

x = Cum(1);
lastx = LastValue(x);
selv = SelectedValue(x);

aaa = LinRegIntercept(mm, per);
bbb = LinRegSlope(mm, per);

daa = SelectedValue(ValueWhen(x, aaa, 1));
dbb = SelectedValue(ValueWhen(x, bbb, 1));

xx = IIf(x > selv - per AND x <= selv, x - (selv - per),Null);

yy = daa + dbb * xx;

dhh = abs(H - yy);
dll = abs(L - yy);
dtt = Max(dhh,dll);

wd = SelectedValue(HHV(dtt,per));

SetChartOptions(0, chartShowDates);
GraphXSpace = 5;

Slope = LinRegSlope(yy , 2);
Colorchange = IIf(slope > 0, colorBlue, IIf(slope < 0, colorRed, colorWhite));


Plot(C,"",colorWhite,64);
Plot(yy, "LinReg", colorChange );
Plot(yy + wd, "Upper Boundary", colorRed, 4 );
Plot(yy - wd, "Lower Boundary", colorBrightGreen, 4 );
EDIT 2: Actually, in the backtest it didnt work the way it was supposed to. :(

I put (just an example):

BuyCondition1 = cross( Macd() , Signal () );
BuyCondition2 = Slope > 0;

Buy = BuyCondition1 AND BuyCondition2;

It bought when the slope was downward and red. Can anyone help?

Thanks!

EDIT 3 : I did it..

Just:

Slope = bbb; //rewrite the slope variable.
 
Last edited:

xsis

Active Member
dear all

pls help me in making an afl where bollinger bands are used:
  • BUY is break of high of a candle which touches the BBtop
  • SELL is touch of BBbot
  • SHORT is break of low of a candle which touches the BBbot
  • COVER is touch of BBtop

thks
 

cellclinic

Well-Known Member
HEY FRIENDS ...

This afl is plotting only in current days HLC... it is much better if it is possible to get in each day which will help to back-test or practicing in bar replay ...

Regards ...

below code will plot only line

_SECTION_BEGIN("PreDay HLC");
//TIME FRAME CALCULATION
H1 = TimeFrameGetPrice("H", inDaily, -1); // yesterdays high
L1 = TimeFrameGetPrice("L", inDaily, -1); // low
C1= TimeFrameGetPrice("C", inDaily, -1); // close
DayO = TimeFrameGetPrice("-1", inDaily); // current day open

//PLOTS

Plot(H1, "",colorRed,styleLine+styleThick+styleNoRescal e+st yleNoLabel);
Plot(L1, "",colorBrightGreen,styleLine+styleThick+style NoLa bel);
Plot(C1, "",colorLightGrey,styleLine+styleNoRescale+sty leNo Label);
_SECTION_END();

Thanks
 

Similar threads