gomt5

package module
v0.1.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 28, 2026 License: MIT Imports: 11 Imported by: 0

README

go-mt5

Go Reference Go Report Card Release

Native Go client for MetaTrader 5. Communicates directly with the MT5 terminal via Windows Named Pipe IPC, the same mechanism used by the official Python MetaTrader5 package. No Expert Advisor needed.

Features

  • Direct IPC connection to terminal64.exe via Windows Named Pipes
  • Reverse-engineered binary protocol (same as MetaTrader5.pyd)
  • context.Context support on all methods for cancellation and timeouts
  • Account and terminal information
  • Real-time symbol info, tick data, and market book (depth of market)
  • Historical rates and ticks (OHLCV, copy from position/date/range)
  • Order management (send, check, calc margin/profit)
  • Position and history queries with rich filters (symbol, ticket, group)
  • Pluggable logger and request hooks for observability
  • Zero external dependencies (only golang.org/x/sys)

Requirements

  • Windows (named pipes are a Windows kernel feature)
  • MetaTrader 5 terminal running with an active account
  • Go 1.21+

Installation

go get github.com/mukbeast4/go-mt5

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	gomt5 "github.com/mukbeast4/go-mt5"
)

func main() {
	ctx := context.Background()

	client, err := gomt5.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	fmt.Printf("Connected to MT5 build %d\n", client.Build())

	account, err := client.AccountInfo(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Account: %s Balance: %.2f %s\n",
		account.Name, account.Balance, account.Currency)

	tick, err := client.SymbolInfoTick(ctx, "EURUSD")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("EURUSD Bid: %.5f Ask: %.5f\n", tick.Bid, tick.Ask)
}

API

Group Methods
Connection NewClient(ctx), NewClientFromConn(ctx, conn), Close(), Build(), LastError()
Account AccountInfo(ctx), TerminalInfo(ctx), Version(ctx)
Symbols SymbolsTotal(ctx), SymbolsGet(ctx, group), SymbolInfo(ctx, symbol), SymbolInfoTick(ctx, symbol), SymbolSelect(ctx, symbol, enable)
Market Data CopyRatesFrom(ctx, ...), CopyRatesFromPos(ctx, ...), CopyRatesRange(ctx, ...), CopyTicksFrom(ctx, ...), CopyTicksRange(ctx, ...)
Market Book MarketBookAdd(ctx, symbol), MarketBookGet(ctx, symbol), MarketBookRelease(ctx, symbol)
Trading OrderSend(ctx, req), OrderCheck(ctx, req), OrderCalcMargin(ctx, ...), OrderCalcProfit(ctx, ...), OrdersTotal(ctx), OrdersGet(ctx, *OrderFilter)
Positions PositionsTotal(ctx), PositionsGet(ctx, *PositionFilter)
History HistoryOrdersTotal(ctx, from, to), HistoryOrdersGet(ctx, *HistoryFilter), HistoryDealsTotal(ctx, from, to), HistoryDealsGet(ctx, *HistoryFilter)
Debug SendRaw(ctx, cmdID, params)
Options
gomt5.NewClient(ctx,
	gomt5.WithPipeName(`\\.\pipe\MT5.123456`),
	gomt5.WithTimeout(30*time.Second),
	gomt5.WithDebug(true),
	gomt5.WithLogger(myLogger),
	gomt5.WithOnRequest(func(cmdID uint32, d time.Duration, err error) {
		// metrics hook
	}),
)
Filters
positions, _ := client.PositionsGet(ctx, &gomt5.PositionFilter{
	Symbol: "EURUSD",
})

positions, _ = client.PositionsGet(ctx, &gomt5.PositionFilter{
	Ticket: 12345,
})

positions, _ = client.PositionsGet(ctx, &gomt5.PositionFilter{
	Group: "EUR*",
})

// nil filter returns all
positions, _ = client.PositionsGet(ctx, nil)

Protocol

Request:  [payload_len:LE32][cmd_id:LE32][params...]
Response: [payload_len:LE32][cmd_echo:LE32][success:LE32][data...]
  • Integers: LE32/LE64
  • Floats: IEEE 754 double LE64
  • Strings: [char_count:LE32][UTF-16LE data]
  • Booleans: LE64 (0/1)

Python API Compatibility

