Instant price trigger Buy / Short

Hello friend,

i want to try to instantly price trigger buy / short. so i try the cross function. but not getting result in my side. i know my mistak.

please help any one.

Untitled


dn = DateNum();
new_day = dn != Ref(dn, -1);
Plot( new_day, "", colorBlue, styleHistogram | styleOwnScale | styleDashed, 0, 1 );

SetTradeDelays( 0, 0, 0, 0 );
// In your case to disable H-L price bound checking use following option.
// https://forum.amibroker.com/t/overriding-amibroker-backtester-settings-generating-unrealistic-results/7374
SetOption( "PriceBoundChecking", False );
// https://forum.amibroker.com/t/incremental-loop-to-add-columns/10703/2
selected_dn = Status("rangetodate");
last_day = dn == selected_dn;

_Buy = Cross( Close, BuyValue ) OR Cross( BuyValue, Close );
_Sell = Cross( SellStopLevel, Close );
_Short = Cross( ShortLevel, Close ) OR Cross( Close, ShortLevel );
_Cover = Cross( Close, CoverStopLevel );

// https://forum.amibroker.com/t/sumsince-vs-highestsince-lowestsince/15233/6
function SumSinceInclusive( condition, array )
{
  return Sum( condition, array ) + ValueWhen( condition, array );
}

// trades limit
N = 2;
// modify Buy array and allow only first N signals
Buy = Buy AND SumSinceInclusive( Buy, BarsSince( new_Day) +1 ) <= N;
// modify Short array and allow only first N signals
Short = Short AND SumSinceInclusive( Short, BarsSince( new_Day) +1 ) <= N;

// Initialize variables
Buy = Sell = Short = Cover = Null; 
LongFlag = ShortFlag = 0; // Flags to record trade state
			
for( i = 0; i < BarCount; i++ ) 
{
	// Long Positions
	if( _Buy[ i ] && !LongFlag && last_day[i] ) 
	{
		Buy[ i ] = 1;							
		LongFlag = 1; // To record that we are in Long position
	}
		if( _Short[ i ] && LongFlag ) 
		{
			Sell[ i ] = 1; // Selling-off the Long position
			Short[ i ] = 1; // Shorting-off the Long position
			LongFlag = 0;  // Reseting LongFlag back to False, to denote that we are no longer in "Long" position
		}

	// Short Positions
	if( _Short[ i ] && !ShortFlag && last_day[i] ) 
	{
		Short[ i ] = 1;
		ShortFlag = 1;	 // To record that we are in Short position
	}
		if( _Buy[ i ] && ShortFlag ) 
		{
			Cover[ i ] = 1; // Covering the Short position
			Buy[ i ] = 1; // Buying the Short position
			ShortFlag = 0;  // Reseting ShortFlag back to False, to denote that we are no longer in "Short" position
		}
}

Plot( BuyValue , "Buy", colorGreen);
Plot( SellStopLevel, "Sell", colorRed);
Plot( ShortLevel, "Short", colorRed);
Plot( CoverStopLevel , "Cover", colorGreen);

PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-25);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-35); 
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-30); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=25);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=35); 
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-30);

Any one help me the solution.

Start by correcting the errors in AFL , like BuyValue used without beeing inatialized
Then try debugging it...

thanks for reply.:slightly_smiling_face::slightly_smiling_face::slightly_smiling_face::slightly_smiling_face:

i have anticipate input before market start through Excel. BuyValue / SellValue / ShortValue / Cover value

see the below my full code.

_SECTION_BEGIN("Excel to Ami Input");

// http://www.amibroker.com/kb/2014/09/30/gen-backtest-from-a-file/
//#pragma maxthreads 1

tn = TimeNum();
startTime = 091500; // start in HHMMSS format
endTime = 144000;  // end in HHMMSS format
timeOK = tn >= startTime AND tn <= endTime;

dn = DateNum();
new_day = dn != Ref(dn, -1);
Plot( new_day, "", colorBlue, styleHistogram | styleOwnScale | styleDashed, 0, 1 );

file = "C:\\Users\\LENOVO\\Desktop\\07-02-2020\\MCLevel.csv"; // change this to real location of your data file

dt = DateTime();
SetTradeDelays( 0, 0, 0, 0 );
// In your case to disable H-L price bound checking use following option.
// https://forum.amibroker.com/t/overriding-amibroker-backtester-settings-generating-unrealistic-results/7374
SetOption( "PriceBoundChecking", False );
// https://forum.amibroker.com/t/incremental-loop-to-add-columns/10703/2
selected_dn = Status("rangetodate");
last_day = dn == selected_dn;

