0% found this document useful (1 vote)
467 views

Entry & Exit in Same Candle - AFL Programming - Am PDF

The document provides instructions for posting on the AmiBroker Community Forum. It asks users to read guidelines, search the forum for existing solutions, and check the AmiQuote FAQ before posting. It also reminds users to be running the up-to-date software version.

Uploaded by

Hitesh Chaudhary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
467 views

Entry & Exit in Same Candle - AFL Programming - Am PDF

The document provides instructions for posting on the AmiBroker Community Forum. It asks users to read guidelines, search the forum for existing solutions, and check the AmiQuote FAQ before posting. It also reminds users to be running the up-to-date software version.

Uploaded by

Hitesh Chaudhary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Welcome to AmiBroker Community Forum!

We understand that you may be in a hurry, but before you post pretty please do the following:

Read How to use this site - really it is essential to read at least 3 top points
Search the forum (use magnifying glass in upper right corner) to find already existing solutions first
Check AmiQuote FAQ - 99% of all AmiQuote questions are answered already there and any new
AmiQuote questions should go there.

Make sure you are using up-to-date version of the software. Your very first step should be updating your

Entry & Exit in same Candle


intraday

dtm Oct '19

I am trying price action based strategy, where I want to exit in the same candle if my exit price matches. But
none of my trades are exiting in the same candle even though price hit the target in the same candle, its
exiting in the next candle when the price hit the target or exiting at open, if open is above target.
Not sure if I am missing any function.

Attaching a simple sample code as reference only.


Copy

Buy = H>Prev_Day_High;
BuyPrice = Prev_Day_High;
Sell = H>(BuyPrice + Prev_Day_High*0.001);

Can anyone help here, or share any similar reading material.

Solved by Cougar in post #2

