Get-IbTrade.psm1

<#
 .Synopsis
  Displays flex query results from Interactive Brokers.
 
 .Description
  Displays flex query V3 results from Interactive Brokers.
 
 .Parameter Query
  Flex query ID of Interactive Brokers.
 
 .Parameter Token
  Your flex web service token in Interactive Brokers.
 
 .Example
   # Display flex query result, token is store in $Env:ibtoken.
   Get-IbTrade -Query <Flex Query ID>
 
 .Example
   # Display flex query result, specific token parameter.
   Get-IbTrade -Query <Flex Query ID> -Token <Token>
 
 .LINK
   Online version: https://www.interactivebrokers.com/en/software/am/am/reports/flex_web_service_version_3.htm
#>




function Get-IbTrade {
param(
    $Query,
    [Parameter(Mandatory)]$Token = $env:ibtoken
    )

## Determine the first day of the start and end months.
$ib_token = $token
$ib_version = 3
$init_url = "https://gdcdyn.interactivebrokers.com/Universal/servlet/FlexStatementService.SendRequest"
$getdata_url = "https://gdcdyn.interactivebrokers.com/Universal/servlet/FlexStatementService.GetStatement"

#Authenticate to server
$Body = @{
    t = $ib_token
    q = $query
    v = $ib_version
}
$response = Invoke-WebRequest $init_url -Body $Body -Method 'POST'
[xml]$ib_ref = $response.Content

# Display IB Response Code
# $ib_ref.FlexStatementResponse.ReferenceCode

#Retrieve statement data
$Body = @{
    q = $ib_ref.FlexStatementResponse.ReferenceCode
    t = $ib_token
    v = $ib_version
}
$response = Invoke-WebRequest $getdata_url -Body $Body -Method 'POST'
[xml]$xml = $response.Content


#TCF
if ($xml.FlexQueryResponse.type -eq "TCF"){
$result = $xml.FlexQueryResponse.FlexStatements.FlexStatement.TradeConfirms.TradeConfirm
}



#AF
if ($xml.FlexQueryResponse.type -eq "AF"){
$result = $xml.FlexQueryResponse.FlexStatements.FlexStatement.ChangeInDividendAccruals.ChangeInDividendAccrual
}


#Print result
return $result

}
Export-ModuleMember -Function Get-IbTrade