Python function go-mt5 equivalent Status
initialize() NewClient(ctx) Done
shutdown() Close() Done
login() Login(ctx, login, password, server) Done
version() Version(ctx) Done
account_info() AccountInfo(ctx) Done
terminal_info() TerminalInfo(ctx) Done
symbols_total() SymbolsTotal(ctx) Done
symbols_get() SymbolsGet(ctx, group) Done
symbol_info() SymbolInfo(ctx, symbol) Done
symbol_info_tick() SymbolInfoTick(ctx, symbol) Done
symbol_select() SymbolSelect(ctx, symbol, enable) Done
market_book_add() MarketBookAdd(ctx, symbol) Done
market_book_get() MarketBookGet(ctx, symbol) Done
market_book_release() MarketBookRelease(ctx, symbol) Done
copy_rates_from() CopyRatesFrom(ctx, ...) Done
copy_rates_from_pos() CopyRatesFromPos(ctx, ...) Done
copy_rates_range() CopyRatesRange(ctx, ...) Done
copy_ticks_from() CopyTicksFrom(ctx, ...) Done
copy_ticks_range() CopyTicksRange(ctx, ...) Done
orders_total() OrdersTotal(ctx) Done
orders_get() OrdersGet(ctx, *OrderFilter) Done
positions_total() PositionsTotal(ctx) Done
positions_get() PositionsGet(ctx, *PositionFilter) Done
history_orders_total() HistoryOrdersTotal(ctx, from, to) Done
history_orders_get() HistoryOrdersGet(ctx, *HistoryFilter) Done
history_deals_total() HistoryDealsTotal(ctx, from, to) Done
history_deals_get() HistoryDealsGet(ctx, *HistoryFilter) Done
order_send() OrderSend(ctx, req) Done
order_check() OrderCheck(ctx, req) Done
order_calc_margin() OrderCalcMargin(ctx, ...) Done
order_calc_profit() OrderCalcProfit(ctx, ...) Done
last_error() LastError() Done
go-mt5 extras (not in Python API)
Feature Method
Request hooks WithOnRequest(hook)
Debug logging WithDebug(true), WithLogger(l)
Tick streaming (polling) SubscribeTicks(ctx, symbol)
Trade helpers tradeutil.Buy(), Sell(), ClosePosition(), etc.
Data analysis analysis.NewRateSeries(), SMA(), EMA()
CSV export analysis.ToCSV(writer, rates)
Time helpers ToTime(), FromTime(), .TimeUTC() methods
Request validation TradeRequest.Validate()
Auto-reconnect WithAutoReconnect(true)

Upgrading from v0.1.0

All public methods now require context.Context as the first parameter:

// Before (v0.1.0)
client, _ := gomt5.NewClient()
info, _ := client.AccountInfo()
positions, _ := client.PositionsGet("EURUSD")

// After (v0.1.1+)
ctx := context.Background()
client, _ := gomt5.NewClient(ctx)
info, _ := client.AccountInfo(ctx)
positions, _ := client.PositionsGet(ctx, &gomt5.PositionFilter{Symbol: "EURUSD"})

Other breaking changes:

  • NewClientFromConn(conn) -> NewClientFromConn(ctx, conn, opts...)
  • OrdersGet(symbol) -> OrdersGet(ctx, *OrderFilter)
  • PositionsGet(symbol) -> PositionsGet(ctx, *PositionFilter)
  • HistoryOrdersGet(from, to) -> HistoryOrdersGet(ctx, *HistoryFilter)
  • HistoryDealsGet(from, to) -> HistoryDealsGet(ctx, *HistoryFilter)
  • SendRaw(cmdID, params) -> SendRaw(ctx, cmdID, params)

Limitations

  • Windows only: Named pipes are a Windows kernel feature. The library cannot connect to MT5 from Linux or macOS (cross-compilation works, but runtime requires Windows).
  • Reverse-engineered protocol: The binary protocol is not documented by MetaQuotes. Command IDs and payload formats were discovered by analyzing the official Python MetaTrader5.pyd library. Some commands (e.g., Login) are not yet mapped because their IDs have not been identified in the pipe protocol.
  • MT5 build compatibility: MetaQuotes may change the pipe protocol between MT5 builds without notice. If something breaks after an MT5 update, please open an issue with your build number.
  • Broker differences: Different brokers configure their MT5 servers differently. Filling modes, symbol visibility, available order types, and margin calculation methods vary. Always check SymbolInfo before trading.
  • Single terminal: The library connects to one MT5 terminal instance. If multiple terminals are running, use WithPipeName to target a specific one.
  • No tick streaming yet: Real-time tick push from the pipe protocol has not been reverse-engineered. Use polling via SymbolInfoTick or CopyTicksFrom as a workaround.

Testing

go test ./...

Tests use an in-memory mock pipe, no MT5 instance needed.

Project Structure

go-mt5/
├── *.go                     # Public API (package gomt5)
├── internal/
│   ├── protocol/            # Binary codec + message framing
│   └── pipe/                # Windows named pipe transport
└── .github/                 # CI workflows

Contributing

We welcome contributions! Please read our Contributing Guide and Code of Conduct before submitting a pull request.

Security

