Exit-only strategy on existing open positions
Author: Sarath1
Creation Date: 5/26/2020 7:18 AM
profile picture

Sarath1

#1
I have muliples of Existing Open Positions bought through other Fidelity tools
and I plan to create Exit/Sell Strategy on them based on mutli-factors using WealthLab for Back-testing and eventually Auto-Trading.

I do see Examples code of Pre-defined strategies involves both Buy and Sell together and not match my requirements. Can you please share me example Code to read the "Buy Price and also Quantity #shares of Existing Open Positions from Fidelity account and as such it reads the Symbols but not reading other Buy Transaction details when loading as DataSets.

I searched with keywords "closeout, existing position" etc on your Forum and Wiki and not able to find example code.

Appreciate your help on this.
profile picture

Eugene

#2
profile picture

Sarath1

#3
Sure, have got some idea to code about using given samples and Thanks!

Actually above helps but not precisely for Wealth-Lab's reports as this logic picks some random Buy Price which is not Actual...
Can we make it read the actual Buy Price from all Existing Positions in Fidelity account ? and if this is not possible can we do hard-coding of Buy Price values ?

profile picture

Eugene

#4
Reading data from the actual Fidelity account is not considered.

With the help of "ImportHistoricalTrades" solution from Community Components you could import real (historical) trades from either Wealth-Lab's Accounts tool or from a text file (CSV). If your actual trading history can somehow be exported from Fidelity's website to a compatible text file and it's long enough (many records) then this is the way to go.

For only a handful of entries it makes sense to simply hardcode them in the Wealth-Lab Strategy using EnterAtPrice (ImportHistoricalTrades is driven by it internally):

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

superticker

#5
QUOTE:
If your actual trading history can somehow be exported from Fidelity's website to a compatible text file
Log into the Fidelity website and display your portfolio. When doing so, select the Positions tab. There you will see a Download tag where you can download an Excel readable file of all your current positions including share quantity and prices. From there, you can have Excel save that as a text file.

You can also right click on the WL Account Balances and Positions window, select "copy", and place that information on the Clipboard as a tab delimited text file. You can certainly paste that into Excel if you want to pick out certain columns.
profile picture

Sarath1

#6
Thanks @eugene and @superticker for info.

@eugene actually I have multiple tens of entries keep varying every week and so best for me to read from WealthLab Accounts file which just works fine for me if below works,
CODE:
Please log in to see this code.


But it throws error when I just tried your given sample code and do we need to install any additional for this "ImportHistoricalTrades" to work..
Please find below the Code and Errors when try to run code,

Please find attachment the Snip for Errors
profile picture

Eugene

#7
You have to install Community Components and restart WLP before using this code.
profile picture

Sarath1

#8
Thanks a lot @eugene and with all details now I got installed brought up Community Components and those old errors are gone.

>>> Now getting into File processing error as it looks for AccountsFile it expects file on specific location as per below errors seen of that same code given earlier,

Error processing symbol XXX Could not find file 'C:\Users\XXX\AppData\Roaming\Fidelity Investments\WealthLabPro\1.0.0.0\Data\TradeHistory.xml'.
profile picture

Eugene

#9
TradeHistory.xml is the file where your Wealth-Lab trading history is contained. It's generated by WLP as you do Paper and Live trading in WLP. You've confused it with trades made in your Fidelity account on the website or ATP platform. These trades will not appear there as WLP neither has means to pick them up nor is designed to do so. Predictably, the TradeHistory.xml file doesn't exist so the TradeFileImportMode.AccountsFile mode you're trying to put to use will fail.

Please carefully review my post #4 for the general idea and then @superticker's post #5 for instructions. Follow them to 1) download your trade history from Fidelity's website, 2) copy it to Excel or Notepad++ (your choice), 3) modify so it conforms to either SimTradeFile or SimTradeFile2 format, save to a TXT/CSV file and 4) then use TradeFileImportMode.Format1 or TradeFileImportMode.Format2 as exemplified in the manual:

Import real (historical) trades
profile picture

Sarath1

