About‎ > ‎

Using backtester from .NET

AFL code

MaPeriod = 20;
MyTypicalPrice = (High + Low + 2 * Close) / 4;

MyMa = MA(MyTypicalPrice, MaPeriod);
Plot(MyMa, "MyMa", colorBlack, styleThick);

MyFastEma = EMA(Close, 5);
Plot(MyFastEma, "Ema5", IIf(MyMa < MyFastEma, colorDarkGreen, colorBrown), styleLine);

PlotOHLC(Open, High, Low, Close, "Close", colorBlack, styleCandle);

Buy = Cover = Cross(MyFastEma, MyMa);
Short = Sell = Cross(MyMa, MyFastEma);

BuyPrice = ShortPrice = Open;
SellPrice = CoverPrice = Close;

PlotShapes(IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, BuyPrice);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0, SellPrice);

PlotShapes(IIf(Short, shapeHollowDownArrow, shapeNone), colorRed, 0, ShortPrice);
PlotShapes(IIf(Cover, shapeHollowUpArrow, shapeNone), colorGreen, 0, CoverPrice);

SlippageLong =Param("Slippage (Long)", 1, 0, 10, 1);
SlippageShort =Param("Slippage (Short)", 3, 0, 10, 1);
SlippageTickSize =Param("Slippage Tick Size)", 0.01, 0, 10, 0.0001);

SetOption("UseCustomBacktestProc", True );
SetOption("PriceBoundChecking", False);

BasicSampleCS8();

 

.NET code

[ABMethod]
public void BasicSampleCS8()
{
     try
     {
         float slippageLong = ATAfl.ReadFrom("SlippageLong").GetFloat();
         float slippageShort = ATAfl.ReadFrom("SlippageShort").GetFloat();
         float tickSize = ATAfl.ReadFrom("SlippageTickSize").GetFloat();

         if (AFMisc.StatusAction() == Action.Portfolio)
         {
             Backtester bo = AFTools.GetBacktesterObject();

             bo.PreProcess();

             for (int bar = 0; bar < BarCount; bar++)
             {
                 for (Signal sig = bo.GetFirstSignal(bar); sig != null; sig = bo.GetNextSignal(bar))
                 {
                     if (!sig.IsEntry())     // if exit signal
                     {
                         if (sig.IsLong())
                             sig.Price = sig.Price - slippageLong * tickSize;
                         else
                             sig.Price = sig.Price + slippageShort * tickSize;
                     }
                 }
                 bo.ProcessTradeSignals(bar);
             }

             bo.PostProcess();
         }
         else
             if (tickSize == ATFloat.Null || tickSize == 0.0f)
                 throw new Exception("TickSize must be set for the ticker!");

     }
     catch (Exception e)
     {
         // present error message on indicator panel and the Log-Trace window
         YException.Show("Error while executing indicator.", e);
     }
 }