Calculate trade profit PowerShell Get-PnL

In order to know which trade would be the most profitable, it is necessary to estimate the potential profit. Thanks to this Get-PnL function in PowerShell it is possible to calculate the PnL (Profit and Loss) taking into account the broker fees.

If you are interested in automating some mechanism or creating a bot or whatever, check out this blog post on Binance API and PowerShell.

function Get-PnL{
    <#
		.SYNOPSIS
        Return the profit/loss of a trade
        
        .PARAMETER FeesPercentage
        The broker's transaction fees as a percentage
        
        .PARAMETER PriceBuy
        The purchase price of your pair

        .PARAMETER PriceSell
        The selling price of your pair

        .PARAMETER Investment
        The amount invested in your trade
        
        .EXAMPLE
        Get-PnL -FeesPercentage 0.1 -PriceBuy 52000 -PriceSell 58000 -Investment 8000
	#>

    [cmdletbinding()]
    param(
	    [Parameter(Mandatory=$false)] 
		[ValidateSet(0.1, 0.075)]
		[double]$FeesPercentage = 0.1,

	    [Parameter(Mandatory=$true)] 
		[double]$PriceBuy,

	    [Parameter(Mandatory=$true)] 
		[double]$PriceSell,

	    [Parameter(Mandatory=$true)] 
		[double]$Investment
    )

    BEGIN{
        [double]$TransactionFees = 0
        [double]$PnL = 0
        [double]$PnLPerc = 0
        [bool]$IsTradePositive = $false
    }
    
    PROCESS{
        $PnLPerc = (($PriceSell - $PriceBuy) / $PriceBuy) * 100
        $TransactionFees = ($FeesPercentage * $Investment / 100) * 2
        $PnL = [math]::Round(($Investment * $PnLPerc) / 100 - $TransactionFees, 2)
       
        if($PnL -gt 0){
            Write-Verbose "Winning $PnL$"
            $IsTradePositive = $True
        }
        else{
            Write-Verbose "Loss of $PnL$"
            $IsTradePositive = $False
        }

        $ObjTradeResult = [PSCustomObject]@{
            PnL             = $PnL
            Fees            = $TransactionFees
            PnLPerc         = $PnLPerc
            IsTradePositive = $IsTradePositive
        }
    }

    END{
        return $ObjTradeResult
    }
}

About this function

  • Adjust the FeesPercentage according to your broker

  • The function returns an object with the essential data

Examples

Function in PowerShell to calculate profit or loss

Related post

  1. Retrieve prices from Binance API PowerShell
  2. Get trading info from Binance API PowerShell
  3. Interact with Binance using API PowerShell
  4. New-Order API Binance PowerShell
  5. Retrieve Binance Balance API PowerShell
  6. Open Order Binance PowerShell API

Leave a Comment