To and from Buy and Hold.
Author: EJoub
Creation Date: 3/9/2012 9:23 AM
profile picture

EJoub

#1
Hi

I have a position in Buy and Hold which I must maintain until I get an alert to invest elsewhere. Then at the sell alert, back to same Buy and Hold. How can this be coded?

If you wonder why I need above strange strategy... I'm working a fund and this company/broker
doesn't have a cash holding facility...so I'm forced into a Buy and Hold position when I,m
between trades. Good profits but must first back test.

Thanks
JEJ
profile picture

Cone

#2
"Elsewhere" has to be a symbol with data, otherwise it's cash. Assuming that the script runs on the "Buy & Hold" symbol...

CODE:
Please log in to see this code.
profile picture

EJoub

#3
QUOTE:
"Elsewhere" has to be a symbol with data, otherwise it's cash. Assuming that the script runs on the "Buy & Hold" symbol...

Yes and yes to above.

Do I read your code correctly?
When ElsewhereSymbol gets a buy alert, then exit Buy & Hold and buy Elsewheresymbol
at Bar +1.
When ElsewhereSymbol gets a sell alert, then exit Elsewheresymbol and buy Buy & Hold
at Bar + 1.
Ok, I'm guessing.

The buy and sell alerts from my existing strategy ( still in WL4 ) must be inserted into above.
I have no clue as to how.
BTW my WL6 contains above symbols.
profile picture

Cone

#4
There is no explicit buy condition for Elsewhere other than you buy it when you need to sell the primary symbol, and vice versa.

The code is not complete. You have to build your strategy around it to execute the two pieces when it's right time.
profile picture

EJoub

#5
QUOTE:
if (p != null && p.Symbol == "ElsewhereSymbol")


What is the meaning of above statement? WL6 code is Greek to me.
profile picture

Cone

#6
It means:

IF p, the Position object variable, is not null AND its symbol is "ElsewhereSymbol" THEN do something, i.e., sell it.
profile picture

EJoub

#7
Thanks. You have just elevated my level of ignorance to the next level, therefor I can't
use you advice below.
QUOTE:
The code is not complete. You have to build your strategy around it to execute the two pieces when it's right time.


profile picture

Cone

#8
Start by comparing the dozens of direct translations for scripts from Version 4 that you'll find in the Version 6 installation and from Strategy Downloads. You'll see that there is not that much difference in the structure of a C# script; mainly it's just syntax. You'll need to work with it for a couple months to get comfortable and to wean yourself off Version 4...we all had to do that, but it was about 4 or 5 years ago!
profile picture

EJoub

#9
You are obviously correct. I'm halfway there. My present situation limits my time to essentials. If back testing and trading history looks good I use discretion where my simple code doesn't work well. Not the best but safe.

Back to my proposed strategy. For back testing we need for instance Buy and Sell and the same for trading. Because I'm using funds in one company in this case, they simply switch the numbers between funds. This is the best situation. I also trade funds in other companies... this is a real problem. For instance the ElsewhereSymbol mentioned above.
The way I'm trading it at present, if i'm in the market for 5 days, my cash is tied up for 2 days before and 5 days afterwards... if I'm lucky. So much for administration for this type of trading. Ok, my choise, my problem and not yours.
The main problem in this company is that they don't have a cash facility where I can park my money beteeen trades... pathetic.

...And I'm asking for more assistance if possible at all. Thanks.
profile picture

Cone

#10
I can't make promises on writing your code (Our Support Policy), but I've already answered the only question you've asked!
profile picture

EJoub

#11
I appreciate your reply.

I would have translated Strategy to C#, but I have a problem with the translator as well.
It is in an old support ticket but let’s not go there at this time.

Let’s assume I'm in symbol ABC in B$H mode (this is where I must be because a cash position is not possible)

The following code gets an initial Enter signal on XYZ and the trade entry is delayed by 2 days. For clarity; The alerts are used for trading and the delays are the actual trade prices I use for back testing.
The initial signal for this entry must trigger a sell of ABC and a buy of XYZ which will be executed 2 days later. Vice versa when XYZ gets an initial exit signal it should exit next day and buy ABCwhich will be executed 2 days later. The underlined must be inserted in the following code...the rest of the code is present and working well.
CODE:
Please log in to see this code.
profile picture

Cone

#12
Please clarify:
If you want to "delay" the buy of the opposite symbol, then you are "in cash" for those bars of delay, but you said it's not possible to be in cash.

