SWS Forum

Products => Beyond Charts => Topic started by: JohnR on 06/03/2019, 12:01:10 PM

Title: Help with BCFL custom Scans & Coding
Post by: JohnR on 06/03/2019, 12:01:10 PM
The perfect place to share any working scan and indicator formula with the SWS community.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 06/03/2019, 12:13:08 PM
MACD 100,50,30 crossover help please.

I'm completely 'fresh off the boat' when it comes to SWS/Metastock language.
My current competency is with Pine for TradingView (limited but functional) where the Pine language is "self evident", I'm finding the SWS formula language a bit cryptic.

So any help with my first attempt greatly appreciated.
MACD (100,50) main crossing the Signal (30) scan for crossing up over signal line.

What I have so far, and is copied directly off a metastock web page and adjusted for the macd settings:
{New Indicator} M9:= Mov(MACD(),100,E); X:=Cross(Mov(C,50 {opt1},E),Mov(C,30 {opt2},E)); X AND Alert( M9<0 AND Cross(MACD(),M9),5); { Alert() Holds signal TRUE for 5 bars or whatever number you choose}

Output:
-> There is 1 unassigned output. The unassigned output will have priority over all assigned outputs
-> There is 1 unassigned output. The unassigned output will have priority over all assigned outputs
-> There is 1 unassigned output. The unassigned output will have priority over all assigned outputs
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 06/03/2019, 05:12:36 PM
Hi John,

An unassigned output is a line of BCFL that does not have a 'variable' container or a name for the calculation.

It is more of a warning message than an error, as the formula will still save. It is saying that the BCFL engine has found an unassigned output and this will have priority over an assigned outputs it may find.

This is so 1 line formulas like "C > REF(C, -1)" (check if close is higher than yesterdays) for example will still operate which can be common in the metastock programs, due to limited character allowances.

An assigned output version of your formula would look like this:

{New Indicator}
M9:= Mov(MACD(),100,E);
X:=Cross(Mov(C,50,E),Mov(C,30,E));
Alert1 := Alert( M9<0 AND Cross(MACD(),M9),5); { Alert() Holds signal TRUE for 5 bars or whatever number you choose}
Output := X AND Alert1;
Output;

The key difference is the name of the calculation is on its own line. The important of this is it allows you to plot more than 1 calculation on to the chart, in case you wanted to see how a specific one was working. This is useful for indicators with more than 1 calculation or if you want to test your formula to ensure it's doing what you think it is.

For instance, to see what composes the output, you would have this instead:

{New Indicator}
M9:= Mov(MACD(),100,E);
X:=Cross(Mov(C,50,E),Mov(C,30,E));
Alert1 := Alert( M9<0 AND Cross(MACD(),M9),5); { Alert() Holds signal TRUE for 5 bars or whatever number you choose}
Output := X AND Alert1;
{ Testing the output contents }
X;
Alert1;

--

I hope this makes sense and let me know if you would like any more clarification.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 09/03/2019, 03:20:44 PM
Hi Campbell, good to have the brains trust of the whole operation on board here :thumb:
Firstly; are there any manuals for SWS BCFL that you can direct me to?

I found this Metastock primer website, will this be worth reading?
https://www.metastock.com/customer/resources/formulas/primer.aspx (https://www.metastock.com/customer/resources/formulas/primer.aspx)

I put the MACD Histogram script into the editor :
{ MACD Histogram }
MACD_Hist := macd(100) -mov(macd(50),30,E);
MCAD_Hist

Output:
-> MACD function has invalid number of arguments

What does the 'E' do in the above  :confused:


Maybe I should explain and graphically show you what I want to do with the MACD and histograms signals; primarily for forward scanning of the Investor ATR-TS and Spa3 SIROC entry signals, and forward of the exit signals, and to eliminate (false or low momentum / high risk) system signals leading to over-trading costs and draw downs.

Primarily to validate system entry and exit strategies against the MACD 120,260-90 and 50,100-30 states; to rule out the system very fast buy sell signals (they are about 3 days apart) when the MACD lines and histogram are signaling "high risk" when compared to zero line, and when the MACD.main has crossed its signal line.

I have found that the MACD setting of 120,260-90 as measured on the histogram finds its peak level that very closely corresponds to the MACD 50,100 main crossing the 30 signal line (or when the histogram drops below zero line by a bar or two).
Also there exists a zone of pre-warning that momentum is dropping off prior to the MACD 50,100 crossing, when the histogram also falls bellow the most recent dip prior to a high level, and measured/visualised by drawing a line from the recent high dip extending horizontally, any histogram pips that fall below the line have high percentage chance of leading to the histogram falling below zero leading into higher risk.

This MACD 50,100-30 histogram falling and then crossing zero; correlates to the MACD 120,260-90 losing momentum. The same can be said of the rising momentum of the MACD combination.

There are four basic states for each of the two MACD's: Main greater than Signal and Main less than Signal;  occurring above zero and below zero. And these four states generally reflect bullish and bearish momentum surprisingly accurately.

Any shallow MACD 50,100-30 histogram levels around the zero line indicate low momentum that then can be assessed against the MACD 120,260 main being above or below its 90 signal line for risk assessment.

A third faster MACD can then be used to also qualify the MACD 100,50-30 histogram signals earlier, like a MACD 12,50-25.
And to avoid line clutter on the chart I have found it best to use the histograms only overlaid onto each other:


Having eyeballed the system triggers on the chart for entry and exits and correlated against the two MACD's; there could be written a formula set to qualify those entries as high risk and low risk, maybe as bright yellow symbols or candle background colour on the chart, maybe to scan the market to enter positive results into a watch list for monitoring to optimize entry and exit strategies prior to system triggers.

(http://)
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 10/03/2019, 06:19:13 PM
Have TradingView Pine code trend candle colour based on the 50,100-30 with additional fast MACD as an entry exit stinger (aqua / fuchsia).
I can't imagine trying to setup a scan in SWS BCFL for something similar, too many variables to consider given each MACD has 8 states and each histogram has four.
Best approach is to eyeball it! might have another go later though for the fast MACS stinger early entry and exit chart signals.

Image is chart in Trading View (30 minute time frame, MACD's are set with WMA's, outmacd2 = 50,100-90)
Pine candle full colour:

M1a = outmacd2 > 0 and outmacd2 > outsignal2 and outmacd2 > outmacd2[1]
M1b = outmacd2 > 0 and outmacd2 > outsignal2 and outmacd2 < outmacd2[1]
M2a = outmacd2 > 0 and outmacd2 < outsignal2 and outmacd2 > outmacd2 [1]
M2b = outmacd2 > 0 and outmacd2 < outsignal2 and outmacd2 < outmacd2[1]

M3a = outmacd2 < 0 and outmacd2 < outsignal2 and outmacd2 > outmacd2[1]
M3b = outmacd2 < 0 and outmacd2 < outsignal2 and outmacd2 < outmacd2[1]
M4a = outmacd2 < 0 and outmacd2 > outsignal2 and outmacd2 > outmacd2[1]
M4b = outmacd2 < 0 and outmacd2 > outsignal2 and outmacd2 < outmacd2[1]

SH1b = outHist3 > 0 and outHist3 < outHist3[1]
SH2b = outHist3 <= 0 and outHist3 > outHist3[1]

bc=input(true, title="Color bars based on MACD 2 Trend")
barmacd2col = outmacd2<0 and SH2b ? aqua : M2b and SH2b ? aqua : SH1b ? fuchsia :
    M1a ? green : M1b ? red : M2a ? #00cc00 : M2b ? red : M3a ? gray : M3b ? red : M4a ? white : M4b ? red : yellow
barcolor(bc ? barmacd2col : na)
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 12/03/2019, 05:15:16 PM
Hi Campbell, good to have the brains trust of the whole operation on board here :thumb:
Firstly; are there any manuals for SWS BCFL that you can direct me to?

I found this Metastock primer website, will this be worth reading?
https://www.metastock.com/customer/resources/formulas/primer.aspx (https://www.metastock.com/customer/resources/formulas/primer.aspx)

Thanks! Brains trust maybe not, but I am happy to help and if anyone else has any questions about what they are doing, please feel free to chip in.

This is usually the one we point people towards. While the user interface that you see in Beyond Charts is not the same, the language is. For anyone who wants to know how to 'get around' the formula editor, have a look under Home -> TutorMe for the time being.

Quote

I put the MACD Histogram script into the editor :
{ MACD Histogram }
MACD_Hist := macd(100) -mov(macd(50),30,E);
MCAD_Hist

Output:
-> MACD function has invalid number of arguments

What does the 'E' do in the above  :confused:

The output is because the MACD() function is pre-set and does not take a number in the parentheses. It's part of a generic error, usually to say you have not formatted a function correctly. When this comes up, use the quick reference panel from the right hand side BCFL Library to see what the editor is expecting.

A traditional MACD uses a 26 EMA - 12 EMA, that is how the '14' discussed around MACD comes up. You would need to quickly build your own MACD then push that calculation through to the rest of the formula to achieve the 50 MACD for instance:

My_MACD := MOV(C, 100, E) - MOV(C, 50, E);
MACD_Hist := My_MACD - mov(My_MACD,30,E);
MACD_Hist;

The 'E' refers to Exponential. There are others like W for Weighted and S for Simple.

Quote
Maybe I should explain and graphically show you what I want to do with the MACD and histograms signals; primarily for forward scanning of the Investor ATR-TS and Spa3 SIROC entry signals, and forward of the exit signals, and to eliminate (false or low momentum / high risk) system signals leading to over-trading costs and draw downs.

Primarily to validate system entry and exit strategies against the MACD 120,260-90 and 50,100-30 states; to rule out the system very fast buy sell signals (they are about 3 days apart) when the MACD lines and histogram are signaling "high risk" when compared to zero line, and when the MACD.main has crossed its signal line.

I have found that the MACD setting of 120,260-90 as measured on the histogram finds its peak level that very closely corresponds to the MACD 50,100 main crossing the 30 signal line (or when the histogram drops below zero line by a bar or two).
Also there exists a zone of pre-warning that momentum is dropping off prior to the MACD 50,100 crossing, when the histogram also falls bellow the most recent dip prior to a high level, and measured/visualised by drawing a line from the recent high dip extending horizontally, any histogram pips that fall below the line have high percentage chance of leading to the histogram falling below zero leading into higher risk.

This MACD 50,100-30 histogram falling and then crossing zero; correlates to the MACD 120,260-90 losing momentum. The same can be said of the rising momentum of the MACD combination.

There are four basic states for each of the two MACD's: Main greater than Signal and Main less than Signal;  occurring above zero and below zero. And these four states generally reflect bullish and bearish momentum surprisingly accurately.

Any shallow MACD 50,100-30 histogram levels around the zero line indicate low momentum that then can be assessed against the MACD 120,260 main being above or below its 90 signal line for risk assessment.

A third faster MACD can then be used to also qualify the MACD 100,50-30 histogram signals earlier, like a MACD 12,50-25.
And to avoid line clutter on the chart I have found it best to use the histograms only overlaid onto each other:


Having eyeballed the system triggers on the chart for entry and exits and correlated against the two MACD's; there could be written a formula set to qualify those entries as high risk and low risk, maybe as bright yellow symbols or candle background colour on the chart, maybe to scan the market to enter positive results into a watch list for monitoring to optimize entry and exit strategies prior to system triggers.


With regards to SPA3 Investor, there has been many discussions on this forum I believe about changes and modifications and how they affect investment plans. I have also talked about it lots over the phone and by email, I am sure the rest of the team have as well, but it comes down to the rule of unitended consequences. Small changes can have big affects to portfolio outcomes over a large sample of trades, some will come off worse while some will improve the system. When we do our research, not enough over the years have 'moved the needle' enough to warrant an integrated change in SPA3.

That is as much as I will say around that for now. You can always take entries and exits and do a bit of a manual backtest to see the outcomes yourself in Excel and decide if you are on to something that you believes will improve, by the sounds of it you are confident in that regard. As long as you have confidence to execute in the market and you are not taking hours a day to make decisions or with subjective criteria, that is the main goal.

Now I'll talk more on the BCFL side of things. SPA3 is not involved or integrated in to BCFL, but you can run BCFL scans over the SPA3 Investor watch lists provided in Beyond Charts for results of which ones do hit the mark and take on actions as appropriate.

Unfortunately the images came across a bit small. Feel free to send them in to support or try and re-upload them here if you wish, but the general idea I believe is that you can take the code I provided above and perhaps plot out 2 histograms and the moving averages can also be put in to their own variables for output on top of this.

MACD1 := MOV(C, 100, E) - MOV(C, 50, E);
MACD2 := MOV(C, 260, E) - MOV(C, 120, E);
MACD1_Signal := mov(MACD1,30,E);
MACD2_Signal := mov(MACD2,90,E);
MACD_Hist := MACD1 - mov(My_MACD,30,E);
MACD_Hist2 := MACD2 - mov(My_MACD,90,E);
MACD_Hist;
MACD_Hist2;

Naming wise it is a bit ungamely and probably can be refined by sectioning out the histograms correctly. You could also split the 2 MACDs in to seperate formulas and then in a 3rd formula call them with the FML() function to assign to their own variables (the left hand side of := is the variable name) for output. It just depends how you prefer to store formula calculations, what is 'readable' to you, which normally comes along with exposure to BCFL.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 12/03/2019, 05:30:47 PM
Have TradingView Pine code trend candle colour based on the 50,100-30 with additional fast MACD as an entry exit stinger (aqua / fuchsia).
I can't imagine trying to setup a scan in SWS BCFL for something similar, too many variables to consider given each MACD has 8 states and each histogram has four.
Best approach is to eyeball it! might have another go later though for the fast MACS stinger early entry and exit chart signals.

Image is chart in Trading View (30 minute time frame, MACD's are set with WMA's, outmacd2 = 50,100-90)
Pine candle full colour:

M1a = outmacd2 > 0 and outmacd2 > outsignal2 and outmacd2 > outmacd2[1]
M1b = outmacd2 > 0 and outmacd2 > outsignal2 and outmacd2 < outmacd2[1]
M2a = outmacd2 > 0 and outmacd2 < outsignal2 and outmacd2 > outmacd2 [1]
M2b = outmacd2 > 0 and outmacd2 < outsignal2 and outmacd2 < outmacd2[1]

M3a = outmacd2 < 0 and outmacd2 < outsignal2 and outmacd2 > outmacd2[1]
M3b = outmacd2 < 0 and outmacd2 < outsignal2 and outmacd2 < outmacd2[1]
M4a = outmacd2 < 0 and outmacd2 > outsignal2 and outmacd2 > outmacd2[1]
M4b = outmacd2 < 0 and outmacd2 > outsignal2 and outmacd2 < outmacd2[1]

SH1b = outHist3 > 0 and outHist3 < outHist3[1]
SH2b = outHist3 <= 0 and outHist3 > outHist3[1]

bc=input(true, title="Color bars based on MACD 2 Trend")
barmacd2col = outmacd2<0 and SH2b ? aqua : M2b and SH2b ? aqua : SH1b ? fuchsia :
    M1a ? green : M1b ? red : M2a ? #00cc00 : M2b ? red : M3a ? gray : M3b ? red : M4a ? white : M4b ? red : yellow
barcolor(bc ? barmacd2col : na)

This is a bit of a step up in BCFL technical ability and comprehension of all the moving parts, it is not possible right now in 1 single formula. You would need to utalise BCFL Highlights and set up all the indicator variations in one formula, which each variation having their own variable.

So something like:
{Indicator Formula}
Instance_1 := ...;
Instance_2 := ...;

Then assuming none of the criteria overlap or conflict, you can use the Formula Variable Call function from the BCFL Library ( FMLVAR("Indicator Formula", "Instance_1") in the editor for example ) to tell BCFL to look at that formula, grab the specific indicator and do the checks on that. Using the BCFL highlight capabilities to dictate what colour the highlight changes to when the criteria is met.

So it will be work to setup, but not something I see as expressly unachiveable.

BCFL Highlights: https://beyondcharts.com/education/tutorme.php?s=latest
BCFL Library: https://education.beyondcharts.com/tutorme.php?s=bcfl
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 13/03/2019, 12:25:52 AM
Looks like I've more reading to do re the BCF Language.

And as my Spa3 Trader scans watch list grows and stocks remain in Spa3 conditions and MACD parameters, the scan results should optimise recurring signal entries & exits, at least in relation to the MACD 100 crossings. This might save having to review every stock in the watch list, something I definitely want to get away from having to do every night, in three chart programs!
This MACD system is hard to back test for having only visual parameters and nothing in code for programming at this time.

I might add the way I picked up Pine scripting was by having plenty of examples to examine and copy, adjust and cut & paste from the TV user base library.
If there were the same for SWS of functioning formulas it would make it much easy to see and understand the process, as I'm still trying to get a MACD working.

ps. not sure why the images were too small, they were saved as 900x600 pixel sized.

Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 14/03/2019, 10:10:04 AM
Feel free to copy and paste in what you are working on with a description of the next step you are trying to accomplish, we can help unravel it and move you in the right direction.

There is a learning curve with most scripting languages and we can get you to where you need to be.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 25/03/2019, 10:08:32 PM
Ok thanks.
Understood about "the rule of unintended consequences."
I need to set this up and review the results to make any decision. If anything it will aid decision making, reducing any uncertainty with system signals that I have observed.

Here's the first attempt at MACD2 (50,100-30) for testing; would like signal symbol on chart as well as being able to use in a filter scan.

The following script executed but did not trigger any alerts and did not place any symbols on charts, so there must be something wrong or missing. Is there a plot function/routine I'm not aware of?

with the comment line: { Alert() Holds signal TRUE for 5 bars or whatever number you choose}, I'm not sure what this means, does it refer to the scan will return codes up to 5 days after trigger?

{------------------------------------------------}
{Macd Medium (50,100-30) formula}
MACD2 := mov(C, 100, E) - mov(C, 50, E);
MACD2sig := mov(C, 30, E);

MACD2hist := (MACD2 - MACD2sig);
MACD2hist;

{------------------------------------------------}
{Alert: Macd Medium Main crosses signal line below zero}
MACD2_X_1a:= Cross(MACD2, MACD2sig);

AlertMACD2_1a := Alert( MACD2 <=0 and Cross(MACD2, MACD2sig),5); { Alert() Holds signal TRUE for 5 bars or whatever number you choose}
OutputMACD2_1a := MACD2_X_1a AND AlertMACD2_1a;
{ Testing the output contents }
MACD2_X_1a;
AlertMACD2_1a;

{------------------------------------------------}
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 26/03/2019, 02:29:45 PM
The comment refers to the Alert(logic check, days to sustain) function the formula you found uses. So when the logic check is found positive, it will stay positive for the given amount of bars ahead of it regardless if it is still true or false.

In this case, it is 5 bars. Using the term bars as it is dependant if you are using a daily or weekly chart if it is 5 days or 5 weeks.

The scan outputs positive results, so if you output the number 1, you will get a list back of everything you are scanning over. In your formula, there are a few reasons why you never hit results which are in the numbered list below.

My preference here would be to keep the histogram as its own formula that you can plot on to the chart, then have a 2nd formula purely for scans. This way it is easier to see on sight what is intended to be pushed back out, otherwise BCFL will give a result for a positive histogram which goes against the logic later on (MACD2 <= 0).

Also I prefer my formulas to scans to have only one output - 1 scan for 1 output, so I know exactly the result I am looking for.


Formula 1 - Pretty much fine as was with the signal line tweak
{Macd Medium (50,100-30) formula}
MACD2 := mov(C, 100, E) - mov(C, 50, E);
MACD2sig := mov(MACD2, 30, E);

MACD2hist := (MACD2 - MACD2sig);
MACD2hist;


Formula 2
{Macd Medium (50,100-30) formula}
MACD2 := mov(C, 100, E) - mov(C, 50, E);
MACD2sig := mov(MACD2, 30, E);

{Alert: Macd Medium Main crosses signal line below zero}
MACD2_X_1a := Cross(MACD2, MACD2sig);

AlertMACD2_1a := Alert( MACD2 <=0 and MACD2_X_1a, 5); { Alert() Holds signal TRUE for 5 bars or whatever number you choose}
{CS Note: The above will give positive for the bar where histogram < 0, when the cross occurs and for the 4 bars after)

{ Testing the output contents }
AlertMACD2_1a;
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 27/03/2019, 12:17:48 PM
OK that got it working! although the crossing is in both direction up and down for the one symbol and colour, and also for above zero.
So just looking at the symbols on chart scripts at this point;

I take it there will need to be another script to get a red Symbol for SELL for when the Main crosses below the Signal line; Alert(MACD2 <=0 leading into separate scripts for the above and below zero MACD cross states; one for crosses up <0 & >0 representing BUY, and one for crosses down <0 & >0 representing SELL?

or 4 different scripts with colour symbols one for each of the 4 states below zero and above zero.
A limitation of not being able to assign multiple symbols and or colours to differing states of a single indicator script plotting onto the chart, compared to Pine or QuoteTracker PaintBar scripts do/did so well.

Now looking at the system script (MACD Crossover to enter a long trade) I see that:
A := MACD();
B := MOV(A, 9, E);
CROSS(A, B)
 cross A,B would infer a crossing of A to above B as the way the computer differentiates the cross direction? conversely CROSS (B,A) would be the downward cross?
Yet I can't see the difference with the one I authored: MACD2_X_1a := Cross(MACD2, MACD2sig) where I get all crosses <0 & >0 plotting onto the chart. Or is there something else missing in the script?

Formula 2
Yes I was wondering about the duplication of code within the brackets, I actually took that code out and replaced it with CROSS(MACD2_X_1a), but got bad output. I see now from your example how to do this: Alert(MACD2 <=0 and MACD2_X_1a, 5)
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 27/03/2019, 03:52:01 PM
Every formula will have the same colour and symbol, if it is happening on downward crosses it would likely be due to the alert part of the formula as it is extending the signal for an extra 4 days after the criteria is hit. Cross(A, B) only flags when A crosses above B. That should answer your question at the end as well.

To differentiate, you may wish to use a system (https://education.beyondcharts.com/tutorme.php?s=bcfl , ~2mins 20) where you would need another script with the differences you are after. You can right click in the long entry / long exit boxes to customise the appearances on the chart.

It depends on the intentions, as using a system will make it easier to scan as you can choose which alerts you are looking for instead of creating 4 different scans as you would have to for a formula.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 14/04/2019, 02:11:40 PM
OK I will get to the system formula later once I get the intended alerts and scanning correct, as the 'systems' are slightly more complex.

Just to clarify the intention:
a) signal for MACD 100 crossing Signal with the following qualifier;
b) MACD(260) is greater than MACD(260) 2 bars back hold signal for 5 bars.

This will get some early potential trender's into the watch list.

I take it there will need to be two scripts; one for the graphic alerts plotted onto charts and setup as an 'overlay', and one for the actual filter screener with qualifiers?

When the above is working I will then add other screener qualifiers for value and volume, and or one of the system indicators like RSC ranking and ROC(126), ATRVe (15) to pull into the scan more 'system' like stocks.
What would be good here would be something that leads into the ATR-TS Investor signal prior to it happening (SIROC?) from my observance the MACD(100) crossing its signal line with MACD(260) rising for more than a few bars does a pretty good job for the 5 to 15 bars prior to the ATR-TS signal.

So with that in mind; that is the MACD plan for now.

Formula as it is now (not saving):
{------------------------------------------------}
{Macd 1 Long 260,120-90}
M1:= mov(C, 260, W) - mov(C, 120, W);
M1sig := mov(M1, 90, W);
M1hist := (M1-M1sig)

{Macd 2 Medium 100, 50-30}
M2:= mov(C, 100, E) - mov(C, 50, E);
M2sig := mov(M2, 30, E);

{Alert: Macd Medium Main crosses signal line, M1 histogram rising x nos bars }
M2_xUP := Cross(M2sig, M2) and (M1hist>M1hist-2);

{ Alert signal holds signal TRUE for 5 bars or whatever number you choose}
Alert_M2 := Alert (M2_xUP, 5);

{ Testing the output contents }
Alert_M2;
{------------------------------------------------}

Output -> Identifier M2 is not defined

I've been over this a few times and can't see why the M2 is not defined. The "M2_xUP := Cross(M2sig, M2)" part works by itself giving the correct cross over direction.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 15/04/2019, 02:29:13 PM
I would definitely do it that way - have one script for the chart and another for finding the signal to be used in scans.

In terms of the intention, with M2_xUP to be clear, as code is now you are asking if the 100 day MACD signal has gone above the 100 day MACD and that the M1histogram is higher than itself -2.

So to look for a value bars ago, use the REF() function. REF(<something>, -1) grabs the value of "something" a singe bar back. Something is not valid or tangible, just an example. Below is how it should look for looking 2 bars back:

{Alert: Macd Medium Main crosses signal line, M1 histogram rising x nos bars }
M2_xUP := Cross(M2sig, M2) and (M1hist>REF(M1hist,-2));

Now with the script as a whole - this is one of those scripting issues where a "clear" error is not apparent until you have run in to it 1 or 2 times then you will understand the logic behind it. By saying "M2" is not defined - it is saying it has found M2 but it does not know what to do with it. It's a total unknown.

The cause in this instance is with M1hist - it needs a semi colon on the end:

M1hist := (M1-M1sig) to M1hist := (M1-M1sig);

This says M1hist has ended, so it is free to assume  that M2 will be a variable name.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 19/04/2019, 02:57:40 PM
Ok have a working script to filter for MACD Weekly and MACD Daily scans" thanks.
Not sure of the logic behind having two separate scripts for a. stock filter, and b. graphic signal, as the one script seems to do both presently (graphic symbols saved as overlay F key with additional technical indicators).

Filter scan for weekly data MACD 100 (about equal to a MACD 260 Daily data):

{------------------------------------------------}
{Macd 1 Long 100,50-30}
MACD1:= mov(C, 100, E) - mov(C, 50, E);
MACD1sig := mov(MACD1, 30, E);
MACD1hist := (MACD1-MACD1sig);

{Macd 2 Medium 50, 24-18}
MACD2:= mov(C, 50, E) - mov(C, 24, E);
MACD2sig := mov(MACD2, 18, E);
MACD2hist := (MACD2-MACD2sig);

MACD3:= mov(C, 12, E) - mov(C, 26, E);
MACD3sig := mov(MACD3, 9, E);
MACD3hist := (MACD3-MACD3sig);


{Alert: Macd Medium Main crosses signal line, M1 histogram rising x nos bars }
MACD2_xUP := Cross(MACD2sig, MACD2)
AND (MACD1hist>REF(MACD1hist,-2)
AND MOV(CLOSE,21,S) * MOV(VOLUME,21,S) >= 50000);

{ Alert signal holds signal TRUE for 5 bars or whatever number you choose}
Alert_MACD2 := Alert (MACD2_xUP, 5);

{ Testing the output contents }
Alert_MACD2;
{------------------------------------------------}

And Daily data MACD 260:

{------------------------------------------------}
{Macd 1 Long 260,120-90}
MACD1:= mov(C, 260, W) - mov(C, 120, W);
MACD1sig := mov(MACD1, 90, W);
MACD1hist := (MACD1-MACD1sig);

{Macd 2 Medium 100, 50-30}
MACD2:= mov(C, 100, E) - mov(C, 50, E);
MACD2sig := mov(MACD2, 30, E);


{Alert: Macd Medium Main crosses signal line, M1 histogram rising x nos bars }
MACD2_xUP := Cross(MACD2sig, MACD2)
AND (MACD1hist>REF(MACD1hist,-2)
AND MOV(CLOSE,21,S) * MOV(VOLUME,21,S) >= 50000);

{ Alert signal holds signal TRUE for 5 bars or whatever number you choose}
Alert_MACD2 := Alert (MACD2_xUP, 5);

{ Testing the output contents }
Alert_MACD2;
{------------------------------------------------}


But when I attempt a fast MACD "turning up by 2 bars or so from running down" (below zero) script to run on the above MACD scan results watch list, nothing seems to work:
(I take it the MACD greater than MACD 1 bar back means the indicator is rising no falling) as the MACD index is greater as it falls lower than zero and above zero?
I'll be using this indicator / histogram turning state quite a lot so would like to know how the code should read.

{------------------------------------------------}
MACD3:= mov(C, 12, E) - mov(C, 50, E);
MACD3sig := mov(MACD3, 25, E);
MACD3hist := (MACD3sig-MACD3);

MACD3_UP:= (MACD3 <0 AND MACD3 > REF(MACD3,-1) AND (MACD3,-1 < REF(MACD3,-2)));

{Alert: Macd Fast turning up, hold x nos of bars }
Alert_MACD3 := Alert (MACD3_UP, 3);

{ Testing the output contents }
Alert_MACD3;
{------------------------------------------------}

OUTPUT= -> There is no function defined. Please define your function with valid arguments

Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 23/04/2019, 02:43:38 PM
The logic is that for an "indicator" type script, you will always get a new number day to day. IE. 7, 10 or 15 depending on what the indicator is.

When scanning for results, the scan gives a result for anything that provides a result for 1 (or greater!). So by scanning for an indicator, results of 0.63 will not show up, even if you want them. By changing a scan formula to give you a 1 (for yes) or 0 (for no), it is much easier to understand why results come up.

If there is a lot going on, it may not be inherently useful if you decide to look at it in 6 months or in 1 years time. Anything that checks for a cross, or asks if two conditions are true, returns a 1 or 0 and is instantly ready to be used for scanning. The way you have the top 2 formulas are suitable for scanning because of this.

When plotted on a chart, 1 or 0 is only really useful if you understand what that 1 or 0 represents as an indicator on a given chart.

Re: the script.

The error is because of the MACD3_UP line, there is thing part: MACD3,-1 < REF(MACD3,-2); that is throwing BCFL in to a spin. It can see the ,-1 and it cannot find the function this corrolates to. Commas are only used within the paranteheses for functions in order to split parameters such as with MOV or REF. I assume by context you were trying to use a REF here.

as the MACD index is greater as it falls lower than zero and above zero?
- Not 100% sure how to interpret this but I think you are going for a U shape where it goes below 0, declines but then comes back up above 0? Right now I can't see any condition that looks at if the value is above 0 - only below it.

In full - this line, assuming you were after a REF, is doing this:

MACD3_UP:= MACD3 < 0 [1] AND MACD3 > REF(MACD3,-1) [2] AND (REF(MACD3,-1) < REF(MACD3,-2))[3];

[1] MACD3 (most recent bar) is less than 0
[2] MACD3 (most recent bar) is greater than the previous bar
[3] MACD3 on the previous bar, is less than the value 2 bars ago.

When all 3 of these conditions line up, it will return 1 for yes otherwise 0 for no.

If you are going for a below 0 but then above 0 and I assumed correctly. Either REF(MACD3, -2) or REF(MACD3, -1) should cross under 0 OR < 0 depending on what you are after specifically, then the current bar > 0. Posting or linking to a clear example of when this has happened on a chart can help for me to get a better idea of your goals. Possibly zoom in before copying and saving the chart in case it uploads too small again.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 23/04/2019, 11:44:17 PM
Spent the entire long weekend trying to get a number of scripts working like the proverbial 100 monkeys on typewriters, to achieve nothing that works.
So I will have to post here the couple of things I want to do with the now working MACD's.

I'm finding saving graphics as a separate script to function keys cumbersome to implement with limited F keys already mostly mapped, and the MACD's I have setup already needing to be applied to each scan type, when the "alert :=" parts are taken out it doesn't work as a scan only script. It only works as a complete script, but without the graphics part configured. I don't want to complicate your responses so i'll come back to this later on when other things are working.


Firstly; yes 'U' trigger for scanning and for chart graphics.
 
Actually, the turning of the MACD histogram is the indicator I want to initially apply the script to for scanning selected watch lists for, as the histogram mostly starts rising prior to the MACD.main, but the line of script can be adapted for lots of others indicators I might develop. It's one of those base functionality scripts that define a trigger that can be re-used in others.

The simple turning script in Pine as follows, in this case to plot a single histogram bar a unique colour, or place a graphic symbol on the chart in later plot= or plotshape= code:
Hist_TurnUp_Col = outHist3<0 and outHist3 > outHist3[1] and outHist3[1] < outHist3[2]
Hist_TurnDn_Col = outHist3>0 and outHist3 < outHist3[1] and outHist3[1] > outHist3[2]

This should work in most scripting languages, with a bit of variation.
Can I get both directions working in the one BCFL script, or would that result in a 1 and 0 result?

Secondly; for some reason I'm unable to combine two MACD's into one line trigger line; but this works for the previous REF(MACD2hist-2) code, but completely ignores the (MACD1 >=0) or (MACD1 > MACDsig) type qualifier as follows:
Works:
MACD2_xUP := Cross(MACD2sig, MACD2)
AND (MACD1hist>REF(MACD1hist,-2)
AND MOV(CLOSE,21,S) * MOV(VOLUME,21,S) >= 50000);

Doesn't work:
MACD_BUY := (MACD1 >= MACD1sig) AND cross(MACD3, MACD3sig);
and
MACD_BUY := (MACD1 >= 0) AND cross(MACD3, MACD3sig);


Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 24/04/2019, 05:22:10 PM
Re: Graphics. It may get some getting used to, but the key point to keep in mind is not everything you do in a formula needs a graphical version necessarily. If you are building a custom indicator you cannot achieve from the preset varients, then that is when it would be appropriate. Otherwise you could reasonably give it a miss for now. Concentrate on seeing and scanning over the information you wish to see and scan over.

If you have Overlays that already do the job, use those.

For the U shape, it may be better to lay out the exact criteria you want it to do in terms of steps and then work towards building the blocks to ensure all those checks are met. From the attached screenshot, I have some impression that it may not necessarily be a 3 consecutive bar affair but I could still be wrong. From the lines provided, you definitely could replicate this in BCFL, assuming that outHist3 is defined (the MACD?) earlier.

It would come in a 1 or 0 result, or a boolean, as BCFL will be checking to see if all 3 checks are met or not and give a result based on that.

With the works / doesn't work if the variables (MACD1, MACD1sig, MACD3, MACD3sig) exist in the formula and are defined it all checks out. If you are definitely seeing error messages I will need the full context of the formula you are using it in.

Just remember that you can plot individiaul variables out to a chart to see what is happening, comment code with '{ }' on the start and end of the line to temporarily take it out of action. A bit of debugging to understand what BCFL is doing can make it easier to manipulate to what you are after.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 25/04/2019, 03:46:29 PM
A lot of de-bugging going on here.
Ok, finally got the two macd's in the one script working by putting the cross() bit first then adding onto with others with 'AND'. I still can't get the MACD1 (260,120-90) reading as a line but does work with histogram being greater than histogram -1. But I still need to work this macd set to hone in on what produces better scan results, so far not happy.

The turning of the line or histogram bit of code as follows:

{ MACD2 Histogram Turning up from moving down }
{------------------------------------------------}
{--- Macd 2 Medium ---}
MACD2:= mov(C, 50, E) - mov(C, 100, E);
MACD2sig := mov(MACD2, 30, E);
MACD2hist := (MACD2 - MACD2sig);

{------------------------------------------------}
MACD2hist_TUP := MACD2hist<0 AND MACD2hist > MACD2hist,-1 AND MACD2hist,-1 < MACD2hist,-2;
{BELOW WORKS IN PINE SCRIPT:                                                                                                         }
{MACD2hist_TUP = MACD2hist <0 and MACD2hist > MACD2hist[1] and MACD2hist[1] < MACD2hist[2]}
{------------------------------------------------}

{ ---Alert signal holds signal TRUE for x nos bars---}
Alert_MACD2hist_TUP := Alert (MACD2hist_TUP,1);

{ ---Testing the output contents (not sure why this is done)---}
Alert_MACD2hist_TUP;

Output -> There is no function defined. Please define your function with valid arguments

This would be a useful bit of base script I will use for various indicators.
Have tried variations of parenthesis() with no luck.
See image of intention for output (first lime bar is result of same Pine formula, but second cluster easier to see:

Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 26/04/2019, 03:27:51 PM
That script shares the issue explained a couple of posts back:

"The error is because of the MACD3_UP line, there is thing part: MACD3,-1 < REF(MACD3,-2); that is throwing BCFL in to a spin. It can see the ,-1 and it cannot find the function this corrolates to. Commas are only used within the paranteheses for functions in order to split parameters such as with MOV or REF. I assume by context you were trying to use a REF here."

In this formula it is this line:

MACD2hist_TUP := MACD2hist<0 AND MACD2hist > MACD2hist,-1 AND MACD2hist,-1 < MACD2hist,-2;

BCFL has no idea what "MACD2hist,-1" actually means. If you want to grab the prior value (ie. 1 or 2 bars) ago it should look like this using the REF() function:

MACD2hist_TUP := MACD2hist<0 AND MACD2hist > REF(MACD2hist,-1) AND REF(MACD2hist,-1) < REF(MACD2hist,-2);

This is how I would save it to get what you are after, in case it helps. I output MACD2hist when testing along with the end product, so I can see what BCFL is calculating along the way to the desired final logic. Then I comment it out in the end.

Also since you are sending the alert out to just 1 bar - it does not strictly need to be included:

{ MACD2 Histogram Turning up from moving down }
{------------------------------------------------}
{--- Macd 2 Medium ---}
MACD2:= mov(C, 50, E) - mov(C, 100, E);
MACD2sig := mov(MACD2, 30, E);
MACD2hist := (MACD2 - MACD2sig);

{ Criteria Checks }
MACD_Less_0 := MACD2hist<0;
MACD_Higher_1_Bar_Ago := MACD2hist > REF(MACD2hist,-1);
MACD_2BarsAgo_Higher_1BarAgo := REF(MACD2hist,-1) < REF(MACD2hist,-2);

{ Bringing it all Together }
MACD2hist_TUP := MACD_Less_0 AND MACD_Higher_1_Bar_Ago AND MACD_2BarsAgo_Higher_1BarAgo;

{ --- Output to Chart / Scan Engine --- }
{ MACD2hist; }
MACD2hist_TUP;
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 29/04/2019, 03:23:35 PM
Ok have a few working SYSTEM scan results.
ASX 300, Period:200d, Period Type:Day, (Data Mode:Day)
The Benchmark scan result is the SIROC 21:8 same settings as above (except for data mode = no setting).

Now if I got the coding correct and the scan correct the following results are for the following MACD systems:
MACD-0 = two MACD's: Long 260.120-90 and Short 100,50-30

1) (orange) MACD-0 = MACD Main Turning (MACD.Main turns up from down)
2) (blue)  MACD-0 = MACD Histograms turning (Histogram turning up from down)
3) (lime) MACD-0 = MACD Crossing system (main crossing signal line)