#10
hm! now I could understand the actual reasons for those ideas given earlier.
Sure, let me try them. Thanks for clarifications.

Also the WL enhancement which could help many of us will be if you could create API to parse whatever shown on WL Accounts/Positions which you already have them listed when logged into Fidelity because it helps Dynamic & Automatic processing without any manual interventions... But I believe based on your previous comments, looks some current Business agreements between WL and Fidelity maybe stopping it....
profile picture

Eugene

#11
Provided there's significant demand for such an API, why not give it a chance. But hey, there have to be much more than 1 or 2 requests for it in over a decade of WLP existence! :P

That's why I said that Reading data from the actual Fidelity account is not considered.
profile picture

Sarath1

#12
Got it :-)
profile picture

Sarath1

#13
Got it :-)

Thanks again and now I could get the CodeLogic running success using SimTradeFile2 format to parse my sample data.
So now stepping into next-level issues... and as I assume "SimTradeFile2" when success already converted the given File-records(XXX.csv) as historical Entry points already happened but below is what I observed,
1) PrintDebugs shows ActivePositions.Count shows Zero as like nothing Entry happened for historical data from the given file.
2) because of the above the next expected strategy of Exit/Sell never happened...


>>>>Please find below my Data File on SimTradeFile2 format and the Code parsing it..

>>>> C:\Users\XXX\Documents\XXX.csv
PLAY;02-10-2020;Buy;46.0;120
SAVE;02-10-2020;Buy;44.0;100


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

superticker

#14
QUOTE:
Also the WL enhancement which could help many of us will be if you could create API to parse whatever shown on WL Accounts/Positions
I too would be interested in having such an API.

What I do today is copy the contents of the Accounts/Positions window to the Clipboard, then I have a command line C# program read the Clipboard and write a file to disk at the end of each trading day. My own DLL library classes then use these file contents so if I miss a trade the day before, my strategy suggests it again with the appropriate Alert. But these are advanced custom libraries I crafted for my own trading style. They may not be appropriate for everyone.

My point is, if you're willing to do a little Clipboard and disk I/O, you can craft your own class libraries to do the same thing for your own trading style. But I would learn the salient operations of WL first before partaking down such an adventurous path. Happy coding to you.
profile picture

Eugene

#15
1. This second call is superfluous and has to be removed:
CODE:
Please log in to see this code.


2. Make sure you've loaded enough data for all the symbols in your trade file for all your historical trades show up in the backtest. I think this is what you're missing.

Before you ask any further questions on this please exhaust the Setup and troubleshooting section of the Wiki online user guide.
profile picture

Sarath1

#16
Sure & Thanks @eugene and @superticker for inputs and let me debug more accordingly to get this through. Thanks!
profile picture

Eugene

#17
Glad to help you!
profile picture

Sarath1

#18
Hi @Eugene,
have exhausted all of given "Setup and troubleshooting" and in-fact went beyond checking with reference to its source code and multiple related Forum discussions and all I could suspect now is for some reason "EnterAtPrice" is not working on my setup and so the reason "ImportHistoricalTrades" also not working as it depends on it and my doubt because of below reasons,

>>> when I try similar hard-coded approach "BuyAtMarket" using DateTimeToBar it just works fine on my setup triggering Buy trades per hard-coded value but limitation it takes only hard-coded "Date" and not the "Price"

>>> Also your given Sample Code on this thread #4 which uses "EnterAtPrice" and when I just try that given sample Code as it is.... with only my data-set changes to point to hardcoded (SPY and May/14/2020), I could observe No buy trades triggered.

So, please let me know to execute your #4 code-sample, anything else to be installed ?
profile picture

Eugene

#19
Maybe it's because *AtPrice methods are reluctant to trigger trades in the future as the computer doubts that you have a crystal ball? ;) Take a careful look at your (irrelevant) date/time format and the October 2020 trades:

QUOTE:
PLAY;02-10-2020;Buy;46.0;120
SAVE;02-10-2020;Buy;44.0;100


CODE:
Please log in to see this code.


Further reading:

* Standard date and time format strings
* Custom date and time format strings
profile picture

