Skip to main content

ExchangeTrade gRPC Method

Loading...

Updated on
May 13, 2025

ExchangeTrade gRPC Method

Parameters

from
string
REQUIRED
Loading...
exchangeID
integer
REQUIRED
Loading...
tokenID
string
REQUIRED
Loading...
amountToken
integer
REQUIRED
Loading...
amountExpected
integer
REQUIRED
Loading...

Returns

transaction
object
Loading...
raw_data
object
Loading...
ref_block_bytes
string
Loading...
ref_block_num
integer
Loading...
ref_block_hash
string
Loading...
expiration
integer
Loading...
auths
array
Loading...
data
string
Loading...
contract
array
Loading...
type
string
Loading...
parameter
object
Loading...
value
string
Loading...
type_url
string
Loading...
provider
string
Loading...
ContractName
string
Loading...
Permission_id
integer
Loading...
scripts
string
Loading...
timestamp
integer
Loading...
fee_limit
integer
Loading...
signature
array
Loading...
ret
array
Loading...
fee
integer
Loading...
ret
string
Loading...
contractRet
string
Loading...
assetIssueID
string
Loading...
withdraw_amount
integer
Loading...
unfreeze_amount
integer
Loading...
exchange_received_amount
integer
Loading...
exchange_inject_another_amount
integer
Loading...
exchange_withdraw_another_amount
integer
Loading...
exchange_id
integer
Loading...
shielded_transaction_fee
integer
Loading...
orderId
string
Loading...
orderDetails
array
Loading...
makerOrderId
string
Loading...
takerOrderId
string
Loading...
fillSellQuantity
integer
Loading...
fillBuyQuantity
integer
Loading...
withdraw_expire_amount
integer
Loading...
cancelUnfreezeV2Amount
object
Loading...
txid
string
Loading...
constant_result
array
Loading...
result
object
Loading...
result
boolean
Loading...
code
string
Loading...
message
string
Loading...
energy_used
integer
Loading...
logs
array
Loading...
address
string
Loading...
topics
array
Loading...
data
string
Loading...
internal_transactions
array
Loading...
hash
string
Loading...
caller_address
string
Loading...
transferTo_address
string
Loading...
callValueInfo
array
Loading...
callValue
integer
Loading...
tokenId
string
Loading...
note
string
Loading...
rejected
boolean
Loading...
extra
string
Loading...
energy_penalty
integer
Loading...
Request
1
package main
2
3
import (
4
"context"
5
"crypto/tls"
6
"encoding/json"
7
"fmt"
8
"github.com/fbsobreira/gotron-sdk/pkg/client"
9
"google.golang.org/grpc"
10
"google.golang.org/grpc/credentials"
11
)
12
13
// Quicknode endpoints consist of two crucial components: the endpoint name and the corresponding token
14
// For eg: QN Endpoint: https://docs-demo.tron-mainnet.quiknode.pro/abcde123456789
15
// endpoint will be: docs-demo.tron-mainnet.quiknode.pro:50051 {50051 is the port number for Tron gRPC}
16
// token will be : abcde123456789
17
18
var token = "YOUR_TOKEN"
19
var endpoint = "YOUR_ENDPOINT:50051"
20
21
type auth struct {
22
token string
23
}
24
25
func (a *auth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
26
return map[string]string{
27
"x-token": a.token,
28
}, nil
29
}
30
31
func (a *auth) RequireTransportSecurity() bool {
32
return false
33
}
34
35
func main() {
36
37
opts := []grpc.DialOption{
38
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),
39
grpc.WithPerRPCCredentials(&auth{token}),
40
}
41
conn := client.NewGrpcClient(endpoint)
42
if err := conn.Start(opts...); err != nil {
43
panic(err)
44
}
45
defer conn.Conn.Close()
46
47
from := "TZ4UXDV5ZhNW7fb2AMSbgfAEZ7hWsnYS2g" // Address performing the trade
48
exchangeID := int64(123) // ID of the exchange pair
49
50
fmt.Printf("Verifying exchange ID %d...\n", exchangeID)
51
exchange, err := conn.ExchangeByID(exchangeID)
52
if err != nil {
53
fmt.Printf("Error: The specified exchange does not exist: %v\n", err)
54
return
55
}
56
57
firstTokenID := string(exchange.FirstTokenId)
58
secondTokenID := string(exchange.SecondTokenId)
59
fmt.Printf("Exchange %d contains tokens: %s and %s\n",
60
exchangeID, firstTokenID, secondTokenID)
61
62
tokenID := firstTokenID
63
amountToken := int64(1000000)
64
amountExpected := int64(1800000)
65
66
if tokenID != firstTokenID && tokenID != secondTokenID {
67
fmt.Printf("Error: Token %s is not in exchange %d\n", tokenID, exchangeID)
68
return
69
}
70
71
fmt.Printf("Checking token balance for %s...\n", tokenID)
72
var tokenBalance int64
73
// The method to get balance depends on whether we're trading TRX or a TRC10 token
74
if tokenID == "" {
75
// For TRX
76
account, err := conn.GetAccount(from)
77
if err != nil {
78
fmt.Printf("Error getting account: %v\n", err)
79
return
80
}
81
tokenBalance = account.Balance
82
} else {
83
// For TRC10 tokens
84
account, err := conn.GetAccount(from)
85
if err != nil {
86
fmt.Printf("Error getting account: %v\n", err)
87
return
88
}
89
90
found := false
91
for tokenName, balance := range account.AssetV2 {
92
if string(tokenName) == tokenID {
93
tokenBalance = balance
94
found = true
95
break
96
}
97
}
98
if !found {
99
tokenBalance = 0
100
}
101
}
102
103
fmt.Printf("Token balance: %d\n", tokenBalance)
104
105
if tokenBalance < amountToken {
106
fmt.Printf("Error: Insufficient token balance. Have: %d, Need: %d\n", tokenBalance, amountToken)
107
fmt.Println("Please make sure you have enough tokens before trading.")
108
return
109
}
110
111
// Create the trade transaction
112
fmt.Println("Creating exchange trade transaction...")
113
114
tx, err := conn.ExchangeTrade(
115
from, // The trader's address
116
exchangeID, // Exchange ID
117
tokenID, // Token ID to trade
118
amountToken, // Amount to trade
119
amountExpected, // Minimum expected return
120
)
121
122
if err != nil {
123
fmt.Printf("Error creating trade transaction: %v\n", err)
124
return
125
}
126
127
fmt.Println("Trade transaction created successfully. Transaction details:")
128
jsonData, _ := json.MarshalIndent(tx, "", " ")
129
fmt.Println(string(jsonData))
130
131
// NOTE: In a production environment, the transaction should be signed here
132
fmt.Println("\nBroadcasting transaction to the TRON network...")
133
result, err := conn.Broadcast(tx.Transaction)
134
if err != nil {
135
fmt.Printf("Error broadcasting transaction: %v\n", err)
136
return
137
}
138
139
if !result.GetResult() {
140
fmt.Printf("Broadcast failed: %s\n", result.GetMessage())
141
return
142
}
143
144
fmt.Println("Trade executed successfully! Result:")
145
resultJSON, _ := json.MarshalIndent(result, "", " ")
146
fmt.Println(string(resultJSON))
147
}
Don't have an account yet?
Create your Quicknode endpoint in seconds and start building
Get started for free