I just don't understand how your fund cannot have a cash facility. Anyway, this strategy with a 2-bar RSI is going to be triggering trades very frequently. Is the idea to always be in a position, "ABC" or "XYZ" except for the 2 days of delay after exiting the opposite symbol?
profile picture

EJoub

#13
An oops on my side and a very good catch on your side.

Reality.
I’m holding money in ABC... because no cash facility (yes, quite rare not to be able to keep money in cash...big company trading worldwide)

START
Holding ABC most of the time.

Then an entry signal for XYZ early morning on Tuesday (Based on Monday EOD)

I place an online switch instruction, from ABC to XYZ at 10h00 on Tues. Both are switched on Tues EOD price. (Note: The price which gave the alert was EOD Monday ie not the same price as on Tues EOD)
Thus Delay was 1 day (between alert and actual purchase) (It would be fantastic but not essential, to have the 2- day delay as well... one more parameter to play with)

And vice versa for Exit signal for XYZ.

QUOTE:
Please clarify:
If you want to "delay" the buy of the opposite symbol, then you are "in cash" for those bars of delay, but you said it's not possible to be in cash.

The delay is the 1 day between the trade alert (When I hit the button to trade) and the actual trade (Day of actual purchase)

QUOTE:
I just don't understand how your fund cannot have a cash facility. Anyway, this strategy with a 2-bar RSI is going to be triggering trades very frequently.

No, on average 17 times a year the last seven years, on XYZ.

Thank you once again.

profile picture

Cone

#14
QUOTE:
Both are switched on Tues EOD price
In other words, when RSI crosses under Y you Sell 'ABC' AtClose and Buy 'XYZ' AtClose. That would make sense for going from ABC (cash equivalent) to XYZ.

QUOTE:
And vice versa for Exit signal for XYZ.
"vice versa" is not clear, but I take it to mean that when RSI > X, you still delay the 1 (or 2) bars and Sell 'XYZ' AtClose and Buy 'ABC' AtClose.

Assuming that's correct (and I hope it is because I can't dedicate any more time for the foreseeable future), here you go -

CODE:
Please log in to see this code.

Caution!
Do not use 100% Equity Sizing unless you know what you're doing. This script will always hypothetically hold a Position, but whether or not that Position appears after sizing is a differently story. See User Guide: Strategy Window > Backtesting Strategies > 100% of Equity Sizing
profile picture

EJoub

#15
Thank you very much...it's 2 am Sun morning. See you tomorrow in case I have a snagg.

And thanks for the warning.
profile picture

EJoub

#16
QUOTE:
Both are switched on Tues EOD price
In other words, when RSI crosses under Y you Sell 'ABC' AtClose and Buy 'XYZ' AtClose. That would make sense for going from ABC (cash equivalent) to XYZ.

Above is only partially correct.
Note That RSI crosses under Y on Monday. So to simplify, I observe (the alert)
crossing on Monday at close and can only sell and buy (switch) Tuesday at close...which is equal to 1 day delay.

QUOTE:
"vice versa" is not clear, but I take it to mean that when RSI > X, you still delay the 1 (or 2) bars and Sell 'XYZ' AtClose and Buy 'ABC' AtClose.

Correct and exactly vice versa.
Note That RSI crosses over X on Monday. So to simplify, I observe (the alert)
crossing on Monday at close and can only sell and buy (switch) Tuesday at close... which is equal to 1 day delay.

I modified "ABC" in code to the FundSymbol I'm actually using and I'm running the code on XYZ.
Unfotunately the code show the following:
QUOTE:
Runtime error; Basis price for Position entry cannot be zero
At WL WScript BuyAtLimit(Int32 bar, Double LimitPrice)
At WL WScript BuyAtLimit(Int32 bar, Double LimitPrice, String signalName)
At WL WScript BuyAtLimit a(Double A_O)


Your assistance with this final step(hoping) would really be appreciated...thanks.

Note: Why did you use "AtLimit"? The PriceSeries show only Closing price... there is only one price at the close...no ohlc prices.

Sample:
QUOTE:
Open High Low Close
02/01/2007 1222.819946 1222.819946 1222.819946 1222.819946
03/01/2007 1223.160034 1223.160034 1223.160034 1223.160034
04/01/2007 1238.869995 1238.869995 1238.869995 1238.869995
05/01/2007 1238.869995 1238.869995 1238.869995 1238.869995

profile picture

Cone