Sarath1

#20
@eugene :-)
but that was old one and even I found out during my debugging yesterday and tried correcting those but still didn't help as there is something else and so the reason we doubt now EnterAtPrice and just to rule out all of my any wrong possibilities, so I am executing your given same example code itself #4 of this thread and No-Success..

Appreciate your help if you check #4 of this thread and provide some inputs/clues for me to check further..
profile picture

Eugene

#21
No need to check #4 as it just works.

If you can provide an all-in-one, detailed report (instead of hints) which includes a bullet list of your data loading and position sizing settings, symbol(s), code, and the trade data file, then I could look into it.
profile picture

Sarath1

#22
Sure, Please find below the requested list of details,

Scale: Daily
Data Range: 30 Days
Position Size: $2500

Symbol: SAVE


CODE:
Please log in to see this code.



>>Trade Data File C:\Users\n.sarath\Documents\XXX.csv,
SAVE,26-05-2020,Buy,11.5,245

profile picture

Eugene

#23
Works as expected:



Position size and data range are OK, not a factor here. Sometimes, subtle options like "Limit a position's quantity..." may have an effect - you might want to review your Wealth-Lab's Preferences.

P.S. Please wrap embedded code in CODE tags. There's # button for that, no need in those ### (that I have to convert into code in your posts).
profile picture

Sarath1

#24
Not for me... :-(
please find attached

Sure, will do include code using # button
profile picture

Eugene

#25
You have a (new) runtime error there which isn't mentioned in your error report (sigh). That's the deal breaker. Firstly, check out the WL Wiki for "Object reference not set to an instance of an object" (at the bottom). There are at least 3 suggestions that may apply in your case: "Benchmark B&H", On Demand Update, and chart drawing objects (unlikely). If neither one helps then it's something specific to your configuration (which I cannot reproduce) upsets the method :/
profile picture

Sarath1

#26

Well, the reason I had not mentioned it because last couple days my debugging I clearly found it not relevant on this because we see that errors only because "ImportHistoricalTrades didn't Enter the position" but later trying to check ActivePosition to ExitPosition and so errors..

If I commented-out those ActivePosition to ExitPosition lines and run the strategy, there are no such runtime errors as you could find below attached but neither there No EnterPosition per "ImportHistoricalTrades" which we expect to see for this as confirmed on Debug of Positions count....



profile picture

Eugene

#27
You're right, I should've noticed the code is trying to exit a non-existent (null) LastPosition.

It's not that EnterAt* fails internally. In this case it would pass on the error to the Debug log. Perhaps the method couldn't find the trade date. How is the date/time format set up in your Windows and what are your regional settings?
profile picture

superticker

#28
QUOTE:
... because we see that errors only because "ImportHistoricalTrades didn't Enter the position" but later trying to check ActivePosition to ExitPosition and so errors ...
Yes, your historical trades never entered some positions because you didn't use WL to enter those positions originally (via the WL Orders window). Let me make an alternative suggestion.

1) Capture all your current existing positions with Excel as discussed in Post# 5. Highlight those symbols with Excel and paste them into a new WL dataset (call it "existing positions") to use with your favorite trading strategy below.

2) With your favorite strategy (any strategy with a trading FOR loop will work), edit the commented out line below and replace it with "true" as shown. That will force your chosen strategy to only Sell (and never Buy).
CODE:
Please log in to see this code.