To report a security vulnerability, please see our Security Policy.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	ResOK                   = 1
	ResEFail                = -1
	ResEInvalidParams       = -2
	ResENoMemory            = -3
	ResENotFound            = -4
	ResEInvalidVersion      = -5
	ResEAuthFailed          = -6
	ResEUnsupported         = -7
	ResEAutoTradingDisabled = -8
	ResEInternalFail        = -10000
	ResEInternalFailSend    = -10001
	ResEInternalFailReceive = -10002
	ResEInternalFailInit    = -10003
	ResEInternalFailConnect = -10004
	ResEInternalFailTimeout = -10005
)
View Source
const (
	RetcodeOK            uint32 = 10009
	RetcodeDone          uint32 = 10008
	RetcodeRequote       uint32 = 10004
	RetcodeReject        uint32 = 10006
	RetcodeCancel        uint32 = 10007
	RetcodeInvalidFill   uint32 = 10030
	RetcodeInvalidVolume uint32 = 10015
	RetcodeInvalidPrice  uint32 = 10016
	RetcodeInvalidStops  uint32 = 10017
	RetcodeTradeDisabled uint32 = 10018
	RetcodeMarketClosed  uint32 = 10019
	RetcodeNoQuotes      uint32 = 10024
	RetcodeTooManyOrders uint32 = 10028
)

Variables

View Source
var (
	ErrNotConnected  = errors.New("mt5: not connected")
	ErrTimeout       = errors.New("mt5: request timeout")
	ErrWindows       = errors.New("mt5: native pipe requires Windows")
	ErrFailed        = errors.New("mt5: request failed")
	ErrDisconnected  = errors.New("mt5: disconnected")
	ErrReconnecting  = errors.New("mt5: reconnecting")
	ErrTerminalClose = errors.New("mt5: terminal closed")
	ErrTradeDisabled = errors.New("mt5: trading disabled")
)

Functions

func FromTime added in v0.1.1

func FromTime(t time.Time) int64

func FromTimeMsc added in v0.1.1

func FromTimeMsc(t time.Time) int64

func ToTime added in v0.1.1

func ToTime(unix int64) time.Time

func ToTimeMsc added in v0.1.1

func ToTimeMsc(msc int64) time.Time

Types

type AccountInfo

type AccountInfo struct {
	Login             int64   `json:"login"`
	TradeMode         int64   `json:"trade_mode"`
	Leverage          int64   `json:"leverage"`
	LimitOrders       int64   `json:"limit_orders"`
	MarginSOMode      int64   `json:"margin_so_mode"`
	TradeAllowed      bool    `json:"trade_allowed"`
	TradeExpert       bool    `json:"trade_expert"`
	MarginMode        int64   `json:"margin_mode"`
	CurrencyDigits    int64   `json:"currency_digits"`
	FIFOClose         bool    `json:"fifo_close"`
	Balance           float64 `json:"balance"`
	Credit            float64 `json:"credit"`
	Profit            float64 `json:"profit"`
	Equity            float64 `json:"equity"`
	Margin            float64 `json:"margin"`
	FreeMargin        float64 `json:"free_margin"`
	MarginLevel       float64 `json:"margin_level"`
	MarginSOCall      float64 `json:"margin_so_call"`
	MarginSOSO        float64 `json:"margin_so_so"`
	MarginInitial     float64 `json:"margin_initial"`
	MarginMaintenance float64 `json:"margin_maintenance"`
	Assets            float64 `json:"assets"`
	Liabilities       float64 `json:"liabilities"`
	CommissionBlocked float64 `json:"commission_blocked"`
	Name              string  `json:"name"`
	Server            string  `json:"server"`
	Currency          string  `json:"currency"`
	Company           string  `json:"company"`
}

type BookEntry added in v0.1.1

type BookEntry struct {
	Type       BookType `json:"type"`
	Price      float64  `json:"price"`
	Volume     int64    `json:"volume"`
	VolumeReal float64  `json:"volume_real"`
}

type BookType

type BookType int
const (
	BookTypeSell       BookType = 1
	BookTypeBuy        BookType = 2
	BookTypeSellMarket BookType = 3
	BookTypeBuyMarket  BookType = 4
)

func (BookType) String added in v0.1.1

func (b BookType) String() string

type CheckResult

