Hi there,
I'm trying to understand how applyStop works a simple system I am trying to test. I want to sell when the stock closes below the 10day EMA or when my set stop that I import into Amibroker triggers.
Symbol | Trade | Date | Price | Shares | Stop |
---|---|---|---|---|---|
PLAN | Buy | 9/1/2020 | 62.83 | 1000 | 61.39 |
GRWG | Buy | 9/2/2020 | 16.57 | 4000 | 16.17 |
BA | Buy | 9/3/2020 | 179.75 | 500 | 177.21 |
I have 3 stocks with different results here. The stop price that I want to be triggered is in the "stop" column in the CSV file. All stocks should be stopped out on the same day and at that price. However, only PLAN worked as intended and stopped out next day. GRWG sold next day at open (although the price did go lower than the stop the prior day) while BA sold it end-of-day. May I know why there is this consistency - is this due to EOD data being used, and my "buy price" being used as EOD data vs intraday?
Here is the code I am using, adapted from http://www.amibroker.com/kb/2014/09/30/gen-backtest-from-a-file/
file = "C:\\Users\\Bryan\\Documents\\Amibrokertest.csv"; // change this to real location of your data file
dt = DateTime();
//
// Initialize variables
Buy = Sell = possize = stopPrice = 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 ) );
shares = StrToNum( StrExtract( line, 4 ) );
stop = StrToNum( StrExtract( line, 5 ) );
//
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 );
stopPrice = IIf(newbuy, stop, stopPrice );
}
//
if ( trade == "Sell" )
{
newsell = dt == trade_datetime;
Sell = Sell OR newsell; // combine previous sell signals with new
SellPrice = IIf( newsell, price, SellPrice );
}
}
}
//
fclose( fh );
}
else
{
Error( "ERROR: file can not be open" );
}
//
SetOption("InitialEquity", 1576836);
SetOption("AccountMargin", 50);
SetPositionSize( possize, spsShares );
SetOption("MaxOpenPositions", 200);
Short = Cover = 0;
StopLoss = BuyPrice - stopPrice;
ApplyStop(stopTypeLoss, stopModePoint, StopLoss, ExitAtStop = 1);
Sell = Close< EMA(Close, 10);