3) Optionally, reduce the number of trading iterations in the trading FOR loop to the last 10 Daily bars as shown. (In theory, you could reduce it to one Daily bar, but let's not do that here; you might miss a recent Sell.)
CODE:
Please log in to see this code.

---
I think Step# 3 is unnecessary if you reduce your Data Range to 100 (or so) Daily bars. You should still learn how to use ImportHistoricalTrades because that may come in handy for other things.
profile picture

KGo

#29
Easy way:
1 Save the trades from Fidelity.com or Fidelity Active Trader Pro as csv file. Save as HistoricalTrades.csv in Documents folder. Use website or ATP column headings to sort by date with buys before sells on each date. No need to remove or change or copy/paste any transactions. Remove disclaimer at bottom of the website file and add this line to the top of both.
QUOTE:
DEFAULT ~EnterAt:SDP ~ExitAt:SDP ~Print:All ~Transfers:off ~Symbol:NOSub:FDRXX=SKIPIT ~%Equity: ~EntryName: ~ShowPositionLine:On ~TransPhrases:distr : tax paid :royalty: in leiu:fee charged ,


2. Open Historical Trades: No Coding... select Wealth Script Override in data panel and execute. See your trades.

5. Add exit code at the very bottom before bracket labeled End Execute.

Check Debug window. Many messages will print. Done.
profile picture

Sarath1

#30
Thanks @Eugene and @superticker and @KGo for inputs/ideas matching for my requirement.

@KGo I just got downloaded of "Historical Trades" and also so quick to see the Historical Trades updated with actual count of shares and split etc but there is no "Editor" tab shown and please let me know how do I add my exit-code which you mention as bottom before labelled End execute..



profile picture

Eugene

#31
You must have picked "Historical Trades" from "Wealth-Lab Community Components" folder? Being a compiled strategy embedded into and delivered with C.Components, this one will not have the Editor exposed. You should click the "Download..." button in the "Open Strategy" dialog, click "Begin Download" (with "Download Public..." checked and "Published since" UNchecked) to get all downloadable strategies, then find the "...No coding..." strategy in the Utilities folder.
profile picture

Sarath1

#32
Great & Thanks @Eugene and that helps to view the code and now I can go about try my exit ideas.
profile picture

Eugene

#33
Glad to help you. Kudos to @KGo for his solution.
profile picture

Sarath1

#34
@KGo
For Backtesting inside the Strategy window, your given "Historical Trades" works great reading all the HistoricalTrades from file and also Exit strategy just works great per my code/designs generating both the Trades and also New Alerts.
But when I include it part of "Strategy Monitor" with "Auto Staging" enabled, I neither see Trades nor see Alerts and when checking the Strategy Monitory Debuging logs it shows below,

QUOTE:
6/16/2020 8:28:09 PM: Run Once beginning ...
6/16/2020 8:28:09 PM: RunNow Processing Beginning
6/16/2020 8:28:09 PM: Preparing for initial Data Population
6/16/2020 8:28:09 PM: Starting Populate Thread
6/16/2020 8:28:09 PM: In Populate Thread
6/16/2020 8:28:09 PM: Populating: X_DS_Save
6/16/2020 8:28:09 PM: Updating: X_DS_Save
6/16/2020 8:28:09 PM: Symbols already up to date: SAVE
6/16/2020 8:28:09 PM: Symbols already up to date: SAVE
6/16/2020 8:28:09 PM: Loading Data for SAVE
6/16/2020 8:28:09 PM: 104 bars returned
6/16/2020 8:28:09 PM: Creating Executor
6/16/2020 8:28:09 PM: Executing: SAVE
6/16/2020 8:28:09 PM: Error(4): Object reference not set to an instance of an object.
6/16/2020 8:28:09 PM: Run Once Processing Completed
6/16/2020 8:28:09 PM: Run Now Ended
6/16/2020 8:28:09 PM: Leaving Populate Thread


I know I am missing something basics and Appreciate your help/inputs.
profile picture

KGo

#35
Perhaps Eugene may have some insight. Historical Trades is producing correct trades and new alerts so he should be able to help with the other tools. The log messages are unknown to me.
profile picture

Eugene

#36
@Sarath1

For sure I could help with troubleshooting the SM error message but only as long we count out the Historical Trades strategy. If you can provide a short sample code with related data (symbols, data range, position sizing and other settings + SM log) that demonstrates the error, feel free to start a new forum topic (or post in a closely matching existing one). However, it should not have anything to do with troubleshooting KGo's highly complex strategy like I said.
profile picture

Sarath1

#37
Sure & Thanks!
Have opened new Forum Topic for this as below,
QUOTE:
"Historical Trades: No Coding" works perfect inside Strategy Window but errors on SM

profile picture

Eugene

#38
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).