Help with scale out

Hello. I am using the code from the knowledge base to generate trades from a file: http://www.amibroker.com/kb/2014/09/30/gen-backtest-from-a-file/

I have modified it to my needs. But I need to close partially a position (sell 1 contract out of 2 initial) and I cannot make it work. The file includes a line with the partial trade. But the backtester closes completely the trade so it is not in the open position list.

c38

This is the code with my attemp to Scale Out:

file = "C:\\Program Files\\AmiBroker\\files\\trades.csv"; // fichero con las operaciones
dt = DateTime(); 
// 
// Initialize variables 
Buy = Sell = Short = Cover = possize = shares = trade = 0;  
// 
fh = fopen( file, "r" ); 
// 
if( fh ) 
 { 
     while( ! feof( fh ) ) 
     { 
         line = fgets( fh ); 
         // get the ticker symbol from the file 
         sym = StrExtract( line, 0, ';' ); 
         // if ticker matches current symbol 
         if ( Name() == sym ) 
         { 
             // extract data from line of text 
             trade = StrExtract( line, 1, ';'); 
             trade_datetime = StrToDateTime( StrExtract( line, 2, ';') ); 
             price = StrToNum( StrExtract( line, 3, ';') ); 
				fuera = price > High OR price < Low;  //cuando el precio ya no sirve por el cambio de historico
				price = IIf(fuera, Close, price); //si hay un cero significa a cierre
             shares = StrToNum( StrExtract( line, 4, ';') ); 
             // 
              if ( trade == "Buy" ) 
             { 
                 newbuy = dt == trade_datetime; 
                 Buy = Buy OR newbuy; // combine previous buy signals with new 
                 BuyPrice = IIf( newbuy, price, BuyPrice ); 
                 possize = IIf( newbuy, shares, possize ); 
                 
             } 
              if ( trade == "Sell" ) 
             { 
                 newsell = dt == trade_datetime; 
                 Sell = Sell OR newsell; // combine previous sell signals with new 
                 SellPrice = IIf( newsell, price, SellPrice ); 
                 possize = IIf( newsell, shares, possize ); 
                 Buy = IIf(shares < possize, sigscaleout, Buy);
             } 
             if ( trade == "Short" ) 
             { 
                 newshort = dt == trade_datetime; 
                 Short = Short OR newshort; // combine previous buy signals with new 
                 Shortprice = IIf( newshort, price, ShortPrice ); 
                 possize = IIf( newshort, shares, possize ); 
                 
             } 
             if ( trade == "Cover" ) 
             { 
				newcover = dt == trade_datetime; 
                Cover = Cover OR newcover; // combine previous sell signals with new 
                Coverprice = IIf( newcover, price, CoverPrice ); 
             } 
         } 
     } 
     // 
     fclose( fh ); 
 } 
 else 
 { 
     Error( "ERROR: file can not be open" ); 
 } 
 
 //DIMENSIONAMIENTO// 
SetOption( "initialequity", 100000 ); // starting capital   
SetOption("WarningLevel", 1 ); 
MarginDeposit = 1; PositionSize = shares;    

…is where your issue lies. newsell is going to be True simply because there is a Sell signal, so for scale outs you’ll end up with a Sell and a sigScaleOut in the Buy array. Needless to say the Sell is then trumping your scale out signal.

One way around it would be to make newsell dependent on the shares being equal to the possize.

newsell = dt == trade_datetime AND shares == possize;
/*...*/
Buy = IIf(shares < possize, sigscaleout, Buy);
possize = IIf( shares < possize, possize - shares, IIf(newsell, 0, possize)); // reduce position size if Scale Out, set to 0 if full Sell

