New-Order API Binance PowerShell

In this article, we are going to see how we can place an order to buy or sell any crypto on the Binance platform with PowerShell and the function New-Order.

If you haven’t read the previous article Interact with your Binance account using API and PowerShell which contains all the necessary functions in order to use New-Order, you should probably read it first.

New-Order

Updated 5/25/2021

function New-Order{
    <#
		.SYNOPSIS
		Place an order to buy or sell crypto

        .PARAMETER Symbol
        The crypto you want to buy or sell

        .PARAMETER Side
        ValidateSet "BUY" or "SELL"

        .PARAMETER OrderType
        ValidateSet "OrderMarket" or "OrderLimit" or "OrderStopLimit"

        .PARAMETER Price
        Specifies the price at which you want to buy. This param is only available for OrderLimit and OrderStopLimit

        .PARAMETER StopPrice
        Specifies the price for the StopLimit. This param is only available for OrderStopLimit

        .PARAMETER Quantity
        Specifies the amount you want to spend (when buying) or receive (when selling)

        .PARAMETER FiatAmount
        specifies the amount you want to spend in USDT 

        .EXAMPLE
        New-Order -Symbol BTCUSDT -Side BUY -OrderType OrderMarket -FiatAmount 20 -Verbose

        .EXAMPLE
        New-Order -Symbol BTCUSDT -Side BUY -OrderType OrderLimit -FiatAmount 1000 -Price 33000    
        
        .EXAMPLE
        New-Order -Symbol BTCUSDT -Side BUY -OrderType OrderStopLimit -Quantity 0.002 -Price 33000 -StopPrice 36000

        .EXAMPLE
        New-Order -Symbol XRPUSDT -Side SELL -OrderType OrderLimit -Quantity 100 -Price 0.5 
        
        .EXAMPLE
        New-Order -Symbol XRPUSDT -Side SELL -OrderType OrderStopLimit -Quantity 100 -Price 0.55 -StopPrice 0.5
	#>

    [cmdletbinding()]
    param(
        [Parameter(Mandatory=$true)] 
        [string]$Symbol,

        [Parameter(Mandatory=$true)] 
        [ValidateSet("BUY", "SELL")]
        [string]$Side,

        [Parameter(Mandatory=$true)] 
        [ValidateSet("OrderMarket", "OrderLimit", "OrderStopLimit")]
        [string]$OrderType,

        [Parameter(Mandatory=$true, ParameterSetName = 'quantity')]
        [double]$Quantity,
    
        [Parameter(Mandatory=$true, ParameterSetName = 'quantity2')] 
        [double]$FiatAmount
    )

    DynamicParam{
        $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary

        if ($OrderType -ne "OrderMarket"){
            # price param
            $attributes = New-Object -Type System.Management.Automation.ParameterAttribute
            $attributes.Mandatory = $true
            $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
            $attributeCollection.Add($attributes)

            $dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("Price", [double], $attributeCollection)
            $paramDictionary.Add("Price", $dynParam1)
        }
      
        if ($OrderType -eq "OrderStopLimit"){
            # StopPrice param
            $attributes2 = New-Object -Type System.Management.Automation.ParameterAttribute
            $attributes2.Mandatory = $true
            $attributeCollection2 = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
            $attributeCollection2.Add($attributes2)

            $dynParam2 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("StopPrice", [double], $attributeCollection2)
            $paramDictionary.Add("StopPrice", $dynParam2)
        }

        return $paramDictionary
    }

    BEGIN{
        # Check prerequisit
        try{
            Get-Command -Name Get-UnixTimeStamp -ErrorAction Stop | out-null
            Get-Command -name Get-BinanceAPISignature -ErrorAction Stop | Out-Null
            Get-Command -Name Get-BinanceAPIHeader -ErrorAction Stop | Out-Null
            Get-Command -Name Request-API -ErrorAction Stop | Out-Null
            Get-Command -Name Get-Price -ErrorAction Stop | Out-Null    
        }
        catch{
            Write-Host "Load Get-UnixTimeStamp, Get-BinanceAPISignature, Get-BinanceAPIHeader, Request-API, Get-Price  first prior to laod the current script" -b red
            Break
        }

        $TimeStamp = Get-UnixTimeStamp
        # retrieve value from dyn param
        if ($OrderType -ne "OrderMarket"){
            $Price     = $paramDictionary.values[0].value[0]
            $StopPrice = $paramDictionary.values[0].value[1]
        }

        switch($OrderType){
            "OrderMarket"{
                if($PSBoundParameters.ContainsKey('Quantity')){
                    $QueryString = "symbol=$Symbol&side=$Side&type=MARKET&quantity=$Quantity&timestamp=$TimeStamp&recvWindow=5000"
                }
                else{                                                                   
                    $QueryString = "symbol=$Symbol&side=$Side&type=MARKET&quoteOrderQty=$FiatAmount&timestamp=$TimeStamp&recvWindow=5000"
                }
            }
            
            "OrderLimit"{
                if($PSBoundParameters.ContainsKey('FiatAmount')){
                    $CurrentPrice = Get-Price -Symbol $Symbol -Decimal 8
                    $Quantity = [math]::Round($FiatAmount / $CurrentPrice, 2)
                }
                $QueryString = "symbol=$Symbol&side=$Side&type=LIMIT&price=$Price&timeInForce=GTC&quantity=$Quantity&timestamp=$TimeStamp&recvWindow=5000"
            }

            "OrderStopLimit"{

                # We need to get the price in order to define the type variable. See the API doc for more information.
                $CurrentPrice = Get-Price -Symbol $Symbol -Decimal 6

                if($PSBoundParameters.ContainsKey('FiatAmount')){
                    $Quantity = [math]::Round($FiatAmount / $CurrentPrice, 6)
                }

                if($CurrentPrice -gt $Price){
                    $Type="STOP_LOSS_LIMIT"
                }
                else{
                    $Type = "TAKE_PROFIT_LIMIT"
                }
                $QueryString = "symbol=$Symbol&side=$Side&type=$Type&stopPrice=$StopPrice&price=$Price&timeInForce=GTC&quantity=$Quantity&timestamp=$TimeStamp&recvWindow=5000"
            }
        }
    }
    
    PROCESS{
        $URI = Get-BinanceAPISignature -QueryString $QueryString -EndPoint "/api/v3/order"
        $Headers = Get-BinanceAPIHeader
        $ObjResults = $null # need to do this?
        $ObjResults = Request-API -Method POST -URI $URI -Headers $Headers
    }

    END{
       return $ObjResultsd
    }
}

