Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dharmatech/af0c7144dc6122befd81edd104b759a0 to your computer and use it in GitHub Desktop.
Save dharmatech/af0c7144dc6122befd81edd104b759a0 to your computer and use it in GitHub Desktop.
$api_key = '{0}' -f (Get-Content C:\Users\dharm\Dropbox\api-keys\polygon-io)
$ws = [System.Net.WebSockets.ClientWebSocket]::new()
$buffer = [byte[]]::new(1024 * 4)
function send ($msg)
{
$msg_bytes = [System.Text.Encoding]::UTF8.GetBytes($msg)
$array_segment = New-Object System.ArraySegment[byte] -ArgumentList @(,$msg_bytes)
$ws.SendAsync($array_segment, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, [System.Threading.CancellationToken]::None).GetAwaiter().GetResult()
}
function receive ()
{
$buffer_ = New-Object System.ArraySegment[byte] -ArgumentList @(,$buffer)
$memory_stream = [System.IO.MemoryStream]::new()
do {
$task = $ws.ReceiveAsync($buffer_, [System.Threading.CancellationToken]::None)
while (!$task.IsCompleted) { Start-Sleep -Milliseconds 100; Write-Host '_' -ForegroundColor Yellow -NoNewline }
$result = $task.GetAwaiter().GetResult()
$result_write = $memory_stream.Write($buffer_.Array, $buffer_.Offset, $result.Count)
}
while (!$result.EndOfMessage)
$result_seek = $memory_stream.Seek(0, [System.IO.SeekOrigin]::Begin)
$stream_reader = [System.IO.StreamReader]::new($memory_stream, [System.Text.Encoding]::UTF8)
$json = $stream_reader.ReadToEnd()
$json | ConvertFrom-Json
}
# ----------------------------------------------------------------------
Write-Host 'ConnectAsync' -ForegroundColor Yellow
# $task = $ws.ConnectAsync([Uri]::new('wss://delayed.polygon.io/stocks'), [System.Threading.CancellationToken]::None)
$task = $ws.ConnectAsync([Uri]::new('wss://delayed.polygon.io/options'), [System.Threading.CancellationToken]::None)
while (!$task.IsCompleted) { Start-Sleep -Milliseconds 100 }
receive
# ----------------------------------------------------------------------
send (@{ action = 'auth'; params = $api_key } | ConvertTo-Json)
receive
# ----------------------------------------------------------------------
send '{"action":"subscribe", "params":"AM.*"}'
receive
# ----------------------------------------------------------------------
# options loop
# ----------------------------------------------------------------------
$data = @()
while ($true)
{
$result = receive
$data += $result
$result = $result | Select-Object *, @{ Label = 'value'; Expression = { $_.c * $_.v }; }
$result | ? value -ge 5000 | ft *
}
exit
# ----------------------------------------------------------------------
$data | Select-Object *, @{ Label = 'value'; Expression = { $_.c * $_.v }; } | Sort-Object value | Select-Object -Last 20 | ft *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment