Exporting historical data from ThinkorSwim for external analysis

@korygill the script works now. Thank you so much for the help.


Hi,

Below script is working and creating csv file as well.
Code:
#
# Get-SOHLCP.ps1
#
# Script to convert a TOS ThinkOrSwim kg_EveryTickSOHLCP strategy report csv file to an object and/or proper csv data file.
#
# Author: Kory Gill, @korygill
# Version: 20200304.2300
#
# Examples
# $x = gci 'D:\Database\MarketData\TOS-StrategyReport-Files-SOHLCP\UseThinkScriptDemo\StrategyReport*' | Select -ExpandProperty FullName | D:\Source\Repos\technical-analysis-dev\dev\Get-SOHLCP.ps1 -InformationAction Continue
#
# Get the symbol back:
# $m = 'SOHLCP-(~ES.XCME)(1.21.20 5.00 AM - 1.27.20 1.14 PM).csv' | Select-String -Pattern '\((.*?)\)' -AllMatches; $m.Matches[0].Groups[1].Value -replace '~', '/'
#
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string[]]
$File,

[switch]
$ExportAsObject
)

Begin {
function Convert-CurrencyStringToDecimal ([string]$input)
{
((($input -replace '\$') -replace '[)]') -replace '\(', '-') -replace '[^-0-9.]'
}

$global:sohlcpAllData = New-Object System.Collections.Generic.List[PSCustomObject]
}

Process {
foreach ($f in $File)
{
if (-not (Test-Path $f))
{
throw "Cannot open file '$f'."
}

Write-Information "Processing file: '$f'."

# read csv file
$content = Get-Content -Path $f

# generate filename
$csvSymbol = ($content[1] -split 'Symbol: ')[1] -replace '/', '~' -replace ':', '.'
$csvWorkTime = ($content[2] -split 'Work Time: ')[1] -replace '/', '.' -replace ':', '.'
$outFile = 'SOHLCP-(' + $csvSymbol +')('+ $csvWorkTime + ')'

# find the lines that contain price information
$csvdata = $content | ? {$_ -match ";.*;"} | ConvertFrom-Csv -Delimiter ';'

# filter just the lines with (OHLC on them and make into CSV structure
$data = $csvData | ? {$_ -match "\(SOHLCP"}

$sohlcpFileData = New-Object System.Collections.Generic.List[PSCustomObject]

foreach ($item in $data)
{
# capture the OHLC data
$null = $item.Strategy -match "\(SOHLCP\|(.*)\)"
$v = $Matches[1] -split '\|'

$symbol = $v[0]
$open = $v[1] | Convert-CurrencyStringToDecimal
$high = $v[2] | Convert-CurrencyStringToDecimal
$low = $v[3] | Convert-CurrencyStringToDecimal
$close = $v[4] | Convert-CurrencyStringToDecimal
$prevClose = $v[5] | Convert-CurrencyStringToDecimal
$macdValue = $v[6] | Convert-CurrencyStringToDecimal
$macdAvg = $v[7] | Convert-CurrencyStringToDecimal


# add to our $outData array
$cleanDateTime = [System.Text.RegularExpressions.Regex]::Replace($item.'Date/Time', '[^\x00-\x7F]', ' ').Trim()
$sohlcpData = [PSCustomObject]@{
'Symbol' = $symbol

'DateTime' = ([datetime]::parse($cleanDateTime))
'Open' = [decimal]$open
'High' = [decimal]$high
'Low' = [decimal]$low
'Close' = [decimal]$close
'PrevClose' = [decimal]$prevClose
'macdValue' = [decimal]$macdValue
'macdAvg' = [decimal]$macdAvg
}

# add to our $sohlcpData array
$null = $sohlcpFileData.Add($sohlcpData)
$null = $sohlcpAllData.Add($sohlcpData)
}

# save to file
$sohlcpFileData | Export-Csv -Path (Join-Path (Split-Path -Path $f -Parent) ($outFile + '.csv')) -Force -NoTypeInformation -Encoding ASCII
}
}

End {
if ($ExportAsObject)
{
# helpful message to show caller our output variable
Write-Information "Out Data $($sohlcpAllData.Count) items (exported as `$sohlcpAllData)"
}
else
{
# don't show any extraneous output, and just return the data to the pipeline
return $sohlcpAllData
}
}

When running this script, I get the error:

Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null.
At C:~get_SOHLCP(M-d-yyyy).ps1:102 char:27
  • ... pFileData | Export-Csv -Path (Join-Path (Split-Path -Path $f -Parent) ...
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: :)) [Export-Csv], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand

Sorry, I've tried Googling various fixes, but I'm not very good with code.
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
311 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top