About this function

  • This function responds to my need. Of course, there are many improvements to do.

  • You can choose the type of order “OrderMarket”, “OrderLimit” or “OrderStopLimit”

  • For a better user experience, I added DynamicParam{}.
    More information

  • The commands Get-UnixTimeStamp, Get-BinanceAPISignature, Get-BinanceAPIHeader, Request-API, Get-Price must be loaded before using the New-Order function.

  • In the PROCESS script block, we call our previous functions.

Examples

Example using New-Order and BUY
Example using New-Order and SELL
VERBOSE: GET https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT with 0-byte payload
VERBOSE: received 45-byte response of content type application/json;charset=UTF-8
VERBOSE: POST https://api.binance.com/api/v3/order?symbol=BTCUSDT&side=BUY&type=LIMIT&price=33000&timeInForce=GTC&quantity=0.000405&timestamp=1614865133778&recvWindow=5000&signature=s4572a32s79w98ff3ee30338310571azu31b3857392372e40eada2570a10d3ced with 0-byte payload
VERBOSE: received 312-byte response of content type application/json;charset=UTF-8

Serie of post blog Crypto Binance API PowerShell

Once you have digested this implementation, you should be able to create all the other functions you need. Send me a message if you like.

  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

8 thoughts on “New-Order API Binance PowerShell”

  1. Hi Yann,

    Thanks you very much for the detailed Powershell solution to Binance API.
    Could you help me with a powershell script to retreive the ‘Binance account balance’
    from my Wallet/Spot? I can’t get it to work, can you help me? Can you send me an email?

    Reply
  2. Hello, I am having a hard time coding a New-Order. This is my command:

    $ordertype = “OrderStopLimit”
    $price = “-Price ” + $textboxPrice.Text
    $stopprice = “-StopPrice ” + $textboxStopPrice.Text
    New-Order -Symbol $combobox1.Text -Side $side -OrderType $ordertype -FiatAmount $textboxFiatAmount.Text $price $stopprice

    However, it does not recognize the -Price or -StopPrice parameters. When I leave the variables out, it then prompts me to enter them. Any reason why those variables cannot be added to the command?

    Reply
    • Hello Abiezer Fraga,

      the function use DynamicParams. The -price param is only available if -OrderType is not “OrderMarket” and the -StopPrice param is only available if it’s an OrderStopLimit.
      I noticed that as long as you don’t provide all the variables they don’t show up. That’s probably the issue? See the examples and try in this order.

      Technically this works in my console PowerShell 5.1.

      Or you can make more simple and just remove the dynamic parameters and use these params only if you need them. That was for me a little challenge to setup them 😉

      Please let me know if you have an update.

      Yann

      Reply
  3. Hello

    If I want use the function to sell my entire holding in a symbol/pair, is that possible, even if I don’t know the quantity?

    Reply

Leave a Comment