#17
The Limit order is only to open the initial 'ABC' Position to initialize the strategy. Just change it to a Market order.

CODE:
Please log in to see this code.
profile picture

EJoub

#18
Cone, you are one fantastic supporter...I hope your employer knows and pays accordingly...

The code addition works as expected.

The profit performance is about the same as without the ABC trades but the results are weird to say the least...you should try it...you most certainly did so. Try running ABC
on the ABC symbol just for fun.

Initially I thought that if ABC gives a 1% profit and the gains from XYZ is very good, the net result would very good.
Do you spot the erroneous thinking? Yes, I forgot about the losses along the
way caused by ABC. The net profit for ABC over 3 years was 6% per annum and its losses
reduced XYZ by 6%.

All the other parameters for this strategy are also very different (besides profit), half are worse, especially DD at 17%.

General: Isn't there a CUM PROFIT Colum in the Trades view?
Isn't there a work around in WL6 for the EOD scanning (WL4) which could also be
used for creating watch lists or data sets?

This was quite a good learning experience for me and I'm very thankful that you dragged me along.

Thanks again
Ernst
profile picture

Cone

#19
I'm glad the code worked out for you :)

Cum Profit appears to have been axed in favor of simplification.. (as I recall, as soon as you sorted the columns in WL4, the Cum Profit never was quite right).

We're hoping to see the "WatchList functions" make it back into WL6, and even though it is highly-requested, this feature hasn't been winning the priority battles... but you never know what Eugene is going to surprise us with next ;)
profile picture

EJoub

#20
Real funny results...I have just changed backtest period by 6 months shorter in the 3 year period of the test. ABC profit is now bigger than XYZ. So the following can't be true;
QUOTE:
Do you spot the erroneous thinking? Yes, I forgot about the losses along the
way caused by ABC. The net profit for ABC over 3 years was 6% per annum and its losses
reduced XYZ by 6%.


Another short run and doing a manual calculation using the trades profit/losses in the trade view, the net profit in the performance view is correct. Thus above statement is true...grrr. Lesson, don't look at ABC (B & H column)... stupid! This time ABC net profit
is 13 times less than XYZ.

Again, a CUM PROFIT Colum in the Trades view would have shown this!

Its 1 am Again.
profile picture

EJoub

#21
This strategy is doing very well.

To make it more user friendly I would like to see the correct trades on a chart
for ABC. This could be a problem... where would/should this show? Maybe a new strategy
for for ABC based on ALERTS from XYZ. Probably not worth the trouble or maybe it is.

At the moment I see only the chart for XYZ.
The combined trades are normal in the performance view as to be expected.
profile picture

Cone

#22
See PlotSymbolTrades in the Community.Components. (The Wiki code formatting is temporarily in disarray.)

Note: You need to install the Community.Components extension and make the following modifications to the code above:

CODE:
Please log in to see this code.
profile picture

Eugene

#23
QUOTE:
(The Wiki code formatting is temporarily in disarray.)

Fixed.
profile picture

EJoub

#24
Thanks to both of you. I'll try my best.
profile picture

EJoub

#25
No joy so far...

QUOTE:
Note: You need to install the Community. Components extension:

Which one of the many extensions?

QUOTE:
// add this after the "for" trading loop

I have tried to add the suggested code or (parts of this code as in PlotSymbolTrades)
at various places, to no avail.
CODE:
Please log in to see this code.

Above is my idea of: after the "for" trading loop.

Results: All correct besides the two graphs. ABC graph contains incorrect trades. XYZ
shows a partial black screen.

I got PlotSymbolTrades working, so I now know what the graphs look like.

I have downloaded the extension containing "PlotSymbolTrades"

This has been quite a tour of WL6... the enjoyable/useful work.

More assistance will be welcome. Thanks.

profile picture

Eugene

#26
QUOTE:
Which one of the many extensions?

Community Components library.
profile picture

EJoub

#27
Yep, that is the one containing "PlotSymbolTrades". I assume it contains code which is required to run my strategy.

Thanks for the reply to the first question in my post but I did
download the correct extension before I attempted to add the additions.

The problems in the rest of my post, remains. I don't know how to proceed and assistance would be appreciated.
profile picture

Eugene

#28
To visualize trades taken on external symbols, refer to code from Cone's 3/17/2012 2:18 PM post.
profile picture

EJoub

#29
I have tried that but I can't get it to work. See my post on 3/18/2012 2:05 PM

