Scaling in/out of a security while between the main buy/sell signals poses a unique problem as your position size has to be monitored somehow in order to have enough funds when you want to scale back in to a full position. If you don't keep track and you don't have enough funds, the scale-in signal will be ignored.
I couldn't find a solution to this problem so I came up with the following solution:
BuySignal = { Your buy condition }
//-----------------------------------------------------------------
// ScaleIn / ScaleOut:
//-----------------------------------------------------------------
DoScaleOut = { Your Scale-out condition }
DoScaleIn = { Your Scale-in Condition }
ScaleOutSize = Param( "ScaleOutSize", 33, 0, 100, 1 ) ;
CountScaleOutFromBuySignal = SumSince( BuySignal, DoScaleOut ) ;
CountScaleOutFromDoScaleIn = SumSince( DoScaleIn, DoScaleOut ) ;
ScaleOutCount = Min( CountScaleOutFromBuySignal, CountScaleOutFromDoScaleIn ) ; // Count the scale-outs since the buySignal and also since Scale-in and keep the lowest count as that would be the most recent entry signal. The Scale-in would be a purchase to bring position back to full.
ScaleOutOK = ScaleOutCount <= 3 ; // Counter to limit number of scale-outs
DoScaleOut = DoScaleOut AND ScaleOutOK ; // if count is <= 3, then scale-out otherwise ignore signal.
ScaleOutCount = IIf( ScaleOutCount <= 3, ScaleOutCount, 3 ) ; // keep the scale-out count at a max of 3
PosSize = ( 100 * ( 1- ScaleOutSize ) ^ ScaleOutCount ) / ( ( 1- ScaleOutSize - 1 ) ^ ScaleOutCount ) ; // Calculation to determine position size required to get back to full position by reverse calculating the scale-outs. In the divisor of this calculation, I subtracted 1 as shown: ( 1- ScaleOutSize - 1 ) to increase the size of the divisor which makes the full position size a little smaller. This ensures that I don't get a "not enough funds" error and Amibroker ignores the trade signal.
//-----------------------------------------------------------------
Buy = { Your Buy Signal }
Sell = { Your Sell Signal }
Buy = Buy + sigScaleIn * DoScaleIn + sigScaleOut * DoScaleOut; ;
SetPositionSize( 100, spsPercentOfEquity );
SetPositionSize( ScaleOutSize * ( Buy == sigScaleOut ) + PosSize * ( Buy == sigScaleIn ), spsPercentOfPosition * ( Buy == ( sigScaleOut OR sigScaleIn ) ) );
You'll probably find out as I did that scaling in and out of a stock decreases performance over simply using the main buy/sell signals. Let me know if you find this true also.