π Quick Connect to MT5 (QuickConnect)ΒΆ
Sugar method: Easiest way to connect to MT5 Terminal - just provide cluster name and you're connected!
API Information:
- Method:
sugar.QuickConnect(clusterName) - Package:
mt5(MT5Sugar), importmt5 "github.com/MetaRPC/GoMT5/examples/mt5"- it lives in the repository's examples module (github.com/MetaRPC/GoMT5/examples), so you get it by cloning the repository, not bygo getof the SDK package - Underlying calls:
account.ConnectEx()withpb.ConnectExRequest{User, Password, MtClusterName, TimeoutSeconds} - Timeout: the server waits up to 120 seconds (
TimeoutSeconds) for the terminal to start and log in; the call itself has a 130-second deadline - Cleanup: call
sugar.Disconnect()when you are done - also whenQuickConnectreturned an error
π Method SignatureΒΆ
π½ InputΒΆ
| Parameter | Type | Description |
|---|---|---|
clusterName |
string |
MT5 cluster name (e.g., "FxPro-MT5 Demo", "FxPro-MT5 Live") |
β¬οΈ OutputΒΆ
| Return | Type | Description |
|---|---|---|
error |
error |
nil if connected successfully, error otherwise |
π¬ Just the EssentialsΒΆ
- What it is: Simplest connection method - connects using just cluster name (login and password were given to
NewMT5Sugar). - Why you need it: You don't need to know the broker's MT5 server host/port - just the cluster name from MT5 terminal.
- Sanity check: After successful connect,
IsConnected()returnstrue.
π― PurposeΒΆ
Use it when you want the simplest connection:
- Quick connection - One parameter, one call
- Auto-discovery - The cluster name is resolved server-side; no MT5 server host/port needed
- Beginner-friendly - No need to configure the broker's host:port (the gRPC gateway address is the third
argument of
NewMT5Sugar;""means"mt5.mrpc.pro:443") - Demo/Live switching - Just change cluster name
π§© Notes & TipsΒΆ
- Cluster name - Same as in MT5 Terminal (File β Open Account)
- Case sensitive - Must match exactly
- Demo vs Live - Usually ends with "Demo" or "Live"
- First call - Must be called before any trading operations
- One-time - Only need to connect once per session
- Check connection - Use
IsConnected()to verify - Slow first start - A terminal that is not running yet has to start first; that can take well over 30 seconds, which is why the server waits up to 120 s and the call has a 130 s deadline
- Always disconnect - Call
sugar.Disconnect()when the program is done, also whenQuickConnectfailed (the server may already have started the terminal). Otherwise the terminal keeps running on the server.Disconnect()stops the terminal,Disconnect(true)deletes it; a second call is a no-op
π§ Under the HoodΒΆ
func (s *MT5Sugar) QuickConnect(clusterName string) error {
// A terminal that is not running yet starts first: that takes longer than 30 seconds at times. The server waits
// up to TimeoutSeconds for the login; the call itself gets that plus a margin.
timeoutSeconds := uint32(120)
ctx, cancel := context.WithTimeout(s.ctx, time.Duration(timeoutSeconds+10)*time.Second)
defer cancel()
req := &pb.ConnectExRequest{
User: s.user,
Password: s.password,
MtClusterName: clusterName,
TimeoutSeconds: &timeoutSeconds,
}
_, err := s.GetAccount().ConnectEx(ctx, req)
return err
}
Only User, Password, MtClusterName and TimeoutSeconds (120) are set - no base chart symbol (there is no such
field), no experts. The context deadline is 130 seconds (120 + 10 s margin).
On success ConnectEx stores the returned terminal instance id in the account, and every later call uses it.
Disconnect() (see MT5Service.Disconnect) sends the Disconnect request with a 30-second timeout, then closes the
gRPC connection, and returns the disconnect error ("Disconnect failed: ...").
What it improves:
- β Simple API - One parameter instead of multiple
- β No config needed - Don't need to know server details
- β Automatic lookup - Cluster β server resolution
π Low-Level AlternativeΒΆ
WITHOUT sugar:
// helpers "github.com/MetaRPC/GoMT5/package/Helpers", pb "github.com/MetaRPC/GoMT5/package", "github.com/google/uuid"
account, _ := helpers.NewMT5Account(12345678, "your_password", "mt5.mrpc.pro:443", uuid.New())
timeoutSeconds := uint32(120)
ctx, cancel := context.WithTimeout(context.Background(), 130*time.Second)
defer cancel()
_, err := account.ConnectEx(ctx, &pb.ConnectExRequest{
User: 12345678,
Password: "your_password",
MtClusterName: "YourBroker-MT5 Demo",
TimeoutSeconds: &timeoutSeconds,
})
WITH sugar:
sugar, _ := mt5.NewMT5Sugar(12345678, "your_password", "mt5.mrpc.pro:443")
defer sugar.Disconnect()
err := sugar.QuickConnect("YourBroker-MT5 Demo")
Benefits:
- β Shorter and clearer
- β Same simplicity
- β Built into Sugar instance
π Usage ExamplesΒΆ
1) Basic connectionΒΆ
package main
import (
"fmt"
mt5 "github.com/MetaRPC/GoMT5/examples/mt5"
)
func main() {
// Create Sugar instance
sugar, err := mt5.NewMT5Sugar(
591129415,
"your_password",
"mt5.mrpc.pro:443",
)
if err != nil {
fmt.Printf("Failed to create Sugar: %v\n", err)
return
}
// Stop the terminal on the server when done - also when QuickConnect fails
defer func() {
if err := sugar.Disconnect(); err != nil {
fmt.Printf("Disconnect failed: %v\n", err)
}
}()
// Connect to MT5
err = sugar.QuickConnect("FxPro-MT5 Demo")
if err != nil {
fmt.Printf("Connection failed: %v\n", err)
return
}
fmt.Println("β
Connected successfully!")
// Now you can use any Sugar methods
balance, _ := sugar.GetBalance()
fmt.Printf("Balance: %.2f\n", balance)
}
2) Connection with verificationΒΆ
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
// Connect
err := sugar.QuickConnect("FxPro-MT5 Demo")
if err != nil {
fmt.Printf("β Connection failed: %v\n", err)
return
}
// Verify connection
connected := sugar.IsConnected()
if connected {
fmt.Println("β
Connected and verified!")
} else {
fmt.Println("β Connection failed!")
}
3) Demo vs Live switchingΒΆ
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
// Connect to DEMO
err := sugar.QuickConnect("FxPro-MT5 Demo")
if err != nil {
fmt.Printf("Demo connection failed: %v\n", err)
return
}
fmt.Println("β
Connected to DEMO account")
// ... Later, to switch to LIVE: the cluster name is the only thing QuickConnect takes,
// login and password come from NewMT5Sugar - so a live account with its own login
// needs its own instance:
// sugarLive, _ := mt5.NewMT5Sugar(liveLogin, "live_password", "mt5.mrpc.pro:443")
// sugarLive.QuickConnect("FxPro-MT5 Live")
4) Connection retry logicΒΆ
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
maxRetries := 3
clusterName := "FxPro-MT5 Demo"
for i := 0; i < maxRetries; i++ {
fmt.Printf("Connection attempt %d/%d...\n", i+1, maxRetries)
err := sugar.QuickConnect(clusterName)
if err == nil {
fmt.Println("β
Connected successfully!")
break
}
fmt.Printf("β Attempt %d failed: %v\n", i+1, err)
if i < maxRetries-1 {
fmt.Println("Retrying in 5 seconds...")
time.Sleep(5 * time.Second)
} else {
fmt.Println("β All connection attempts failed")
return
}
}
5) Connection with timeoutΒΆ
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
defer sugar.Disconnect() // also runs when the connect failed or timed out
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// Connect (QuickConnect has its own 130 s deadline; this shorter one only stops
// waiting - the connect keeps running in the goroutine)
done := make(chan error, 1)
go func() {
done <- sugar.QuickConnect("FxPro-MT5 Demo")
}()
select {
case err := <-done:
if err != nil {
fmt.Printf("Connection failed: %v\n", err)
return
}
fmt.Println("β
Connected successfully!")
case <-ctx.Done():
fmt.Println("β Connection timeout")
return
}
6) Get account info after connectionΒΆ
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
err := sugar.QuickConnect("FxPro-MT5 Demo")
if err != nil {
fmt.Printf("Connection failed: %v\n", err)
return
}
// Get account information
accountInfo, err := sugar.GetAccountInfo()
if err != nil {
fmt.Printf("Failed to get account info: %v\n", err)
return
}
fmt.Println("βββββββββββββββββββββββββββββββββββββββββ")
fmt.Println("β ACCOUNT INFORMATION β")
fmt.Println("βββββββββββββββββββββββββββββββββββββββββ")
fmt.Printf("Login: %d\n", accountInfo.Login)
fmt.Printf("Balance: %.2f %s\n", accountInfo.Balance, accountInfo.Currency)
fmt.Printf("Equity: %.2f %s\n", accountInfo.Equity, accountInfo.Currency)
fmt.Printf("Leverage: 1:%d\n", accountInfo.Leverage)
fmt.Printf("Company: %s\n", accountInfo.Company)
7) Connection from environment variablesΒΆ
import (
"os"
"strconv"
)
// Get credentials from environment
loginStr := os.Getenv("MT5_USER")
password := os.Getenv("MT5_PASSWORD")
server := os.Getenv("MT5_GRPC_SERVER")
cluster := os.Getenv("MT5_MT_CLUSTER")
// Validate
if loginStr == "" || password == "" || server == "" || cluster == "" {
fmt.Println("β Missing environment variables")
return
}
// NewMT5Sugar takes the login as uint64
login, err := strconv.ParseUint(loginStr, 10, 64)
if err != nil {
fmt.Printf("β MT5_USER is not a number: %v\n", err)
return
}
// Connect
sugar, err := mt5.NewMT5Sugar(login, password, server)
if err != nil {
fmt.Printf("Failed to create Sugar: %v\n", err)
return
}
err = sugar.QuickConnect(cluster)
if err != nil {
fmt.Printf("Connection failed: %v\n", err)
return
}
fmt.Printf("β
Connected to %s\n", cluster)
8) Connection status monitoringΒΆ
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
// Initial connection
err := sugar.QuickConnect("FxPro-MT5 Demo")
if err != nil {
fmt.Printf("Connection failed: %v\n", err)
return
}
fmt.Println("β
Initial connection successful")
// Monitor connection in background
go func() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for range ticker.C {
connected := sugar.IsConnected()
if connected {
fmt.Println("π‘ Connection: OK")
} else {
fmt.Println("β οΈ Connection: LOST - Attempting reconnect...")
err := sugar.QuickConnect("FxPro-MT5 Demo")
if err == nil {
fmt.Println("β
Reconnected!")
} else {
fmt.Printf("β Reconnect failed: %v\n", err)
}
}
}
}()
// Main program continues...
time.Sleep(5 * time.Minute)
9) Multiple account handlingΒΆ
// Demo account
sugarDemo, _ := mt5.NewMT5Sugar(591129415, "demo_pass", "mt5.mrpc.pro:443")
err := sugarDemo.QuickConnect("FxPro-MT5 Demo")
if err != nil {
fmt.Printf("Demo connection failed: %v\n", err)
} else {
fmt.Println("β
Demo account connected")
}
// Live account (different credentials)
sugarLive, _ := mt5.NewMT5Sugar(123456789, "live_pass", "mt5.mrpc.pro:443")
err = sugarLive.QuickConnect("FxPro-MT5 Live")
if err != nil {
fmt.Printf("Live connection failed: %v\n", err)
} else {
fmt.Println("β
Live account connected")
}
// Now you can use both accounts
demoBalance, _ := sugarDemo.GetBalance()
liveBalance, _ := sugarLive.GetBalance()
fmt.Printf("Demo balance: %.2f\n", demoBalance)
fmt.Printf("Live balance: %.2f\n", liveBalance)
10) Connection helper functionΒΆ
func ConnectToMT5(login uint64, password, server, cluster string) (*mt5.MT5Sugar, error) {
// Create Sugar instance
sugar, err := mt5.NewMT5Sugar(login, password, server)
if err != nil {
return nil, fmt.Errorf("failed to create Sugar: %w", err)
}
// Connect
err = sugar.QuickConnect(cluster)
if err != nil {
sugar.Disconnect() // the server may already have started the terminal
return nil, fmt.Errorf("connection failed: %w", err)
}
// Verify connection
connected := sugar.IsConnected()
if !connected {
sugar.Disconnect()
return nil, fmt.Errorf("connection not established")
}
return sugar, nil // the caller calls sugar.Disconnect() when done
}
// Usage:
sugar, err := ConnectToMT5(
591129415,
"password",
"mt5.mrpc.pro:443",
"FxPro-MT5 Demo",
)
if err != nil {
fmt.Printf("β %v\n", err)
return
}
defer sugar.Disconnect()
fmt.Println("β
Connected and ready to trade!")
π Related MethodsΒΆ
π¬ Other connection methods:
IsConnected()- Check if connectedPing()- Verify connection health
π Next steps after connection:
GetBalance()- Check account balanceGetAccountInfo()- Get complete account detailsGetAllSymbols()- List available symbols
β οΈ Common PitfallsΒΆ
1) Wrong cluster nameΒΆ
// β WRONG - incorrect cluster name
err := sugar.QuickConnect("FxPro Demo") // Missing "-MT5"
// β
CORRECT - exact cluster name from MT5
err := sugar.QuickConnect("FxPro-MT5 Demo")
2) Not checking connection errorΒΆ
// β WRONG - ignoring error
sugar.QuickConnect("FxPro-MT5 Demo")
balance, _ := sugar.GetBalance() // Will fail if not connected!
// β
CORRECT - check error
err := sugar.QuickConnect("FxPro-MT5 Demo")
if err != nil {
fmt.Printf("Connection failed: %v\n", err)
return
}
balance, _ := sugar.GetBalance()
3) Connecting multiple timesΒΆ
// β WRONG - redundant connections
sugar.QuickConnect("FxPro-MT5 Demo")
sugar.QuickConnect("FxPro-MT5 Demo") // Already connected!
// β
CORRECT - connect once
err := sugar.QuickConnect("FxPro-MT5 Demo")
if err != nil {
fmt.Printf("Connection failed: %v\n", err)
return
}
// Now use Sugar methods without reconnecting
4) Using wrong credentialsΒΆ
// β WRONG - login in QuickConnect (it's already in NewMT5Sugar)
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
sugar.QuickConnect("591129415") // WRONG! This is cluster, not login
// β
CORRECT - cluster name
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
sugar.QuickConnect("FxPro-MT5 Demo")
5) Never disconnectingΒΆ
// β WRONG - the terminal keeps running on the server after the program exits
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
if err := sugar.QuickConnect("FxPro-MT5 Demo"); err != nil {
return // a failed connect may already have started the terminal
}
// β
CORRECT - disconnect on every path, also after a failed QuickConnect
sugar, _ := mt5.NewMT5Sugar(591129415, "password", "mt5.mrpc.pro:443")
defer sugar.Disconnect() // stops the terminal; Disconnect(true) deletes it
if err := sugar.QuickConnect("FxPro-MT5 Demo"); err != nil {
return
}
π Pro TipsΒΆ
- Always check errors - Connection can fail for many reasons
- Use environment variables - Don't hardcode credentials
- Verify after connect - Use
IsConnected()to double-check - One connection per session - Don't reconnect unless necessary
- Demo first - Always test on demo before live
- Cluster name - Copy exact name from MT5 Terminal
- Always Disconnect -
defer sugar.Disconnect()right afterNewMT5Sugar, beforeQuickConnect
See also: IsConnected.md, Ping.md