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.