Buy-scaleIn and Sell on same bar

Please see the code below it is complete. Also data file link is given below:

SetCustomBacktestProc( "" );
_TRACE( "!CLEAR!" );
_SECTION_BEGIN( "Price" );
SetChartOptions( 0, chartShowArrows | chartShowDates | chartWrapTitle );
_N( Title = StrFormat( "{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}} ", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ) );
PlotOHLC( O, H, L, C, "Traded", colorRed, styleBar , Null, Null, 0, 1, 1 );
_SECTION_END();

dt = DateNum();
//_TRACE("Datenum="+DateNum());
tnum = timenum();
//_TRACE("timenum="+tnum);

Sell = 0;
Buy = 0;



Buy = IIf( tnum == 110000, 1, Buy );



buy = IIf( tnum == 134500, sigscaleout, buy );


buy = IIf( tnum == 151500, sigscaleIn, buy );
BuyPrice = 345.35;

Sell = IIf( tnum == 151500, 1, sell );
SellPrice = 344.15;

SetPositionSize( 10, spsPercentOfEquity );
SetPositionSize( 50, spsPercentOfPosition * ( Buy == sigScaleOut  ) ); // scale out 50% of position
SetPositionSize( 50, spsshares * Buy == sigScaleIn);
//_TRACE("buy="+Buy+", sell="+Sell);



if( Status( "action" ) == actionPortfolio )
{
    bo = GetBacktesterObject(); // Get backtester object
    //bo.Backtest( True ); // Run backtests with no trade listing
    bo.PreProcess();
    stat = bo.GetPerformanceStats( 0 ); // Get Stats object for all trades

    dt = DateTime();
    thisBarDate = DateTimeConvert( 0, dt );

    for( i = 0; i < BarCount; i++ )
    {
        formatedDateTime = DateTimeFormat( "%d-%m-%Y %H:%M:%S", dt[i] );


        for( sig = bo.GetFirstSignal( i ); sig; sig = bo.GetNextSignal( i ) )
        {


            if( sig.Type == 1 || sig.Type == 3 || ( sig.Type == 5 && openPosition ) ) //if buy, short or scalein
            {

                //sig.Type=5;sig.possize=-16;
                _TRACE( "sig.type = " + sig.Type + " for "
                        + sig.Symbol + " sig.PosSize =" + sig.PosSize + ",  sig.Price = " + sig.Price + ", at " + formatedDateTime );

            }

        }

        bo.ProcessTradeSignals( i );
    }

    bo.PostProcess();

}

Data file is here Easyupload.io - Upload files for free and transfer big files easily.
It's 15 minute tf.

At time 1515 I expect scaleIn first and then Sell but it is happening in the wrong sequence. I expect the position to be closed but it remains open because first it sells all open quantity and then it buys more. Why is this happening?

Please read resolving same bar conflicts section in the manual

https://www.amibroker.com/guide/h_portfolio.html

Exits are handled before entries if same bar exit option is turned off.

I added to the top of the script. But STILL NOT WORKING. There is no change. see screenshot of detailed log below.

SetOption("AllowSameBarExit", True);

If i set it to false like below then scalein signal is ignored all together. see below

SetOption("AllowSameBarExit", False);

That is correct, because you can't scale into position that is NOT present in open positions lists at all. The manual lists explicitly supported scenarios in the "Resolving same bar conflicts". Anything that is NOT described in the manual is NOT supported. As it is written in the manual when same bar exit option is turned off, exits are handled before entries. So position is exited first and there is no position to be scaled into.

Generally speaking if you are unable to achieve what you are after using either backtestRegular or backtestRegularRaw modes, your solution is to use low-level custom backtest and call EntryTrade/ExitTrade/ScaleTrade directly, as these calls allow you to do any sequence of any number of entry entries, scales, exits on any bar.

http://www.amibroker.com/guide/a_custombacktest.html

No swearing on the forum. Failure to comply with forum rules will result in permanent ban

1 Like