Watch List Filter

Dear Members,

i have a system which i am testing on paper and it is giving me a desired result as per my requirement.

However i am looking for solution for which i have not being able to find the solution by myself.

I need to to generate Sell signal from the watchlist for only those scrip in which i am holding a buy position.

I have gone through many similar post but i have not being able to relate my problem with the solution provided on those post.

Any help or reference would be useful for me to proceed.

below is my code for reference.

Buy = Sell = 0;
BuyPrice = SellPrice = 0;
LongFlag = 0; //Simple Flag arrays to identify position

for ( i = 1; i < BarCount; i++ )
{
    if ( Buy_Cond [i])
		{
		Buy [i] = 1; //Enter Long Positions//
        Buy = Ref(Buy_Cond,-2);
        BuyPrice = ValueWhen(Buy,C,1);
        LongFlag = 1;
		}
  
	if (Sell_Cond [i] AND LongFlag ==1 )
		{
	    Sell [i] = 1; //Exit Long Positions//
	    Sell = Ref(Sell_Cond,-2);
	    SellPrice = ValueWhen(Sell,C,1);
	    LongFlag = 0;   //Reseting LongFlag back to False, to denote that we are no longer in "Long" position//
		}
 }

RequestTimedRefresh(1);

function writeLine( line )
{
	for( i = 1; i < 10; i++ ) {
		fh = fopen("D:\\Users\\hp\\Desktop\\MARKET\\Tradelog.csv", "a");
		if (fh) 
		{
			fputs( line + "\n", fh );
			fclose( fh );
			break;
		} 
		else 
		{
		_TRACE("[Try: " + i + "] Failed to write line: " + line);
		}
	}
}

qty = floor((Param("Amount",10000,1000000,5000))/Close[barcount-1]);

date1 = DateTime();
date1format = "\n%d-%m-%Y\n";

	function get (varname)
	{
		return StaticVarGet(Name()+varname);
	}

	function set (varname,value)
	{
		StaticVarSet(Name()+varname,value,True);
		
	}
 
 	toggle = ParamToggle("Reset","NO|YES",0);
 	delay = Param("Second to Delay",300,1,26000,1);
 	seconds = 	Now(4); 

	if(toggle==1)
	{
	set("time",seconds);
	printf(EncodeColor( colorGreen ) +" <b>Reseting Values</b>\n");
	}

diff_seconds = (seconds-get("time"));

printf("Seconds - " + seconds + "\nDiff - " + diff_seconds);

sep = ",";

if (Buy[BarCount-1]==True AND diff_seconds>delay)
	{
		line=StrFormat(Name()+sep+"BUY"+sep+Close+sep+DateTimeToStr(date1[BarCount-1])+sep+(qty));
		writeLine(line);
		_TRACE(line);
		set("time",seconds);
		
	}

if (Sell[BarCount-1]==True  AND diff_seconds>delay)
	{
		line=StrFormat(Name()+sep+"SELL"+sep+Close+sep+DateTimeToStr(date1[BarCount-1])+sep+(qty));
		writeLine(line);
		_TRACE(line);
		set("time",seconds);
	}

AlertIf( Buy, "", "BUY @ " + C, 1 );
AlertIf( Sell, "", "SELL @ " + C, 2 );

The code is 100% INCORRECT for simple reason: you don't put array functions (ValueWhen/Ref) inside loop that goes bar by bar.

The loop should be removed completely it is NOT needed at all and the working code is 80% shorter. ValueWhen calls are also incorrect and should be removed.

First read: Understanding AFL

Second read: http://www.amibroker.com/guide/h_backtest.html (look at "controlling trade price"). To buy at and sell at close it is totally enough to just write

BuyPrice = Close; 
SellPrice = Close;

ValueWhen calls are totally unnecessary and in fact wrong. The remaining of spaghetti code is also totally for no reason and no purpose.

My advice for you is to hire programmer: Third party services, blogs, courses, books, add-ons

@Tomasz Thanks for your advice will surely look into it.

@Tomasz however on this part i disagree, as there is always a reason if the question has being raised... Since at the beginning of my post i clarified that i am paper trading and not trading live which means instead of managing my position on broker terminal i wanted to manage the position on .csv file to stimulate the entry and exit of scrip and calculate the p&l before going live.

My code generate enough buy & Sell signal and write them into the log file but every day i have to filter the unnecessary noise from it and do it manual, hence i was hoping for a reference.

Hiring a third party service was an easiest part, and i would have done it way back when i posted my first post, but rather i choose to learn and not depended on choosing third party service.

As to evaluate the correctness of Third party service one need to have a basic knowledge of it.

Novices in my opinion have strange habit of jumping head down into deep water without ability to swim. That is recipe for failure. You want too much too fast. You need to step back, start from the absolute beginning, from easiest things and make baby steps, see: How do I learn AFL?

4 Likes

@Tomasz Noted i will definitely clear my basics fundamentals and revisit the link to begin .

However still my original question remain unanswered while our discussion moved to other direction.

Should you learn the basics http://www.amibroker.com/guide/h_understandafl.html you will know how things work and would know the answer.

Normally you just don't need to do what you are asking for because backtester does not act upon excess Sell signal if there is no matching Buy (if position is not open).
It is obviously explained in very detail in the Users' Guide:
http://www.amibroker.com/guide/h_portfolio.html

Really you would do yourself a big favor if you read the documentation. 100% of questions that you have are already answered in docs.