Where to add Cone's code from 3/17/2012 2:18 PM post into his strategy from 3/10/2012 4:03 post, is the problem.

Here is my attempt where I have added cone's code at the end of the loop:
CODE:
Please log in to see this code.

Thanks.
profile picture

Eugene

#30
No wonder that it doesn't work: a commented line in Cone's post instructs to place it...
CODE:
Please log in to see this code.
profile picture

EJoub

#31
QUOTE:
// add this after the "for" trading loop


I thought that I have found the meaning of above but obviously not. Please deliver me
from my delusion.

I have tried to add the suggested code (or parts of this code as in PlotSymbolTrades)
at various places, to no avail.

Are you referring to this... doesn't make sense either:

QUOTE:
How to: Convert Strategy Code into a Screen

Quick answer: Remove the main looping statement and assign the variable bar to the last chart bar.



You can actually use the Strategy Builder to create a simple screen. First, select the Convert to Code-Based Strategy action in the Rules view. By default, the Strategy Builder includes a for loop as shown above. To turn it into a Screen, you need only to replace the "for" looping statement by assigning the variable bar to the last chart bar as shown:

profile picture

Eugene

#32
When you programmed your chartscripts in WL4, how does the trading loop look like?
CODE:
Please log in to see this code.

In WL6, it's the same with the syntax being a little bit different:
CODE:
Please log in to see this code.

The idea is to insert the block of code after the loop as suggested.

I strongly recommend you take a look at the Wiki FAQ for pointers on learning C# 101:
I'm a Wealth-Lab 3/4 user, how to learn C# ?
profile picture

EJoub

#33
Please see code
CODE:
Please log in to see this code.


Using your post, the block of code should be inserted directly after this
CODE:
Please log in to see this code.


This spot for the code block indicates an error; Type name 'Utility'could not be found.

Please advise.
profile picture

Eugene

#34
QUOTE:
Using your post, the block of code should be inserted directly after this

Yes.
QUOTE:
This spot for the code block indicates an error; Type name 'Utility'could not be found.

One more step left to go, and to finish this quest, you have to carefully re-read everything in Cone's post.
profile picture

EJoub

#35
Now that is positive.

QUOTE:
See PlotSymbolTrades in the Community.Components.

I saw PlotSymbolTrades and even got it working.
You said
QUOTE:

(The Wiki code formatting is temporarily in disarray.)

Fixed.
So no problem here...hope its still fixed. Maybe I must upgrade again.

I have done the following...it is installed but I haven't seen the contents if that's possible.
QUOTE:
You need to install the Community.Components extension and make the following modifications to the code above:

I have the following:
QUOTE:
// add this at the top using Community.Components;


Maybe I should use a Limit Order instead of Market Order.

Now a question for you. How many times do you think I have red above & Guides & & & ?
Clue, I can't even get onto the learning curve. On a positive note...imagine the scope I have.



profile picture

Eugene

#36
QUOTE:
Now a question for you. How many times do you think I have red above & Guides & & & ?

I deliberately do not deliver a turnkey solution because I'm a firm believer in learning by example. This is not nearly rocket science, so I do know that it does not take bashing one's head against the wall. Cone's instruction is a simple, two-step how-to on copying and pasting.

So if the hint says "add this line at the top", take a careful look at your Strategy code, notice the similarities... and just add this line at the top where it belongs! :)
CODE:
Please log in to see this code.



profile picture

EJoub

#37
QUOTE:
look at your Strategy code, notice the similarities... and just add this line at the top where it belongs! :)
This contains the clue but it is as open as Cone's. (How long is a piece of string?)

If I look at the PlotSymbolTrades top section I see "using Community.Components;" is the
last item in the column at the top. See
CODE:
Please log in to see this code.


Its position makes a difference but I can't see the pattern or rule. I moved it in the
PlotSymbolTrades code and it didn't make a difference. In my code it does and adding it to the top column in the last position doesn't work.

So I'm not on solid ground yet. :)




profile picture

Eugene

#38
Alright, you've got the "using" directive pasted in the proper place.

If the code still does not deliver a nice two-pane of your stock vs. the cash symbol ("ABC"), and/or there's an error message, my efforts from 3/19/2012 11:10 AM were futile. You've still not found the end of the trading loop.
profile picture

Cone

#39
CODE:
Please log in to see this code.
profile picture

EJoub

#40
Eugene,
QUOTE:
If the code still does not deliver a nice two-pane of your stock vs. the cash symbol ("ABC"), and/or there's an error message
That is correct.