Thanks for your answer. Unfortunately your solution keeps all Longs open. I am getting confused with SigscaleOut in the Buy array, and Sells, altogether. This is very complicated for me :((

c49c48

With some changes it seems to work now. This is the code that scales out:

file = "C:\\Program Files\\AmiBroker\\files\\trades.csv"; // fichero con las operaciones 
dt = DateTime();  
//  
// Initialize variables  
Buy = Sell = Short = Cover = possize = shares = trade = 0;   
//  
fh = fopen( file, "r" );  
//  
if( fh )  
 {  
     while( ! feof( fh ) )  
     {  
         line = fgets( fh );  
         // get the ticker symbol from the file  
         sym = StrExtract( line, 0, ';' );  
         // if ticker matches current symbol  
         if ( Name() == sym )  
         {  
             // extract data from line of text  
             trade = StrExtract( line, 1, ';');  
             trade_datetime = StrToDateTime( StrExtract( line, 2, ';') );  
             price = StrToNum( StrExtract( line, 3, ';') );  
				fuera = price > High OR price < Low;  //cuando el precio ya no sirve por el cambio de historico 
				price = IIf(fuera, Close, price); //si hay un cero significa a cierre 
             shares = StrToNum( StrExtract( line, 4, ';') );  
             //  
              if ( trade == "Buy" )  
             {  
                 newbuy = dt == trade_datetime;  
                 Buy = Buy OR newbuy; // combine previous buy signals with new  
                 BuyPrice = IIf( newbuy, price, BuyPrice );  
                 possize = IIf( newbuy, shares, possize );  
              }  
              if ( trade == "Sell" )  
             {  
				 newsell = dt == trade_datetime;   
				 Sell = Sell OR newsell; // combine previous sell signals with new 
				 SellPrice = IIf( newsell, price, SellPrice );
				 //dont sell if number of contracts dont match
				 scale = shares < ValueWhen(Buy, possize);
				 Sell = IIf(scale, 0, Sell);
				 Buy =  IIf(scale, sigScaleOut,Buy);
				 possize = IIf( newsell, shares, possize);
			 }  
             if ( trade == "Short" )  
             {  
                 newshort = dt == trade_datetime;  
                 Short = Short OR newshort; // combine previous buy signals with new  
                 Shortprice = IIf( newshort, price, ShortPrice );  
                 possize = IIf( newshort, shares, possize );                   
             }  
             if ( trade == "Cover" )  
             {  
				newcover = dt == trade_datetime;  
                Cover = Cover OR newcover; // combine previous sell signals with new  
                Coverprice = IIf( newcover, price, CoverPrice ); 
                //dont Cover if number of contracts dont match
				 scale = shares < ValueWhen(Short, possize);
				 Cover = IIf(scale, 0, Cover);
				 Short =  IIf(scale, sigScaleOut,Short); 
                possize = IIf( newcover, shares, possize );   
             }  
         }  
     }  
     //  
     fclose( fh );  
 }  
 else  
 {  
     Error( "ERROR: file can not be open" );  
 }  
  
 //DIMENSIONAMIENTO//  
SetOption( "initialequity", 100000 ); // starting capital    
MarginDeposit = 1;  
SetPositionSize( possize, spsShares );
2 Likes

Hi Guys,

Anyone have any advice or experience using SigScaleIn for a list of trades from a CSV where 2 buys were taken on the same day/bar?

I have also been tinkering with the template code and the Scale commands and have them pretty much worked out but I cant seem to get it to buy both "buys" if the tradedate is the same. It always takes only the last trade of the day. I assume this is because as checks for equality of dt == trade_datetime it writes a 1 to the buy array for the first row in the CSV but then as it moves to the next row and finds equality it overwrites the buy array for that day making the previous row in the spreadsheet a 0.

Im not sure if im explaining this the best but I dont come from a CS background so im slowly getting my head around how it all works but it is fascinating nonetheless.

I wont post the entire code as its the same as the template pretty much but below is the modified buy section and also a screenshot of the CSV and the results.

I have read most of the topics on scaling and one gave me the impression this is only possible if I either use low level CBT (im def not there yet) or flatten it with VBA (more likely answer - unless I can do it in AB for the challenge and lesson)

Any assistance is appreciated.

Also, out of curiosity why does the scale-in show up under exit signal in the detailed log?

Cheers

if ( trade == "Buy" )  
             {  
                 newbuy = dt == trade_datetime;  
                 //Buy = Buy OR newbuy; // combine previous buy signals with new  
                 BuyPrice = IIf( newbuy, price, BuyPrice );  
                 possize = IIf( newbuy, shares, possize );  
                 Buy = IIf(newbuy, sigScaleIn, Buy);
              }  
              Sell = 0;

AB Backtest GMV exampleAB CVS GMV example