If you want to remove excess Sell signals (those without matching buy) without backtester you can do so using ExRem http://www.amibroker.com/f?exrem or using Equity(1) http://www.amibroker.com/f?equity

Sell = ExRem( Sell, Buy ); // would remove excess Sell signals that don't have Buy before

If you don't understand how given function works - use exploration as explained here How do I debug my formula? - There is nothing better than seeing yourself the function in action.

There are literally hundreds of useful resources to learn the basics. Google is your friend. Use it and learn. There is no substitute for your own effort. At least watch this https://www.youtube.com/watch?v=aay6rKWSgVc&list=PL6DW1D2ifJ39G71F7CW_vPJhB-viunWjM&index=3 See footnote

It takes 2 seconds to find it using Google.

Giving you ready-to-use code to copy-paste does not work. Without understanding how basics work you won't be able to use the code properly. Someone who does not know how to hold the violin bow can't play Vivaldi even if he sees exact score for "Four Seasons"

Footnote: while Dave's videos are great and entertaining and I love the positive vibe and I would not come up with anything nicer to watch myself, they contain some simplifications and omissions, so while they are good starting point, once you get a basic grasp of things, there is no substitute for checking original documentation http://www.amibroker.com/guide/tutorial.html

2 Likes

@Tomasz Sorry to say but you really need to read my post carefully sentence by sentence i had never ever asked for ready-made code i simply asked for reference to proceed & for that whatever reference you had given i really appreciate the time and effort you have taken to revert will definitely go through your each and every suggestion and try to figure out the solution.

Oh here we come again - the "ego". I have read your post. And I have read thousands of similar posts. I am answering to the FORUM, to everyone, not to you alone. The comment you quoted applies to everyone, not just you. And I just hope that maybe, just maybe, someone else in the future will use this genuinely good advice without repeating the same over again.

How about actually clicking on links provided and checking out the good stuff? (The video hasn't been clicked even though it answers your questions)

And on the side note: I don't play violin myself but my son does. And I have seen with my own eyes how much effort from both teacher and student side it takes to actually teach somebody how to just hold the violin bow properly, before even playing single note. The amount of detail to control it is huge. And this applies to pretty much every musical instrument on professional level. I like to think that AmiBroker can be compared to musical instrument that you need to learn slowly to make it sound beautifully.

4 Likes

@Tomasz, I have gone through the inputs provided by you but it hasn't worked for me yet, may be i was not clear enough to describe my problem however below are some of findings.

Instead of writing the Buy & Sell in loop i have write it as per below including Exrem, it has definitely reduce the scan time, however Exrem hasn't done any special except removing the repeat signal from single scrip, loop was also resetting the Buy & Sell and avoiding the repeat signal in same scrip but was little slower you than the suggested way.

Buy = Buy_Cond;
Buy = Ref(Buy_Cond,-2);
BuyPrice = Close;
          
Sell = Sell_Cond;
Sell = Ref(Sell_Cond,-2);
SellPrice = Close;

Buy = Exrem(Buy,Sell);
Sell = Exrem(Sell,Sell);

However my problem was more related to positional management which i may have not being able to describe properly, however below is the temporarily solution which i have found so far.

  1. Rather than generating a both buy & sell signal through one trading system i have split the code to generate separate buy & separate sell signal from two different scanning window.

  2. My problem was to avoid repeated Buy on those scrip in which i am already holding the position and only generate sell signal (currently avoiding the same through creating the watch list of open position and excluding buy signal through exclude filter).

  3. And for rest other watch-list generate both buy & sell signal simultaneously.

Since my system work well in long, hence currently i am avoiding repeatedly buying during down trend, and during uptrend i also doesn't want to send unnecessary signal to the exchange in which i am not holding the position.

However since i mentioned this the temporary solution and not so efficient, and already working on position management which is taking time as per my knowledge at present but i am sure will get it done till the time hope if someone can suggest the better way to achieve so.

Also as per http://www.amibroker.com/guide/h_portfolio.html below is the Portfolio Code in my system.

//Initial Capital & Risk//  
SetTradeDelays( 1, 1, 1, 1 );
SetOption("InitialEquity", 1500000);  
SetOption("RefreshWhenCompleted",True); // Refresh when completed // 
SetOption( "AllowPositionShrinking", True ); // Shrink Position on Loss // 
SetOption( "UsePrevBarEquityForPosSizing", 1 ); // set the use of last bars //
SetPositionSize( 5 , spsPercentOfEquity);
Numpos = Optimize("NPOS",30,10,50,1);
SetOption("MaxOpenPositions", Numpos); // Max open Position at any time//
liquidStock = LLV(C*V,252) > 100000;
VolatilityFilter=ATR(14)/C<0.05;

// SET COMMISSIONS//  
SetOption("CommissionMode", 1); // Percent Mode  
SetOption("CommissionAmount",0.25); // 0.25% of Trade Value

@Tomasz I have gone through the KB article and have found the working loop solution suggest by you of limiting the Trade through this article

https://www.amibroker.com/kb/2015/09/26/limit-number-of-trades-per-day-in-a-backtest/

Also as mentioned above regarding managing open positions through different scan now i can read it from single. CSV file through my multiple original code and can avoid buying on similar symbol in which I am already holding the position as of now this seems to be more efficient way for me to manage my position in real time scanning.

However I have stuck to a point on above trade limit code in which although it restrict to the limited number of trade as define, but in the event of falling market trade limit get exhaust with in certain time hence wanted to create the time gap of 30 min between each trade so that I can average to best possible rate.

Any lead would be helpfull.

Thanks

Deepak