I could end up doing dozens of MACD scans for the tri-macd setup I've been using, and for the combinations of two MACD's allowed for the system scans.
Not sure how to proceed at this point, it all looks so visually simple and convincing on my chart setups.

I think instead of an absolute MACD tri-setup system for buy and sell long and short, I need to focus more on a complimentary setup to just filter out SPA3 Trader excessive signals especially in overbought and oversold scenarios, where I can visually identify a resistance level not being broken and where the MACD 100 histogram is clearly descending from a high turning point to a lower trough and then making lower lows and losing momentum (although by that time the SIROC is or is about to trigger a sell anyway, but from the looks of it a few bars later then the MACD histigram, it's the few bars that the MACD histogram rescues the trade), and where I believe, the SIROC starts producing multiple buy sell signals as the SIROC bounces in overbought territory and starts producing loss trades in addition to excessive trade fees.

At this point I'm struggling with the correct 3 MACD histogram coding to implement the above statement.
BTW Is there a way to produce, and overlay on other, scan results an equity curve (key components) of the results?
Scan results as follows:

Bench Mark SIROC 21:8
(http://BENCHMARK_SPA3 Trader SIROC 21-8 200D Daily ASX300.JPG)
MACD System 1), 2) and 3).


Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 30/04/2019, 11:20:30 AM
At this point - I would not be looking at the system results for benchmarking with too much emphasis. Not all trades are equal with SPA3 money management. Just over 1/3 of the last 200 days have been in a high market risk environment, with 124 in low market risk. Depending on your investment plan from there would dictate which trades are not taken.

There is no way to produce an equity curve of results within Beyond Charts. You may need to export and do any further work in Excel becuase there is no portfolio charting software inside Beyond Charts itself. This can be done by CTRL + A on the trades tab so they are all highlighted -> Home tab at the top -> Export -> CSV or XLS depending on preference.

Regardless, as you are intending to work side by side with SPA3, now that you have the MACDs entry and exit criteria defined is to work out the overall process flow. You will have at least 2 scans - one for SPA3 signals and one for the MACD system(s), I expect. I work well with bullet point lists, as it helps break down big ideas in to the smaller steps then you can tackle each one off like a shopping list.

For instance I would start off with are you looking for SPA3 signals first, or are you interested only in the SPA3 trades that meet your criteria? Once you have done one scan over a length of time, use the watch list button at the top of the scan results to overwrite an existing watch list that fuels the other scan depending which way you go.

Just starting off this exercise will help you define the process of how you are going to approach this to do what you are looking to do. This will help the realistic trades come out to you as a combined methodology rather than independant systems which may help you judge the viability of the extra steps.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 01/05/2019, 10:55:11 PM
Agreed about the system results.
have been looking at this from different angles to see what might eventuate to a complimentary system of Tri-MACD related scans that will find (in trend or very early in trend) stocks that the system hasn't signalled for yet, [edit] and find triggers for entries 'in trend' by the MACD 12,50-25 short period histogram turning up.

The ATR Trailing Stop found in the indicator list, but not in the BCFL list; is this able to be coded up in BCFL for scanning? it would make another good way to get into a stock in early trend phases.
Also the RSI of the MACD histograms in the lower panel; is this able to be coded for in BCFL?

Looking at the MACD 260,120-90 (that I find excellent for identifying trending stocks), I have converted this into two moving averages, one a moving average of the first, to be a near equivalent to the long term set MACD 260 as follows:
{------------------------------------------------}
MA1 := MOV(CLOSE, 60, W);
MA1sig := MOV(MA1, 90, W);
{------------------------------------------------}

SCAN_TRIG := cross(MA1, MA1sig);
{------------------------------------------------}

{ ---Alert signal holds signal TRUE for x nos bars---}
Alert_BUYMAX := Alert (SCAN_TRIG,1);
Alert_BUYMAX;
{------------------------------------------------}

Above comes close to the MACD 260 on most stocks, and works well at finding initial crossings at or near the current period price support level similar to the MACD 260 rising to a crossing of signal line, and I want to stress these two points; I prefer to jump into stocks in the initial phase of what is indicated to be an early trend, than to go into stocks in upper mature trends in the hope they continue upwards. I identify these upper mature trend stocks by the level of MACD 100,50-30 histogram in combination the MACD 260 histogram levels; a dropping MACD 100 histogram from high indicates the longer term will also start losing momentum.  A minor percentage of stocks will keep going up but even these at some point will become 'overly' overbought to the point of retracing anywhere up to 50%.

The other point is that I can't accept anywhere near the system draw down amounts (from multiple stocks) beyond $800, especially when I read the MACD mid and long histograms being very high levels and losing momentum, (although sometimes you can't help taking draw-downs because the stock moves very quickly against you).

Once the early stage stocks are identified it becomes a matter of using the short and mid term MACD (or system SIROC signals if they kick in) to pyramid into and lighten out of.

Following charts are of the first two stocks found with the Moving Average scan of ASX All Ordinaries (499 stocks) and are a good example of what I like the look of:

[edit]
Have back dated scans for MA (above), although some of the scans look promising, a greater proportion fail the MA crossing up completely without any price momentum to carry them up. So the qualifier will have to include a momentum strength indicator like the MACD above zero or above an numerical indexed level, and or above signal. Might just add I'm yet to find anything to perform as well as the system does when the SPA3 Trader finds stocks in early trend phase (looking back over the chart).
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 03/05/2019, 02:15:07 PM
Hi John,

The RSI in the indicators list and inbuilt in to BCFL are based on the close price. When deviating away from the close, it does become tricky to do in BCFL because there is no way to say "skip" for when calculating over a lookback / previous period. It is "A" form of RSI.

{ RSI }

{ 100 - [100 / (1 + Avg Gain / Avg Loss ] }
{ Avg Gain = Avg of all up periods for calc }
{ Avg Loss = Avg of all down periods for calc (in positive cont) }

periods := 14;
{Change C for what the RSI is to be based on if not the close }
change:= ROC(C,1,$);
Gain :=Sum(If(change>0,change,0),periods);
Loss :=Sum(If(change<0,Abs(change),0),periods);
AvgCalc := Gain / Loss;

{ Output }
output := 100-(100/(1+AvgCalc));
output;

As for the vanilla ATR TS indicator, again, you can plug in a form of it in to BCFL. This is one I have on hand:

{ Trailing_Stop }
atrper := 14;
up_atrfact:= 3;
dn_atrfact := 3;
up_loss:=up_atrfact*ATR(atrper);
dn_loss:=dn_atrfact*ATR(atrper);
trail:=
If(L>PREV AND Ref(L,-1)>PREV,
Max(PREV,L-dn_loss),
If(L<PREV AND Ref(L,-1)<PREV,
Min(PREV,L+up_loss),
If(L>PREV,L-dn_loss,L+up_loss)));
trail;

For the rest - it sounds like you are struggling to find what criteria you want to identify stocks with still. Scans are great for finding stocks that meet 1 or more set of criteria, given that they all occur on a given bar.

This can extend in to a MACD crossing over another indicator and has risen in value for 2 consecutive bars. Now that you have largely the indicators you want defined - it really is just about writing down what exactly you want to have happened when you open a chart from a scan. Computers and BCFL are only as smart as the instructions they are given to execute, or possible to be executed in a given area.

So if the MOV is not doing it for you. Try and concentrate on defining how you want the MACD itself to work for you.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 03/05/2019, 06:21:13 PM
Exactly that, I 'am' struggling to execute in code the specific idea, looking at charts and seeing the potential helps direct my efforts but actually implementing a structural approach is like asking me to re-invent what you have already done with the SIROC system.
And if I manage to re-invent the wheel you already have, after many hours on the computer, this still doesn't help when deploying and managing real capital into a non-system that falls outside the strict Beyond Charts and Trade Master system of which I can only act on system signals. Something I was unaware of when I bought into the software.
So with that realisation is where I'm currently struggling to implement any optimization I might come up with. I think it best I do complimentary code work within system at this point in time. And when satisfied move on to a stand alone system, if I find it necessary.

I'm getting used to system signals and operation, but still have nagging issues with it, this is my main focus now. Maybe the issues will fade once I gain confidence they will make some money, and I become more complacent with them.

Setting up the MA code in prior post with the ATR-TS is helping define the tradeable zone of the trend where I could employ the MACD3 fast to trigger on the turnings, although in strong trends this also fails more often. And I take it this is the reason why SWS have used the SIROC.
I have a number of fast clean cycle MACD's in pine that could be used like the CCI Schaff MACD, Hull MACD, Normalized MACD. Havn't tried to convert Pine script to BCFL yet.


*Thanks for the code in prev. post. I will spend the weekend tinkering.
Have sufficient code in the collection now, I might do more reading to connect with the more advanced Metastock type formula.

[edit] Re the RSI of the MACD; I've already mentioned this to the help desk people, could you note my interest and request to add a smoothing options to the MACD histogram for the charts; so that the chart indicator is in sync with the BCFL alert symbols and the chart MACD+Signal when using smoothings.

Also I would like to add an RSI smoothing option to the request, as I would like to smooth the RSI of the MACD histogram to remove choppiness of the shorter term one.

Thanks.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 04/05/2019, 11:56:47 AM
Just realised something in BCFL that will save a lot of time when doing scan studies for indicators that you then have to then setup the indicators for each time you adjust the formula and re-run the scan;
you can drag and drop the formula onto a preset indicator chart saved as an overlay.
And here i was re-creating the base chart indicators every time! A very DOH! moment.  ::)
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 05/05/2019, 01:48:35 PM
The ATR-TS works well at scanning. If I use the 'Simple' for smoothing (as I have with the chart indicator), where would you place the 'S'?
The RSI of the MACD I will have to do more work with.

I might spend more time trying to get better quality stock selections in the scan results; so moving on with configuring Beyond Charts scanning options and adding criteria to BCFL or preferably to add Parameters in the Parameter Editor linked to the Scan Profiles.

As the SPA3 system uses Parameter profiles, and they are already set-up I've copied the parameters values to my own Parameter profile.
The question is how do you link to the parameter profiles from BCFL Scan Profile as there seems to be no item to select from?

Thanks.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 07/05/2019, 11:40:46 AM
Hi John,

Quote
Exactly that, I 'am' struggling to execute in code the specific idea, looking at charts and seeing the potential helps direct my efforts but actually implementing a structural approach is like asking me to re-invent what you have already done with the SIROC system.
And if I manage to re-invent the wheel you already have, after many hours on the computer, this still doesn't help when deploying and managing real capital into a non-system that falls outside the strict Beyond Charts and Trade Master system of which I can only act on system signals. Something I was unaware of when I bought into the software.
So with that realisation is where I'm currently struggling to implement any optimization I might come up with. I think it best I do complimentary code work within system at this point in time. And when satisfied move on to a stand alone system, if I find it necessary.

Looking at your most recent post, I was out of the office yesterday, I think this is still something you need to do as much as you think it is re-inventing the wheel. BCFL does NOT have SPA3 indicators built in to it and definitely not the signals.

SPA3 Parameters deal with the settings for how the indicators used in conjunction with the SIROC look like for finding SPA3 system signals. So that is why BCFL has no room for them - as without knowing what to look for, having a set of settings for different indicators does not help a BCFL formula with its objective. It has no idea what to do with this data. This is very similar with a BCFL scan, you need to define somewhere what to look for and the why (in your head, on a piece of paper, as a comment) to be able to purpose the data that comes out of the BCFL scan as actionable information in some way.

As you are trying to interface with SPA3, any BCFL formulas or BCFL scans will be best utalised to act as a filter before the fact or after the fact around the SPA3 methodologies entry or exit signals. You cannot get around this right now in a with the tools and, thought needs to be made on what your scanning ojective is and then how the process look around that. If you cannot define this or do not put thought in to it - then it is the same as navigating a ship without a map to me. It is working without the objective in mind.

It seems to me that you have a manual process outlined - so putting it in to BCFL should be more so about how to optimise alerts to tell you that this manual process may be occuring. A best fit implementation, with the tools at hand, perhaps is another angle to consider it from.

Without any processes of how you expect the whole overall to work with these points in mind - then you can start thinking about how money real world works with the system. I definitely do not and no one here at SWS want you to put cash in to signals that you are not confident in. Without processes and belief, you cannot be objective with your market participation.

You can enter non-system trades in to TradeMaster via the Act On Menu -> New Buy as well which you may want to take a look into.

As for simple smoothing on the trailing stop, it would look as so. Where the ATR period setting was is now in the moving average of the ATR:

{ Trailing_Stop SIMPLE SMOOTHING }
ATR_smoother := MOV(ATR(1), 14, S);
up_atrfact:= 3;
dn_atrfact := 3;
up_loss:=up_atrfact*ATR_smoother;
dn_loss:=dn_atrfact*ATR_smoother;
trail:=
If(L>PREV AND Ref(L,-1)>PREV,
Max(PREV,L-dn_loss),
If(L<PREV AND Ref(L,-1)<PREV,
Min(PREV,L+up_loss),
If(L>PREV,L-dn_loss,L+up_loss)));
trail;
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 07/05/2019, 02:24:58 PM
Thanks for sorting out the ATR code with smoothing;
I like the ATR-TS for getting into stocks early; this is a primary driver ATM for code time, and combined with the posted MA code seems to work even better at finding early trenders than the MACD set, or at least before they kick in with any certainty as the MACD 100 warbles about for weeks until the MACD 260 finds certainty. So the MA I set up to reflect the MACD 260 does an excellent job here.

Yes I need to focus, and time will be needed to think it through.
Having given the predicament some thought I see the following as current goals:

Goal 1. Find quality early stocks that could potentially fit the "system scanned" parameters of stocks that will be triggered in a few days/weeks time. Early entries that can be traded in and out of by MACD3 Short histogram timing.
Goal 1 Indicators for code to find stocks: (MA 65,W with Signal of the MA), (ATR-TS, S), (Money Flow Indicator MFI 100 or 60 with Simple signal line). Back up will be the MACD1 260 with complimentary MACD 100.

Goal 2. Work within system for stocks already holding or recently holding (still in primary trend) through the SPA3 triggers to "graphically signal for" clean exits that occur on the MACD3 short histogram or similar cyclic indicator (if one exists in BCFL).
Goal 2. Indicators: Set up a MACD3 histogram code for alert graphic symbol to overlay on the main chart set up I use. Could do entries also but if you don't hold the stock then you are outside the system so it would have to be a separate watch-list based for scanned potential entries of recent holdings that remain within my MA or MACD 1 Long term trend (this shows potential to work well as I frequently see the system trade back in a few days later anyway on the same stock many times in some trends; exactly what I would like to eliminate).

Goal 3. Exit Sell "graphic Sell signals" for stocks already bought, that might outperform system ones, by simply using an overlay of the code to give graphic signals. In addition to short term 'in trend' signals identify long term trend phase out locations by long term indicators.
Goal 3. Indicators for code: (MACD3 Short histogram) and  (MACD2 medium histogram) for top turning identification, and finally MACD3, ATR-ST and MA crossings for stop loss, as well as SPA3 signal stops, sell all end of trend get out signals.

Next step will be to set up a portfolio (that you mentioned) and watch-list for these trades. I need to work out what percentage of trade allocation $ to retain in a stock whilst in trend as MACD3 trades out of cycle, as a base holding. I note SPA3 Trader system sells 100% upon signal triggers, I question this if the trend is measured and indicated as strongly intact. I would like to retain a base amount in the holding.


Q. re the BCFL Money Flow: Just setting one up, BCFL doesn't like what I have coded is there a specific setup of moving averages I need to use in place of the MFI(100) line?

{ ---- Money Flow Index ---- }
 MFI( 21 )
MFIsig := MOV(MFI, 50, S)


Thanks.
[edit] I think I may have asnwered the MFI line by plugging in the same line as the AT-RTS and changing to MFI:
{ ---- Money Flow Index ---- }
{ MFI( 14 ); original from BCFL library}

MFI_1 := MOV(MFI(1), 21, S);
MA_MFI := MOV(MFI_1, 50, S);

would this be correct?
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 08/05/2019, 11:53:31 AM
Fantastic that you have a process to work to - at least this will get the work a line in the sand initially. I think it definitely is important.

Quote
... I need to work out what percentage of trade allocation $ to retain in a stock whilst in trend as MACD3 trades out of cycle, as a base holding. I note SPA3 Trader system sells 100% upon signal triggers, I question this if the trend is measured and indicated as strongly intact. I would like to retain a base amount in the holding.

In this scenario you may wish to take it as we call a lighten signal - or a 33% reduction in the position size. It takes some off the table and usually we do not do it for more than once per trade. Could be the midway point you are looking at here.

Quote
Q. re the BCFL Money Flow: Just setting one up, BCFL doesn't like what I have coded is there a specific setup of moving averages I need to use in place of the MFI(100) line?

{ ---- Money Flow Index ---- }
 MFI( 21 )
MFIsig := MOV(MFI, 50, S)


Thanks.
[edit] I think I may have asnwered the MFI line by plugging in the same line as the AT-RTS and changing to MFI:
{ ---- Money Flow Index ---- }
{ MFI( 14 ); original from BCFL library}

MFI_1 := MOV(MFI(1), 21, S);
MA_MFI := MOV(MFI_1, 50, S);

Depends what you are trying to replicate or achieve with this question so bare with me on this one. Also I am not sure where the MFI 100 you mentioned comes in?

MFI() is the same as the indicator panel in BCFL, so if you are replicating a moving average of the MFI what you had initially looks correct to me. BCFL editor might be companing about that lack of designated output and semi-colons though, so it should look like this if you wanty to see how the indicator calculation looks on the chart:

MFIsig := MOV(MFI(21), 50, S);
MFIsig;
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 08/05/2019, 01:48:54 PM
Thanks, the Money Flow saved no problems.
Re the Money Flow;  I was looking for an additional qualifier to aid in weeding out junk stocks. It also fits to the RSI of the MACD Histogram panel without distortion.

Over at Incredible Charts I use the Twiggs Money Flow (TMF) and Twiggs Momentum Oscillator (TMO) their proprietary indicators, so looking for something similar here. Although I might try to implement the Metastock (TMF) code.

TMF (Proprietary see footnote *) http://www.incrediblecharts.com/indicators/twiggs_money_flow.php?clientID=228052&app_productcode=101&ic_a_id=1_25_25_0 (http://www.incrediblecharts.com/indicators/twiggs_money_flow.php?clientID=228052&app_productcode=101&ic_a_id=1_25_25_0)
TMO (Proprietary) http://www.incrediblecharts.com/indicators/twiggs_momentum_oscillator.php?clientID=228052&app_productcode=101&ic_a_id=1_25_25_0 (http://www.incrediblecharts.com/indicators/twiggs_momentum_oscillator.php?clientID=228052&app_productcode=101&ic_a_id=1_25_25_0)

* Twiggs Money Flow is a proprietary indicator. Readers are permitted to explain/describe Twiggs Money Flow on other websites/publications and/or to include/reproduce the formula in other software provided that they display a hyperlink to this web page.

For reference I include the Metastock (TMF) formula:
periods:=Input("TMF periods",1,100,21);
TRH:=Max(Ref(C,-1),H);
TRL:=Min(Ref(C,-1),L);
TR:=TRH-TRL;
ADV:=((C-TRL)-(TRH-C))/If(TR=0,999999,TR)*V;
If(Wilders(V,periods)=0,0,Wilders(ADV,periods)/Wilders(V,periods))

Q1. Could you recommend an indicator or series that could weed out the non performing junk stocks?
Have added this to some scans for volume, not sure how effective it is at this stage:
AND MOV(CLOSE,21,S) * MOV(VOLUME,21,S) >= 50000;

Q2. Also having problems with getting the TMF to code correctly for use in lower code, if you could point me in the right direction, I assume it's an indicator script without an output?. I'm tempted to think it needs a MOV(ADV,,) type line? but when I tried this it didn't want to save.