QUOTE:
my efforts from 3/19/2012 11:10 AM were futile
Not so!

Cone, thanks! Will take a look.
profile picture

EJoub

#41
Yep, working now... ABC panel normal, correct but only 2 cm high.

Ok, panel now correct size!

You both have again walked the proverbial extra mile...outstanding!

Thank you.
profile picture

EJoub

#42
My post of 3/16/2012:
QUOTE:
To make it more user friendly I would like to see the correct trades on a chart
Cone and Eugene assisted with this and it works very well but I can't see any other performance data for ABC.

Now that I know the limitations of above the following is what I actually require.
QUOTE:
Maybe a new strategy for ABC based on ALERTS from XYZ.
I know about an example of this but I cannot modify mine accordingly...the jump is to great for me.

This strategy started out as research but its testing on six years of prices and on other symbol pairs is the best I have seen on local funds.

Cone warned about 100% equity in backtesting. I found that a 4:1 margin works but not
2:1. Does this mean that much more cash is borrowed than using 2:1?...sample calculations show borrowing to be in the order of 0.02% to 0.03% of equity at that point. Do you agree? I know it is a variable %.

You assistance would be appreciated very much.
profile picture

Cone

#43
The problem with 100% is two-fold: having funds available after exits and the effect of Basis Price on sizing Positions. A must read is the User Guide about how Basis Price and Position Sizing works in Wealth-Lab; see the topic on 100% Equity Sizing.

If there´s still a problem, please use specific examples with dates and recognizable symbols, preferrable using Y! data so that we´re on the same page.
profile picture

EJoub

#44
I have made a study of 100% sizing and it's not a big issue. I'm making comparisons with
40% with a margin of 1:1.

With reference to above code, can you assist with trading ABC using signals from XYZ so that I can see all the performance metrics of ABC ? The present code use ABC as an alternative cash holding, but ABC must just be part of the pair. Thanks.



profile picture

Cone

#45
ABC (your symbol that you use as the cash alternative) is the pair trade with XYZ (the primary symbol on which the script runs). You can't run the script on ABC and get the same results as running the other way. Unfortunately, the BySymbol visualizer doesn't work unless the backtest is MSB mode (clicking on the DataSet), which would not be valid here.

You'll probably have to resort to right clicking, copying, and pasting the Trades view into Excel and do your analysis there. Or, creating your own custom Visualizer for Wealth-Lab is always an option.
profile picture

Eugene

#46
I don't think that creating a custom Visualizer is an option here. In single-symbol backtests, the SystemPerformance.Bars list will only hold the current Bars object i.e. XYZ. In other words, there is no positions for ABC, so nothing to calculate here.
profile picture

EJoub

#47
QUOTE:
You'll probably have to resort to right clicking, copying, and pasting the Trades view into Excel and do your analysis there.
I have been doing exactly that.

I had something simpler in mind. A separate script with the sole purpose of monitoring the total performance of only ABC and not for trading. Just running this script on XYZ, using XYZ and its own trading rules to trigger trades on ABC.

Here is your own example indicating what I have in mind.
CODE:
Please log in to see this code.


profile picture

Cone

#48
Sure, that's a good idea.. create an equivalent script that runs on ABC using the opposite logic used for XYZ.

In fact, if you want to operate that way always, forget about the pairs script altogether. Create two scripts with opposite logic. You can then run them separately or see their combined performance in a Combination Strategy.

Note: If you're running a script on ABC and want to trade ABC, then there's no need to use the Set/RestoreContext() statements.
profile picture

EJoub

#49
QUOTE:
Sure, that's a good idea.. create an equivalent script that runs on ABC using the opposite logic used for XYZ.
I don't understand this because I need the RSI curve of XYZ to drive the trading on ABC. And I only need this script for information and not for trading. The other script we worked on earlier, is for actual trading...and is working very well.

profile picture

EJoub

#50
Due to misunderstanding this original post and the previous post had to be completely rewritten. Sorry...

And yes please, I stil need a starter pack re script in previous post. Thanks.
profile picture

Cone

#51
Here's a quick look at it, maybe this will work. Time is very tight this week, so if it doesn't work I probably won´t answer until next week.

CODE:
Please log in to see this code.
profile picture

EJoub

#52
Thanks a lot. Take care and watch out for stress symbols.
This website uses cookies to improve your experience. We'll assume you're ok with that, but you can opt-out if you wish (Read more).