Please refer to Allow same bar exit section of System test settings window guide. Search the forum too
(this is discussed several times). Also refrain from using ExRem() function while same bar exit is "on".
Limitation of Exrem or Flip functions: It has nothing to do with the platform (in this cas…

Cougar Oct '19

Please refer to Allow same bar exit section of System test settings window guide. Search the forum too
(this is discussed several times).

Also refrain from using ExRem() function while same bar exit is "on".

Limitation of Exrem or Flip functions: It has nothing to do with the platform (in this case AB) but more to do
with the logic of your strategy. As per definition, Exrem( ARRAY1, ARRAY2 ) removes excessive signals;
returns 1 on the first occurrence of "true" signal in Array1 then returns 0 until Array2 is true even if
there are "true" signals in Array1. Now, what if by virtue of the strategy used, both Array1 and Array2
becomes true at the same time on a single bar? The below code can be used to control such specific
situation otherwise Exrem function is well-off - depending on the strategy.
Copy

//Using For-Loop to generate Buy/Sell Signal instead of using ExRem


_SECTION_BEGIN( "For-Loop Buy/Sell" );
//A Simple Demo strategy
Per = Param( "Periods", 15, 3, 144, 1 );
HigherHighs = HHV( H, Per );
LowerLows = LLV( L, Per );
_Buy = Cross( H, Ref( HigherHighs, -1 ) );
_Short = Cross( Ref( LowerLows, -1 ), L );

//Array Initialization
Buy = Sell = Short = Cover = Null;
LongFlag = ShortFlag = 0; //Simple Flag arrays to identify whether in a Lo

//Using Loop to generate signals


for( i = 0; i < BarCount; i++ )
{
//Long Positions
if( _Buy[ i ] AND LongFlag == 0 )
{
Buy[ i ] = 1;
LongFlag = 1; //To record that we are in Long position
}
if( _Short[ i ] AND LongFlag == 1 )
{
Sell[ i ] = 1; //Selling-off the Long position
LongFlag = 0; //Reseting LongFlag back to False, to denote that
}

//Short Positions
if( _Short[ i ] AND ShortFlag == 0 )
{
Short[ i ] = 1;
ShortFlag = 1; //To record that we are in Short position
}
if( _Buy[ i ] AND ShortFlag == 1 )
{
Cover[ i ] = 1; //Covering the Short position
ShortFlag = 0; //Reseting ShortFlag back to False, to denote tha
}
}

//Plotting
Plot( C, "", colorDefault, styleBar | styleThick );
Plot( HigherHighs, "Highs", colorDarkGreen );
Plot( LowerLows, "Lows", colorBrown );
PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ), colorBrightGreen, 0, L, -
PlotShapes( IIf( Sell, shapeSmallDownTriangle, shapeNone ), colorBrown, 0,

PlotShapes( IIf( Short, shapeDownArrow, shapeNone ), colorRed, 0, H, -30 )


PlotShapes( IIf( Cover, shapeSmallUpTriangle, shapeNone ), colorDarkGreen,
_SECTION_END();

dtm Oct '19

Thanks mate, your help worked.

Cougar Oct '19

If you want to delve deeper, you might consider applying a:

Controlled Trailing Stop-Loss (TSL): It is necessary to ensure that TSL always goes up for Long positions
and goes down for Short positions or remains constant to the previous value. "Percentage or Points" based
TSLs does not account market Volatility, so it is not dynamic. "Standard Deviation" based TSL (for e.g. Kase
DevStop ) or "ATR" based TSLs are ideal. For demo using ATR based TSL here:
Copy

_SECTION_BEGIN( "Controlled TSL" );


MultATR = Param( "ATR Multiplier", 2, 1, 4, 0.5 );
PerATR = Param( "ATR Period", 14, 3, 89, 1 );
_ATR = ATR( PerATR );

//A Simple Demo strategy


Per = Param( "Swing Periods", 15, 3, 144, 1 );
HigherHighs = HHV( H, Per );
LowerLows = LLV( L, Per );
_Buy = Cross( H, Ref( HigherHighs, -1 ) );
_Short = Cross( Ref( LowerLows, -1 ), L );

//Array Initialization
Buy = Sell = Short = Cover = TSL = Null;
LongFlag = ShortFlag = 0; //Simple flags

//Using Loop to generate signals


for( i = 0; i < BarCount; i++ )
{
//Long Positions
if( _Buy[ i ] AND LongFlag == 0 )
{
Buy[ i ] = 1;
LongFlag = 1; //To record that we are in Long position
}
if( LongFlag )
{
if( TSL[ i - 1 ] > H[ i ] - _ATR[ i ] * MultATR )
TSL[ i ] = TSL[ i - 1 ];
else
TSL[ i ] = H[ i ] - _ATR[ i ] * MultATR;
}

if( ( _Short[ i ] OR ( L[ i ] < TSL[ i - 1 ] ) ) AND LongFlag == 1 )


{
Sell[ i ] = 1; //Selling-off the Long position
LongFlag = 0; //Reseting LongFlag back to False, to denote that w
}

//Short Positions
if( _Short[ i ] AND ShortFlag == 0 )
{
Short[ i ] = 1;
ShortFlag = 1; //To record that we are in Short position
}
if( ShortFlag )
{
if( TSL[ i - 1 ] < L[ i ] + _ATR[ i ] * MultATR )
TSL[ i ] = TSL[ i - 1 ];
else
TSL[ i ] = L[ i ] + _ATR[ i ] * MultATR;
}

if( ( _Buy[ i ] OR H[ i ] > TSL[ i - 1 ] ) AND ShortFlag == 1 )


{
Cover[ i ] = 1; //Covering the Short position
ShortFlag = 0; //Reseting ShortFlag back to False, to denote that
}
}

//Plotting
Plot( C, "", colorDefault, styleBar | styleThick );
Plot( HigherHighs, "Highs", colorDarkGreen, styleDashed | styleNoRescale )
Plot( LowerLows, "Lows", colorBrown, styleDashed | styleNoRescale );

PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ), colorBrightGreen, 0, L, -


PlotShapes( IIf( Sell, shapeSmallDownTriangle, shapeNone ), colorBrown, 0,

PlotShapes( IIf( Short, shapeDownArrow, shapeNone ), colorRed, 0, H, -30 )


PlotShapes( IIf( Cover, shapeSmallUpTriangle, shapeNone ), colorDarkGreen,

Plot( TSL, "TSL", colorPink, styleThick | styleNoRescale ); //Trailing Sto


_SECTION_END();

Trying to switch type of stop loss while in trade


yogi Nov '19

Can same be achieved without using loop?


Using array or staticvar.

Cougar Nov '19

yogi:

Can same be achieved without using loop?

Purely circumstantial - depends on the strategy! If the system demands explicit segregation, then TINA than
looping.

Few things previously mentioned by Tomasz:

Keep signal active for more than one bar

To keep signals you have to have them IN STATE form as opposed to Signal (Pulse) form.

Counting bars in trade resulting in 2 sell exit strategies

BarsSince can be used if signal is in pulse form


Copy

Buy = Cross( 22, RSI( 2 ) ); // pulse form of buy signal

Your Buy is NOT in pulse form and you can’t use BarsSince then.

Secondly, you are doing other mistakes such as using = (assignment) instead of comparison (==).
These are basic mistakes that you need to get rid of otherwise all formulas will be wrong.
https://www.amibroker.com/guide/a_mistakes.html

Thirdly if you are using loop, you don’t need ExRem or BarsSince or anything like that

Using OR in a Sell Condition allows Mutliple entries on same Symbol

So if you don't want same bar entry-exit and exit-entry you need to
Turn OFF / Remove that option / line from the code

Consult the manual regarding supported scenarios:


http://www.amibroker.com/f?applystop
http://www.amibroker.com/guide/h_portfolio.html

Help with Intrabar Exit

It was written a number of times already: remove ExRems. They are not needed. ExRem() and Flip()
logically are working like set-reset latch flip-flop device . So obviously the same time "set" and "reset" is
not allowed. If you don't understand how ExRems work you should follow advice given here: How do I
debug my formula? and specifically this http://www.amibroker.com/kb/2014/09/29/debugging-
techniques-part-1-exploration/
yogi Nov '19

Trying to get the same formula (supertrend) in array:


Copy

function SuperTrend(lenATR, width)


{
nATR = ATR(lenATR);
pAvg = (H+L) / 2;

upperBand = pAvg + width * nATR;


lowerBand = pAvg - width * nATR;
isUpTrend = True;
dn = DateNum();

for (i=lenATR; i<BarCount; ++i)


{
if (C[i] > upperBand[i-1])
isUpTrend[i] = True;
else if (C[i] < lowerBand[i-1])
isUpTrend[i] = False;
else
isUpTrend[i] = isUpTrend[i-1];

if (isUpTrend[i])
lowerBand[i] = Max(lowerBand[i], lowerBand[i-1]);
else
upperBand[i] = Min(upperBand[i], upperBand[i-1]);
}

super = IIf(isUpTrend, lowerBand, upperBand);


return super;
}

st = SuperTrend(10,3);

///////////////////////////////////////////////////////////////////////////////
BASIC UPPERBAND = (HIGH + LOW) / 2 + Multiplier * ATR
BASIC LOWERBAND = (HIGH + LOW) / 2 - Multiplier * ATR
FINAL UPPERBAND = IF( (Current BASICUPPERBAND < Previous FINAL UPPERBAND) and
FINAL LOWERBAND = IF( (Current BASIC LOWERBAND > Previous FINAL LOWERBAND) and
SUPERTREND = IF(Current Close <= Current FINAL UPPERBAND ) THEN Current FINAL U
///////////////////////////////////////////////////////////////////////////////
_AT = ATR(10);
_Mul = 3;
BUB = ((High + Low)/2) + (_Mul * _AT);
BLB = ((High + Low)/2) - (_Mul * _AT);
FUB = IIf(BUB <= P_FUB OR P_C >= P_FUB, BUB, P_FUB);

I am stuck in getting the first value for "Previous Final upperband".

Please guide.

TrendSurfer Nov '19

@yogi ,

Do you have an AmiBroker License?

You cannot post in this section of the forum if you don't.

See license-verified-badge .

mradtke Nov '19

Also, the SuperTrend function that you have posted was written by me. So first, you should either ask
permission or at least give credit of some sort when you're referencing someone else's work. Second, I
resorted to a loop because you can't write the SuperTrend logic using only array functions. The reason is
that the upper and lower band values get modified as you iterate through the array, and they feed back into
the isUpTrend array.

You might also like