Once that is achieved I would like next to code for a TMF >=0 and less then 15, or any number of indexed levels. Is the index level built into the indicator formula or do you need to build one seperately?
(I guess this question covers any indicator that could be referenced to an index level like; RSI (of MACD) and MACD itself, ultimately to code for a crossing above a line level like 20 or 50 for buys and downward 50 80 or 90 for sells. I know the cross() script but does it apply to index levels also?
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 08/05/2019, 06:54:00 PM
Ok here's a problem I've had all along where the MACD above and below zero qualifier is ignored by the scan:

{ ---- Parameters ---- }
MACD1_DN := MACD1<0 and MACD1<MACD1sig;
MACD2_UP := MACD2<0 and MACD2<MACD2sig and MACD2 > REF(MACD2,-1);
MACDhist_converge := MACD2hist > REF(MACD2hist,-1) and MACD1hist < REF(MACD1hist,-1);

{ ---- Scan triggers ---- }
SCAN_TRIG_BUY := MACD1_DN and MACD2_UP and MACDhist_converge and MOV(CLOSE,21,S) * MOV(VOLUME,21,S) >= 50000;

{ ---- Alert Signals ---- }
Alert_BUY_MACD_hist := Alert (SCAN_TRIG_BUY, 1);

{ ---- Output to Scan Engine ---- }
Alert_BUY_MACD_hist;
SCAN_TRIG_BUY;

I noted in the third post the M9<0 was placed in the lower Alert lines, not sure why though, as it forms part of the MACD state qualifying parameters:

M9:= Mov(MACD(),100,E);
X:=Cross(Mov(C,50,E),Mov(C,30,E));
Alert1 := Alert( M9<0 AND Cross(MACD(),M9),5); { Alert() Holds signal TRUE for 5 bars or whatever number you choose}
Output := X AND Alert1;
Output;

Once I get the last few posts sorted, it should be all I need to do go forward with the tr-MACD scan and alerts on charts. I have done dozens of formulas already but most seem to be over signalling or incorrectly signalling (ignoring the >0 <0 part), and pulling in too many junk stocks, the TMF should sort the latter out though.
And having eyeballed 100's of scan result charts now, I can identify that the RSI of the MACD histogram panel does the better read for cleaner entries most of the time over the direct read of the MACD histogram, but there are always areas that go saw toothed, which I think some MACD histogram smoothing and RSI smoothing might help with in the display of the indicators.

Thanks.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 09/05/2019, 02:38:46 PM
The RSI of the MACD histogram; would this be correct for a crossing of the 20 index level:

{ ---- Macd 2 Medium ---- }
MACD1:= mov(C, 100, E) - mov(C, 50, E);
MACD1sig := mov(MACD1, 30, E);
MACD1hist := (MACD1 - MACD1sig);
{-------------------------------------}

{ 100 - [100 / (1 + Avg Gain / Avg Loss ] }
{ Avg Gain = Avg of all up periods for calc }
{ Avg Loss = Avg of all down periods for calc (in positive cont) }

periods := 5;
{Change C for what the RSI is to be based on if not the close }
change:= ROC(MACD1hist,1,$);
Gain :=Sum(If(change>0,change,0),periods);
Loss :=Sum(If(change<0,Abs(change),0),periods);
AvgCalc := Gain / Loss;
RSIM_out := 100-(100/(1+AvgCalc));
RSIM_out;

{ ---- Formula ---- }
RSIM_X20 := RSIM_out cross(RSIM_out,1, 20);

{ ---- Alerts ---- }
ALERT_RSIM_x20 := alert(RSIM_X20);

{ ---- Output to Scan Engine ---- }
ALERT_RSIM_x20;
RSIM_X20;

Outout -> RSIM_OUT is unrecognised

Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 09/05/2019, 03:07:59 PM
Q1. Could you recommend an indicator or series that could weed out the non performing junk stocks?
Have added this to some scans for volume, not sure how effective it is at this stage:
AND MOV(CLOSE,21,S) * MOV(VOLUME,21,S) >= 50000;

That formula calculation is definitely how to set a liquidity benchmark requirement.

It is part of SPA3 criteria for RSC parameters to be met.  Section 9.5 of the reference manual goes in to more detail: https://documentation.beyondcharts.com/SPA3_REF.php

The RSC formula for comparing a stock to the index is provided in the Sample Formula section of the Formula Explorer, which can be imported to your formula with this line:

RSC_Comp := FML("Relative Strength Comparison");

Then to convert it in to a moving average:

RSC_MOV := MOV(RSC_Comp, 30, E);

Then to acheieve a similar effect to the SPA3 Trader system built in to your scans, you just need to compare the position of the RSC to the RSC MOV. Section 9.5.3 goes in to more detail as to why this in particular is useful for finding currently outperforming stocks.

Q2. Also having problems with getting the TMF to code correctly for use in lower code, if you could point me in the right direction, I assume it's an indicator script without an output?. I'm tempted to think it needs a MOV(ADV,,) type line? but when I tried this it didn't want to save.

The way it is setup is designed to be used on its own with the IF statement working out the only output. It can get a bit messy and I personally, am not a fan of inputs (still work though), but I would defintely change the last line to this:

TMF := If(Wilders(V,periods)=0,0,Wilders(ADV,periods)/Wilders(V,periods));

Then the calculation can be referenced easier. It does work as-is in its own formula.

Once that is achieved I would like next to code for a TMF >=0 and less then 15, or any number of indexed levels. Is the index level built into the indicator formula or do you need to build one seperately?

(I guess this question covers any indicator that could be referenced to an index level like; RSI (of MACD) and MACD itself, ultimately to code for a crossing above a line level like 20 or 50 for buys and downward 50 80 or 90 for sells. I know the cross() script but does it apply to index levels also?
[/quote]

Plot TMF as an output on to a chart and work this one out. It is a good habit to get in to, to know what is actually happening with the indicator. In this case it seems to osscilate above and under 0.

So depending on what you are looking for - you can always check if say TMF > 0 or <-0.5 depending what you are interested in.

Ok here's a problem I've had all along where the MACD above and below zero qualifier is ignored by the scan:

{ ---- Parameters ---- }
MACD1_DN := MACD1<0 and MACD1<MACD1sig;
MACD2_UP := MACD2<0 and MACD2<MACD2sig and MACD2 > REF(MACD2,-1);
MACDhist_converge := MACD2hist > REF(MACD2hist,-1) and MACD1hist < REF(MACD1hist,-1);

{ ---- Scan triggers ---- }
SCAN_TRIG_BUY := MACD1_DN and MACD2_UP and MACDhist_converge and MOV(CLOSE,21,S) * MOV(VOLUME,21,S) >= 50000;

{ ---- Alert Signals ---- }
Alert_BUY_MACD_hist := Alert (SCAN_TRIG_BUY, 1);

{ ---- Output to Scan Engine ---- }
Alert_BUY_MACD_hist;
SCAN_TRIG_BUY;

You have 2 outputs here - best to keep it to 1 for scans so it's clear what you are searching for. In this case, have you dragged this formula on to a chart to check what it is doing and ensure it lines up to what you are expecting?

Remember if you put MACD1; or MACD1_DN; on their own line in the output at the end - you can see on the chart what that calculation is actually doing. If you get a few lines, right click the chart background -> panel -> add.

Then drag one of the lines in to their own empty panel - makes it easier to read and understand what each calculation is actually producing. If you are not sure to do this let me know and I can produce a quick video about it by COB tomorrow.

Quote
{ ---- Formula ---- }
RSIM_X20 := RSIM_out cross(RSIM_out,1, 20);

{ ---- Alerts ---- }
ALERT_RSIM_x20 := alert(RSIM_X20);

{ ---- Output to Scan Engine ---- }
ALERT_RSIM_x20;
RSIM_X20;

Stay RSIM_out is not defined ie. BCFL does not understand.

Also the cross function is cross(some indicator, some other indicator) checking if A has gone above B for a certain bar. So if you wanted to see if it moved above a value of 20 it would look like this:

RSIM_X20 := cross(RSIM_out, 20);
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 09/05/2019, 10:52:59 PM
Just something you mentioned about setting up the TMF as an indicator, were you referring to an actual indicator like the Money Flow in the Indicators list or was that a BCFL alert signal output insert or overlay?
I would like to have the TMF as an actual indicator if that can be done.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 10/05/2019, 03:45:15 PM
Hi John,

As an indicator, but the indicator is the formula itself. Have a look at the BCFL editor video:

https://beyondcharts.com/education/tutorme.php?s=bcfl

You'll see the default for any formula (like the original TMF, if you saved it as its own stand alone formula) is a line in its own panel when plotted on the chart. You can change this to other styles which is shown in the 2nd half of that video, but its the general idea of what I meant.

The TMF you have as provided, in its own formula, will work once you click OK to the period input it will ask you as you drag it from the formula explorer (where you drag it from is what you call it when you save it) on to a chart.

Where this change comes in:

TMF := If(Wilders(V,periods)=0,0,Wilders(ADV,periods)/Wilders(V,periods));

Is if you wanted to put the indicator as part of another formula and be able to use the calculation as part of something else.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 10/05/2019, 06:22:20 PM
Got it thanks, even included a signal line :)

{ ---- Twiggs Money Flow ---- }
periods:=Input("TMF periods",1,100,21);
TRH:=Max(Ref(C,-1),H);
TRL:=Min(Ref(C,-1),L);
TR:=TRH-TRL;
ADV:=((C-TRL)-(TRH-C))/If(TR=0,999999,TR)*V;
TMF := If(Wilders(V,periods)=0,0,Wilders(ADV,periods)/Wilders(V,periods));
ADV_out := ADV >0 and ADV < 0.5;

{ ---- Signal Line ---- }
TMFsig := mov(TMF, 50, E);

{ ---- Output ---- }
TMF;
TMFsig;
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 10/05/2019, 08:40:36 PM
Had mixed results with the RSI of MACD1 histogram crossing up over 50 line, using the provided additional code:
When RSIM_out is turn on you can see what the triggers are reporting; why is the RSIM not plotting like the RSI of the panel of the MACD histogram above it, and within the 100 index?
 
{ ---- MACD1 ---- }
MACD1:= mov(C, 260, E) - mov(C, 120, E);
MACD1sig := mov(MACD1, 90, E);
MACD1hist := (MACD1 - MACD1sig);

{ ---- RSI (MACD Histogram) ---- }
{ 100 - [100 / (1 + Avg Gain / Avg Loss ] }
{ Avg Gain = Avg of all up periods for calc }
{ Avg Loss = Avg of all down periods for calc (in positive cont) }

periods := 5;
{Change C for what the RSI is to be based on if not the close }
change:= ROC(MACD1hist,1,$);
Gain :=Sum(If(change>0,change,0),periods);
Loss :=Sum(If(change<0,Abs(change),0),periods);
AvgCalc := Gain / Loss;
RSIM_out := 100-(100/(1+AvgCalc));

{ ---- MACD1hist  crosses above 50 mid line ---- }
RSIM_X := cross(RSIM_out, 50);

{ ---- Alerts ---- }
ALERT_RSIM_X := alert(RSIM_X,1);

{ ---- Output to Scan Engine ---- }
ALERT_RSIM_X;
RSIM_out;

Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 13/05/2019, 05:11:41 PM
This is where the BCFL 'version of an RSI' is starting to show I think. The re-computation using the raw language just is not as good compared to the in-built RSI calculation at handling the values the RSI needs.

I have raised a change off the back of this to the development team, asking to expand the RSI function capabilities in BCFL to include custom data sets (not just the close data as it is now). Due to the development work that's prioritised I am unable to give a timeline of when this will come in to Beyond Charts.

Below is the best fit I can get right now, changing the smoothing over to wilders instead of a raw sum so it stays within the 0 to 100 bounds and matches the movements of the RSI of the MACDH. Also the MACD1hist had to be flipped around, so the data values where positive and negative in the right places compared to the hard coded indicator we are basing it off.

It seems to struggle most tracking the acension of increasing negative values within the wilder smoothing itself. I'll have another look at this tomorrow and see if there is any further improvements we can make on this end - but otherwise it may be the closest fit available for the time being.

{ ---- MACD1 ---- }
MACD1:= mov(C, 260, E) - mov(C, 120, E);
MACD1sig := mov(MACD1, 90, E);
MACD1hist := (MACD1sig - MACD1);

{ ---- RSI (MACD Histogram) ---- }
{ 100 - [100 / (1 + Avg Gain / Avg Loss ] }
{ Avg Gain = Avg of all up periods for calc }
{ Avg Loss = Avg of all down periods for calc (in positive cont) }

{Change C for what the RSI is to be based on if not the close }
periods := 14;
change:= ROC(MACD1hist,1,$);
Gain :=Wilders(If(change>0,change,0),periods);
Loss :=Wilders(if(change<0,abs(change),0),periods);
AvgCalc := Gain / Loss;
RSIM_out := 100-(100/(1+AvgCalc));

{ ---- MACD1hist  crosses above 50 mid line ---- }
RSIM_X := cross(RSIM_out, 50);

{ ---- Output to Scan Engine ---- }
RSIM_out;
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 14/05/2019, 03:15:49 PM
Ok thanks for the effort, I wouldn't know where to start with this.
I was left wondering why BCFL RSI raw code is not available to users (does that apply to most BCFL indicators?), I understand proprietary being locked but common garden variety ones not.
Note how TradingView deal with this in that they reference locked indicators like rma(see image).

I have tried a few different open source Metastock ones also without any success. So you efforts are my best source.

The RSI is what I'm focusing on currently as it doesn't whipsaw as severely and frequently as the raw MACD histograms so the RSI acts as a whipsaw filter, and will make a much cleaner signaling and scanning system, even better with algo-smoothings for each indicator used (when implemented).

To test the worthiness of the RSI MACD histogram (RSIMh) combination I have gone back to Pine to finish what I started there a few months ago and are proceeding to code the key triggers to display on charts and is quite straight forward for this, but cannot do scans for RSIMh's in TradingView.

BTW no hurry here, I need time to draft up the triggers and signal codes and index of terms anyway.
And your efforts are respectfully appreciated :)
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 15/05/2019, 03:24:57 PM
The BCFL raw code is not in BCFL, really. The functions like SUM(data array, # of bars) or MOV(data array, # of bars, type of smoothing) are all coded in to Beyond Charts+ using C# which the rest of the software is programmed in. So there is a degree of limitations in BCFL of what is possible based on what is programmed in to be manipulated via BCFL.

Now the RSI that is achiveable via BCFL compared to C# mainly is limited because there are no loops in BCFL. The formula is run over each individual bar in full instead of running only a small portion of the code in one area before moving on. BCFL also lacks an ability to change multiple variables when one condition is met. Both of these would take significant time to address. Now a raw RSI largely can be done - as long as you don't have these great big rises like the MACDH can have from an all time low to a new peak.

This is because when you average out based on a small number of periods, eventually the average loss over the periods is going to hit 0 since a loss has not happened for quite some time.

But it can be solved by just taking the previous value and pushing it along. This makes the volatility of the RSI sharper (well, is one of the reasons) and may over a long period cause one or two false cross overs compared to the hard coded indicator as the dips are longer from the top of the range - but until we expand the BCFL function capability (for RSI) this is likely the most that's possible using the BCFL language.

{ ---- MACD1 ---- }
MACD1:= mov(C, 260, E) - mov(C, 120, E);
MACD1sig := mov(MACD1, 90, E);
MACD1hist := (MACD1sig - MACD1);

{ ---- RSI (MACD Histogram) ---- }
{ 100 - [100 / (1 + Avg Gain / Avg Loss ] }
{ Avg Gain = Avg of all up periods for calc }
{ Avg Loss = Avg of all down periods for calc (in positive cont) }

{Change C for what the RSI is to be based on if not the close }
{ RSI primer }
period := 14;
currentValue := MACD1hist;
previousValue := REF(MACD1hist, -1);

change := currentValue - previousValue;

Gain := if(cum(1) > period, sum(If(change>0, change, 0), period), 0);
Loss := if(cum(1) > period, sum(If(change<0, abs(change), 0), period), 0);

Avg_Gain := Gain / period;
Avg_Loss := Loss / period;

Avg_Change := if(Avg_Loss > 0, Avg_Gain / Avg_Loss, PREV);

{ Calc RSI }
RSIM_out := 100-(100/(1+Avg_Change));

{ ---- MACD1hist  crosses above 50 mid line ---- }
RSIM_X := cross(RSIM_out, 50);

{ ---- Output to Scan Engine ---- }
{RSIM_out}
RSIM_X;
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 18/05/2019, 12:00:24 PM
Quote
BCFL also lacks an ability to change multiple variables when one condition is met.
Point taken, don't quite understand this, no doubt will come back to bite me later on.

Re:
Quote
Ok here's a problem I've had all along where the MACD above and below zero qualifier is ignored by the scan:
Quote
You have 2 outputs here - best to keep it to 1 for scans so it's clear what you are searching for. In this case, have you dragged this formula on to a chart to check what it is doing and ensure it lines up to what you are expecting?
Remember if you put MACD1; or MACD1_DN; on their own line in the output at the end - you can see on the chart what that calculation is actually doing. If you get a few lines, right click the chart background -> panel -> add.
Then drag one of the lines in to their own empty panel - makes it easier to read and understand what each calculation is actually producing. If you are not sure to do this let me know and I can produce a quick video about it by COB tomorrow.

The MACD 260,120-90 is completely ignored by the scan, returning results that  are based on something? but not the MACD1 criteria.

[edit]
Having done some testing I found is what I thought was being ignored is in fact to do with the code, so when I reversed the criteria it scans correctly for what I was expecting:

{ ---- MACD1 ---- }
MACD1:= mov(C, 260, E) - mov(C, 120, E);
MACD1sig := mov(MACD1, 90, E);
MACD1hist := (MACD1 - MACD1sig);

{ ---- MACD1 is above signal line and above zero ---- }
MACD1_UP := MACD1sig >= MACD1 and MACD1 <0;

{ ---- Output to Scan Engine ---- }
MACD1_UP;

 returns the opposite of what is coded where the MACD1 Main is greater than the MACD1 Signal and MACD1 is greater than zero line :confused: everything is upside down!
Added the MACD code as an indicator and sure enough every things upside down:

[edit]
Found the problem: reversing the 260 with the 120 fixed this upside downess. No wonder the MACD scans weren't producing results as expected.
{ ---- MACD1 Indicator---- }
MACD1:= mov(C, 120, E) - mov(C, 260, E);
MACD1sig := mov(MACD1, 90, E);
MACD1hist := (MACD1 - MACD1sig);
MACD1;
MACD1sig;
MACD1hist;
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 19/05/2019, 03:37:24 PM
Re the Relative Strength Comparison;

Quote
The RSC formula for comparing a stock to the index is provided in the Sample Formula section of the Formula Explorer, which can be imported to your formula with this line:
RSC_Comp := FML("Relative Strength Comparison");

Then to convert it in to a moving average:
RSC_MOV := MOV(RSC_Comp, 30, E);

Then to achieve a similar effect to the SPA3 Trader system built in to your scans, you just need to compare the position of the RSC to the RSC MOV. Section 9.5.3 goes in to more detail as to why this in particular is useful for finding currently outperforming stocks.

There are two versions of the RSC; one from your earlier post and one from the BCFL Sample Formula list, question is which one to use:

RSC 1:
{ Description:  This Script can be used to compare the price movement of a stock with another stock, sector, or index}
{ RSC INDEX EXAMPLE }
COMPARISON:= Security(INDEX,C);
RSC:= (C/COMPARISON)*1000000;
RSC;

RSC_MOV := MOV(RSC, 150, W);
RSC_MOV;

RSC 2:
RSC_Comp := FML("Relative Strength Comparison");
RSC_Comp;

RSC_MOV := MOV(RSC_Comp, 150, W);
RSC_MOV;

Both these work ok as indicators.

When I use the system Indicator for RSC it auto selects the Industry Sector to the current stock in the chart, and displays the name of the industry sector.

When I tried an index code like $XEJ in place of the 'INDEX' in line 1 of the sample code; BCFL complains about -> Identifier $XEJ is not defined. Although when the INDEX is left as is, the System Indicator compared to the BCFL code indicator looks the same when I go through the stock scan list, so I assume it is auto selecting the correct industry for the stock and I don't have to add in the sector code manually? This must have something to do with BCFL not integrated into C# program as you mentioned before.

So; when I use RSC in a custom BCFL coded scan for selection criteria filter, am I simply comparing the RSC; with the RSC_MOV; to find out performing stocks? like this:

RSC_filter := RSC > RSC_MOV;

What I might do is use a Moving Average Envelope to reduce 'ranging' RSC comparisons that move up and down across the MA that will trigger.
I note there is no BCFL Library list entry for Envelope Trading Bands, so will need to create the code for an indicator from raw MetaStock source code for a Moving Average x% offset:

Raw MaetaStock formula for trading bands (changed the 10% to /100):
Band_upper := Mov(C, 150,S) +10/100;
Band_lower := Mov(C, 150,S) - 10/100;
Mov_S := Mov(C,150,S);

Band_upper;
Band_lower;
Mov_S;

This plots over the price ok, but not the RSC. had to take out the /100 to get it to work on RSC and drop the 10 to 7 for the fit I was looking for and to match the System Envelope of 5% over the RSC:

The Envelope inclusion:
RSC_Comp := FML("Relative Strength Comparison");
RSC_Comp;

RSC_MOV_W := MOV(RSC_Comp, 150, W);
RSC_MOV_W;

RSC_MOV_S := MOV(RSC_Comp, 150, S);
RSC_MOV_S;

Band_upper := Mov(RSC_Comp, 150, S) + 7;
Band_lower := Mov(RSC_Comp, 150, S) - 7;
Band_upper;
Band_lower;


I think this will do, And I'm slightly impressed with myself, although it consumed most of my day!




Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 21/05/2019, 04:10:26 PM
There is definitely a few ways to do RSC. The FML("Relative Strength Comparison") is a reference to grabbing the output (or calculation result) from the Relative Strength Comparison formula under the sample formula group section. This is found in the left hand side Formula Explorer panel.. You can right click and edit this sample formula name and you'll see the formula it is made up of, which is the 1st example you asked about. So they are both the same.

To expand the focus on why you may do one approach or the other. The sample formula is a pre-configured, uneditable bit of formula. You may want to use the longer format if you are looking at stocks from XASX, XNAS or XNYS (depending on what is available) to compare against an individual stocks sector, dynamically:

COMPARISON:= Security(SECTOR,C);
RSC:= (C/COMPARISON)*1000000;
RSC;

If you wanted to plug in a code directly it needs to look like below. The hardcoded approach means, well in this example, everything will be compared to the energy sector even if they are not part of it.

COMPARISON:= Security("$XEJ.XASX",C);
RSC:= (C/COMPARISON)*1000000;
RSC_MOV := MOV(RSC, 105, E);

This is all possible as we extended the ability of the Security function to dynamically grab relevant sector and indexes for comparison, when possible, using the keywords INDEX or SECTOR. Otherwise you would have to save 10 different formulas (essentially) with only the index code reference in the Security function being different and set up 10 different scans to accomodate them all.

You can see this work in practice by dragging the sample formula Relative Strength Comparison on to a blank chart from the Formula Explorer panel and then applying the RSC indicator from the indicators panel (parameters set to Comparison: Auto & Level: Market). They will both be the same.

This post is mainly a confirmation of what you have already worked out it seems!
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 26/05/2019, 12:22:03 PM
Having set up a number of RSI of MACD Histograms, and RSI of MACD.Main and Signal to test and adjust the Code for the RSI to fairly equal the System RSI of the MACD histogram and MACD.Main line; 1,2 and 3.
It seems BCFL won't take more than one RSI in the code, to have a pre qualifier for the trigger signal / alert; like RSIMH1 is greater than 90 with the trigger RSIMH3 crosses 10.
In the code (below) the output indicator produces a flat line when combining two RSIMH's, but they work individually. Is there a better approach when using two RSI's of the MACD histogram? because I would eventually like to have two pre-qualifying RSIMH's (1 & 2 for trigger 3)

{ ---- MACD 1 ---- }
MACD1:= mov(C, 120, E) - mov(C, 260, E);
MACD1sig := mov(MACD1, 90, E);
MACD1hist := (MACD1 - MACD1sig);

{ ---- MACD 3 ---- }
MACD3:= mov(C, 12, E) - mov(C, 50, E);
MACD3sig := mov(MACD3, 25, E);
MACD3hist := (MACD3 - MACD3sig);


{ ---- RSIMH1 ---- }
period := 5;
currentValue := MACD1hist;
previousValue := REF(MACD1hist, -5);
change := currentValue - previousValue;
Gain := if(cum(1) > period, sum(If(change>0, change, 0), period), 0);
Loss := if(cum(1) > period, sum(If(change<0, abs(change), 0), period), 0);
Avg_Gain := Gain / period;
Avg_Loss := Loss / period;
Avg_Change := if(Avg_Loss > 0, Avg_Gain / Avg_Loss, PREV);
RSIMH1 := 100-(100/(1+Avg_Change));


{ ---- RSIMH3 ---- }
period := 5;
currentValue := MACD3hist;
previousValue := REF(MACD3hist, -5);
change := currentValue - previousValue;
Gain := if(cum(1) > period, sum(If(change>0, change, 0), period), 0);
Loss := if(cum(1) > period, sum(If(change<0, abs(change), 0), period), 0);
Avg_Gain := Gain / period;
Avg_Loss := Loss / period;
Avg_Change := if(Avg_Loss > 0, Avg_Gain / Avg_Loss, PREV);
RSIMH3 := 100-(100/(1+Avg_Change));


{ ---- Criteria ---- }
RSIMH1_UP := RSIMH1 >90;
RSIMH3_X10 := cross(RSIMH3,10);

{ ---- Alert ---- }
ALERT_RSIMH_TRIG:= RSIMH1_UP and RSIMH3_X10;

{ ---- Output to Scan Engine ---- }
ALERT_RSIMH_TRIG;

EDIT
It seems the second RSI is not being read by BCFL engine, only the top one.
I wonder if there is a way to do the following output by having 3 different inputs; MACDhist1,  MACDhist2 and MACDhist3 in one formula without duplicating the entire formula?:

{ ---- MACD 1 ---- }
MACD1:= mov(C, 120, E) - mov(C, 260, E);
MACD1sig := mov(MACD1, 90, E);
MACD1hist := (MACD1 - MACD1sig);

{ ---- MACD 2 ---- }
MACD2:= mov(C, 50, E) - mov(C, 100, E);
MACD2sig := mov(MACD2, 30, E);
MACD2hist := (MACD2 - MACD2sig);

{ ---- MACD 3 ---- }
MACD3:= mov(C, 12, E) - mov(C, 50, E);
MACD3sig := mov(MACD3, 25, E);
MACD3hist := (MACD3 - MACD3sig);

{ ---- RSIM Formula --- }
period := 5;
currentValue := MACD1hist;
previousValue := REF(MACD1hist, -5);
change := currentValue - previousValue;
Gain := if(cum(1) > period, sum(If(change>0, change, 0), period), 0);
Loss := if(cum(1) > period, sum(If(change<0, abs(change), 0), period), 0);
Avg_Gain := Gain / period;
Avg_Loss := Loss / period;
Avg_Change := if(Avg_Loss > 0, Avg_Gain / Avg_Loss, PREV);
RSIMH1 := 100-(100/(1+Avg_Change));
RSIMH2 := 100-(100/(1+Avg_Change));
RSIMH3 := 100-(100/(1+Avg_Change));

Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 29/05/2019, 12:33:59 AM
I have a work-around for now simply substituting the RSIMH1 trend with the MACD1 Histogram or even just the MACD.Main > Signal
But clearly it isn't optimised due to the RSI code output. I don't mind the current RSIMH3 absolute extension into the O/B O/S where the system RSI of the macd histogram doesn't always extend to.

period := 5;
currentValue := MACDH3;
previousValue := REF(MACDH3, - 6);

settings adjusted to extend as high into the 90 zone as possible to eliminate flat spots at the same time limiting lag by having longer Previous Values.

Currently only using a single RSIMH3 for the trigger crossing 10 and 90 line for testing but have introduce 'longer trend' qualifier zones as per above MACDH1 rising filter.
until I examine the non trending zone triggers (of which some very oversold stocks can prove to be a profitable trades based on the RSIMH3 triggers alone).

The current RSIMH3 does trigger closer to the highs and lows when looking back over the chart of recent SPA3T triggered stocks.
Maybe too many close to each other signals, and some unnecessary ones too.

It's a bit hit and miss, but might improve when optimised by a better RSI code and inclusion of other RSIMH's in the code.

Cyan and Fuchsia diamond above and below are the trigger symbols.
Have also added candle conditions for a 'heads up' on the Moving Average scans I am now doing as they are proving to be not to shabby!

I'm waiting to see just how many chart overlays i can put onto the chart before memory limits are reached!



Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 29/05/2019, 02:57:18 PM
Hi John,

With the 1st formula from this post (pre-edit): http://www.sharewealthsystems.com/forum/index.php/topic,3526.msg16036.html#msg16036

The condition is that the 1st RSI has to be greater than 90 AND the 2nd RSI is crossing the value of 10 on the same bar. You are correct that the RSIs both work, but it looks like they oscilate between 0 and 1.

So a small tweak in the criteria gets the formula firing:

{ ---- Criteria ---- }
RSIMH1_UP := RSIMH1 >.9;
RSIMH3_X10 := cross(RSIMH3,.10);

You may have worked this out already it looks like.

With the formula duplication question in the edit - due to the way BCFL is the answer is no. You can put common elements in their OWN formula and then get the result of that formula as part of another.

ie this formula 1 called MACD1 in the left hand side Formula Explorer

{ ---- MACD 1 ---- }
MACD1:= mov(C, 120, E) - mov(C, 260, E);
MACD1sig := mov(MACD1, 90, E);
MACD1hist := (MACD1 - MACD1sig);

{ ---- RSIM Formula --- }
period := 5;
currentValue := MACD1hist;
previousValue := REF(MACD1hist, -5);
change := currentValue - previousValue;
Gain := if(cum(1) > period, sum(If(change>0, change, 0), period), 0);
Loss := if(cum(1) > period, sum(If(change<0, abs(change), 0), period), 0);
Avg_Gain := Gain / period;
Avg_Loss := Loss / period;
Avg_Change := if(Avg_Loss > 0, Avg_Gain / Avg_Loss, PREV);
RSIMH1 := 100-(100/(1+Avg_Change));
RSIMH1;

This is formula 2 called: MACD2

{ ---- MACD 2 ---- }
MACD2:= mov(C, 50, E) - mov(C, 100, E);
MACD2sig := mov(MACD2, 30, E);
MACD2hist := (MACD2 - MACD2sig);

{ ---- RSIM Formula --- }
period := 5;
currentValue := MACD2hist ;
previousValue := REF(MACD2hist, -5);
change := currentValue - previousValue;
Gain := if(cum(1) > period, sum(If(change>0, change, 0), period), 0);
Loss := if(cum(1) > period, sum(If(change<0, abs(change), 0), period), 0);
Avg_Gain := Gain / period;
Avg_Loss := Loss / period;
Avg_Change := if(Avg_Loss > 0, Avg_Gain / Avg_Loss, PREV);
RSIMH2 := 100-(100/(1+Avg_Change));
RSIMH2;

This is another formula that gets both of these * individual * formulas and plots their calculations.

{ New Formula }
RSI1 := FML("MACD1");
RSI2 := FML("MACD2");

RSI1;
RSI2;

The implications of this may be useful for using common calculations to shortern specific formulas (or multiple ones) and you only need to perform edits in a single place.
Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: JohnR on 30/05/2019, 06:39:10 PM
Linking formulas certainly broadens the scope for BCFL scanning etc., I was vaguely aware of this just have not put it into practice yet and something I will be looking into.

The RSI code implemented for the macd histogram is still giving me trouble; this time I was looking at getting a closer fit to the system 'RSI of macd histogram' and also see what a bar highlight colours would look like so started with two separate formulas for:
RSIMH1 > ref(RSIMH1, -1); and also
RSIMH1 < ref(RSIMH1, -1);

The above is for the coded RSI:
period := 5;
currentValue := MACDH1;
previousValue := REF(MACDH1, -1);

Assuming the System RSI has a *PreviousValue of -1 so have used that for this test.
MACDH1 used above is the histogram of MACD 120,260,90.

The results plotted as indicator don't look right at all, and seem to only fire when the RSIMH1 moves up slightly and then reversed down, firing in a binary fashion, unlike the system RSI of the macd histogram which has varying indexed levels. Although I am unable to test this due to not having a dotted line type to see where the points are located in the coded and system RSI lines, or being able to do a system profile of RSI of MACD 1 histogram.

As you mention before the coded RSI "it looks like they oscillate between 0 and 1".
The question remains why, and what can be done to fix the coded RSI to more resemble the System one?




Title: Re: FORMULA & INDICATOR SHARED LIBRARY
Post by: Campbell Sinclair on 31/05/2019, 03:38:00 PM
It's because of how the RSI is calculated and the constraints of how the language works.

BCFL is great for going one bar at a time and building indicators based on calculations, but the RSI is itself a 2 step calculation. You find the average up and down movements over the initial time period parameter, but then for each bar after the first say 14 days, you are recalculating both the up and down movements in different ways depending on the movement of that individual bar.

For instance say the initial averages have been done (step1 of the RSI formula).

On day 15 it is an up day:
Up movement average = method A: (Up Movements *  Period  ) + (Todays close - Yesterday close ) / Period
Down movement average = method B: (Down movements * Period) / Period

On day 16 it is a down day:
Up movement average = method B on this set
Down movement average = method A on this set

You cannot do this in BCFL as you cannot edit multiple variables based on what happens. You may be able to provide some very extensive IF conditioning to get there, but it is a departure in itself from how the first days are handled. BCFL has to repeat the script on every bar, which is where the implementation difficulties come in again because you can seperate the data involved in step 1 and step 2.

The full composition is outlined here: https://www.investopedia.com/terms/r/rsi.asp
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 03/06/2019, 01:18:21 PM
What about this pine script, I understand you have indicated short comings within BCFL in regards to the RSI, but if I can't get the rsi of macd's working here I may as well just use Trading View which does, with the addition of intra-day time frames.

Is there any hope of using a better code base for the RSI than the one you supplied, or is it simply a limitation of BCFL full stop.

I persist with the RSI of MACD Histogram and Main (RSIMH, RSIMM) because it doesn't produce over signalling like the MACD Histogram does for the faster period settings and the reaction time of the RSIM's is excellent for major turning points, can be related to O/B O/S indexed levels, and the RSIMH and RSIMM could very well be deployed as a System in BCFL. But until the RSI issues are resolved it remains hit and miss which is not good for an additional alert setup for optimised real money trading.

If BCFL had reference in Library for these built-ins could the RSI work? I.O.W. are the BCFL Library items within the C# area of the program?

Pine Script:
hist1 = macd histogram 1
rma, max, change & -min are Pine built-in functions

// ============== RSIMH 1 histogram ============== //

src1 = hist1, len = input(5, minval=1, title="Length")
up1 = rma(max(change(src1), 0), len)
down1 = rma(-min(change(src1), 0), len)
RSIMH1 = down1 == 0 ? 100 : up1 == 0 ? 0 : 100 - (100 / (1 + up1 / down1))


Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 04/06/2019, 03:42:23 PM
We can expand RSI to take parameters as I outlined initially, so that you can choose which data sets the BCFL RSI function is applied to instead of just the close - although this will be down the track once the development team completes their current business projects.

The BCFL Library are the pre-built functions, so it is the RSI in here that would be expanded.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 05/06/2019, 12:50:56 AM
OK, I'm thinking more along the lines of going long on some of the stronger looking scans and judging the state of the trend for BC daily data within TradingView's intra day time frame; 1 hour seems to work. This works much like a weekly data chart (long entry, exit) with taking signals on the daily data charts (short entry, exit).

The RSI of MACD histograms work well on the intra day charts, so will go with this for now, and it makes picking swing tops and bottoms much easier than relying on basing trades on signals generated on the previous days data, if the signal happened yesterday morning and the TM trade action takes place today at some point, the risk is the sell side on some stocks might look too thin today to place a direct price trade, forcing to sell down several price points to get the bulk of the order filled, or sit on the sell side with fingers crossed. Maybe I can pick the turning point clearer on the 1 hour chart data (see example images).

It will be a juggle to organise rapid turnover that SPA3-T, as well as my own scans, and to manage it all through the portfolio manager, but I've already started to go long on some of the New Entries and other scans ignoring system signals where they occur in strong trends to ride the trend until Moving Average, MACD2 and MACD1 loses momentum.

Re the formula for:
>mentioned in a few posts back was the short form formula:
"This is another formula that gets both of these * individual * formulas and plots their calculations."

{ New Formula }
RSI1 := FML("MACD1");
RSI2 := FML("MACD2");

RSI1;
RSI2;

If the MACD has 3 outputs (as indicator), how do you reference one or two of those outputs where;
saved formula title = MACD1:

{ ---- MACD 1 ---- }
MACDM1:= mov(C, 120, E) - mov(C, 260, E);
MACDS1 := mov(MACDM1, 90, E);
MACDH1 := (MACDM1 - MACDS1);
MACDM1;
MACDS1;
MACDH1;

In short form when calling the title name:

MACD1 := FML("MACD1");

but want a qualifier for MACDH1, MACDS1 and or MACDM1; does th short form automatically read all the outputs to put into the qualifying parameters?

QF1 := MACDM1 > MACDS1;
TRIG_UP := MACDH2 > REF(MACDH2, -1) and REF(MACDH2,-1) < REF(MACDH2,-2);


Thanks.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 05/06/2019, 02:51:34 PM
As long as you have a process outlined!

Volume depth for orders or liqudity at certain price points and the importance should be reconciled with the risk of waiting on the sidelines. We believe it is better to follow the defined exit signals for peace of mind alone than chasing price points, as any system with sufficient edge will reveal itself over time via execution of the process. The process being following the defined entry and exit signals that build towards that reseached edge.

As for the formula, you want the fmrvar() function.

input_A := fmlvar("MACD1", "MACDH1");

and the syntax is:

input_A := fmlvar("Formula Name", "Variable Name in Formula");
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 06/06/2019, 12:53:52 PM
Thanks for the formula.

Quote
Volume depth for orders or liqudity at certain price points and the importance should be reconciled with the risk of waiting on the sidelines.
Yes, am beginning to see this through practical experience; held IAG for this very reason (in fact a few stocks with thin buy sides), This is what is prompting me to use Trading View's intra-day time frames to spot any turning points, although it multiplies my workload.

I guess this is what happens when you get multiple trading systems all triggering sells at the same time = a rush for the exit doors! the herd following rules can alone move a stock considerably downward. Although IAG still in underlying trend I do expect from being so severely oversold a correction of sorts.


I have a question in regards to porting the Hull MACD over to BCFL and was wondering if the same RSI limitation in BCFL might effect this indicator (p.s. don't spend too much time on this):
Where round and sqrt = attached images. And obviously minus the plot lines.

{ ---- HULL MACD 1 ---- }
f_hma(_src, _length)=>
    _return = wma((2 * wma(_src, _length / 2)) - wma(_src, _length), round(sqrt(_length)))

len_fast1 = input(120, "Fast MA", minval=1)
len_slow1=input(260, "Slow MA", minval=1)
len_sig1=input(90, "Signal Length", minval=1)

fast_ma1 = f_hma(source, len_fast1)
slow_ma1 = f_hma(source, len_slow1)

MACDM1 = fast_ma1 - slow_ma1
MACDS1 = wma(MACDM1, len_sig1)
MACDH1 = MACDM1 - MACDS1

plot(MACDH1, style=histogram, linewidth=2,color=#2b77f2, transp=10)
plot(MACDM1, color=blue, linewidth=2)
plot(MACDS1, color=red, linewidth=2)

Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 06/06/2019, 03:51:54 PM
No not really - as the RSI is in effect a 2 part calculation, and inputs to the final calculation are updated differently depending on how the price action moves. This cannot be easily replicated in the style of language that BCFL is.

SQRT() and ROUND() are both Math functions that can be accessed in BCFL, which will provide senisble output given the input in to either is a number.

ie. SQRT(Round(20.5)); will give back 4.47.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 12/06/2019, 12:27:55 PM
Hi Campbell,
If the RSI is broken for BCFL I am wondering about using another indicator to take the MACD histograms data.

Are you able to list the BC indicators that will take another indicators values like the RSI and MACD to be used in BCFL?

Thanks.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 12/06/2019, 03:06:33 PM
Hi John,

The base language it is based off does not have this capability either, the functionality you are looking for just goes a little bit beyond what these languages do until we can naturally extend its base capabilities.

For what you have asked - look at the right hand side BCFL Library. This is a list of all the functions in BCFL and there's a dedicated indicator section.

Highlight the top indicator, then open the quick reference section (the book icon with the thunderbolt) at the top of the panel. This is the documentation for the indicators and it gives examples of what each function requires to operate.

An indicator with the DATA ARRAY syntax can take other indicators as an input to the calculation. This is also a great place to look to see how functions work when you come back to formulas in the future.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 14/06/2019, 05:47:14 PM
Is it possible to apply an output with: line, or histogram, or colour to an output entity?
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 18/06/2019, 12:31:20 PM
Hi Campbell, when you get some spares, could you give an idea if adding the MACD histogram to the ATR-TS input would be possible. As there is no BCFL ATR-TS code to review for DATA ARRAY syntax.

I'm thinking instead of routing the MACD histogram through the RSI for an indexed oscillator, it might be better to go directly onto price chart as an atr-ts type oscillator. The ATR-TS would signal when the MACD histogram long turns down from rising and visa-versa, or same done with the main macd line if the histogram was too sensitive, although the long 120, 260, 90 histogram should be ok.

I'm aware you don't like inputs, so can the first two lines be restructured to take the macd histogram (MACDH1) as the data source?

{MACDH1}
MACDH1:= fmlvar("MACD1", "MACDH1");

{ATR-TS}
atrper:=Input("ATR period :",1,100,14);
atrfact:=Input("ATR multiplication :",1,10,4.5);
loss:=atrfact*ATR(atrper);
ATR_TS_L :=
If(C>PREV AND Ref(C,-1)>PREV,
Max(PREV,C-loss),
If(C<PREV AND Ref(C,-1)<PREV,
Min(PREV,C+loss),
If(C>PREV,C-loss,C+loss)));
ATR_TS_L;

Or in fact the ATR-TS you posted earlier:

{ Trailing_Stop SIMPLE SMOOTHING }
ATR_smoother := MOV(ATR(1), 14, S);
up_atrfact:= 3;
dn_atrfact := 3;
up_loss:=up_atrfact*ATR_smoother;
dn_loss:=dn_atrfact*ATR_smoother;
trail:=
If(L>PREV AND Ref(L,-1)>PREV,
Max(PREV,L-dn_loss),
If(L<PREV AND Ref(L,-1)<PREV,
Min(PREV,L+up_loss),
If(L>PREV,L-dn_loss,L+up_loss)));
trail;

Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 18/06/2019, 01:59:21 PM
Is it possible to apply an output with: line, or histogram, or colour to an output entity?

Not 100% sure what you are looking for with the histogram, but colour is a per system component or per formula setting.

There are otherwise 2 ways to produce a line:

Hi Campbell, when you get some spares, could you give an idea if adding the MACD histogram to the ATR-TS input would be possible. As there is no BCFL ATR-TS code to review for DATA ARRAY syntax.

I'm thinking instead of routing the MACD histogram through the RSI for an indexed oscillator, it might be better to go directly onto price chart as an atr-ts type oscillator. The ATR-TS would signal when the MACD histogram long turns down from rising and visa-versa, or same done with the main macd line if the histogram was too sensitive, although the long 120, 260, 90 histogram should be ok.

I'm aware you don't like inputs, so can the first two lines be restructured to take the macd histogram (MACDH1) as the data source?

{MACDH1}
MACDH1:= fmlvar("MACD1", "MACDH1");

{ATR-TS}
atrper:=Input("ATR period :",1,100,14);
atrfact:=Input("ATR multiplication :",1,10,4.5);
loss:=atrfact*ATR(atrper);
ATR_TS_L :=
If(C>PREV AND Ref(C,-1)>PREV,
Max(PREV,C-loss),
If(C<PREV AND Ref(C,-1)<PREV,
Min(PREV,C+loss),
If(C>PREV,C-loss,C+loss)));
ATR_TS_L;

Or in fact the ATR-TS you posted earlier:

{ Trailing_Stop SIMPLE SMOOTHING }
ATR_smoother := MOV(ATR(1), 14, S);
up_atrfact:= 3;
dn_atrfact := 3;
up_loss:=up_atrfact*ATR_smoother;
dn_loss:=dn_atrfact*ATR_smoother;
trail:=
If(L>PREV AND Ref(L,-1)>PREV,
Max(PREV,L-dn_loss),
If(L<PREV AND Ref(L,-1)<PREV,
Min(PREV,L+up_loss),
If(L>PREV,L-dn_loss,L+up_loss)));
trail;

The ATR calculation part of the trailing stop are these lines:

ATR_smoother := MOV(ATR(1), 14, S);
up_atrfact:= 3;
dn_atrfact := 3;
up_loss:=up_atrfact*ATR_smoother;
dn_loss:=dn_atrfact*ATR_smoother;

It depends how you want the MACD to be integrated. The up_loss and dn_loss are the variables used in the final calculation of where the trailing stop line should sit. It is multiplying the smoothed ATR by the desired factor. 

You could use the MACD instead of the ATR_Smoother in the up_loss and dn_loss lines if you wanted to replace the ATR.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 23/06/2019, 01:26:03 PM
Hi Campbell,
The ATR-TS of the MACD histogram didn't work, it did produce an indicator but wasn't usable.
At this point I might move onto other indicator sets and just use the three MACD's and the RSI of the three histograms as a visual system, until the BC RSI gets an upgrade. I have this working in Trading View anyway with enough triggers to fill the screen and keep me busy.

What I have found mucking around with introduced indicators is a very solid setup that could potentially overtake my interest in the MACD as the primary indicator, especially the Histogram as this was always my indicator of interest for catching the tops and bottoms in trend; the new indicator set being two ATR trailing stops one set long and one set short and combined with a public domain (PD-SIROC) indicator for trading within the ATR-TS / MACD defined trend, of which I can setup in BCFL to give triggers and scans for.

I have found after four and a half months of using both SPA 3 systems in the test portfolios is that the Investor portfolio has substantially out performed the Trader one, in fact the Trader portfolio at this stage is a basket case, probably due to leaving trending stock to early on 21:8 Siroc cycles and then being directed to new trades that might go up briefly or might not then requiring draw downs into capital, of which there has been a few.

The two ATR-TS combination do an excellent job at defining clearly trend start points and end points, where the objective trading strategy could be to allocate capital for an initial entry via Trade Master portfolio manager and pyramid and lighten 50% additional $ trades off the PD-SIROC cycles triggers as this is what the Siroc excels at, and there will be the SPA3 Trader signals to follow as a back up; volatility stop exits etc. (I find the 13:5 better for the above purpose). This approach might get the trader portfolio to be more of a medium to longer term trend system, and will be combined with the RSC Index indicator, and Money Flow indicator.

What ever system I create to adopt will need to work with Trade Master, so the additional 50% $ Pyramid and Lighten phases get reported correctly. The stop loss final exit taken for the initial capital amount if not already lightened out of when the short ATR-TS indicates resistance, and when the long term ATR-TS triggers and MACD clearly loses momentum identifying end of primary trend conditions.

The objective strategy is to not completely exit the longer 'in the zone' trending stocks but allow the trade to run and utilise the trend to trade additional 50% dollar amounts if the stock displays in trend volatility enough for cycle trading off the PD-SIROC.


Problems with BCFL introduced indicators;
There are chart crashes when overlaying the SIROC signals for Main crossing Signal line, which I suspect are completely crashing BC, or are produce empty charts since introducing them.

Although not directly related to the above chart crashes you mentioned earlier about the code Inputs, so I would like to swap out the input lines with non inputs; with the following code is this possible to do as this is the preferred ATR-TS? (14, 4.5 being the inputs).

atrper:=Input("ATR period :",1,100,14);
atrfact:=Input("ATR multiplication :",1,10,4.5);
loss:=atrfact*ATR(atrper);
ATRTS_L :=
If(C>PREV AND Ref(C,-1)>PREV,
Max(PREV,C-loss),
If(C<PREV AND Ref(C,-1)<PREV,
Min(PREV,C+loss),
If(C>PREV,C-loss,C+loss)));
ATRTS_L;

I did try to do this myself but just messed the code up!
Thanks.

[EDIT]
In fact the crashes were related to the ATRTS chart signal alert symbol where I renamed the code output but didn't rename the fmlvar reference. Could there be some kind of error warning about this?
Also maybe a script list page that lists all the BCFL indicators, highlights and ribbons to be able to identify and remove non working BCFL coded entries?
Just a thought, would help error trouble shooting.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 25/06/2019, 05:36:22 PM
John,

Right now the public portfolio SPA3 Trader portfolios are sky rocketing for the ASX and USA. It comes with the territory of investment systems that the edge needs time to play out with mechanical ruleset, as each day is a new starting point for the portfolio with different entry oppertunities. There has also been a couple of sectors in the market that have done extremely well, which would be a boost to any portfolio that exposed themselves to those areas. This was covered by Gary in the most recent eUGM.

SPA TradeMaster can have trades inputted in to it manually out of system, so recording your transactions should not be a problem.

I am very glad you have the criteria almost down pat, given some work on our side as well.

To hard code the values it is quite simple, replace the input() function with the desired value:

atrper:=14;
atrfact:=4.5;
loss:=atrfact*ATR(atrper);
ATRTS_L :=
If(C>PREV AND Ref(C,-1)>PREV,
Max(PREV,C-loss),
If(C<PREV AND Ref(C,-1)<PREV,
Min(PREV,C+loss),
If(C>PREV,C-loss,C+loss)));
ATRTS_L;

As for the error - I will have a play around and raise it as a bug. From the sounds of it you had a working FMLVAR reference, but the variable name being referenced was changed, which caused the FMLVAR to break as it was already a successfully saved formula?
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 26/06/2019, 01:58:39 PM
Yes pat yourself on the head for the help Thanks!
Almost done with additional systems although not implemented in the way I originally planned, it will suffice for now. I wanted to get this done before the end of the FY as I want to start real money trading in July. The last 4.5 months ? (feels longer) has brought me up to speed with BCFL code structure for assembling formulas for indicators, scanning and chart overlays for alert signals etc. I could offer quite a few suggestions there for additional bells and whistles if you are stuck for imagination on improvements.

Re the "var" reference in formulas:
And yes that's right; if the formula output is variable is renamed no error is detected be the system (although not fully tested), but if the Title of the formula (fml) is renamed the system throws an error indicating the title change name is not present (in scans).

So if the chart is set up using a fmlvar with chart signals etc. and the referenced fmlvar ("1", "2"); output '2' name is changed the charts does terrible things and even crashes the program, and you have to guess what and where the change "var" was made. This is especially tricky as you may be working in another function key saved chart setup at the time, the changed 'var' comes back to back to bite you when you load the another chart setup, basically there is no error checking by the system to indicate what or where has gone wrong. This has happened more than once, I remember sending a crash report through to help desk there recently, I suspect this was the problem.

Gets even more tricky when you have 3 fmlvar's referenced in 5 or 6 different formulas as you lose track of where you have put the "fmlvar".

I think a formula style sheet could help, listing the loaded formulas in a chart and their status? similar to an AutoCad List pop up box that gives a text list readout of every entity in a loaded component assemble object, that you are trouble shooting.
Not sure how this could be applied to BCFL though or if this be the most efficient way of dealing with it.
Leave it with you, if you need more details let me know.

BTW is it faster for the BCFL system to load fmlvar's over having the referenced subject indicator code within the formula?
I ask because I've noticed since using the fmlvar's and or the new (3x) ATR-TS and (2x) SIROC's I have introduced a considerable slow down in loading charts, and when scanning, using the BCFL formulas, so it could be attributed to either using 'fmlvar's or the introduced indicators, or Input code in these indicators.

Thanks.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 27/06/2019, 01:12:20 PM
John,

From an execution point of view - the more data that has to be sifted through, the more time it will take to process. It may be worth condenscing formulas once everything is said and done on the build side of things.

Naming conventions and stability in leaving what is there would definitely help on the FMLVAR side of things, but I understand edits happen as you tinker away and this is a possibility. I keep a look out for it as I am looking in to your crashing.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 02/07/2019, 12:34:43 PM
Quote
condenscing formulas
Might have to be more specific re the condensing the formula for system speed with the reference indicator being in the formula or referenced via fmlvar syntax.

Sorry should have mentioned; the ATR-TS SuperTrend indicator, seems to be mostly the cause of the slow downs in scanning and chart loadings, maybe there is a more efficient way to code this one?

{ ---- ATR-TS SUPERTREND ---- }
atrper:= 14;
atrfact:= 9.5;
loss:=atrfact*ATR(atrper);
ATRTS_SUPT :=
If(C>PREV AND Ref(C,-1)>PREV,
Max(PREV,C-loss),
If(C<PREV AND Ref(C,-1)<PREV,
Min(PREV,C+loss),
If(C>PREV,C-loss,C+loss)));
ATRTS_SUPT;
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 02/07/2019, 12:51:57 PM
Re scanning to an event that occurred 34 days ago;
I'm looking at doing a scan for a pd-siroc turning up trigger that occurres within the last 34 days of an atr-ts crossing specifically.
I tried this; QF1 := CROSS(ATRTS_L, ATRTS_SUPT, -34);  but BCFL won't accept.

Full code here:
{ ---- ATR-TS ---- }
ATRTS_L := fmlvar("ATR-TS_LONG", "ATRTS_L");
ATRTS_S := fmlvar("ATR-TS_SHORT", "ATRTS_S");
ATRTS_SUPT := FMLVAR("ATR-TS_SUPERTREND", "ATRTS_SUPT");
{ ---- RSC INDEX MA X ---- }
RSC_MOV1 := FMLVAR("RSC INDEX","MOV1");
RSC_MOV3_SIG := FMLVAR("RSC INDEX","MOV3");
{ ---- SIROCS ----}
SIROC_MS := fmlvar("SIROC1_D SHORT", "SIROCM1");
ATRTS_SUPT := FMLVAR("ATR-TS_SUPERTREND", "ATRTS_SUPT");
{==================================}

TRIG_SIROC_SUP := SIROC_MS > REF(SIROC_MS, -1) and REF(SIROC_MS,-1) < REF(SIROC_MS,-2);
QF1 := CROSS(ATRTS_L, ATRTS_SUPT, -34);
QF2 := CLOSE > 0.05;
QF3 := RSC_MOV1 > RSC_MOV3_SIG;

SCAN_TRIG := TRIG_SIROC_SUP AND QF1 AND QF2 AND QF3;
SCAN_TRIG;

Thanks in advance :)
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 03/07/2019, 04:13:42 PM
Quote
condenscing formulas
Might have to be more specific re the condensing the formula for system speed with the reference indicator being in the formula or referenced via fmlvar syntax.

Sorry should have mentioned; the ATR-TS SuperTrend indicator, seems to be mostly the cause of the slow downs in scanning and chart loadings, maybe there is a more efficient way to code this one?

{ ---- ATR-TS SUPERTREND ---- }
atrper:= 14;
atrfact:= 9.5;
loss:=atrfact*ATR(atrper);
ATRTS_SUPT :=
If(C>PREV AND Ref(C,-1)>PREV,
Max(PREV,C-loss),
If(C<PREV AND Ref(C,-1)<PREV,
Min(PREV,C+loss),
If(C>PREV,C-loss,C+loss)));
ATRTS_SUPT;

No way ot make it more efficient unfortunately that will make any substantial difference, as it uses the self reference of the PREV statement. There seems to be a compounding from having a look myself in to what you have been doing. The more that is being computed, the longer it will take to collect that data and plot all the points. You can see this if you reduce the amount of data being loaded to a single formula ATR-TS on the chart or change the period from all data to 5 years and then try to move to the same chart in a watch list.

The previous suggestion was about making the formulas one long script, as I have seen evidence that can work in the past for speed, but maintainability of the scripts definitely becomes questionable and is not something I recommend usually.

Re scanning to an event that occurred 34 days ago;
I'm looking at doing a scan for a pd-siroc turning up trigger that occurres within the last 34 days of an atr-ts crossing specifically.
I tried this; QF1 := CROSS(ATRTS_L, ATRTS_SUPT, -34);  but BCFL won't accept.

Full code here:
{ ---- ATR-TS ---- }
ATRTS_L := fmlvar("ATR-TS_LONG", "ATRTS_L");
ATRTS_S := fmlvar("ATR-TS_SHORT", "ATRTS_S");
ATRTS_SUPT := FMLVAR("ATR-TS_SUPERTREND", "ATRTS_SUPT");
{ ---- RSC INDEX MA X ---- }
RSC_MOV1 := FMLVAR("RSC INDEX","MOV1");
RSC_MOV3_SIG := FMLVAR("RSC INDEX","MOV3");
{ ---- SIROCS ----}
SIROC_MS := fmlvar("SIROC1_D SHORT", "SIROCM1");
ATRTS_SUPT := FMLVAR("ATR-TS_SUPERTREND", "ATRTS_SUPT");
{==================================}

TRIG_SIROC_SUP := SIROC_MS > REF(SIROC_MS, -1) and REF(SIROC_MS,-1) < REF(SIROC_MS,-2);
QF1 := CROSS(ATRTS_L, ATRTS_SUPT, -34);
QF2 := CLOSE > 0.05;
QF3 := RSC_MOV1 > RSC_MOV3_SIG;

SCAN_TRIG := TRIG_SIROC_SUP AND QF1 AND QF2 AND QF3;
SCAN_TRIG;

Thanks in advance :)

CROSS only accepts 2 arguments - CROSS(what I want to see cross over something else, the something else)

As I think you are looking within 34 days, BARSSINCE(Cross(ATRTS_L, ATRTS_SUPT) < 34 may be the statement you are looking for. As we utalise a vector / data array based language, this will not return something if it never actually happened to start counting from.

BARSSINCE() is literally counting the number of bars since an event occured. It cannot give a number if it never happened. IsDefined() is a function that checks to see if a statement is giving back a number or not.

So from that knowledge, you can do something like this in the situation:

Test := IF(ISDEFINED(BARSSINCE(Cross(ATRTS_L, ATRTS_SUPT)), BARSSINCE(Cross(ATRTS_L, ATRTS_SUPT) < 34, 0);

The variable Test will give back 1 for Yes, it happened in the last 34 days, or 0 for no it did not.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 06/07/2019, 07:54:59 PM
Thanks for coding that up, it could be the trick.

BCFL won't save with -> Missing bracket ')'
I've been over it a number of times adding brackets here and there to close the argument but BCFL resists my efforts and finally returns:
-> BARSSINCE function has invalid number of arguments.

When you have a spare 5 could you take another look please.

Cheers.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 09/07/2019, 02:31:58 PM
Hi John,

My apologies! There were a couple missing.

Test := IF(ISDEFINED( BARSSINCE( Cross(ATRTS_L, ATRTS_SUPT) ) ), BARSSINCE(Cross(ATRTS_L, ATRTS_SUPT) < 34, 0 ));
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 11/07/2019, 04:09:16 PM
This must be especially tricky for BCFL as the compiler returned this:

QF1 := IF(ISDEFINED( BARSSINCE( Cross(ATRTS_L, ATRTS_SUPT) ) ), BARSSINCE(Cross(ATRTS_L, ATRTS_SUPT) < 34, 0 ));

-> BARSSINCE function has invalid number of arguments
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 12/07/2019, 09:38:32 AM
Correct amount of brackets but my placement of 1 was wrong side of the 0 to complete the IF. Sorry about the delay.

QF1 := IF( ISDEFINED( BARSSINCE( Cross(ATRTS_L, ATRTS_SUPT))), BARSSINCE( Cross(ATRTS_L, ATRTS_SUPT) < 34), 0);
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 13/07/2019, 10:53:01 AM
Thanks, quite happy to wait as this line of code would have taken me several years, like the proverbial hundred monkeys on keyboards, to work out myself! it's quite a valuable string that I will refer to a fair bit.
BTW  what does the zero do at the end there? or does this explain that: "The variable Test will give back 1 for Yes, it happened in the last 34 days, or 0 for no it did not"

To test the code (below) is working I set up two scans for 1971 FPO stocks;
When I run  the IsDefined code with the moving average crossing signal, with scan Settings Period set to 1 by default; BCFL doesn't get past Initialise.
Same when run the above IsDefined code with scan Settings Period 34.

When I run the crossing code alone (green text within parenthesis) and scan Period set to 34 days; I get 204 hits from 1971 (FPO), hopefully meaning there were 204 crossings of the MA signal line in last 34 days, some being duplicate stocks.

I assume this is the best way to test the IsDefined code is working, and both scans should return the same number of crossings?

Have run a few different scans and none produced any hits, so I assume the IsDefined code either isn't working or isn't deployed within the scan correctly.

MAM1 := fmlvar("MA 60:90", "MAM1");
MAS1 := fmlvar("MA 60:90", "MAS1");

{MA1_CROSS := cross(MAM1, MAS1);}
MA1_CROSS := IF( ISDEFINED( BARSSINCE( Cross(MAM1, MAS1))), BARSSINCE( Cross(MAM1, MAS1) < 34), 0);
{TRIG_SUP := SIROC_SM > REF(SIROC_SM, -1) and REF(SIROC_SM,-1) < REF(SIROC_SM,-2);}

SCAN_TRIG := MA1_CROSS;
SCAN_TRIG;

So next up is to include the IsDefined code as a qualifier to find the (open source) Siroc indicator turning up within the 34 day period after the Moving Average main crosses the signal line, with Scan Settings Period set to 1:

MAM1 := fmlvar("MA 60:90", "MAM1");
MAS1 := fmlvar("MA 60:90", "MAS1");

SIROC_SM := fmlvar("SIROC1_D SHORT", "SIROCM1");
SIROC_SS := fmlvar("SIROC1_D SHORT", "SIROCS1");

QF1 := IF( ISDEFINED( BARSSINCE( Cross(MAM1, MAS1))), BARSSINCE( Cross(MAM1, MAS1) < 34), 0);

TRIG_SUP := SIROC_SM > REF(SIROC_SM, -1) and REF(SIROC_SM,-1) < REF(SIROC_SM,-2);

SCAN := TRIG_SUP  and QF1;
SCAN;

After initialisation the scan gets to 3 of 1971 1AG: Altera Limited; and freezes there for some reason.
So conclude the IsDefined code is problematic, unless deployed incorrectly.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 15/07/2019, 04:45:11 PM
Thanks, quite happy to wait as this line of code would have taken me several years, like the proverbial hundred monkeys on keyboards, to work out myself! it's quite a valuable string that I will refer to a fair bit.
BTW  what does the zero do at the end there? or does this explain that: "The variable Test will give back 1 for Yes, it happened in the last 34 days, or 0 for no it did not"

Correct. It is all part of the IF statement: IF(This happens to be true, do this, else do this). The 0 is the "else do this part".

To test the code (below) is working I set up two scans for 1971 FPO stocks;
When I run  the IsDefined code with the moving average crossing signal, with scan Settings Period set to 1 by default; BCFL doesn't get past Initialise.
Same when run the above IsDefined code with scan Settings Period 34.

When I run the crossing code alone (green text within parenthesis) and scan Period set to 34 days; I get 204 hits from 1971 (FPO), hopefully meaning there were 204 crossings of the MA signal line in last 34 days, some being duplicate stocks.

I assume this is the best way to test the IsDefined code is working, and both scans should return the same number of crossings?

Have run a few different scans and none produced any hits, so I assume the IsDefined code either isn't working or isn't deployed within the scan correctly.

You are halfway there with the comparison.

You are correct that 204 hits with MA1_CROSS means 204 crosses occured. What the IF statement is doing is asking how many days since the cross occured.

So to test IsDefined itself, you have to see what ISDEFINED( BARSSINCE( Cross(MAM1, MAS1) ) is doing. That is the pivot of the IF statements decision making, which Cross is a part of.

If you can pass through the code for MAM1 and MAS1 I will be able to take a further look at what is causing the freeze in the scan.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 16/07/2019, 11:36:39 AM
Moving Average code :
{---- My Moving Average of MACD1 ---- }
MAM1 := MOV(CLOSE, 60, E);
MAS1 := MOV(MAM1, 90, E);
MAM1;
MAS1;

BTW been meaning to ask about the indicator smoothing options:
SMOOTHING:  - EXPONENTIAL[E], WEIGHTED[W], TIMESERIES[T], TRIANGULAR[TRI], VOLUMEADJUSTED[VOL]

Is there a smoothing option for Moving Average Variable as per the indicator lists? tried V & VAR but didn't take.

Thanks.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 18/07/2019, 02:29:28 PM
It looks like a bug has cropped back in to IsDefined(), it looks like it is crashing when events that have not happened (so there is no data to process). Currently talking to the developers about it and what can be done about it as well.

As for the variance MOV - we do not have it as a present MOV option within the MOV function. It is a bit more complicated than that and does not really necessarily need a period setting as it reacts based off a given volatility ratio of a stock.

This will get the same result as the hardcoded indicator with this:

{ Variable Moving Avg }
Check_CMO := CMO(C, 9);
New_CMO := Check_CMO / 100;
Final_CMO := if(New_CMO < 0, -1 * New_CMO, New_CMO);
VMA := (Final_CMO * C) + (1 - Final_CMO) * PREV;
VMA;
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 29/07/2019, 12:23:38 PM
Ok moving on, there is a TradingView indicator called a variable moving average that I would like to implement as a stand alone indicator and as the basis for other indicators.
I have sifted through and added the required syntax punctuation etc. but there is one embedded Pine reference that I'm struggling with at this point; the nz built in function as follows from Pine script language reference manual:
nz
Replaces NaN values with zeros (or given value) in a series.
nz(x, y) → integer
nz(x, y) → float
nz(x, y) → color
nz(x, y) → bool
nz(x, y) → series[integer]
nz(x, y) → series[bool]
nz(x, y) → series[color]
nz(x, y) → series
nz(x) → color
nz(x) → bool
nz(x) → integer
nz(x) → float
nz(x) → series[integer]
nz(x) → series[bool]
nz(x) → series[color]
nz(x) → series
EXAMPLE
nz(sma(close, 100))
RETURNS
Two args version: returns x if it's a valid (not NaN) number, otherwise y
One arg version: returns x if it's a valid (not NaN) number, otherwise 0
ARGUMENTS
x (series) Series of values to process.
y (float) Value that will be inserted instead of all NaN values in x series.

Original TradingView script:

src=close
len2 = input(10, title = "VMA 2 Length")
std2 = input(true, title = "Show Trend Direction")
bc2 = input(false, title = "Color bars based on Trend")
showVMA2 = input(true, title="Show VMA 2?")
k2 = 1.0/len2
pdm2 = max((src - src[1]), 0)
mdm2 = max((src[1] - src), 0)
pdmS2 = ((1 - k2)*nz(pdmS2[1]) + k2*pdm2)
mdmS2 = ((1 - k2)*nz(mdmS2[1]) + k2*mdm2)
s2 = pdmS2 + mdmS2
pdi2 = pdmS2/s2
mdi2 = mdmS2/s2
pdiS2 = ((1 - k2)*nz(pdiS2[1]) + k2*pdi2)
mdiS2 = ((1 - k2)*nz(mdiS2[1]) + k2*mdi2)
d2 = abs(pdiS2 - mdiS2)
s12 = pdiS2 + mdiS2
iS2 = ((1 - k2)*nz(iS2[1]) + k2*d2/s12)
hhv2 = highest(iS2, len2)
llv2 = lowest(iS2, len2)
d12 = hhv2 - llv2
vI2 = (iS2 - llv2)/d12
vma2 = (1 - k2*vI2)*nz(vma2[1]) + k2*vI2*src
//vam line colour
vmaL2=(vma2 > vma2[1]) ? lime : (vma2<vma2[1]) ? red : (vma2==vma2[1]) ? white : red
plot(showVMA2 and vma2 ? vma2 : na, color=std2 ? vmaL2 : aqua, style=line, linewidth=2, transp=0, title="VMA-1")

My efforts to convert script to BCFL:

{--------------- Variable Moving Average ---------------}
src:=close;
len := 10;
k := 1.0/len;
pdm := max((src - src,-1), 0);
mdm := max((src,-1 - src), 0);
pdmS := ((1 - k)*nz(pdmS,-1) + k*pdm);
mdmS := ((1 - k)*nz(mdmS,-1) + k*mdm);
s := pdmS + mdmS;
pdi := pdmS/s;
mdi := mdmS/s;
pdiS := ((1 - k)*nz(pdiS,-1) + k*pdi);
mdiS := ((1 - k)*nz(mdiS,-1) + k*mdi);
d := abs(pdiS - mdiS);
s1 := pdiS + mdiS;
iS := ((1 - k)*nz(iS,-1) + k*d/s1);
hhv := highest(iS, len);
llv := lowest(iS, len);
d1 := hhv - llv;
vI := (iS - llv)/d1;
vma := (1 - k*vI)*nz(vma,-1) + k*vI*src;
vma;

Take your time no hurry.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 30/07/2019, 11:47:50 AM
Hey John,

Can you please post an attachment of what that indicator should look like for comparison purposes as well?
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 01/08/2019, 03:49:53 PM
Image attached in above post.

Re the IsDefined() bug; when I look at the scan criteria settings there is an option for Time Frame > Type, the drop down box lists three options, if Specific Period selected and last 34 day date range chosen, and the scan trigger is for an event like a cross(x,y) would this produce the same results as the IsDefined() code?
Granted the the date range would have to be continually adjusted for the 34 day period so prefer to be using the BCFL code that would be more a running 34 day period if this is correct.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 01/08/2019, 04:18:39 PM
Period is strictly how many bars the scan should be applied on based on the data mode and period type. A Period type of 5 with Data Mode Day and Period Type Day will mean it will scan over the last 5 bars of every chart provided to the scan.

Key point is that it's totally seperate to what a scan actually looks for, it is just extending the processing and lookback time of the criteria.

I have a file that will extend RSI and fix IsDefined for you sitting on my computer that I was given late yesterday. I just need to squeeze out the time to test it properly before I am happy to give you the fix in advance (I'll probably call you directly when it's ready), which will be widly distributed with the next full release of Beyond Charts.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 05/08/2019, 06:55:27 PM
Ok then back to RSI's and MACD's,
I have found a couple of oscillators that sync well with the MACD short, not perfect they all seem to lag and want to cycle downward mid trend making them very frustrating to configure, thus the focus on the RSI to handle the MACD longer trend cycles.

I note the system SIROC trends well with price action over prolonged trend periods, the only oscillator I have found to do similar is the RSI III with Wilder and ROC in the formula.
 
I do have another RSI on my to do list for BCFL, and have been searching the Metastock websites for something similar with no luck just yet.

The indicator is from Incredible Charts and I believe is one of the better RSI's out there, formula is not available on the I.C. website so will post an image for comments.
Called the 'Smoothed RSI' with Wilder smoothing (see image), it stays high with a trending stock.

I think when combined with the MACD histogram set it might produce competitive indicators.
Would it be possible to incorporate the Smoothed RSI with Wilder smoothing into the new work being done with the BCFL RSI release, or even better for coding off, recommend a similar RSI code?
Thanks.


Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 06/08/2019, 03:45:45 PM
Hi John,

I am happy with the fixes. I will contact you directly this afternoon via email about starting to hand these to you as a once off as they are relevant to what you are doing, until the next Beyond Charts release goes wider.

To give a preview, this is what a formula will look like. The RSI has an optional DATA ARRAY parameter. So RSI(14) will still work, but the RSI will be applied on a data array (like the MACD in this example) if it is given one.

{ ---- MACD1 ---- }
MACD1:= mov(C, 260, E) - mov(C, 120, E);
MACD1sig := mov(MACD1, 90, E);
MACD1hist := (MACD1sig - MACD1);

{ ---- RSI (MACD Histogram) ---- }
RSIM_out := RSI(MACD1hist, 14);

{ ---- MACD1hist  crosses above 50 mid line ---- }
RSIM_X := cross(RSIM_out, 50);

{ ---- Output to Scan Engine ---- }
{RSIM_out;}
{RSIM_out output is to compare with MACD with RSI applied from indicators panel}
RSIM_X;

For the Welles Wilder smoothing - Welles Wilder smoothing which can be found in the indicators panel and applied on top of the BCFL output.

As for the previous VMA - it looks like it is filling in the blanks for data series, which BCFL does not support.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 08/08/2019, 12:04:34 AM
Firstly the RSI with Wilder's Smoothing, I have attempted to do the indicator overlay onto the standard RSI the result is not nearly as clean as the I.C. one. So I tried to code it up in BCFL the result also isn't nearly as similar. Could there be additional code elements to this one? I would very much like to have this one in BC/FL code.
See attached image and my attempt code, lower panel is the code below:

{ RSI with Wilders Smoothing }
RSI_M:= rsi( 14 );
WSMA:= wilders(RSI_M, 14);
WSMA

Secondly; Re the Variable MA, I did find a similar one called Adaptive Zone Indicator in metastock code as shown in the top panel of attached chart. So will go with this for now:

{Adaptive Zones Indicator #1}
Per1:=Input("lookback",10,100,60);
Perc1:=Input("percent uband",.800,.999,.950);
Perc2:=Input("percent lband",1.01,1.2,1.05);
UB:=Ref((HHV(P,Per1)*Perc1),-1);
LB:=Ref((LLV(P,Per1)*Perc2),-1);
MB:=Ref((UB+LB)*.5,-1);
UB;
MB;
LB;

Thirdly; I wasn't expecting any action on the RSI until after next sw iteration delivered next year, so will be good to get that RSIMh nutted out after all the recent indicator code experimenting Iv'e been doing I still rely on the MACD and RSI overlay set as the default indicator reference. Is it just me that sees the RSIM potential?
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 09/08/2019, 03:07:52 PM
IF there is more too it, unfortunately we will not be able to replicate without knowing exactly how it is calculated - which could be IP that is not publicly accessible.

Saying that, the general shape comparison does look better using a smooth RSI of a MACD from the quick look I have had.

As for the potential query. Investors go through discovery and fine tuning at different times, the level of interest at any given time for an area can be subjective. We are always happy to try assist where we can, but our core systems with perhaps a tweak or two are generally fine for most. At some point execution has to be the focus to make the ROI of your time learning & researching worthwhile, where people settle at is different for all.

Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 10/08/2019, 11:34:37 AM
Re post 'happy with the fixes';
To condense the RSI formula you had posted to present syntax works:

MACDH3 := FMLVAR("MACD3","MACDH3");
RSIM3_out := RSI(MACDH3, 14);
RSIM3_X50 := cross(RSIM3_out, 50);
RSIM3_X50;

But when I add the Quick Reference Relative Strength Index syntax as displayed:
SYNTAX                    rsi(DATA ARRAY, PERIODS )
EXAMPLE                  rsi( 21 ), rsi(OPEN, 21)

as follows:
MACDH3 := FMLVAR("MACD3","MACDH3");
RSIM3_out := RSI(5),RSI(MACDH3, 14);
RSIM3_X50 := cross(RSIM3_out, 50);
RSIM3_X50;

produces this:
-> There is no function defined. Please define your function with valid arguments
Not sure why the BCFL QR doesn't work, it would be a treat to have RSI double smoothing, if that was the intention.

Which leads me to ask why there are no inbuilt smoothings for the system RSI unlike other indicators tha have a selection of 5 or so, where the Wilders Smoothing could be applied better than I have done in my attempt to code it off the system RSI. Just one more tweak please?
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 12/08/2019, 10:47:57 AM
A question in regards to cleaning out watch lists; would there be a suitable code sequence to delete (as opposed to add to) from watch lists stocks that have exceeded there 'use by' date?
Manually deleting stocks could be a slow process, although do-able once a filter is set up.
It might require an addition to the right click select action to delete from 'selected watch list'  after bulk selecting from a scan window.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 12/08/2019, 04:46:59 PM
Re post 'happy with the fixes';
To condense the RSI formula you had posted to present syntax works:

MACDH3 := FMLVAR("MACD3","MACDH3");
RSIM3_out := RSI(MACDH3, 14);
RSIM3_X50 := cross(RSIM3_out, 50);
RSIM3_X50;

But when I add the Quick Reference Relative Strength Index syntax as displayed:
SYNTAX                    rsi(DATA ARRAY, PERIODS )
EXAMPLE                  rsi( 21 ), rsi(OPEN, 21)

as follows:
MACDH3 := FMLVAR("MACD3","MACDH3");
RSIM3_out := RSI(5),RSI(MACDH3, 14);
RSIM3_X50 := cross(RSIM3_out, 50);
RSIM3_X50;

produces this:
-> There is no function defined. Please define your function with valid arguments
Not sure why the BCFL QR doesn't work, it would be a treat to have RSI double smoothing, if that was the intention.

Which leads me to ask why there are no inbuilt smoothings for the system RSI unlike other indicators tha have a selection of 5 or so, where the Wilders Smoothing could be applied better than I have done in my attempt to code it off the system RSI. Just one more tweak please?

2 Seperate examples. I'll feed that back to the developers to make it clearer. Per my post you can use RSI(14) or RSI(C, 14), so that formulas that currently will be using RSI(14) or RSI(21) do not break. There is no reason to use RSI(5),RSI(MACDH3, 14); as RSI() is a function call in itself. 

Not all indicators have smoothing, only 4 to 5 of them do depending how you look at the seperate bollinger band functions and none of those have Wilders available as an option inside BCFL itself, so it would be totally new functionality instead of a tweak.

I do believe the expanded RSI(data array, period) syntax has an issue being directly embedded in to another function like Wilders at the moment.

Although Wilders smoothing is similar to the result of an (2*n-1) EMA and is commonly used as the input to the calculation instead of smoothing the end product. For 5 days of wilder you can use a 9 day EMA on the inputs to the RSI itself to achieve wilder smoothing.

A question in regards to cleaning out watch lists; would there be a suitable code sequence to delete (as opposed to add to) from watch lists stocks that have exceeded there 'use by' date?
Manually deleting stocks could be a slow process, although do-able once a filter is set up.
It might require an addition to the right click select action to delete from 'selected watch list'  after bulk selecting from a scan window.

It is best to send technical issues like this to support@sharewealthsystems.com so we can easily track the amount that come through to an area - it contributes to the prioritisation of the next release.

You can delete stocks from a data sheet by highlighting the rows (SHIFT for a block or use ALT to click individual rows) then hitting the delete key on the keyboard which is quicker than a right click menu option once you are used to it.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 16/08/2019, 12:25:41 AM
Quote
Not all indicators have smoothing, only 4 to 5 of them do depending how you look at the seperate bollinger band functions

Bollinger Band functions is something I wasn't expecting in relation to indicator smoothings, could you elaborate on how the BB apply to the indicators with the optional smoothing?
Thanks.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 16/08/2019, 04:23:30 PM
Bollinger Bands consist of 2 functions: top band and bottom band. These are some of the few that use smoothing as part of the parameters.

bbandbot(<DATA ARRAY>, <PERIOD> , <SMOOTHING>, <DEVIATIONS>)
bbandtop(<DATA ARRAY>, <PERIOD> , <SMOOTHING>, <DEVIATIONS>)

Only a few BCFL functions have in-built smoothing options as part of their calculation.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 29/08/2019, 05:07:11 PM
Hi Campbell,
I have an interesting dilemma working out how to produce a component from another indicator (BCFL).
The indicator I have made is a free panel ATR-TS and wc() for the price line both contained in the second lower panel in one BCFL formula:

{ATRTS_L FOR RSI}

atrper:=14;
atrfact:=4.5;
loss:=atrfact*ATR(atrper);
ATRTS_L := If(C>PREV AND Ref(C,-1)>PREV, Max(PREV,C-loss), If(C<PREV AND Ref(C,-1)<PREV, Min(PREV,C+loss), If(C>PREV,C-loss,C+loss)));
{MAIN_L := MOV(ATRTS_L, 1, W);}
PRICE_L :=  wc();

ATRTS_L;
{MAIN_L;}
PRICE_L;


And then I have made another BCFL indicator for the RSI of the above indicator to oscillate the components, (not sure why just want to see how it looks, and it looks like a neat way to judge interim short term highs and lows in relation to the longer term ATRTS levels when combined with a shorter term ATRTS), but cannot for the life of me get the wc() line to look similar to the PRICE_L := wc(); line where it moves across the ATRTS line:


{ RSI OF ATRTS }

IN1 := FMLVAR("ATRTS_L FOR RSI","MAIN_L");
IN2 := FMLVAR("ATRTS_L FOR RSI","PRICE_L");

MAIN_L := RSI(IN1, 14);
PRICE_L := RSI(IN2,14);

MAIN_L;
PRICE_L;


What I get after multiple attempts is an RSI of the wc() independent of the ATRTS_L line; see image attached (two lower panels):
Could you offer suggestions please?

Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 30/08/2019, 11:09:47 AM
Hi John,

The outcome in this instance will be the outcome. There is no way to edit the output of a calculation without editing the inputs that are part of the calculation, or adding or subtracting other variables.

In this case you are osscilating two independant variables... they will not overlap nicely in every instance.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 30/08/2019, 12:50:20 PM
Was hoping to get the RSI of the ATRTS working, There must be a way to fix both independent variables prior to outcome. You notice I used {MAIN_L := MOV(ATRTS_L, 1, W);} so might go back and implement this as the price line and try a few swap-a-rounds. I have rem'd it out for some reason not sure why now.

Another more important problem I'm facing is getting the RSIMH's to oscillate as per the MACD trend state; IOW: macd > signal the rsimh oscillates above 50 mid line, and macd < signal rsimh oscillates bellow 50 mid line, . A bit like fixing the macd signal line to the rsi 50 mid line.
 
Can you offer any insights here or direct me to another indicator that oscillates like this.

Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 30/08/2019, 02:04:38 PM
John,

We are happy to offer assistance with how to turn concepts in to BCFL where possible or explain why certains results come out, but suggesting the indicators and ideas for BCFL we leave to our users and the plethora of third party investment sites. Investopedia.com is probably the most popular for finding technical indicators.

To make a system can take many, many 1000s of hours and it is just outside the current scope of the business. Our Research and Developement team are dedicated with researching SPA3 and testing different ideas.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 30/08/2019, 04:15:26 PM
The upper  and downer oscillations of the  RSI mid line is the extension of the RSIMH I have been working on, and due to not being able to get a clean trending reading from the RSIMH group implementation I'm now looking to split the rsi oscillation between the above 50 for macd 100,50,30 main above signal, so that when the trend flips (up) in the macd indicator the rsi will report a crossing above the rsi 50 mid line giving a clear unambiguous signal.
So macd histogram values above the 50 line (macd main above signal) will vary from 50 to 100, I have noticed that the general height of macd main above signal line do not exceed an average value, observed in many stocks. So the value is definable of the oscillations of the RSI from 50 to 100. I just need a snippet of formula code to get started, which was my request to point me in the right direction for a cut n paste scrap.

To my thinking it would require the rsi 0 to 100 index to be subdivided in two an re expressed as 0 to 50 as -0 to -100 (macd main< signal ) and 50 to 100 as +0 to +100 (macd main > signal) for the rsi of the macd histogram to work within. But my formula expression building ability is limited to cut n paste from other indicator code to experiment with. Do you think the above explanation will work as a formula?

I've been through the many meta stock sites but as yet are unable to locate above formula description.
One formula I am looking at is the Moving Average Oscillator, but need to re express it through the macd histogram output in the RSI of the macd histogram :confused:
What I need is a Qudro indexed rsi :ehh:

maybe I'm over thinking this?
I mean already I'm dealing with the following MACD states plus four 6x2 additional rsi macd histogram states, why would I want to add another 4 rsi states??

MACDM1 := FMLVAR("MACD1","MACDM1");
MACDS1 := FMLVAR("MACD1","MACDS1");
MACDH1 := FMLVAR("MACD1","MACDH1");

MACDM2 := FMLVAR("MACD2","MACDM2");
MACDS2 := FMLVAR("MACD2","MACDS2");
MACDH2 := FMLVAR("MACD2","MACDH2");

MACDM3 := FMLVAR("MACD3","MACDM3");
MACDS3 := FMLVAR("MACD3","MACDS3");
MACDH3 := FMLVAR("MACD3","MACDH3");

{MACD STATES}
{MACD_1 -  RISING / FALLING}
MACDM1_UP := MACDM1 > REF(MACDM1, -1);
MACDM1_DN := MACDM1 < REF(MACDM1, -1);

{MACD_2 -  RISING / FALLING}
MACDM2_UP := MACDM2 > REF(MACDM2, -1);
MACDM2_DN := MACDM2 < REF(MACDM2, -1);

{MACD_3 -  RISING / FALLING}
MACDM3_UP := MACDM3 > REF(MACDM3, -1);
MACDM3_DN := MACDM3 < REF(MACDM3, -1);

{MACD STAGES }
{MACD_1 ABOVE ZERO - POSITIVE & NEGATIVE}

MACDM1_A0_UP1 := MACDM1_UP and MACDM1 > 0 and MACDM1 > MACDS1;
MACDM1_A0_DN1 := MACDM1_DN and MACDM1 > 0 and MACDM1 > MACDS1;
MACDM1_A0_UP2 := MACDM1_UP and MACDM1 > 0 and MACDM1 < MACDS1 ;
MACDM1_A0_DN2 := MACDM1_DN and MACDM1 > 0 and MACDM1 < MACDS1;

{MACD_1 BELOW ZERO - POSITIVE & NEGATIVE}
MACDM1_B0_UP1 := MACDM1_UP and MACDM1 < 0 and MACDM1 > MACDS1;
MACDM1_B0_DN1 := MACDM1_DN and MACDM1 < 0 and MACDM1 > MACDS1;
MACDM1_B0_UP2 := MACDM1_UP and MACDM1 < 0 and MACDM1 < MACDS1;
MACDM1_B0_DN2 := MACDM1_DN and MACDM1 < 0 and MACDM1 < MACDS1;

{MACD_2 ABOVE ZERO - POSITIVE & NEGATIVE}
MACDM2_A0_UP1 := MACDM2_UP and MACDM2 > 0 and MACDM2 > MACDS2;
MACDM2_A0_DN1 := MACDM2_DN and MACDM2 > 0 and MACDM2 > MACDS2;
MACDM2_A0_UP2 := MACDM2_UP and MACDM2 > 0 and MACDM2 < MACDS2;
MACDM2_A0_DN2 := MACDM2_DN and MACDM2 > 0 and MACDM2 < MACDS2;

{MACD_2 BELOW ZERO - POSITIVE & NEGATIVE}
MACDM2_B0_UP1 := MACDM2_UP and MACDM2 < 0 and MACDM2 > MACDS2;
MACDM2_B0_DN1 := MACDM2_DN and MACDM2 < 0 and MACDM2 > MACDS2;
MACDM2_B0_UP2 := MACDM2_UP and MACDM2 < 0 and MACDM2 < MACDS2;
MACDM2_B0_DN2 := MACDM2_DN and MACDM2 < 0 and MACDM2 < MACDS2;

{MACD_3 ABOVE ZERO - POSITIVE & NEGATIVE}
MACDM3_A0_UP1 := MACDM3_UP and MACDM3 > 0 and MACDM3 > MACDS3;
MACDM3_A0_DN1 := MACDM3_DN and MACDM3 > 0 and MACDM3 > MACDS3;
MACDM3_A0_UP2 := MACDM3_UP and MACDM3 > 0 and MACDM3 < MACDS3;
MACDM3_A0_DN3 := MACDM3_DN and MACDM3 > 0 and MACDM3 < MACDS3;

{MACD_3 BELOW ZERO - POSITIVE & NEGATIVE}
MACDM3_B0_UP1 := MACDM3_UP and MACDM3 < 0 and MACDM3 > MACDS3;
MACDM3_B0_DN1 := MACDM3_DN and MACDM3 < 0 and MACDM3 > MACDS3;
MACDM3_B0_UP2 := MACDM3_UP and MACDM3 < 0 and MACDM3 < MACDS3;
MACDM3_B0_DN2 := MACDM3_DN and MACDM3 < 0 and MACDM3 < MACDS3;

In fact, I will not be going down "the comprehensive system rabbit hole", but simply using a MA60:90 or MACD 120,260,90 above signal and above zero line, and not bother with any other variations of the states. KISS is the example you have set with SWS SPA3 Trader, although maybe a bit too generalised i.e. far too may moderate to even trades making it a full time job watching to see if they look like turning into limp biscuits, but what does make the SPA3 system work is the 'trade with the pack' approach that seems to help after day or two. Maybe I'm reflecting on a very difficult period to trade when so many sectors are high risk? and nothing seems to be moving.

I might add; it's all very good selling a long term approach to investments like 20 year future equity curve time frame approach to a portfolio, but if you are looking at retirement down the barrel (and who isn't) with smallish superannuation then you really need to optimise whatever tools you have bought into. And that's the real kicker here; optimisation of the trade within system parameters to keep it safe, being able to get enough from the trade to have fortnightly expenses income, as well as optimised trades for growth, because it's what I'll be living off until pension age; the scalping of profits for income while letting the better trades run for growth. Now if I had 400K plus at this time then I could do both; have solid income and bank 1 to 2 baggers for redeployment. Not everyone is in this position,  I think most people? This is why I persist with optimisations.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 03/09/2019, 01:15:14 PM
Quote
I'm now looking to split the rsi oscillation between the above 50 for macd 100,50,30 main above signal, so that when the trend flips (up) in the macd indicator the rsi will report a crossing above the rsi 50 mid line giving a clear unambiguous signal.

You may need to clear up the intentions here. It is very difficult to follow the specific chain of events you are looking for and what is going to be achieved by piecing together different elements of logic. Without the concise concept, it would be difficult to write up what you are trying to find. 

The CROSS(give me a signal when this, goes above this number or other indicator) which we have discussed before is the closest fit for what you are trying to find from what I can gather. That is when one value goes above another. It may be the key words here are when the RSI goes above 50 so:

Signal1 := CROSS(RSI_Function, 50);
Signal;

Quote
So macd histogram values above the 50 line (macd main above signal) will vary from 50 to 100, I have noticed that the general height of macd main above signal line do not exceed an average value, observed in many stocks. So the value is definable of the oscillations of the RSI from 50 to 100. I just need a snippet of formula code to get started, which was my request to point me in the right direction for a cut n paste scrap.

What exactly in this 50 to 100 range are you looking for though?

Quote
To my thinking it would require the rsi 0 to 100 index to be subdivided in two an re expressed as 0 to 50 as -0 to -100 (macd main< signal ) and 50 to 100 as +0 to +100 (macd main > signal) for the rsi of the macd histogram to work within. But my formula expression building ability is limited to cut n paste from other indicator code to experiment with. Do you think the above explanation will work as a formula?

This seems like you are multipying out ranges, but there is little use in doing so if you know where to target and you can define what threshold you are interested in. BCFL is full of little building blocks, you can use them best if you can define the logic first of what you are trying to do.

The key concept of SPA3 is having trust in the edge. We have trust that ours is proven to work, over many trades, based exactly on that long term equity curve. It may be worth having a discussion with David M here in the office about your reservations on SPA3 after looking through the 1st video here: https://learn.sharewealthsystems.com/courses/331967/lectures/10469997 .

In brief, we believe that you will still need to be an investor during retirement and that is when most of the returns to pay for life expenses are made. Most retirements based on life expecteancy, will be 20 years or thereabouts.

Within the last financial year, our public portfolis for SPA3 Trader provided at 23.64% return. Of course there would be given variation for each investor, but having trust in the edge should not be a full time job. Yes, it may not be perfect and there is highly likely room for optmisations, but it should be in the balance of time spent identifying then implementing where those improvements are.

You will never find a system that works in all market conditions 100% of the time or even close to it. The purpose of looking at the history of a system and looking over different time periods is to ensure it is acceptably robust through multiple market conditions. To trust that it will come out the other end without having any grevious drawdown an investor may not be able to handle. Trying to find the best system for any given moment in the market, is an extremely tough job.

Again, happy to help, but there should be a defined end game and process for what you are trying to achieve. The best way to do this is list out step by step how each signal should come about. What precise criteria is needed? Then you look at the functions or tools in BCFL that can help get to that result.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 03/09/2019, 03:44:01 PM
Well that is exactly what it is that I'm doing EXPLORING options within the tool set.
I have the RSIM as best as I will ever achieve without exploring formula code (don't have the time to dig deeper into math equations at this point).

Having done the RSI I have moved onto other set ups like doing medians of two indicator sets to balance out the jerkiness of one over the other. This is a piecing together bits and pieces exploration of which I will need feedback on to achieve the objective of optimising SPA3 Trader trades once they are initially signaled and acted on or sent to watch lists. Median calcs are where I found the Bressert DSS oscillation above 50 for trending and jumps below 50 for non trending (based on MA 60:90 observations), and am trying to apply that oscillating type to other set ups like siroc and rsi of macd, and this is also an extension of the macd histogram the way it makes lower highs or gives divergence readings as the trend cycle shuts down.

Don't get me wrong I am developing trust in the system, more so now, for implementing different trade choices that I would never had exposure to, it's a good way to find stocks to trade, and to have built in safety systems. But I feel these trades still need optimisation for critical exit points and re-entry points when the underlying trend remains intact for the MA 60:90. This is my underlying objective for all BCFL efforts. Just have to make this clear so as to not introduce confusion as to where I'm going with it all.

Quote
Within the last financial year, our public portfolis for SPA3 Trader provided at 23.64% return
You seem to be satisfied with this outcome, would you think improving this level of return could be of benefit? I would like to see upside of 60% through better capture of entry and exit points, longer trend duration holdings and action point timings. I don't believe one indicator approach will be sufficient though.

I'm finding my own scans less reliable without implementing more SPA3 parameters to nail the MA 60:90 and MACD medium and longer setups (I'm primarily using to find crossing for new potential trends and relying on to identify trend duration). These two indicators alone are the backbone of everything I'm doing in BCFL, as moving averages they are also close enough to price action. If I can set up a scan to find in advance future SPA3 trades, and have trust in that scan, then it will be worthwhile exploring.

Within that process of 'logic' I'm learning to trust the SPA3 Trader and Investor systems, but feel a blend of SPA3 Trader into the SPA3 Investor open trades could produce a better edge. I will look into this once I have a stable of custom indicators set ups for the faster SPA3 Trader system (almost there). This is not something I am doing consistently every day, sometimes I'm to lazy to bother and just go with the flow of SPA3 exits and entry signals and Market risk profiling, but have been day trading some high risk stocks from both systems over the last few weeks.

As for the ATR-TS indicator set I was looking at I can't see this working due to the nature of the ATR-TS reversals jumping up and down above price line, but had to explore the formula sets to see if I could draw out one output from two inputs.

Having the RSIM out of the way I'm now looking at percentage above a signal line to primarily identify overbought and oversold conditions (which was what the RSIMH was all about: macd short histogram (for the leader of the MACD main line) tracked through the RSI). I can see how this percentage high and low states could be a very useful technique if a signal system can by implemented.
The RSI does this already in a way and so does the stochastic, (which I have blended through a median formula for one F key setup), the Moving Average Oscillator is now my focus, and I want to get a readout on the chart to highlight what the % above the reference line is, because it rarely gets higher than +10 and -10 on the index within trend, and to signal for these higher peak zone ranges.

This formula code can then be applied to other indicator like ATR-TS's Moving averages to compare % range readouts on the chart, and in scans and scan results, so as to mentally focus on the price panel for less distraction. I will get back to you on this later when I have enough code explored.

I have a bunch of oscillators now that have interbred with each other to produce some very good indicator overlay sets.

[Edit 6/9/19]
What I don't understand, and is the thing I would like not to be closed out from within the system is this happening (in attached image), and I see it often enough in charts to want to fix it with my own indicators and scans. But this does introduce all sorts of complications of having to scan a dual system of watch lists and scans for out of system re-entries further pyramids, lightens and exits. See attached chart of asx.AZJ.
What would cause this gap in SPA3 Trader signals; could it be attributed to volume or indicator? Clearly the trend remains in tact and 'in the zone'.




Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 05/09/2019, 09:37:10 AM
Hi Campbell,
not sure if you can deduce from this scrap of formula line, if so is the int value required to be the same as the other two values for the formula to be 'balanced' or is it possible to use a lower value.
for example:
RSIPeriod:= Int( 13 / (Stdev( C, 13 ) / Stdev( C, 13 )));

or lower value:
RSIPeriod:= Int( 8 / (Stdev( C, 13 ) / Stdev( C, 13 )));

thanks.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 11/09/2019, 10:59:20 AM
Hi Campbell,
Wanting to implement the Swing Chart indicator in BCFL, is the formula available?

In relation to above; I put the Zig Zag from BCFL into a chart but the output gives a flat line:
ZIGZAG :=  zig( CLOSE, 3, % )  or zig(HIGH, 5, %);
ZIGZAG;

Is there something I'm missing here?
EXAMPLE                  zig( CLOSE, 3, % )  or zig(HIGH, 5, PERCENT)
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 11/09/2019, 04:57:06 PM
Hi John,

Re: AZJ

This comes up quite a bit with customers, even ones who have been around for a while. The simple answer, which is the right one, is that the sell signal is a profit stop. This profit stop over a large sample of trades, over many portfolios in our simulations resulted in better portfolio equity curves than not having them. They are a challenging stop because the times it benefits are rarely noticed, they just look like reasonable places to have exits. It allows the capital gained from the trade to compound in another position elsewhere.

By not having a profit stop, there would have been an exit on the signal of high market risk (5th August). The re-entry is based on where the indicators are and which patterns of the SIROC and EMA form for a valid entry signal.

Hi Campbell,
not sure if you can deduce from this scrap of formula line, if so is the int value required to be the same as the other two values for the formula to be 'balanced' or is it possible to use a lower value.
for example:
RSIPeriod:= Int( 13 / (Stdev( C, 13 ) / Stdev( C, 13 )));

or lower value:
RSIPeriod:= Int( 8 / (Stdev( C, 13 ) / Stdev( C, 13 )));

thanks.

Possible to use a lower value. As long as the formula saves it is valid usage of the functions within the formula. You can always 'Save As' a given concept and play around with it if you don't want to lose the original base point.

Hi Campbell,
Wanting to implement the Swing Chart indicator in BCFL, is the formula available?

In relation to above; I put the Zig Zag from BCFL into a chart but the output gives a flat line:
ZIGZAG :=  zig( CLOSE, 3, % )  or zig(HIGH, 5, %);
ZIGZAG;

Is there something I'm missing here?
EXAMPLE                  zig( CLOSE, 3, % )  or zig(HIGH, 5, PERCENT)

The Swing Chart indicator itself - no. It has a lot of customisations that are not suited to a general function for BCFL, such as ignoring inside bars at times. A peak / trough metastock formula will do a similar job, like the one below which I have on hand.

{ User inputs }
change:=3;

{ ZigZag }
diffHi:=H-Ref(H,-1);
diffLo:=Ref(L,-1)-L;
x:=If(diffLo>diffHi,L,H);
zzPer:=Zig(x,change,%);

{ Plot on price chart }
zzPer;
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 12/09/2019, 12:29:27 AM
Great. I'm primarily looking for an HHV and LLV type setup, the BC swing chart fits the precision looking back over the charts. I had a look at some zig-zags but couldn't find anything that worked to expectation.

On closer look I doubt the Swing Chart would work as it lags recent price and takes periods to fill, although I've read it can be combined with macd to fill the last periods data, so if macd maybe another type indicator too. If this is the case then the last period could be used to indicate a rising or falling from recent low swing point (but I guess that's what recent bars are doing anyway), it has my interest.

The zig-zag-macd one I found here(http://trader-online.tk/MSZ/e-w-ZigZag_Combining_With_MACD.html (http://trader-online.tk/MSZ/e-w-ZigZag_Combining_With_MACD.html)) won't save in BCFL for a bracket missing, have been over it a number of times to find where without any success so far, and won't bother you to trouble shoot it, I should exercise my bracket closure skills.

Have searched high and low last few days to find a swing chart that works close enough to the BC one without any success. So will add your m.s. code in and see what can be done.
The Williams is an interesting indicator set pegging the highs and lows sufficiently enough but jumps around too much, so have been attempting smoothing of all sorts to tame it down. Want to do a median with another indicator with it utilising the extreme high and lows for pin pointing with more precision the very oversold buy in points and sell points that will be the money maker of the trade. Iv'e always said; some traders are hitting the lows and highs with a surgical precision that has eluded me.

Will search 'peak / trough metastock formula' , and thanks for the code.

Just a quick question re the SPA3 Investor scans; As I 'll be shifting my attention to doing scans, more so now my indicator sets are done, I was looking for a way to identify all currently 'open' status Investor stocks (and also SPA3 Trader open status stocks), as it seems the scan profiles look for trigger events and dates, not status, am I missing something? 
I will need to introduce custom columns into scan results to identify from all open status Investor and Trader stocks scanned into watch lists the percentage of price move from the initial SPA3 scan trigger dates.
The scan will be ongoing to the same watch lists (x2), eliminating closed stocks as they are closed out of the system. I want to identify strong trending stocks via the percentage price move from initial trigger dates. Does this seem a reasonable way to identify performance stocks?

Cheers.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 12/09/2019, 05:05:55 PM
It is not possible right now to systematically find all open / closed positions. It has not been programmed in that way to Beyond Charts as the function of the system is to follow signals as they appear. So it is only possible via the Alerts App and only for SPA3 Investor. We do know that people interested in open positions, that they have maintained their own watch list in the past. 

Managing your own watch list of open positions does actually interface with BCFL though which is good news.

SHOWCOL(); is a function that lets you define what columns appear in the scan results. Here is a direct link of a quick primer I made at the time of release: https://www.youtube.com/watch?v=BhxpK4ZejnM

What is not covered is that SHOWCOL(); also has a special function of sorts called "WL Name". If you run a BCFL scan over a formula with this line at the end (on its own):

SHOWCOL("DEFAULT", "WL Name");

You will get the usual BCFL result columns, but "WL Name" will tell you which Watch List it comes from. So if you maintain the watch list and find a way to manage them, you can use these watch lists as the items the BCFL scan looks over and Beyond Charts will tell you which list the stock comes from.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 15/09/2019, 12:51:50 PM
Ok the above gets a foot in the door for the potential of scan result custom columns. Watch list identification isn't one of my priorities for scan results as all the daily 21:8 New Entry scans go into the same watch list.
I could use that scan when scans are drawn from multiple watch lists, maybe for identifying non performing stock scans based around an indicator.

I'd like to scan for % gain compared to close (x) periods back or from date of adding to a watch list with percentage added to a column in the scan results, ( I understand the database does not link this data currently), to identify stocks that are gaining in percentage price increase in scan list, as apposed to eyeballing dozens of charts every day.

The point made is the BC Watch Lists do not link in the database the date when added to, or link date to percentage increase since adding to watch lists (extra DB Table with a few relationships?), like how Trade Master does, (and something I have requested in future release for Beyond Charts watch lists), to get a quick visual idea if the item previously triggered in a SPA3 21:8 scan and now in a watch list, has risen or fallen by percent since adding it.
It would be an efficient way to track stocks without having to resort to eyeballing dozens of charts and reference indicators every day/week.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 18/09/2019, 06:27:05 PM
Ok, had time to think out a few scan column additions; one for % rises over several days (see Formula 1 sample).
A scan for indicating duplicate entries within watch lists,
One for identifying non performing watch list entries via an indicator main less than signal report in columns. This will save time going through charts, but will still have to remove them from watch lists manually.
The above non-performing indicator scan works well with SHOWCOL("DEFAULT", "WL Name"); to identify the watch list that have stocks within that are not MACD or MA positive. One down two to go.

I'm not able yet to author my own formulas, the best I can do is cut and paste from elsewhere, so might need some help, sorry.
Are there any other special functions for SHOWCOL() ([EDIT] I see from the BCFL library descriptions the data sheet 'Column Chooser' list is the source),
How would I add a formula result to display in a column, are there any example code of this, adding a formula output doesn't seem to work.

First up; found this formula will have to adapt to BCFL.
Formula 1:

{Performance Daily}
{Stocks sorted on % gains over 1, 2, 3, 4, and 5 days. Rank results for the selected day. Good for finding breakout stocks.}
{Performance Daily}
Stocks sorted on % gains over 1, 2, 3, 4, and 5 days. Rank results for the selected day. Good for finding breakout stocks.
· CLOSE
· ROC(CLOSE,1,percent)
· ROC(CLOSE,2,percent)
· ROC(CLOSE,3,percent)
· ROC(CLOSE,4,percent)
· ROC(CLOSE,5,percent)


My first attempt to BCFL it up:
{Performance Daily}
TODAY := (CLOSE/OPEN) *100;
DAY_1 := (REF(CLOSE,-1) / CLOSE)*100;
DAY_2 := (REF(CLOSE,-2) / CLOSE)*100;
DAY_3 := (REF(CLOSE,-3) / CLOSE)*100,;
DAY_4 := (REF(CLOSE,-4) / CLOSE)*100;
DAY_5 := (REF(CLOSE,-5) / CLOSE)*100;

VDT := VOLUME;
VD1 := REF(VOLUME,-1);
VD2 := REF(VOLUME,-2);
VD3 := REF(VOLUME,-3);
VD4 := REF(VOLUME,-4);
VD5 := REF(VOLUME,-5);

ShowCol("DEFAULT","VDT","TODAY")
ShowCol("DEFAULT","VD1","DAY_1")
ShowCol("DEFAULT","VD2","DAY_2")
ShowCol("DEFAULT","VD3","DAY_3")
ShowCol("DEFAULT","VD4","DAY_4")
ShowCol("DEFAULT","VD5","DAY_5")

-> There is no function defined. Please define your function with valid arguments


I take it the SHOWCOL() in BCFL isn't the sames as metastock filtercol code : https://www.meta-formula.com/Metastock-Explorers-Formula.html (https://www.meta-formula.com/Metastock-Explorers-Formula.html)
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 19/09/2019, 02:43:46 PM
Hi John,

Based on the formula, this is how I would do it:

{Performance Daily}
{Stocks sorted on % gains over 1, 2, 3, 4, and 5 days. Rank results for the selected day. Good for finding breakout stocks.}
TODAY := (CLOSE/OPEN) *100;
DAY_1 := ROC(CLOSE,1,%);
DAY_2 := ROC(CLOSE,2,%);
DAY_3 := ROC(CLOSE,3,%);
DAY_4 := ROC(CLOSE,4,%);
DAY_5 := ROC(CLOSE,5,%);

VDT := VOLUME;
VD1 := REF(VOLUME,-1);
VD2 := REF(VOLUME,-2);
VD3 := REF(VOLUME,-3);
VD4 := REF(VOLUME,-4);
VD5 := REF(VOLUME,-5);

Output := 1;
Output;
ShowCol("DEFAULT",VDT,TODAY,VD1,DAY_1,VD2,DAY_2,VD3,DAY_3,VD4,DAY_4,VD5,DAY_5);

SHOWCOL() is our own little addition. You need Output := 1; Output as the formula needs a reason to put the stock in the results grid.

If you wanted to add a column you can add to the datasheet by right clicking a header -> column chooser such as GICS Industry, it would look like this:

ShowCol("DEFAULT",VDT,TODAY,VD1,DAY_1,VD2,DAY_2,VD3,DAY_3,VD4,DAY_4,VD5,DAY_5,"GICS Industry");.

You do not need "DEFAULT" either if you want to remove some columns. This is perfectly valid to have. It gives you the calculations you want on the results screen with only mandatory columns which are the Security Code, Security Name and Exchange it's listed on. It is good in case you have a lot of columns and want to reduce to as few as possible.

ShowCol(VDT,TODAY,VD1,DAY_1,VD2,DAY_2,VD3,DAY_3,VD4,DAY_4,VD5,DAY_5);
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 26/09/2019, 10:25:12 PM
I like how this works with columns over several days, scans are easy to identify stocks with a continual rise >0 % for 3 bars, scans being focused on the SPA3 watch lists for both Trader, and Investor global.

Could you brief me on the use of ROC(close,Xn,%) [EDIT Sorry found the link in BCFL https://school.stockcharts.com/doku.php?id=technical_indicators:rate_of_change_roc_and_momentum (https://school.stockcharts.com/doku.php?id=technical_indicators:rate_of_change_roc_and_momentum)]

Apart from the above I'm having trouble with the first line for today's input:  TODAY := (CLOSE/OPEN) *100; doesn't report as expected but reports numbers over 100%, so I'm doing something wrong with the calculation obviously (but not to me). I tried;
%_TODAY := ROC(close,1,%); this reported LLC correctly today at 4.23%, so proceeded with;
%_DAY_1 := ROC(CLOSE,2,%);
%_DAY_2 := ROC(CLOSE,3,%); etc., (not sure what the period numerator is doing?)

In the formula code I've also limited the back reporting to 3 days including today so it's 2 days previous to today's close, and added in some filters (ATRTS_L as QF1:

ATRTS_L := FMLVAR("ATR-TS_LONG","ATRTS_L");

%_TODAY := ROC(CLOSE,1,%);
%_DAY_1 := ROC(CLOSE,2,%);
%_DAY_2 := ROC(CLOSE,3,%);

VOL_TODAY := VOLUME;
VOL_DAY_1 := REF(VOLUME,-1);
VOL_DAY_2 := REF(VOLUME,-2);

PCD_TODAY := %_TODAY > 0;
PCD_1 := %_DAY_1 > 0;
PCD_2 := %_DAY_2 > 0;

QF1:=CLOSE>ATRTS_L;
{QF2:=MOV(CLOSE,21,S) * MOV(VOLUME,21,S) >= 100000;}

Output := 1 AND QF1 AND PCD_TODAY AND PCD_1 AND PCD_2;
Output;
ShowCol(VOL_TODAY, VOL_DAY_1, VOL_DAY_2, %_TODAY, %_DAY_1, %_DAY_2, "WL Name");

Today (26/09/19) 3 stocks pop out of the ASX 100 : BOQ, LLC and SGR they all look good, except for SGR.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 30/09/2019, 05:01:53 PM
Rate of Change shows the % or points move between day x and day y. So Really good check to ensure overall movement from point A to point B is all positive along the way.

For a 1 day paramter input, the expanded version is this:

TODAY := ((Close - REF(Close, -1)) / Ref(Close, -1)) * 100;
TODAY;
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 01/10/2019, 12:06:26 AM
Great thanks.
Have added a 3 day 'Total' percent gain for ranking stocks in both SPA3 watch lists, this gives a better way to rank (that which has gone up already).
It really does highlight what i have missed out on as my portfolio has no where near the listed gains over last 3 days as the scan indicate.

I'm going to run these percent gain scans for a week or so and think about how this could be implemented into trade actions or how it can be 'indicator' related to making more precise trade decisions. In fact I've missed quite a few high ranking stocks, more so for the Friday scans after markets close; the shear number is difficult to deal with, and all the SPA3 scan results look positive, and funds will only go so far.

It's an eye opener, I suspect the ROC indicator would be the choice indicator for furthering these studies.
As a side project I experimented by dropping the system SIROC onto the ROC indicator to get a nice midway indicator, but are unable to BCFL code for this, so constructed my own Smoothed Indexed ROC of the ROC indicator that fits very closely to the SIROC of the ROC, so will proceed to code this up for triggers and scans.
{SI_ROC}
ROC1 := MOV(ROC(CLOSE,13,%),1,E);
RMI_IN := RMI(CLOSE,8,21);
SI_ROC:= RSI(MOV(((ROC1 + RMI_IN)/2),5,E),13);
SIGNAL := MOV(SI_ROC, 13, W);

I'm wondering if you could lend your experience with some ideas to clarify the percent gain scans for identifying changing states to higher performance (without having to view individual charts), just a few pointers nothing in detail? Of course the thing I'm looking for with the percent gain scans is being able to identify at the earliest opportunity, the winning quadfecta from the pack, through scans.

The following could be implemented:
a) Deviation from an average range percentile band AND report any change in states to a column (not sure how yet), either be a percentage calculation or indicator condition or level.
b) Could scan data sheet cell background or text be coloured to highlight the change in the state of the above; like green for positive and red for negative and black for within range?
c) Can all stocks within a watch list be overlaid onto a single chart, so any higher performing stock would rise above the pack and be identifiable (see attached image), but would need to be automatic in including additions and deletions from a watch list.

I'll be adding to this list as ideas cross my desk.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 03/10/2019, 11:22:31 AM
I would not use the datasheet for state changes detection via colouring or highlighting. You already have the info at hand really. Instead combine the criteria for what you are looking for to another variable and output that to the datasheet. The main focus of Beyond Charts has always been on the charts themselves rather than the datasheets.

Remember this type of calculation will give 1 for yes, 0 for no:

Check_State := THIS AND THIS_2 AND THIS_3;

If the criteria for This_n are met, then the criteria for Check_State will be met. Having this column would cover the need for looking at THIS_n etc in the datasheet.

With regards to how to detect the highest of performing stocks off the back of SPA3 signals, that is definitely a question. One of the parts of trend following is that the trend has to be there and forming already. Otherwise it cannot be a trend to follow. We take the philosphy that anything can happen and try not to curve fit the signals but still retain a positive portfolio edge.

You probabilistically could find something that may work well enough for you to be happy using going forward for what you are looking to do. In an ideal world it would be something that only works for trades that perform highly (what you seem to be interested in) and not ones that are sideways or low or under performing. Whatever you find, will highly likely end up being a 'degrees of' working and not something with a 100% hit rate, or close to, of excluding stocks that you are not interested in. That would be something worthwhile to keep in mind. 

All I can offer otherwise is that we are a trend following system, so looking in to what builds toward a strong uptrend could be a focus. A set of criteria that has a high occurance rate in what you would have preferred to enter in to. As a simplistic recap - we already look in to what is an established trend, is outperforming the market and by patterns of our technical indicators has a high probability of continuing.

Multi Charts -- you can only do this using the base reference indicator but it is not maintainable based off inputs to a watch list. Here is a video that will be put in the new TutorMe once all the videos are ready: https://vimeo.com/354807148/0313402360
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 04/10/2019, 12:30:42 PM
Thanks Campbell, you've given me something to think about, it will need time to peculate.
A referenced dynamic Ratio system sounds the goods.

I have come to realised the percent gain scan column results (in the above post image) column are not the end result, but the basis of other results, so will not publish those columns but use them for further calculations like ratios of some sort.
What I really need is a ranking system that is able to be tracked visually from day to day, so measurable and quantifiable from casual observation.

Like the above post attachment of the comparison charts showing the breakout from a moving average envelope, or based on an inception point / date, or maybe a price equalisation point for all the stocks being scanned back referenced  by x bars? I'm simply not sure at this stage and will probably need to enlist the proverbial 100 monkeys on keyboards to code this up.

I think if I can nail the above percent scans to narrow down potential gainers to the portfolio list of 10 to 14 stocks as ranked in order of fund allocations, before they really get going, would be ideal; it will suffice for my usage and I can finally go forward with greater confidence into real money trading. I doubt I will need anything more in way of charts and signals, as I have exhausted myself chasing indicator setups and trading techniques over the last 9 months. The only charts I want to see now are the system trigger charts.

So working with the SPA3 system 'forge' in this data sheet way, will further sharpen 'the edge'. And I need a sharpened edge as my funds will only go so far and my SPA3 Investor portfolio is only $361 up as of 5/10/19 after about 8 months having fallen from 5k up 3 weeks ago. At this time my SPA3 Trader portfolio shows the better gains being 10K up. And I have had to employ dynamic management to cut losing trades faster than system triggers to prevent larger losses, and in some cases this has not helped as the stock had dropped then re-gained its positive momentum, by which time I had moved funds on to a newly triggered stock.
Granted it's been a tough year for any portfolio, alas I remain a bit disappointed, more with not being able to choose the better gainer stocks of the last 8 months, or moving into them far too late from Pyramid points.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 07/10/2019, 02:13:49 PM
Remember we have backtested 1000s of portfolios, who take different signals at different times (which is how we come to the 1000s of portfolios). These exits that in combination with money management, provide an edge that results in a rising equity curve. The range of equity curves over the many portfolio outcomes all outperform the market over the long term. 

Using BCFL or fine tuning a selection process is not necessary for SPA3 operation. Based on that most of our customers do not use BCFL for stock selection purposes. When more stocks come up than capital available, all you need is consistent process that can be analytical or non-analytical (ie. A to Z or choosing a letter from the alphabet based on the time of the month). A BCFL can help refine the returns, but does require some amount of effort for an unknown additional change to the edge.

As for the oscilliation, what is described can help narrow the range to index against a value like 100 - not oscillate between 0 and 100. So you can see how it is relative to a given point by it dripping above or below the indexed value.

What you are asking for is how to scale a variable to be between 0 and 100. This is functional maths and is quite simple once you have found the bottom and top for your data. To use the below for other variables, change what is being fed in to data:

{ Move Variable to Scale }
data := ROC(C, 100, %);

max_new := 100;
min_new := 0;
max_old := hhv(data, cum(1));
min_old := llv(data, cum(1));

dot1 := (max_new - min_new) / (max_old-min_old);
dot2 := (data - min_old) + min_new;

result := dot1 * dot2;

result;

I did mean to post this on friday but some interactions with website tools on the server were taking place that stopped the forum updating for a short moment. The above is what I was going to post. Now for indicator values in a formula for scan output, the scan only looks at the indicator you give it. There are a few ways I can take the question, so here are a couple of statements that I think might be the most relevant.

The scan only looks at the variable you want to 'plot' on a chart. In the above case, it is the result variable (as it's on its own line: result;). You can change this to any earlier variable used like dot1 or dot2 and that is the criteria the scan will use. I recommend making the output the last variable created in the formula where possible because you can easily see what a formula is doing this way. 

Otherwise if you want an indicator to be part of a SHOWCOL(...); output, then you will need to either use a BCFL function if available or re-create the indicator as part of the formula. 

Pre-Edit: I see the post has changed again. Trademaster usually does the position size sorting, although you will not be able to take everything across in to Trademaster from a BCFL scan. You can save potential trades in trademaster and access them again via act on -> saved prospects after bringing them in to TradeMaster. 

Everyones portfolio experiences are different, and it is dissapointing to hear of the rapid decrease in value over the last few weeks. It would be best to email David McCulloch directly if you want to discuss your portfolio in fine detail - I can also have him get in touch with you as well - for support with portfolio execution.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 07/10/2019, 08:23:54 PM
Yes I did update the post sorry about that   :blush: several times in fact, it takes me a few attempts to get them right, and as I do work on the subject some content tends to become non relevant as I find a solutions myself. I can see how this could be annoying whilst trying to track a users questions so please bare with me while I refine it all. I only expect an end of week or once a week response or when ever you get the time, no hurry at all.

I will eventually (very soon) have to down scale my efforts to finding an optimised edge, its taking up far too much of my time in BCFL, hence my focus on percentage gains at this point on System scanned stocks collected in watch lists, to sort the short list of System scan results down to the most profitable gainers before they get going. To assist with this I have spent the last week looking at ROC indicators and percent gain scan results, I have a promising basic set up (see attachments), although I would like to get a ranking system up and running (doing google research - nothing yet).
I'm happy to be using the SWS system, and beginning to realise I wouldn't want to be using any other platform to capture trend and preserve trading capital.

Quote
Remember we have backtested 1000s of portfolios, who take different signals at different times (which is how we come to the 1000s of portfolios). These exits that in combination with money management, provide an edge that results in a rising equity curve. The range of equity curves over the many portfolio outcomes all outperform the market over the long term.

Using BCFL or fine tuning a selection process is not necessary for SPA3 operation. Based on that most of our customers do not use BCFL for stock selection purposes. When more stocks come up than capital available, all you need is consistent process that can be analytical or non-analytical (ie. A to Z or choosing a letter from the alphabet based on the time of the month). A BCFL can help refine the returns, but does require some amount of effort for an unknown additional change to the edge.

I understand the principal of the system, your explanations are helpful, my problems arise as a user based experience over the last 8 to 9 months, and how I think there could be improvement for narrowing the field to thoroughbred only race more suitable to my portfolio and cash allocation sizing. I don't see a problem with this, and the tools are there to use in BCFL. If this can be achieved as a scan it will save me time having to go through dozens of extra charts every night/day.

For broader market stock selection I agree you don't need anything more than the system selection criteria offers, and the additional complexity to implement a selection and trading system seems to be a fruitless and very time consuming effort. So I'm now working at scanning within the SPA3 Trader & Investor triggered stock selection group; added to a watch list collection, and as there is no way to screen for open trade stocks this is the best I can do, but it also drags in closed trades of prior triggered stocks, that may well be still in-trend but  are closed system trades (MA and MACD cleanser scan isolates non trending stock from the watch list fortnightly). The draw back are dozens of candidates that I'm trying to narrow down via a ranking system. This can also be applied to New Entries scans that have more than a few to select from just by adding them to the watch list.

The other software package I was (and still are) looking at is VectorVest where they have a stock ranking system of; Relative Value (RV), Relative Safety (RS), and Relative Timing (RT), used by the software.
It might be comparing (SWS software) apples with bananas, but if it works it works. They also have a Realtime Derby type overview of the market to identify outperforming stocks over periods of time,
If you aren't aware of them see link here: https://www.vectorvest.com.au/how-it-works/ (https://www.vectorvest.com.au/how-it-works/)


So just thinking out aloud to overview the potential ranking system inputs in BCFL, in this same way; there could be a value assigned for a bunch of indicators crossing points (MA, and MACD or better the PPO) how long ago, and at what index level, indicators with overbought and oversold index levels, ATRVE level, volumes over period of time, percentage gains or price rises over same period etc. reduced to a numerical value and added together, normalised to derive at a value ranking measure, then reported in a scan column. This could be the way to compare different stocks at least. And then if this value could be then compared with the value of previous periods, maybe that would indicated an improvement, or not, going forward in individual stocks.

I'm wondering how the SPA3 Trader system scan outputs can be used in way of getting a ranking system: ATRVE, Liquidity, Market Cap, and Sector Risk.
How accurate is the ATRVE in ranking stocks? as I haven't paid much attention to this. I remember ATRVE being explained as an answer to one of my very initial questions about how do you select from multiple SPA3 scan results the best few stocks, but when I looked into it I saw no noticeable correlation to higher trend performance, maybe just volatility?, and for higher levels being overbought, but may have overlooked something there. I note the ATRVE index levels for Trade Master trade entry requirements.

Quote
Everyones portfolio experiences are different, and it is disappointing to hear of the rapid decrease in value over the last few weeks. It would be best to email David McCulloch directly if you want to discuss your portfolio in fine detail - I can also have him get in touch with you as well - for support with portfolio execution.
Ok thanks for the offer, I might follow up on this after a few weeks just to see if I can get a recovery happening myself with the new percentage scan selections. I've recently (about 5 weeks ago) adjusted the TM capital allocation to half what it was (now around 5k per stock) due to recent market uncertainty and volatility, and staying largely in cash whilst having a few punts, so profit amounts are down accordingly (one of the trading techniques I mentioned previously) I've been trying different things to compare the outcomes while still doing simulation trades. For a long while there it was the Trader portfolio that was lagging behind the Investor one, so glad to see it pick up recently, but I have had to micro manage trades in IRESS for hours every day, something I want and need to get away from, as I simply can't do this from the deck of a yacht in the middle of the Pacific.

Re the ROC Oscillator; Although my focus is now on the ranking scan system,  I did give the ROC oscillator formula a go but couldn't get it looking right and was clearly way off the mark by several dozen monkeys! What you have done looks good, if a bit raw without other code, adding mov() smoothing tends to just introduces lag. It's a basic start though and gives me the basis of adding other indicators as oscillators.

The only problem with the basic code (due to CUM(1)) is that previous data sets the index to 100 and caps more recent data (see attached chart lower panel for the oscillator), so that recent highs are not indexed to the same higher levels but are constrained. I guess this would mean employing more complex formula code.

Having had a poke around in BCFL Quick Reference I realise the CUM(1) starts indexing from day one of the price data history so replace with this:
max_old := hhv(data, 1000);
min_old := llv(data, 1000);
But this slams the recent highs up flat onto the 100 line in some cases.  Is there a bit of code that will dynamically scale data to index levels from period to period? that's about all I can offer in way of description.
[Edit] Found the Williams code piece does a good job at smoothing (for data input) and using PER() for NumPeriods, although this is not ROC any more.

NumPeriods:= PER();
data := MOV((((HHV(H,NumPeriods) - C)/(HHV(H,NumPeriods) - LLV(L,NumPeriods))) * -100),63,W);

max_new := 100;
min_new := 0;

max_old := hhv(data, cum(1));
min_old := llv(data, cum(1));

{max_old := hhv(data, 1000);}
{min_old := llv(data, 1000);}

dot1 := (max_new - min_new) / (max_old-min_old);
dot2 := (data - min_old) + min_new;
result := dot1 * dot2;

SIGNAL := MOV(result, 21, E);

result;
SIGNAL;

p.s. The system SIROC seems to be the perfect tuned indicator, even working far better than the RSI used in the RSIMH (RSI of the MACD histogram), but without access to it in BCFL there nothing I can do with it. The Metastock code of the public domain SIROC that I modified fits very closely to standard 21:8 but when deployed for the MACDH distorts and is useless.

p.s.s. The 'Base Reference Indicator' seems not available in BCFL? if it were those normalised current values could be reported for comparison in scans between scan candidates.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 10/10/2019, 12:30:23 PM
Quote
Using BCFL or fine tuning a selection process is not necessary for SPA3 operation. Based on that most of our customers do not use BCFL for stock selection purposes. When more stocks come up than capital available, all you need is consistent process that can be analytical or non-analytical (ie. A to Z or choosing a letter from the alphabet based on the time of the month). A BCFL can help refine the returns, but does require some amount of effort for an unknown additional change to the edge.
Ok I think I need to understand what the broader user base is using BCFL for as you seem to have a good understanding of this?

More stocks are continually coming up than I have capital for, and about 50 percent of my portfolio is in varying stage of losses slightly down from gains at any one time. At which point I then go through and cull the worst 2 to 3 stocks on any day to replace them with new incoming entries. It's a tricky business requirng watching IRESS for most of the day, and that I want to get away from doing, so to level out and understand and have better tools for this whole process of do I hold or do I cut, based on a scan ranking system.

Ok so lets take the day of the month example from your quote extract above; lets say first day of the month (or week) as the comparison point of reference for price for all stocks that SPA3 has identified as trade-able from within a watch list as the 'analytical' and apposed to the 'non analytical' "A to Z or choosing a letter from the alphabet based on the time of the month".

How would I code to normalise all stock prices to be comparable? so that higher moving prices on the third day and forth day etc. could be identified in a scan column?
I think it is a 'normalisation code' that could then be applied to other aspects of variables like indicators, index levels, price to volume ratio, percent gains etc. Do you think this is doable in BCFL?
Could it be done by the reduction to a decimal like 0.1 or -0.1 so that adding all the variable decimals within the scan can then be added together to give a total tally for comparison purposes.

Separately but on the same agenda;
Next up is getting the RSI value to work so that the % value today is less or more than the value previous bar ago to asses if the RSI is rising or falling by x percent value over time:

I get the impression your head, Campbell, is chock full of stock formula code, so humbly ask once again if you could try solve the following:
I've tried a number of ways to get it to work without any success, it's another of those standard formula sequences that could be used for different indicators to replace the RSI with like ROC or moving average etc.;

The output I'm looking for is to get a single negative (-3) or positive (+3) % (or number) value output, so I can see if the indicator\price\anything is rising or falling in a scan column. I'm sure its trickier than it first appears so take your time no hurry.

This is what I started with and not sure if I'm heading in the right direction at all does it require the IF() statement:

%DAY_0 := ((RSI(Close,13) - REF(RSI(Close,13), -100)) / Ref(RSI(Close,13), -1)) * 100;
%DAY_1 := ((RSI(Close,13) - REF(RSI(Close,13), -100)) / Ref(RSI(Close,13), -2)) * 100;
%DAY_2 := ((RSI(Close,13) - REF(RSI(Close,13), -100)) / Ref(RSI(Close,13), -3)) * 100;
%DAY_3 := ((RSI(Close,13) - REF(RSI(Close,13), -100)) / Ref(RSI(Close,13), -4)) * 100;


I'll post the full scan code of what I have done so far, as you can see the RSI columns are too numerous and needs to be two column for RSI value and percent gain or loss:

MAM := FMLVAR("MA 60:90","MAM1");
MAS := FMLVAR("MA 60:90","MAS1");
ROC_LEVEL:= ROC(CLOSE,100,%);

RSI_level_0 := RSI(CLOSE,13);
RSI_level_3 := ref(RSI(close,13),-3);
MA_X := CROSS(MAM, MAS);

FILTER1 := MAM > MAS;
FILTER2 := ROC_Level > 8;
FILTER3 := CLOSE > REF(CLOSE, -1) AND REF(CLOSE, -1) > REF(CLOSE, -2) AND REF(CLOSE, -2) > REF(CLOSE, -3);
FILTER4 := MOV(CLOSE,60,S) * MOV(VOLUME,21,S) >= 50000;

%DAY_1 := ((Close - REF(Close, -100)) / Ref(Close, -1)) * 100;
%DAY_2 := ((Close - REF(Close, -100)) / Ref(Close, -2)) * 100;
%DAY_3 := ((Close - REF(Close, -100)) / Ref(Close, -3)) * 100;
{%DAY_4 := ((Close - REF(Close, -100)) / Ref(Close, -4)) * 100;}
{%DAY_5 := ((Close - REF(Close, -100)) / Ref(Close, -5)) * 100;}

RSI_%DAY_0 := ((RSI(Close,13) - REF(RSI(Close,13), -100)) / Ref(RSI(Close,13), -1)) * 100;
RSI_%DAY_1 := ((RSI(Close,13) - REF(RSI(Close,13), -100)) / Ref(RSI(Close,13), -2)) * 100;
RSI_%DAY_2 := ((RSI(Close,13) - REF(RSI(Close,13), -100)) / Ref(RSI(Close,13), -3)) * 100;
RSI_%DAY_3 := ((RSI(Close,13) - REF(RSI(Close,13), -100)) / Ref(RSI(Close,13), -4)) * 100;

Av % Gain 3_Days := (%DAY_1 + %DAY_2 + %DAY_3)/3 { + %DAY_4 + %DAY_5};
Bars_Since MA_X := barssince(MA_X);

Output := 1 AND FILTER1
AND FILTER2
AND FILTER3
AND FILTER4
AND Av % Gain 3_Days
AND ROC_LEVEL
AND Bars_Since MA_X
AND RSI_Level_0
AND RSI_%DAY_0
AND RSI_%DAY_1
AND RSI_%DAY_2
AND RSI_%DAY_3;

Output;
ShowCol(Av % Gain 3_Days, ROC_LEVEL, Bars_Since MA_X, RSI_level_0, RSI_%DAY_0, RSI_%DAY_1, RSI_%DAY_2, RSI_%DAY_3, "WL Name");
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 10/10/2019, 04:38:10 PM
Quote
I understand the principal of the system, your explanations are helpful, my problems arise as a user based experience over the last 8 to 9 months, and how I think there could be improvement for narrowing the field to thoroughbred only race more suitable to my portfolio and cash allocation sizing. I don't see a problem with this, and the tools are there to use in BCFL. If this can be achieved as a scan it will save me time having to go through dozens of extra charts every night/day.

This is fair enough and understood, there will often be cases where there are more positions than cash available. There is also nothing wrong with trying to do what you are doing, but there can be reasons why we have got to the point we have as well. The system design from the team here has focused on the equity curve and the day to day transitions to achieve that equity curve. I could write for days on this and probably go on some cycling ramblings while doing it, but just know it's all fine. The core point I wanted to make was that it is not necessary to use BCFL, or should not be seen as a requirement more so for SPA3 operation.

BCFL is one of those degrees of tools that may make the edge go sideways, back or far higher. You don't know until it is done and it can take a long time to get to "done" or a starting point. I think this is well understood and I'll leave it there.

Quote
So just thinking out aloud to overview the potential ranking system inputs in BCFL, in this same way; there could be a value assigned for a bunch of indicators crossing points (MA, and MACD or better the PPO) how long ago, and at what index level, indicators with overbought and oversold index levels, ATRVE level, volumes over period of time, percentage gains or price rises over same period etc. reduced to a numerical value and added together, normalised to derive at a value ranking measure, then reported in a scan column. This could be the way to compare different stocks at least. And then if this value could be then compared with the value of previous periods, maybe that would indicated an improvement, or not, going forward in individual stocks.

This sounds like a scoring method, based on a number of inputs with different weights and the higher the value the better. An aim could be that the score itself be enough on its own, without having to compare prior periods.

Quote
I'm wondering how the SPA3 Trader system scan outputs can be used in way of getting a ranking system: ATRVE, Liquidity, Market Cap, and Sector Risk.

ATRVE is the volatility in a number. The more volatile a stock the more it can potentially move upwards, same as downwards. A low volatility stock is the same but in smaller amounts each way. Liquidity is used more so for money management & position sizing relative to portfolio, which sector risk is a common one. Market Cap really just tells you the potential circulation for a stock, while liquidity is the active / in transition average of much the stock is moving.

Specifically ATRVE is an indicator that expresses the ATRE as a percentage of the stock’s price on any given day. For an ATRE 15 of a 57 cent stock is 3.1 cents then the ATRVE = 5.43% (3.1 divided by 57). The 3.1 means that the daily average true range exponentially smoothed over the last 15 trading days is 3.1 cents.

You can apply an F5 overlay via Side Panels -> Overlay for your given SIROC setting to see it on a chart and get an eye for it. It does hold true that the more a stock moves (ATR) the higher the indicator value.

Quote
I have had to micro manage trades in IRESS for hours every day, something I want and need to get away from, as I simply can't do this from the deck of a yacht in the middle of the Pacific.

My suggestion would be to find a way to start accepting the outcomes of trades, or at least devise a plan to take a step back from these actions. It sounds like low volume day trading which is a job in of itself. Of course it can come back to being happy with the system / methodology, but also there is a psychology element involved in accepting investment outcomes. Studying (!) "Trading in the Zone" by Mark Douglas is something the team here strongly recommend to take a look in to with these situations, Gary you may have noticed already (or not) swear by it.

Quote
The only problem with the basic code (due to CUM(1)) is that previous data sets the index to 100 and caps more recent data (see attached chart lower panel for the oscillator), so that recent highs are not indexed to the same higher levels but are constrained. I guess this would mean employing more complex formula code.

Having had a poke around in BCFL Quick Reference I realise the CUM(1) starts indexing from day one of the price data history so replace with this:
max_old := hhv(data, 1000);
min_old := llv(data, 1000);

What I see happening is that this function finds what the previous maximum and minimum data points are. By making it 1000, you are capping its look back to the most recent 1000 data points instead of the all time range the function needs to operate. While it is fine for anything 1000 data points or less, generally taking away information may result in distorted outcomes.

If you find the data is staying at 100 or near that, it may be more to do with the data being supplied in moving sideways at a relative point.

Quote
p.s.s. The 'Base Reference Indicator' seems not available in BCFL? if it were those normalised current values could be reported for comparison in scans between scan candidates.

No it is not. You do have access to SECURITY() which grabs the prices from another stock, which can be used in a normalising function, but even if Base Ref was included it would be very manual to compare two items against each other. BCFL will have to be told about the othere existence explicitly.

Quote
Ok I think I need to understand what the broader user base is using BCFL for as you seem to have a good understanding of this?

BCFL exists primarily to implement your own ideas as either a scan (which doubles as a signal on a chart) or an indicator. Of course as you found with the SIROC, not everything in Beyond Charts is interactive with BCFL. SPA3 may not also be the only investment system that someone uses, or method of deciding which stocks to buy.

Quote
More stocks are continually coming up than I have capital for, and about 50 percent of my portfolio is in varying stage of losses slightly down from gains at any one time. At which point I then go through and cull the worst 2 to 3 stocks on any day to replace them with new incoming entries. It's a tricky business requirng watching IRESS for most of the day, and that I want to get away from doing, so to level out and understand and have better tools for this whole process of do I hold or do I cut, based on a scan ranking system.

Most SPA3 Trader trades, statistically which is represented in the back testing, will not be a profit trade. The system edge comes from exiting the losing trades early than the winning trades which results in overall larger winning trades then compounding the returns over time.

All of this can only be implemented and visibly seen in a portfolio outcome (ie. achieved), if you take SPA3 out of the equation for a moment, by having a process and sticking to it. SPA3 is the process enabler. There are systems that do better and do worse than SPA3, which are more active & less active, but finding them and working them out takes time and effort. Generally people come to us as they want to be able to achieve the equity curves that SPA3 has displayed over time and embrace the direction that having signals can provide.

Quote
Ok so lets take the day of the month example from your quote extract above; lets say first day of the month (or week) as the comparison point of reference for price for all stocks that SPA3 has identified as trade-able from within a watch list as the 'analytical' and apposed to the 'non analytical' "A to Z or choosing a letter from the alphabet based on the time of the month".

This is looking far too much in to it. It is a process to enable stock selection, not a system in of itself. The point of analytics vs not using them, is the contents of the process which enables the habits - to be able to follow a system. It all comes back to the portfolio backtests and how those 1000s of portfolios look. In the end, one of the portfolios goes down a different tree point which include the bad and mediocre trades along the way.

Quote
Next up is getting the RSI value to work so that the % value today is less or more than the value previous bar ago to asses if the RSI is rising or falling by x percent value over time:

The output I'm looking for is to get a single negative (-3) or positive (+3) % (or number) value output, so I can see if the indicator\price\anything is rising or falling in a scan column. I'm sure its trickier than it first appears so take your time no hurry.

Instead of looking at a number - what is the end objective you are trying to find? A rank of increase I suppose? Or to see if something is rising, falling or some combination of both? You cannot output text in to the scan columsn, but you can devise an output based on what you are after.

To find if they are rising a singular, sortable number, use the ROC() function over the desired amount of days. You can feed in your own variables as it will look at the change between the current bar and bar n (ago) as a stand alone % difference between the two. Based on your current formula, it could be a function like this perhaps:

ROC(RSI(Close, 13), 5, %);
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 10/10/2019, 10:49:57 PM
Outstanding! thanks for the succinct replies. Going to sit back and read for a few days. You could have easily have flipped me off with all those nube questions, but your professionalism and comprehension of the system clearly shines through, a credit to you and the Share Wealth Team.

I should yield to your wisdom and just eyeball the ROC indicator, cross my fingers and pack all this stuff up and leave you to get on with it, but...

I have the RSI worked out and was going to edit my above post but your reply beat me to it, so will just say the RSI percentage change was nothing more than a subtraction:
RSI_%Change := RSI_% Today - % DAY_3;
This gives the current change percent from bar -3 and the column next to: RSI % Today, so two columns.
Probably not quite what I was looking for but will do for now so I can move on with other columns to build up the code base so I can then cut and paste between indicators..


I take your point about Rate of Change indicator 'as' the measure of comparative change, taken at face value.  So if the ROC formula is compared to another reference value, like a market index, or just the ROC zero line itself from a date like the 1st day of the month, so that a comparative level of reference can be achieved. Sounds simple but my brain doesn't work in code yet, I can think it out in words but zip in code.

Need to chew on this for a bit, might see if anyone has done this sort of thing in TradingView.

Cheers.


 

Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 16/11/2019, 12:49:01 PM
Ok here's the things;
Spa3 Investor is the way in which a 'timed market' approach to investing in equities is 'the' proven methodology and "The Better Way to Invest".

When I list the ETF products like Vanguard ASX ETF's I get (at this time) 29 results, of which only two are SPA3 Investor implemented.
So really I can only track two ETF (VTS, VAS) through SPA3's system, as I don't have access to the ATR-TS system indicator to apply to the other ETF's

The issue I may be facing is that financial advice sought might not be for either of the two Vanguard products tracked by the SPA3 system, but other Vanguard listed ETF's.  (Note: I am preempting the delivery of this advise at this time).

Using a Financial Adviser (FA) is my family's approach to generating an income stream for a senior family member who doesn't really understand how investing is done. I have also impressed upon the FA to consider a low risk growth aspect for future anticipated and unanticipated major expenses outside of a simple income stream.
The FA's approach is explained as 'buy and hold' for long terms (3 years min.) and reviewed annually, which translates to 'buy and hold' passive investing.
And I might add that the SPA3 system I have purchased is at this time, not understood or trusted by the family, along with my efforts to use the system for family related investments is also greatly lacking in faith and trust.

So the best I can personally do is 'back seat' monitor what the FA has selected in way of ASX listed ETF's who are also entrusted to implement the plan. All i can do is monitor through a cobbled together clone of the system SPA3 ATR-TS indicator that is not systematised for portfolio management for timed entry and exit signals. So any future signal recommendations I may put forward to the financial adviser is somewhat subjective based on my own interpreted reading of my own indicator signals, the validity of which may well be challenged by the FA.

How best to go about using the beneficial features of a 'timed market' methodology for investing if the advice is given for non SPA3 ETF's if this eventuates in the FA's statement of advice? And or, how could I best implement a system that would generate sufficient trust for timed signals that could be relayed to FA for action.
With my tendency to stutter, my spoken words  :confused: alone are not very convincing.
Cheers.


Title: Re: Help with BCFL custom Scans & Coding
Post by: Dave McCulloch on 18/11/2019, 04:16:27 PM
Hi John,

As a user of SPA3 Investor on the ASX, you will have access to signals on the following ASX listed ETF's:

IJH (SP400 Mid cap)
IJR (SP600 Small cap)
IVV (SP500)
VTS (US Total Market)
SFY (ASX50)
SLF (ASX 200 listed property)
STW (ASX200)
VAS (ASX300)

I'd strongly recommend reviewing Gary's Blueprint to Wealth Investors Club course, if not for you then definitely for your family.

You'll find a plethora of reasons for taking control of your own investment decisions, and you can review the material at any time.

The universe of SPA3 Investor ETF's is base on extensive research, and supporting the research is that of C.R.I.S.P (Centre for Reseach Into Security Prices) which has data all the way back to 1926.

This is the basis of "The Big Picture" (Available for viewing in the Education Centre)

Research shows that the SP Midcap 400 Index ETF is a great long term out performer and one that beats the SP500 (Warren Buffets preferred index) and smashes any Balance Fund.

I hope this helps and that you'll point your family to these valuable resources.

Regards,

David.


Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 02/12/2019, 08:15:49 PM
Have some issues with the ATR-TS I'm using in that it slows down scanning and also slows loading of charts enough to be annoying. I want to limit the data look back period to 200 bars or any number that works.

I note previously in the oscillator code you provided (several posts back) there was a bit of code: cum(1) for the look back period, I then swapped that bit out and replaced with 200 or 100, and this worked to give that oscillator a full 0 to 100 cycle and not be pegged to the 1st bar.
So wondering what can be done with the ATR-TS code as there is no look back period that I can identify:

IN1 := WC();
atrper := 14;
atrfact := 4.5;
loss := atrfact * ATR(atrper);
ATRTS_L := If( IN1 >PREV AND Ref( IN1 ,-1)>PREV, Max(PREV, IN1 - loss),
If( IN1 < PREV AND Ref( IN1 ,-1)<PREV, Min(PREV, IN1 + loss),
If( IN1 > PREV, IN1- loss, IN1 + loss)));

PS. Anyone home?
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 17/12/2019, 09:21:13 AM
Hi John,

From the last post it read that everything was okay at the time they were both posted.

The ATR look back period is set to 14. Restrict the number of bars it starts at does not work the way you expect, as the calculation still needs to be applied for each bar as an individual script.

You would have better luck using the Chart -> Period -> Custom options restricting the number of bars being loaded on a chart.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 17/12/2019, 11:23:07 AM
Re the ATR-TS:
Ok so there isn't the opportunity to slip in the oscillator cum() line and set it to something like 200 to limit the starting point to 200 bars after first bar, or something like that?:
max_old := hhv(data, cum(200));
min_old := llv(data, cum(200));

The only thing I could request as a future implementation would be to make available the system ATR-TS like you did with the RSI, so it can at least be referenced in BCFL, not just the ATRT-TS but SIROC also and anything else there for the user might need to use.

NEXT UP;
This is probably the last thing I have to work out as I have enough scans set up now and are reasonably comfortable with doing basic MA type coding for the indicators I'm using MAs, MACD, Schaff Trend Cycle, RSI & Stochastic, M.S. SIROC, ROC and various scans;

There is one other thing I would like to request for a future implementation, but first want to discuss it with you; I have come to rely on the Incredible Charts Comparison charts Daily and intra-daily and 1 hour charts (20 min delayed) for stock pre-selection.

I would like to replicate the I.C. setup for breakout type stocks in B.C. to do scans on and for visual reference. as an Index intercept on single price charts (not in a separate indicator panel) with a MA envelope (see attached image of I.C. set up).

Although I'm thinking it could be done in a separate panel through BCFL, if the above price chart was set up to same scale as the reference index chart as in security MOV(C,1,W) or just a close line chart, but would need a left edge intercept reference point for it to work.

This 'all' would be set up as an overlay saved to a function key, with ASX.XDJ and envelopes and apply to any chart for comparison (to single price chart, not multiple price charts overlays as in I.C.), so that the two price lines still intercept at the left edge of the chart at and adjusted to what ever time period is used.

If implemented in B.C. it would be primarily for visual reference when flipping through New Entry scan charts etc., and used in BCFL scans to identify breakouts in relation to the index $XDJ. Or as some kind of work-around with RSC? if overlaying or inserting directly onto price charts, with intercept, isn't do-able at this time.


Firstly; is the current RSC the only way to do comparison within BCFL and B.C.? I haven't identified anything else yet that might work as a direct comparison to $XDJ overlay to price charts, and they only seem to work in separate panels. I simply don't know what the potential overlay arrangements could be. I've tried dropping the RSC onto the price chart but scales are different, but I have had success with a double chart in one panel of the RSC of the ASX and the XDJ RSC of CBA chart. I'ts a bit confusing though and the indexes are not synced or intercepted, only where they match index levels.

I'm thinking the above comparison overlay could be done within code for scans with the output indicating (20)% (or MA Envelope upper band) closes above index $XDJ level if the intercept point is established in code, say; on Daily charts an intercept point of 3 years for example (as per IC image), and  to overlay or insert onto random price charts.

In code for for scans; I guess would be like a % difference to the XDJ index over a set period of time, as a scan output?
More than a bit confused how to set that up, I have tried to put the $XDJ / $XDJA into the RSC code without success, is there a reason for this, and why the 1000000 scaling?

{ RSC INDEX EXAMPLE }
COMPARISON:= Security(INDEX,C);
RSC:= (C/COMPARISON)*1000000;

Thanks.
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 18/12/2019, 02:20:16 PM
Re the ATR-TS:
Ok so there isn't the opportunity to slip in the oscillator cum() line and set it to something like 200 to limit the starting point to 200 bars after first bar, or something like that?:
max_old := hhv(data, cum(200));
min_old := llv(data, cum(200));

The only thing I could request as a future implementation would be to make available the system ATR-TS like you did with the RSI, so it can at least be referenced in BCFL, not just the ATRT-TS but SIROC also and anything else there for the user might need to use.

BCFL does not work the way you are expecting it to. The script must run over each bar in full, so you can make accomodation for visual display to help parse information visually but for speed considerations it will have not significant affect.

Time to compute is reduced with the amount of bars being pulled to display on the chart, which can be set from the period menu.

Not sure what you are referring to with the RSI, was that the function we expanded? The biggest challenge with system indicators is that they are coded entirely different to the rest of BCFL indicators, so the amount of work to port them across is significant. This has to be judged in tandem with other priorities like SPA3 Income, Portfolio Manager and the SWS App for the medium term.

NEXT UP;
This is probably the last thing I have to work out as I have enough scans set up now and are reasonably comfortable with doing basic MA type coding for the indicators I'm using MAs, MACD, Schaff Trend Cycle, RSI & Stochastic, M.S. SIROC, ROC and various scans;

There is one other thing I would like to request for a future implementation, but first want to discuss it with you; I have come to rely on the Incredible Charts Comparison charts Daily and intra-daily and 1 hour charts (20 min delayed) for stock pre-selection.

I would like to replicate the I.C. setup for breakout type stocks in B.C. to do scans on and for visual reference. as an Index intercept on single price charts (not in a separate indicator panel) with a MA envelope (see attached image of I.C. set up).

Although I'm thinking it could be done in a separate panel through BCFL, if the above price chart was set up to same scale as the reference index chart as in security MOV(C,1,W) or just a close line chart, but would need a left edge intercept reference point for it to work.

This 'all' would be set up as an overlay saved to a function key, with ASX.XDJ and envelopes and apply to any chart for comparison (to single price chart, not multiple price charts overlays as in I.C.), so that the two price lines still intercept at the left edge of the chart at and adjusted to what ever time period is used.

If implemented in B.C. it would be primarily for visual reference when flipping through New Entry scan charts etc., and used in BCFL scans to identify breakouts in relation to the index $XDJ. Or as some kind of work-around with RSC? if overlaying or inserting directly onto price charts, with intercept, isn't do-able at this time.

I can point you in a few directions. Execution wise it appears to be a series of moving averages and if that hunch is right you may not need BCFL, but I cannot see the specifics on what you are trying to replicate.

If the chart visual does require BCFL - remember to split what is plotted on to the chart to their individual variables and output all of these. This was covered early on if you need a refresher. Then under the formula properties set the charting mode to Overlay so it appears over price action.

You will need to also define what your intercepts are and how they interact for it to be close to ready be defined & entered in to a scan.

I have a feeling you may be trying to do this: https://www.incrediblecharts.com/indicators/compare_prices.php , just based on how all the stocks seem to start on the same point in your screenshot. This is close to the base reference but not naturally built in to BCFL. It typically involves grabbing a mutual date and then shifting the price based on the ratio of the 2 comparative prices ("normalising" them to be the same). For it to be scan ready, you would need to be able to grab the price for a given reference date and calculate based on the difference.

Where the issue with vector languages like BCFL come in, where a formula is done over each bar and limited looping capabilities, that different charts start on different dates. Taking the 1st bar and running with it is not a like for like comparison. Also you will run in to issues of data not existing if you scan over something that does not have any data with no way to tell BCFL to skip over it.

Give it a try for sure and you may find a process you are more than happy with - I am just trying to point out potential roadblocks to maneuver around before you are stuck with them.

Not sure what you mean by work around either. Relative Strength Comparison is a single indicator that uses a reference base (another chart). Security("$XDJ.XASX", C) is all you need to grab the close price of a specific chart which you can input in to the RSC formula.


Firstly; is the current RSC the only way to do comparison within BCFL and B.C.? I haven't identified anything else yet that might work as a direct comparison to $XDJ overlay to price charts, and they only seem to work in separate panels. I simply don't know what the potential overlay arrangements could be. I've tried dropping the RSC onto the price chart but scales are different, but I have had success with a double chart in one panel of the RSC of the ASX and the XDJ RSC of CBA chart. I'ts a bit confusing though and the indexes are not synced or intercepted, only where they match index levels.

I'm thinking the above comparison overlay could be done within code for scans with the output indicating (20)% (or MA Envelope upper band) closes above index $XDJ level if the intercept point is established in code, say; on Daily charts an intercept point of 3 years for example (as per IC image), and  to overlay or insert onto random price charts.

In code for for scans; I guess would be like a % difference to the XDJ index over a set period of time, as a scan output?
More than a bit confused how to set that up, I have tried to put the $XDJ / $XDJA into the RSC code without success, is there a reason for this, and why the 1000000 scaling?

{ RSC INDEX EXAMPLE }
COMPARISON:= Security(INDEX,C);
RSC:= (C/COMPARISON)*1000000;

Thanks.

Think these questions are covered in the paragraph above. Remember to take a look at the BCFL library and function syntax to see the arguments they accept if something is not being accepted by the editor.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 18/12/2019, 10:31:26 PM
Yes to be specific, the Incredible Charts Comparison type setup, but only with the XDJ index snapped into single charts in BC, so I can judge how far above, equal to, below, each stock in the list is compared to the XDJ / XAO index.

Quote
Execution wise it appears to be a series of moving averages and if that hunch is right you may not need BCFL, but I cannot see the specifics on what you are trying to replicate.
I would like to get a price chart overlay intercept for: Security("$XDJ.XASX", C) if it can be done through BCFL code, and then saved to a function key, so that it intercepts each stock I review from the left hand side.

If I use moving averages for the index, what would be the best direction to take to get an intercept working like you see in I.C.
Overlaying a Formula indicator, set as a moving average doesn't link the two different indexes; price and base index level, and resultant price chart will look squished to allow for the higher index.

So normalising the two data sets is the fist step? matching one data set to the others index level automatically as an overlay overlaid, at the chart window loaded data start period, or at a specific point in time like 4 weeks ago.

Could 'Value When' have some importance?
[Lookup & Reference]
Returns the value of the DATA ARRAY when the EXPRESSION was TRUE on the Nth most recent occurrence.
This includes all data loaded for the security according to the PERIOD selection on the CHART tab.
SYNTAX                      valuewhen(Nth, EXPRESSION, DATA ARRAY )

I was thinking the RSC could be the way in to normalising data to the sector or index used in the code, but when I set up two RSC's in the one formula the second one didn't plot out, or no output. Not sure why. I might try this again tomorrow.

One thing I have noticed is that the reference index ($XDJ) represents as almost a flat linein IC's charts much like a MA / Envelope set to 500 or so.  If the MA could be the actual XDJ line and matched to a data time period point.
I guess its all about the breakout range from the envelopes set at 15% or whatever, so just a moving average envelope might do? as that out sets itself on each chart. need to think this out more. I have a % above a MA line code for an indicator, might set it to 500 and see if it works similar to IC's Comparison.

As far as I can find there isn't a lot on normalising data sets in Metastock there being only one post on their forum about it, and I'm not sure what its about.
https://forum.metastock.com/posts/t144349--Normalized--Relative-Strength-Comparative (https://forum.metastock.com/posts/t144349--Normalized--Relative-Strength-Comparative)

The best I can do is search for others formulas, and by asking questions here. Much of the formula I'll be cut and pasting from others work, if I can find something substantial enough to use.

Post Edit:
Just as a final edit to this post; I have worked the Moving Average Envelope up with the Percent Above MA indicators (Separately, see attached snapshot). If the Moving Average 500 were to actually be the XDJ index line, this would work as a comparison to index. But I can't get my head around how to link the one to many index scales. 'One' being the XDJ, the 'many' being the stock price data charts.
Code here. I tried adopting the RSC code into the MA but didn't work:
> - - - - - - <

{ RSC }
COMP1 := Security("$XDJ.XASX", CLOSE);
RSC1 := (CLOSE / COMP1){*1000000};

MA1 := MOV(CLOSE,500,E);
{ McGinley MA }
MA2 := Ref(Mov(C,60,E),-1)+((C-(Ref(Mov(C,60,E),-1))) / (C/(Ref(Mov(C,2,E),-1))*10));

{ MA Envelope Bands }
Band_upper_inner := Mov(MA1, 1,E) + 0.5;
Band_lower_inner := Mov(MA1, 1,E) - 0.5;
Band_upper_outer := Mov(MA1, 1,E) + 1;
Band_lower_outer := Mov(MA1, 1,E) - 1;

MA1;
MA2;
Band_upper_inner;
Band_lower_inner;
Band_upper_outer;
Band_lower_outer;

> - - - - - - <

This MA1 code doesn't reflect the price chart accurately enough.

{Percent Above/Below Moving Average}
MA1 := ROC(CLOSE, 500, %);
MA2 := MOV(MA1, 50, E);

LINE1 :=0;
LINE1_UP:=50;
LINE1_DN:=-50;

LINE2_UP := 100;
LINE2_DN := -100;
MA1;
MA2;

LINE1;
LINE1_UP;
LINE1_DN;

LINE2_UP;
LINE2_DN;

> - - - - - - <

First Image is of code above in BC.
Second Image IC chart of MP1 and 500EMA bands with Comparison $XDJ
Third Image is the $XDJ with EMA500 Bands and comparison MP1.

I don't think the third will work in BC to flip through stock charts as you can't load in comparison stocks like in I.C. , but the Second would so is my preferred layout, if I can get the MA Bands to fit to the index line not the price chart.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 19/12/2019, 10:59:40 AM
Have found a code for Normalising but not surprisingly it doesn't plot out anything.
Could this be fixed and adapted to the
COMPARISON:= Security(SECTOR, CLOSE);
RSC:= (CLOSE / COMPARISON)*1000000;
code?

{ Moving Average Low Normalized Value }
Periods := Input("Time Periods", 1, 1000, 55);
BaseLow := Mov(LOW,Periods,E);
K := (1+((LOW-BaseLow)/BaseLow))*LastValue(BaseLow);
K;
LastValue(BaseLow);
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 20/12/2019, 02:39:54 PM
there is so much thoughts being recorded here, it is hard to tell what is an honest question and what is a tangent thought, but I will do my best to help direct where I can.

Yes to be specific, the Incredible Charts Comparison type setup, but only with the XDJ index snapped into single charts in BC, so I can judge how far above, equal to, below, each stock in the list is compared to the XDJ / XAO index.

I would like to get a price chart overlay intercept for: Security("$XDJ.XASX", C) if it can be done through BCFL code, and then saved to a function key, so that it intercepts each stock I review from the left hand side.

I can help convert an idea in to BCFL if it is well defined what is trying to be achieved. Saying that we do not write formulas ourselves, in these cases we can point in the right direction & provide some guidance.

What is the intercept you are looking for in terms of how it is calculated? It does not mean much to me as a word on its own so I make a few assumptions from here on in. I am assuming it's the same function I linked to on the previous post.

I will mention it is not always the best move to use BCFL for the sake of using BCFL and I cannot really provide much direction if it is not clear what the requirements are. Right now it is 'an intercept with $XDJ from the left hand side'. What is the left hand side? I am assuming from now on, from the 1st bar of the chart.

Quote
If I use moving averages for the index, what would be the best direction to take to get an intercept working like you see in I.C.

This is something you will need to work out and decide because it all depends how you want to decide the intercept is found.

From the link in my last post, the formula is clearly attributed:

Quote
The Price Comparison line is calculated using the ratio of closing price to that of another security/index, on the first day of the chart. This means that the starting point of the Price Comparison will vary according to the Time Period selected. The line may appear to move if you change time periods; but the slope remains the same.

Price Comparison (Intercept) performs a similar calculation, but on a selected date. If no date is selected, the earliest possible date is used. If the date selected is not a trading day, the next trading day is taken as the intercept date.

This is why I talked about charts starting on different dates, how the formula is done over each bar and how this will need to be taken in to consideration. This is not an insignificant piece of code. If you want to take it to a scan as part of your process, you will need to untangle the net on how you not only make sure the price is being adjusted appropirately in a way you are happy with, but also that the intercept is happening on the correct date.

Quote
So normalising the two data sets is the fist step? matching one data set to the others index level automatically as an overlay overlaid, at the chart window loaded data start period, or at a specific point in time like 4 weeks ago.

Could 'Value When' have some importance?
[Lookup & Reference]
Returns the value of the DATA ARRAY when the EXPRESSION was TRUE on the Nth most recent occurrence.
This includes all data loaded for the security according to the PERIOD selection on the CHART tab.
SYNTAX                      valuewhen(Nth, EXPRESSION, DATA ARRAY )

Value When gives you back the DATA ARRAY (ie. close price) the for the last N time some criteria is met.

If you are looking to normalise an intercept, the starting point is trying to grab the relevant price for the relevant intercept point and make sure it matches the underlying chart it is being applied to.

In that mind, it could if you structured it right. You want the close price for $XDJ on te 1st time that $XDJ was the 1st day of the underlying chart it is being applied to.

Have a look in to the DAY, MONTH and YEAR methods to try and select dates. Remember that you know you are on the 1st bar of a chart when the function CUM(1) equals 1.

Quote
The best I can do is search for others formulas, and by asking questions here. Much of the formula I'll be cut and pasting from others work, if I can find something substantial enough to use.

I want to mention without going in to the details here as the office is closing today and I won't be back until at least the 6th Jan - this does come back to the type of intercept you are looking for and what type of indicator you are trying to create. Otherwise it becomes in to one big guessing game on what you are trying to achieve.

Personally I think this line of thinking is way too over the top for what your charts actually depict is happening. Are you sure the comparison is relative strength and not just pulling the normalised data from another chart?

Beyond Charts overlays are a 1 to many relationship. It is 1 overlay object that can apply to many different charts, with the inputs being largely the same chart to chart but the price action data like open / high / low / close are obviously unique.

You would want anything you create to be flexible from this point of view.

I would suggest to work out exactly what Incredible Charts is calculating or finding a relevant support page for the function, find the formula than try and work from there.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 27/12/2019, 03:05:33 PM
Merry Christmas!  Happy new year! :wave:

I have done a ROC % comparison, although not sure if the comparison works as it should for direct comparison to a security for the relevant sector index. Clearly not as you haven't mentioned ROC % as a method of comparison in any of the  posts I made about it. The difference between the I.C. fixed starting point (3 years) is evident when comparing the two apps charts (see attached images).
I would like to get a price fixed together at a specific date period 'input' to 3 months, or 1 year, or whatever input date selected to use, I'll work this up over the break.

Feedback appreciated.

INDEX_IN := Security("$XDJ.XASX", C);
ROC_INDEX := ROC(INDEX_IN,126,%);
ROC_INDEX;

SECURITY_IN := CLOSE;
ROC_SECURITY := ROC(SECURITY_IN,126,%);
ROC_SECURITY;

{ Envelope Bamds }
MA1 := MOV(ROC_INDEX,21,E);
MA1;

{ Envelope Bamds }
Band_upper_inner := Mov(MA1, 1,E) + 15;
Band_lower_inner := Mov(MA1, 1,E) - 15;
Band_upper_inner;
Band_lower_inner;
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 29/12/2019, 01:25:19 PM
Wondering how to use the Data Window column "Market Cap" data in BCFL to get a daily volume to market capitalisation ratio for a column in scans?

Strange that Volume (Vol) is referenced but not listed in the BCFL Library for Look Up & Reference.
And what other non-listed reference-able entries would there be?
Thanks.
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 14/01/2020, 01:45:55 PM
Re the ATR TS problem:
I found this light weight ATR-TS, it works well for scans unlike the previous one which slowed scans and chart loading down greatly.
But there is a corruption with the system ATR-TS when it is auto loaded into a chart, they are named differently (changed name to see if that helped it didn't so must be a code corruption), haven't tried to fiddle with the code as it's way beyond me. It might be just adding smoothing in there  that might help? I read somewhere that lots of 'PREV' in code slows Metastock down.

Basically the chart corrupts like a BCFL code fmlvar renamed reference does. only way to recover chart is to close it and reopen a new one without the system ATR_TS auto loaded.

Code here:

{ ATRTS NEW }
loss:= 3.75*ATR(10);
ATRTS:=If(C>PREV AND Ref(C,-1)>PREV,Max(PREV,C-loss),If(C<PREV AND Ref(C,-1)<PREV,Min(PREV,C+loss),If(C>PREV,C-loss,C+loss)));
ATRTS;

thanks in advance.

 
Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 15/01/2020, 12:26:34 PM
Merry Christmas!  Happy new year! :wave:

I have done a ROC % comparison, although not sure if the comparison works as it should for direct comparison to a security for the relevant sector index.

 Clearly not as you haven't mentioned ROC % as a method of comparison in any of the  posts I made about it. The difference between the I.C. fixed starting point (3 years) is evident when comparing the two apps charts (see attached images).
I would like to get a price fixed together at a specific date period 'input' to 3 months, or 1 year, or whatever input date selected to use, I'll work this up over the break.

Feedback appreciated.

Happy new year John. Sorry about the delay.

I do often try to make this clear but Rate of Change is a form of relative strength [analysis] that is self-referencing, in that it tells a story about how that particular chart is performing. Relative Strength is a broad time even in technical analysis: it is a group of indicators that do a certain thing (provide a relative measure of strength) and a way of describing analysis or asking a question over a particular set of data.

Relative Strength Comparison compares an underyling chart to a chosen chart that is set as a paramater for the RSC indicator.

What you are asking for is not Relative Strength or Rate of Change (these do not normalise prices on a given day) but base reference and examples are over the previous posts.

Quote

INDEX_IN := Security("$XDJ.XASX", C);
ROC_INDEX := ROC(INDEX_IN,126,%);
ROC_INDEX;

SECURITY_IN := CLOSE;
ROC_SECURITY := ROC(SECURITY_IN,126,%);
ROC_SECURITY;

{ Envelope Bamds }
MA1 := MOV(ROC_INDEX,21,E);
MA1;

{ Envelope Bamds }
Band_upper_inner := Mov(MA1, 1,E) + 15;
Band_lower_inner := Mov(MA1, 1,E) - 15;
Band_upper_inner;
Band_lower_inner;

All I can really talk about is what it does. The ROC_Index being above than ROC_Security is saying if the sector has moved up quicker (in terms of its own previous values) than the security (in terms of its own previous values) over the last 126 days. You can read more on Rate of Change here: https://www.investopedia.com/terms/r/rateofchange.asp

Then there are some moving average bands based around the calcuation. I cannot say if this is wrong or right.

Quote
Wondering how to use the Data Window column "Market Cap" data in BCFL to get a daily volume to market capitalisation ratio for a column in scans?

Strange that Volume (Vol) is referenced but not listed in the BCFL Library for Look Up & Reference.
And what other non-listed reference-able entries would there be?
Thanks.

I am assuming that you mean the data sheet table or the share information panel and not the data window which shows values on the chart. Market Cap is inaccessible as something to be played around with in BCFL as it is fundamental data. You can add it to the scan results by including it in SHOWCOL() which I talked about a few months ago.

Volume is not in the reference list as it is an input to functions as part of the selectable Data Array options (which are O / H / L / C / V). Only functions are on the lookup table.

Quote
Re the ATR TS problem:
I found this light weight ATR-TS, it works well for scans unlike the previous one which slowed scans and chart loading down greatly.
But there is a corruption with the system ATR-TS when it is auto loaded into a chart, they are named differently (changed name to see if that helped it didn't so must be a code corruption), haven't tried to fiddle with the code as it's way beyond me. It might be just adding smoothing in there  that might help? I read somewhere that lots of 'PREV' in code slows Metastock down.

Basically the chart corrupts like a BCFL code fmlvar renamed reference does. only way to recover chart is to close it and reopen a new one without the system ATR_TS auto loaded.

Code here:

{ ATRTS NEW }
loss:= 3.75*ATR(10);
ATRTS:=If(C>PREV AND Ref(C,-1)>PREV,Max(PREV,C-loss),If(C<PREV AND Ref(C,-1)<PREV,Min(PREV,C+loss),If(C>PREV,C-loss,C+loss)));
ATRTS;

thanks in advance.

PREV is a very sensitive beast and we usually do not point peoples attention towards it. It is a function that takes no inputs, because it grabs the last value for that variable on the chart. So every time you say PREV, the software has to recalculate what that value is and stick it in memory to calculate that bar.

Sometimes finding what that value is will not be possible depending how it is used, which in those situations can cause corruptions. It is something you do have to understand to get the most out of it.

The function you provided works fine in my Beyond Charts. What auto load on the chart may be from an earlier instance. What happens when you drag it on to a clean chart (nothing loaded) from the Formula Explorer on the left hand side?
Title: Re: Help with BCFL custom Scans & Coding
Post by: JohnR on 15/01/2020, 11:58:44 PM
Understood about the ROC % comparison, I'm still trying to solve a formula to get a normalised syncing of Sector and stock/s let alone to a specific date period. You mention a number of times "previous post" are you indicating there is something I have overlooked? maybe in Reply #122?
- Whilst on ROC, I have noticed some trades in the SPA3 Portfolio - Risk Profile 1, that the ROC 126% is bellow zero and the RSC for sector is below the 30 signal line. ORA and GGG being the stocks, I was thinking the ROC and RSC were a qualifying factor for stock selection being positive?

Re the column Chooser fields;  sorry I did mean the Column Chooser fields () that can be called in BCFL under ShowCol() I was wondering how to call them into the formula much like a FMLVAR(). Wanting to assess Market Turnover as a ratio of Market Cap for a scan column. I don't quite understand Fundamental data being prohibited in BCFL.

Quote
The function you provided works fine in my Beyond Charts. What auto load on the chart may be from an earlier instance. What happens when you drag it on to a clean chart (nothing loaded) from the Formula Explorer on the left hand side?
The problem is not so much the system ATR_TS when loaded onto a clean chart, and the custom ATRTS is loaded in, they works fine together.

But more when the ATRTS is saved to a function key from the right hand Overlay panel, when dragged onto the chart it corrupts the chart.

It appears the stand alone Overlay of custom ATRTS works with system ATR_TS, but it is when a combination of other formulas saved in the Overlay panel the corruption occurs.

If the chart is already loaded with the Overlay panel indicators in the chart without the system ATR_TS loaded, and then the SPA3 Investor button is selected the system ATR_TS won't load into the chart.

Sorry that's as about as specific as I can describe the problem without showing you directly.
It's a bit of a nuisance as I generally leave the SPA3 Investor button depressed so it loads automatically to identify Investor stocks when I encounter them in scans, but this crashes the chart with my favourite Overlay set ups as the selected indicator set, but I can live with it if not fixable.

I've done some testing tonight by putting about 5 custom indicators and the custom ATRTS saved to an Overlay key without problems. And it doesn't appear to be anything to do with the alert signals I have written for the problematic Overlay key, as without the alerts in the chart the problem exists, so baffled as to the underlying cause, but it does seem to have something to do with the custom ATRTS. Post edit:
Could it be a memory write issue given all the PREV's in the formula conflicting with the system ATR_TS memory writes?
Also what line of code could replace the PREV to avoid it altogether?




Title: Re: Help with BCFL custom Scans & Coding
Post by: Campbell Sinclair on 20/01/2020, 03:33:35 PM
Understood about the ROC % comparison, I'm still trying to solve a formula to get a normalised syncing of Sector and stock/s let alone to a specific date period. You mention a number of times "previous post" are you indicating there is something I have overlooked? maybe in Reply #122?

http://www.sharewealthsystems.com/forum/index.php/topic,3526.msg16170.html#msg16170 In this post. The link I have dropped has the formula inside of it, surrounded by a discussion if it is possible or not in BCFL and what issues may arise.

There are limits to BCFL being a vector language, if you do need loops - you may wish to use something more powerful such as Amnibroker.

Quote
- Whilst on ROC, I have noticed some trades in the SPA3 Portfolio - Risk Profile 1, that the ROC 126% is bellow zero and the RSC for sector is below the 30 signal line. ORA and GGG being the stocks, I was thinking the ROC and RSC were a qualifying factor for stock selection being positive?

SPA3 Trader uses only the RSC as a filter for entry signals, the stock does have to be outperforming the market index. If it dips below while in trade we do not use that as an exit signal.

Quote
Re the column Chooser fields;  sorry I did mean the Column Chooser fields () that can be called in BCFL under ShowCol() I was wondering how to call them into the formula much like a FMLVAR(). Wanting to assess Market Turnover as a ratio of Market Cap for a scan column. I don't quite understand Fundamental data being prohibited in BCFL.

We do not have fundamental data within BCFL because the data format in from the ASX is static. Ie. the same value for the most recent bar would have to be applied for all previous bars. It is not something we are hard & fast about, but it has been left to be looked in to for later down the track while this is the case.

Quote
The problem is not so much the system ATR_TS when loaded onto a clean chart, and the custom ATRTS is loaded in, they works fine together.

But more when the ATRTS is saved to a function key from the right hand Overlay panel, when dragged onto the chart it corrupts the chart.

It appears the stand alone Overlay of custom ATRTS works with system ATR_TS, but it is when a combination of other formulas saved in the Overlay panel the corruption occurs.

If the chart is already loaded with the Overlay panel indicators in the chart without the system ATR_TS loaded, and then the SPA3 Investor button is selected the system ATR_TS won't load into the chart.

Sorry that's as about as specific as I can describe the problem without showing you directly.

It's a bit of a nuisance as I generally leave the SPA3 Investor button depressed so it loads automatically to identify Investor stocks when I encounter them in scans, but this crashes the chart with my favourite Overlay set ups as the selected indicator set, but I can live with it if not fixable.


I've done some testing tonight by putting about 5 custom indicators and the custom ATRTS saved to an Overlay key without problems. And it doesn't appear to be anything to do with the alert signals I have written for the problematic Overlay key, as without the alerts in the chart the problem exists, so baffled as to the underlying cause, but it does seem to have something to do with the custom ATRTS. Post edit:
Could it be a memory write issue given all the PREV's in the formula conflicting with the system ATR_TS memory writes?
Also what line of code could replace the PREV to avoid it altogether?

Overlays recall what is on top of a chart that is generic and able to be placed on top of other data (think BCFL or built in indicators). If you can drag on the ATR_TS that uses PREV from the left hand side BCFL Library on to a blank chart, this formula in particular should not be a problem. There is a lot to follow here though and sending in a copy of your database backup to support@sharewealthsystems.com with the overlay explicitly mentioned may be better so we can take a look at what is going on.

To send your database to us, please follow these instructions after ensuring SPA TradeMaster is closed:

1. In the Application menu to the left of the HOME tab, click BACKUP / RESTORE.
2. Change the BACKUP selection to CUSTOM, then browse (on right) and select your desktop, OK and OK again.
3. When the screen disappears, go back into BACKUP / RESTORE and change the selection back to DEFAULT then click OK.
4. Now, send the backup.zip file that is now on your desktop back to us as an email attachment.

PREV is in built and can not be written over. It is provided as a rudamentary way of looping in BCFL. It is a function in the language BCFL is coded with, not BCFL in of itself.

By the way - when a corruption does occur and you test it. Just make sure you close the chart and open it blank again to or the corruption can persist and the underlying issue can be murkied.