// https://forum.amibroker.com/t/sumsince-vs-highestsince-lowestsince/15233/6
function SumSinceInclusive( condition, array )
{
  return SumSince( condition, array ) + ValueWhen( condition, array );
}
// trades limit
N = 2;

// Initialize variables
_Buy = _Short = _Sell = _Cover = 0; 
Buy = Sell = Short = Cover = Null; // TSL (Trailing Stop-Loss) to be applied on HghrIntrvl
LongFlag = ShortFlag = 0; // Flags to record trade state

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 ) );   
            TradeLevel = StrToNum( StrExtract( line, 3 ) );
            StopLevel = StrToNum( StrExtract( line, 4 ) );
            shares = StrToNum( StrExtract( line, 5 ) );

            if ( trade == "Buy" )
            {				
                _Buy = ( Cross( Close, TradeLevel ) AND timeOK ) OR ( Cross( TradeLevel , Close) AND timeOK );
				_Sell = Cross( StopLevel, Close );
				_Short = Cross( StopLevel, Close ) AND timeOK;
				GfxSelectFont("Times New Roman", 16, 700, True ); 
				GfxTextOut("Percent of shares held by: "+trade, 120 , 50 );						
					for( i = 0; i < BarCount; i++ ) 
					{
						// Long Positions
						if( _Buy[ i ] && !LongFlag && last_day[i] ) 
						{					
							Buy[ i ] = 1;							
							LongFlag = 1; // To record that we are in Long position
						}					
							if( _Short[ i ] && LongFlag && last_day[i] ) 
							{
								Sell[ i ] = 1; // Selling-off the Long position
								Short[ i ] = 1; // Shorting-off the Long position
								LongFlag = 0;  // Reseting LongFlag back to False, to denote that we are no longer in "Long" position
							}
					}
                Plot( TradeLevel, "Buy", colorGreen);
                Plot( StopLevel, "BuyReverse", colorRed);

				// modify Buy array and allow only first N signals
				Buy = Buy AND SumSinceInclusive( Buy, BarsSince( new_Day) +1 ) <= N;
				
				PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-25);
				PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-35); 
				PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-30); 
				PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=25);
				PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=35); 
				PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-30);
            }

            if ( trade == "Short" )
            {
				_Short = ( Cross( TradeLevel, Close ) AND timeOK ) OR ( Cross( Close, TradeLevel ) AND timeOK );

				_Cover = Cross( Close, StopLevel );
				_Buy = Cross( Close, StopLevel ) AND timeOK;				
				GfxSelectFont("Times New Roman", 16, 700, True ); 
				GfxTextOut("Percent of shares held by: "+trade, 120 , 50 ); 
					for( i = 0; i < BarCount; i++ ) 
					{
						// Short Positions
						if( _Short[ i ] && !ShortFlag && last_day[i] ) 
						{							
							Short[ i ] = 1;
							ShortFlag = 1;	 // To record that we are in Short position
						}
							if( _Buy[ i ] && ShortFlag && last_day[i] ) 
							{									
								Cover[ i ] = 1; // Covering the Short position
								Buy[ i ] = 1; // Buying the Short position
								ShortFlag = 0;  // Reseting ShortFlag back to False, to denote that we are no longer in "Short" position
							}
					}

                Plot( TradeLevel, "Short", colorRed);
                Plot( StopLevel, "ShortReverse", colorGreen);

				// modify Buy array and allow only first N signals
				Short = Short AND SumSinceInclusive( Short, BarsSince( new_Day) +1 ) <= N;
				
				PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-25);
				PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-35); 
				PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-30); 
				PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=25);
				PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=35); 
				PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-30);
            }
        }
    }
    //
    fclose( fh );
}
 else
 {
     Error( "ERROR: file can not be open" );
 }

// Price Chart
SetChartOptions(0,chartShowArrows|chartShowDates);
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 

_SECTION_END();

_N( Title = StrFormat( "{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
 

Capture
almost i am try best to code. but little bit to reach. please help.

what value input in excel price , that price breakout real time data i want to buy / short immediately.

@awilson i am try, I missing the trick. Could you please help

Dear Ganesan

If you expect help, you need to do whatever you can, to make it simple to others to help you.

For example, your afl reads a file. Do you expect the helper to type and create a file to test your AFL ?

An image of the file can not be copy/paste. And again have you debug your AFL ?

1 Like