type CheckResult struct {
	Retcode     uint32  `json:"retcode"`
	Balance     float64 `json:"balance"`
	Equity      float64 `json:"equity"`
	Profit      float64 `json:"profit"`
	Margin      float64 `json:"margin"`
	MarginFree  float64 `json:"margin_free"`
	MarginLevel float64 `json:"margin_level"`
	Comment     string  `json:"comment"`
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(ctx context.Context, opts ...Option) (*Client, error)

func NewClientFromConn

func NewClientFromConn(ctx context.Context, conn io.ReadWriteCloser, opts ...Option) (*Client, error)

func (*Client) AccountInfo

func (c *Client) AccountInfo(ctx context.Context) (*AccountInfo, error)

func (*Client) Build

func (c *Client) Build() int

func (*Client) Close

func (c *Client) Close() error

func (*Client) Connected added in v0.1.1

func (c *Client) Connected() bool

func (*Client) CopyRatesFrom

func (c *Client) CopyRatesFrom(ctx context.Context, symbol string, timeframe Timeframe, dateFrom int64, count int) ([]Rate, error)

func (*Client) CopyRatesFromPos

func (c *Client) CopyRatesFromPos(ctx context.Context, symbol string, timeframe Timeframe, startPos, count int) ([]Rate, error)

func (*Client) CopyRatesRange

func (c *Client) CopyRatesRange(ctx context.Context, symbol string, timeframe Timeframe, dateFrom, dateTo int64) ([]Rate, error)

func (*Client) CopyTicksFrom

func (c *Client) CopyTicksFrom(ctx context.Context, symbol string, dateFrom int64, count int, flags CopyTicksFlag) ([]Tick, error)

func (*Client) CopyTicksRange

func (c *Client) CopyTicksRange(ctx context.Context, symbol string, dateFrom, dateTo int64, flags CopyTicksFlag) ([]Tick, error)

func (*Client) HistoryDealsGet

func (c *Client) HistoryDealsGet(ctx context.Context, filter *HistoryFilter) ([]Deal, error)

func (*Client) HistoryDealsTotal

func (c *Client) HistoryDealsTotal(ctx context.Context, dateFrom, dateTo int64) (int, error)

func (*Client) HistoryOrdersGet

func (c *Client) HistoryOrdersGet(ctx context.Context, filter *HistoryFilter) ([]Order, error)

func (*Client) HistoryOrdersTotal

func (c *Client) HistoryOrdersTotal(ctx context.Context, dateFrom, dateTo int64) (int, error)

func (*Client) LastError

func (c *Client) LastError() error

func (*Client) Login added in v0.1.1

func (c *Client) Login(ctx context.Context, login int64, password, server string) error

func (*Client) MarketBookAdd added in v0.1.1

func (c *Client) MarketBookAdd(ctx context.Context, symbol string) error

func (*Client) MarketBookGet added in v0.1.1

func (c *Client) MarketBookGet(ctx context.Context, symbol string) ([]BookEntry, error)

func (*Client) MarketBookRelease added in v0.1.1

func (c *Client) MarketBookRelease(ctx context.Context, symbol string) error

func (*Client) OrderCalcMargin

func (c *Client) OrderCalcMargin(ctx context.Context, action TradeAction, symbol string, volume, price float64) (float64, error)

func (*Client) OrderCalcProfit

func (c *Client) OrderCalcProfit(ctx context.Context, action TradeAction, symbol string, volume, priceOpen, priceClose float64) (float64, error)

func (*Client) OrderCheck

func (c *Client) OrderCheck(ctx context.Context, request TradeRequest) (*CheckResult, error)

func (*Client) OrderSend

func (c *Client) OrderSend(ctx context.Context, request TradeRequest) (*TradeResult, error)

func (*Client) OrdersGet

func (c *Client) OrdersGet(ctx context.Context, filter *OrderFilter) ([]Order, error)

func (*Client) OrdersTotal

func (c *Client) OrdersTotal(ctx context.Context) (int, error)

func (*Client) PositionsGet

func (c *Client) PositionsGet(ctx context.Context, filter *PositionFilter) ([]Position, error)

func (*Client) PositionsTotal

func (c *Client) PositionsTotal(ctx context.Context) (int, error)

func (*Client) SendRaw

func (c *Client) SendRaw(ctx context.Context, cmdID uint32, params []byte) ([]byte, error)

func (*Client) State added in v0.1.1

func (c *Client) State() ConnState

func (*Client) SubscribeTicks added in v0.1.1

func (c *Client) SubscribeTicks(ctx context.Context, symbol string) (<-chan Tick, error)

func (*Client) SubscribeTicksWithErrors added in v0.1.1

func (c *Client) SubscribeTicksWithErrors(ctx context.Context, symbol string) (<-chan Tick, <-chan error, error)

func (*Client) SymbolInfo

func (c *Client) SymbolInfo(ctx context.Context, symbol string) (*SymbolInfo, error)

func (*Client) SymbolInfoTick

func (c *Client) SymbolInfoTick(ctx context.Context, symbol string) (*Tick, error)

func (*Client) SymbolSelect added in v0.1.1

func (c *Client) SymbolSelect(ctx context.Context, symbol string, enable bool) error

func (*Client) SymbolsGet added in v0.1.1

func (c *Client) SymbolsGet(ctx context.Context, group string) ([]SymbolInfo, error)

func (*Client) SymbolsTotal

func (c *Client) SymbolsTotal(ctx context.Context) (int, error)

func (*Client) TerminalInfo

func (c *Client) TerminalInfo(ctx context.Context) (*TerminalInfo, error)

func (*Client) UnsubscribeTicks added in v0.1.1

func (c *Client) UnsubscribeTicks(symbol string) error

func (*Client) Version

func (c *Client) Version(ctx context.Context) (*VersionInfo, error)

type ConnState added in v0.1.1

type ConnState int32
const (
	StateConnected    ConnState = 0
	StateDisconnected ConnState = 1
	StateReconnecting ConnState = 2
)

func (ConnState) String added in v0.1.1

func (s ConnState) String() string

type CopyTicksFlag

type CopyTicksFlag int
const (
	CopyTicksAll   CopyTicksFlag = -1
	CopyTicksInfo  CopyTicksFlag = 1
	CopyTicksTrade CopyTicksFlag = 2
)

func (CopyTicksFlag) String added in v0.1.1

func (f CopyTicksFlag) String() string

type Deal

type Deal struct {
	Ticket     int64     `json:"ticket"`
	Order      int64     `json:"order"`
	Time       int64     `json:"time"`
	TimeMsc    int64     `json:"time_msc"`
	Type       DealType  `json:"type"`
	Entry      DealEntry `json:"entry"`
	Magic      int64     `json:"magic"`
	PositionID int64     `json:"position_id"`
	Reason     int64     `json:"reason"`
	Volume     float64   `json:"volume"`
	Price      float64   `json:"price"`
	Commission float64   `json:"commission"`
	Swap       float64   `json:"swap"`
	Profit     float64   `json:"profit"`
	Fee        float64   `json:"fee"`
	Symbol     string    `json:"symbol"`
	Comment    string    `json:"comment"`
	ExternalID string    `json:"external_id"`
}

func (*Deal) TimeUTC added in v0.1.1

func (d *Deal) TimeUTC() time.Time

type DealEntry

type DealEntry int
const (
	DealEntryIn    DealEntry = 0
	DealEntryOut   DealEntry = 1
	DealEntryInOut DealEntry = 2
	DealEntryState DealEntry = 3
)

func (DealEntry) String added in v0.1.1

func (e DealEntry) String() string

type DealType

type DealType int
const (
	DealTypeBuy               DealType = 0
	DealTypeSell              DealType = 1
	DealTypeBalance           DealType = 2
	DealTypeCredit            DealType = 3
	DealTypeCharge            DealType = 4
	DealTypeCorrection        DealType = 5
	DealTypeBonus             DealType = 6
	DealTypeCommission        DealType = 7
	DealTypeCommissionDaily   DealType = 8
	DealTypeCommissionMonthly DealType = 9
	DealTypeCommissionAgent   DealType = 10
	DealTypeInterest          DealType = 11
	DealTypeBuyCanceled       DealType = 12
	DealTypeSellCanceled      DealType = 13
	DealTypeDividend          DealType = 14
	DealTypeDividendFranked   DealType = 15
	DealTypeTax               DealType = 16
)

func (DealType) String added in v0.1.1

func (d DealType) String() string

type DisconnectHook added in v0.1.1

type DisconnectHook func(err error)

type HistoryFilter added in v0.1.1

type HistoryFilter struct {
	DateFrom int64
	DateTo   int64
	Symbol   string
	Ticket   int64
	Group    string
}

type Logger added in v0.1.1

type Logger interface {
	Debug(msg string, args ...any)
}

type MT5Error

type MT5Error struct {
	Code    int
	Message string
}

func (*MT5Error) Error

func (e *MT5Error) Error() string

type Option

type Option func(*options)

func WithAutoReconnect added in v0.1.1

func WithAutoReconnect(enabled bool) Option

func WithDebug added in v0.1.1

func WithDebug(enabled bool) Option

func WithHeartbeatInterval added in v0.1.1

func WithHeartbeatInterval(d time.Duration) Option

func WithLogger added in v0.1.1

func WithLogger(l Logger) Option

func WithOnDisconnect added in v0.1.1

func WithOnDisconnect(hook DisconnectHook) Option

func WithOnReconnect added in v0.1.1

func WithOnReconnect(hook ReconnectHook) Option

func WithOnRequest added in v0.1.1

func WithOnRequest(hook RequestHook) Option

func WithPipeName

func WithPipeName(name string) Option

func WithReconnectConfig added in v0.1.1

func WithReconnectConfig(initial, max time.Duration, maxRetries int) Option

func WithTickBufferSize added in v0.1.1

func WithTickBufferSize(size int) Option

func WithTickPollInterval added in v0.1.1

func WithTickPollInterval(d time.Duration) Option

func WithTimeout

func WithTimeout(d time.Duration) Option

type Order

type Order struct {
	Ticket         int64        `json:"ticket"`
	TimeSetup      int64        `json:"time_setup"`
	TimeSetupMsc   int64        `json:"time_setup_msc"`
	TimeDone       int64        `json:"time_done"`
	TimeDoneMsc    int64        `json:"time_done_msc"`
	TimeExpiration int64        `json:"time_expiration"`
	Type           OrderType    `json:"type"`
	TypeTime       OrderTime    `json:"type_time"`
	TypeFilling    OrderFilling `json:"type_filling"`
	State          int64        `json:"state"`
	Magic          int64        `json:"magic"`
	PositionID     int64        `json:"position_id"`
	PositionByID   int64        `json:"position_by_id"`
	Reason         int64        `json:"reason"`
	VolumeInitial  float64      `json:"volume_initial"`
	VolumeCurrent  float64      `json:"volume_current"`
	PriceOpen      float64      `json:"price_open"`
	PriceCurrent   float64      `json:"price_current"`
	PriceSL        float64      `json:"price_sl"`
	PriceTP        float64      `json:"price_tp"`
	PriceStopLimit float64      `json:"price_stoplimit"`
	Symbol         string       `json:"symbol"`
	Comment        string       `json:"comment"`
	ExternalID     string       `json:"external_id"`
}

func (*Order) TimeDoneUTC added in v0.1.1

func (o *Order) TimeDoneUTC() time.Time

func (*Order) TimeSetupUTC added in v0.1.1

func (o *Order) TimeSetupUTC() time.Time

type OrderFilling

type OrderFilling int
const (
	OrderFillingFOK    OrderFilling = 0
	OrderFillingIOC    OrderFilling = 1
	OrderFillingReturn OrderFilling = 2
	OrderFillingBOC    OrderFilling = 3
)

func (OrderFilling) String added in v0.1.1

func (f OrderFilling) String() string

type OrderFilter added in v0.1.1

type OrderFilter struct {
	Symbol string
	Ticket int64
	Group  string
}

type OrderTime

type OrderTime int
const (
	OrderTimeGTC       OrderTime = 0
	OrderTimeDay       OrderTime = 1
	OrderTimeSpecified OrderTime = 2
	OrderTimeSpecDay   OrderTime = 3
)

func (OrderTime) String added in v0.1.1

func (t OrderTime) String() string

type OrderType

type OrderType int
const (
	OrderTypeBuy           OrderType = 0
	OrderTypeSell          OrderType = 1
	OrderTypeBuyLimit      OrderType = 2
	OrderTypeSellLimit     OrderType = 3
	OrderTypeBuyStop       OrderType = 4
	OrderTypeSellStop      OrderType = 5
	OrderTypeBuyStopLimit  OrderType = 6
	OrderTypeSellStopLimit OrderType = 7
	OrderTypeCloseBy       OrderType = 8
)

func (OrderType) String added in v0.1.1

func (o OrderType) String() string

type Position

type Position struct {
	Ticket        int64        `json:"ticket"`
	Time          int64        `json:"time"`
	TimeMsc       int64        `json:"time_msc"`
	TimeUpdate    int64        `json:"time_update"`
	TimeUpdateMsc int64        `json:"time_update_msc"`
	Type          PositionType `json:"type"`
	Magic         int64        `json:"magic"`
	Identifier    int64        `json:"identifier"`
	Reason        int64        `json:"reason"`
	Volume        float64      `json:"volume"`
	PriceOpen     float64      `json:"price_open"`
	PriceCurrent  float64      `json:"price_current"`
	PriceSL       float64      `json:"price_sl"`
	PriceTP       float64      `json:"price_tp"`
	Swap          float64      `json:"swap"`
	Profit        float64      `json:"profit"`
	Symbol        string       `json:"symbol"`
	Comment       string       `json:"comment"`
	ExternalID    string       `json:"external_id"`
}

func (*Position) TimeUTC added in v0.1.1

func (p *Position) TimeUTC() time.Time

func (*Position) TimeUpdateUTC added in v0.1.1

func (p *Position) TimeUpdateUTC() time.Time

type PositionFilter added in v0.1.1

type PositionFilter struct {
	Symbol string
	Ticket int64
	Group  string
}

type PositionType

type PositionType int
const (
	PositionTypeBuy  PositionType = 0
	PositionTypeSell PositionType = 1
)

func (PositionType) String added in v0.1.1

func (p PositionType) String() string

type Rate

type Rate struct {
	Time       int64   `json:"time"`
	Open       float64 `json:"open"`
	High       float64 `json:"high"`
	Low        float64 `json:"low"`
	Close      float64 `json:"close"`
	TickVolume int64   `json:"tick_volume"`
	Spread     int32   `json:"spread"`
	RealVolume int64   `json:"real_volume"`
}

func (*Rate) TimeUTC added in v0.1.1

func (r *Rate) TimeUTC() time.Time

type ReconnectConfig added in v0.1.1

type ReconnectConfig struct {
	Enabled      bool
	InitialDelay time.Duration
	MaxDelay     time.Duration
	MaxRetries   int
}

type ReconnectHook added in v0.1.1

type ReconnectHook func()

type RequestHook added in v0.1.1

type RequestHook func(cmdID uint32, duration time.Duration, err error)

type SymbolInfo

type SymbolInfo struct {
	Custom                  bool    `json:"custom"`
	ChartMode               int64   `json:"chart_mode"`
	Select                  bool    `json:"select"`
	Visible                 bool    `json:"visible"`
	SessionDeals            int64   `json:"session_deals"`
	SessionBuyOrders        int64   `json:"session_buy_orders"`
	SessionSellOrders       int64   `json:"session_sell_orders"`
	Volume                  int64   `json:"volume"`
	VolumeHigh              int64   `json:"volumehigh"`
	VolumeLow               int64   `json:"volumelow"`
	Time                    int64   `json:"time"`
	Digits                  int64   `json:"digits"`
	Spread                  int64   `json:"spread"`
	SpreadFloat             bool    `json:"spread_float"`
	TicksBookDepth          int64   `json:"ticks_bookdepth"`
	TradeCalcMode           int64   `json:"trade_calc_mode"`
	TradeMode               int64   `json:"trade_mode"`
	StartTime               int64   `json:"start_time"`
	ExpirationTime          int64   `json:"expiration_time"`
	TradeStopsLevel         int64   `json:"trade_stops_level"`
	TradeFreezeLevel        int64   `json:"trade_freeze_level"`
	TradeExeMode            int64   `json:"trade_exemode"`
	SwapMode                int64   `json:"swap_mode"`
	SwapRollover3Days       int64   `json:"swap_rollover3days"`
	MarginHedgedUseLeg      bool    `json:"margin_hedged_use_leg"`
	ExpirationMode          int64   `json:"expiration_mode"`
	FillingMode             int64   `json:"filling_mode"`
	OrderMode               int64   `json:"order_mode"`
	OrderGTCMode            int64   `json:"order_gtc_mode"`
	OptionMode              int64   `json:"option_mode"`
	OptionRight             int64   `json:"option_right"`
	Bid                     float64 `json:"bid"`
	BidHigh                 float64 `json:"bidhigh"`
	BidLow                  float64 `json:"bidlow"`
	Ask                     float64 `json:"ask"`
	AskHigh                 float64 `json:"askhigh"`
	AskLow                  float64 `json:"asklow"`
	Last                    float64 `json:"last"`
	LastHigh                float64 `json:"lasthigh"`
	LastLow                 float64 `json:"lastlow"`
	VolumeReal              float64 `json:"volume_real"`
	VolumeHighReal          float64 `json:"volumehigh_real"`
	VolumeLowReal           float64 `json:"volumelow_real"`
	OptionStrike            float64 `json:"option_strike"`
	Point                   float64 `json:"point"`
	TradeTickValue          float64 `json:"trade_tick_value"`
	TradeTickValueProfit    float64 `json:"trade_tick_value_profit"`
	TradeTickValueLoss      float64 `json:"trade_tick_value_loss"`
	TradeTickSize           float64 `json:"trade_tick_size"`
	TradeContractSize       float64 `json:"trade_contract_size"`
	TradeAccruedInterest    float64 `json:"trade_accrued_interest"`
	TradeFaceValue          float64 `json:"trade_face_value"`
	TradeLiquidityRate      float64 `json:"trade_liquidity_rate"`
	VolumeMin               float64 `json:"volume_min"`
	VolumeMax               float64 `json:"volume_max"`
	VolumeStep              float64 `json:"volume_step"`
	VolumeLimit             float64 `json:"volume_limit"`
	SwapLong                float64 `json:"swap_long"`
	SwapShort               float64 `json:"swap_short"`
	MarginInitial           float64 `json:"margin_initial"`
	MarginMaintenance       float64 `json:"margin_maintenance"`
	SessionVolume           float64 `json:"session_volume"`
	SessionTurnover         float64 `json:"session_turnover"`
	SessionInterest         float64 `json:"session_interest"`
	SessionBuyOrdersVolume  float64 `json:"session_buy_orders_volume"`
	SessionSellOrdersVolume float64 `json:"session_sell_orders_volume"`
	SessionOpen             float64 `json:"session_open"`
	SessionClose            float64 `json:"session_close"`
	SessionAW               float64 `json:"session_aw"`
	SessionPriceSettlement  float64 `json:"session_price_settlement"`
	SessionPriceLimitMin    float64 `json:"session_price_limit_min"`
	SessionPriceLimitMax    float64 `json:"session_price_limit_max"`
	MarginHedged            float64 `json:"margin_hedged"`
	PriceChange             float64 `json:"price_change"`
	PriceVolatility         float64 `json:"price_volatility"`
	PriceTheoretical        float64 `json:"price_theoretical"`
	PriceGreeksDelta        float64 `json:"price_greeks_delta"`
	PriceGreeksTheta        float64 `json:"price_greeks_theta"`
	PriceGreeksGamma        float64 `json:"price_greeks_gamma"`
	PriceGreeksVega         float64 `json:"price_greeks_vega"`
	PriceGreeksRho          float64 `json:"price_greeks_rho"`
	PriceGreeksOmega        float64 `json:"price_greeks_omega"`
	PriceSensitivity        float64 `json:"price_sensitivity"`
	Basis                   string  `json:"basis"`
	Category                string  `json:"category"`
	CurrencyBase            string  `json:"currency_base"`
	CurrencyProfit          string  `json:"currency_profit"`
	CurrencyMargin          string  `json:"currency_margin"`
	Bank                    string  `json:"bank"`
	Description             string  `json:"description"`
	Exchange                string  `json:"exchange"`
	Formula                 string  `json:"formula"`
	ISIN                    string  `json:"isin"`
	SymbolName              string  `json:"name"`
	Page                    string  `json:"page"`
	Path                    string  `json:"path"`
}

type TerminalInfo

type TerminalInfo struct {
	CommunityAccount     bool    `json:"community_account"`
	CommunityConnection  bool    `json:"community_connection"`
	Connected            bool    `json:"connected"`
	DLLsAllowed          bool    `json:"dlls_allowed"`
	TradeAllowed         bool    `json:"trade_allowed"`
	TradeAPIDisabled     bool    `json:"tradeapi_disabled"`
	EmailEnabled         bool    `json:"email_enabled"`
	FTPEnabled           bool    `json:"ftp_enabled"`
	NotificationsEnabled bool    `json:"notifications_enabled"`
	MQID                 bool    `json:"mqid"`
	Build                int64   `json:"build"`
	MaxBars              int64   `json:"maxbars"`
	CodePage             int64   `json:"codepage"`
	PingLast             int64   `json:"ping_last"`
	CommunityBalance     float64 `json:"community_balance"`
	Retransmission       float64 `json:"retransmission"`
	Company              string  `json:"company"`
	Name                 string  `json:"name"`
	Language             string  `json:"language"`
	Path                 string  `json:"path"`
	DataPath             string  `json:"data_path"`
	CommonDataPath       string  `json:"commondata_path"`
}

type Tick

type Tick struct {
	Time    int64   `json:"time"`
	Bid     float64 `json:"bid"`
	Ask     float64 `json:"ask"`
	Last    float64 `json:"last"`
	Volume  uint64  `json:"volume"`
	TimeMsc int64   `json:"time_msc"`
	Flags   uint32  `json:"flags"`
}

func (*Tick) TimeUTC added in v0.1.1

func (t *Tick) TimeUTC() time.Time

type Timeframe

type Timeframe int
const (
	TimeframeM1  Timeframe = 1
	TimeframeM2  Timeframe = 2
	TimeframeM3  Timeframe = 3
	TimeframeM4  Timeframe = 4
	TimeframeM5  Timeframe = 5
	TimeframeM6  Timeframe = 6
	TimeframeM10 Timeframe = 10
	TimeframeM12 Timeframe = 12
	TimeframeM15 Timeframe = 15
	TimeframeM20 Timeframe = 20
	TimeframeM30 Timeframe = 30
	TimeframeH1  Timeframe = 16385
	TimeframeH2  Timeframe = 16386
	TimeframeH3  Timeframe = 16387
	TimeframeH4  Timeframe = 16388
	TimeframeH6  Timeframe = 16390
	TimeframeH8  Timeframe = 16392
	TimeframeH12 Timeframe = 16396
	TimeframeD1  Timeframe = 16408
	TimeframeW1  Timeframe = 32769
	TimeframeMN1 Timeframe = 49153
)

func (Timeframe) String added in v0.1.1

func (t Timeframe) String() string

type TradeAction

type TradeAction int
const (
	TradeActionDeal    TradeAction = 1
	TradeActionPending TradeAction = 5
	TradeActionSLTP    TradeAction = 6
	TradeActionModify  TradeAction = 7
	TradeActionRemove  TradeAction = 8
	TradeActionCloseBy TradeAction = 10
)

func (TradeAction) String added in v0.1.1

func (a TradeAction) String() string

type TradeError added in v0.1.1

type TradeError struct {
	Result  TradeResult
	Request TradeRequest
}

func (*TradeError) Error added in v0.1.1

func (e *TradeError) Error() string

type TradeRequest

type TradeRequest struct {
	Action      TradeAction  `json:"action"`
	Magic       int64        `json:"magic,omitempty"`
	Order       int64        `json:"order,omitempty"`
	Symbol      string       `json:"symbol,omitempty"`
	Volume      float64      `json:"volume,omitempty"`
	Price       float64      `json:"price,omitempty"`
	StopLimit   float64      `json:"stoplimit,omitempty"`
	SL          float64      `json:"sl,omitempty"`
	TP          float64      `json:"tp,omitempty"`
	Deviation   int          `json:"deviation,omitempty"`
	Type        OrderType    `json:"type,omitempty"`
	TypeFilling OrderFilling `json:"type_filling,omitempty"`
	TypeTime    OrderTime    `json:"type_time,omitempty"`
	Expiration  int64        `json:"expiration,omitempty"`
	Comment     string       `json:"comment,omitempty"`
	Position    int64        `json:"position,omitempty"`
	PositionBy  int64        `json:"position_by,omitempty"`
}

func (*TradeRequest) Validate added in v0.1.1

func (r *TradeRequest) Validate() error

type TradeResult

type TradeResult struct {
	Retcode    uint32  `json:"retcode"`
	Deal       int64   `json:"deal"`
	Order      int64   `json:"order"`
	Volume     float64 `json:"volume"`
	Price      float64 `json:"price"`
	Bid        float64 `json:"bid"`
	Ask        float64 `json:"ask"`
	Comment    string  `json:"comment"`
	RequestID  uint32  `json:"request_id"`
	RetcodeExt int32   `json:"retcode_external"`
}

func (*TradeResult) IsOK added in v0.1.1

func (r *TradeResult) IsOK() bool

type VersionInfo

type VersionInfo struct {
	Version   int
	Build     int
	BuildDate string
}

Directories

Path Synopsis
examples
connect command
rates command
risk command
stream command
ticks command
trade command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL