ctraderopenapi

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

ctrader — Go client for cTrader OpenAPI

This repository provides a compact, idiomatic Go client for the cTrader OpenAPI proxy. It focuses on a small, testable public surface for:

  • sending RPC-like requests (request/response mapped to protobuf messages),
  • subscribing to and listening for streaming server events (push-style),
  • a concurrency-safe event dispatcher and small adapters to wire typed handlers without reflection.
  • an client-side request rate limiter to prevent server-side rate limiting.

Contents

  • Quick highlights
  • Installation (Go modules)
  • Exported types & API summary
  • Examples (connect/request, subscribe + listen, client events)
  • Running tests
  • License

Quick highlights

  • Typed, protobuf-backed request/response helpers.
  • Event handler for both API and client events providing easy abstraction via subscribe/unsubscribe and listen functions.
  • Client-side rate limiter to avoid server-side rate limiting.
  • Small typed adapters (SpawnAPIEventHandler, SpawnClientEventHandler) that adapt generic channels to typed callbacks (they perform runtime type assertions and will drop non-matching events).
  • Connection loss handling; recovering authenticated accounts and active subscriptions on reconnect.

Installation

This library uses Go modules. From your project directory you can add the dependency with:

go get github.com/linuskuehnle/ctraderopenapi@latest

Then import the package in your code:

import "github.com/linuskuehnle/ctraderopenapi"

To install a binary (if provided by this repository) or to run tooling:

go install github.com/linuskuehnle/ctraderopenapi@latest

Exported types & API summary

Key public types and functions (see types.go and api_client.go for full comments and examples):

  • NewAPIClient(cred ApplicationCredentials, env Environment) (APIClient, error) — create a new client instance. Call WithConfig before Connect to adjust runtime buffers/timeouts.
Custom response types for execution requests

Certain requests (ProtoOANewOrderReq, ProtoOACancelOrderReq, ProtoOAAmendOrderReq, ProtoOAAmendPositionSLTPReq, ProtoOAClosePositionReq) do not have explicit response types defined in the cTrader OpenAPI specification. Instead, they are answered asynchronously via ProtoOAExecutionEvent. This client library transparently maps these events back to their originating requests, providing a synchronous request/response interface.

How it works:

  • When you send a request with no explicit response type, you provide a custom response type that is type-aliased to ProtoOAExecutionEvent (e.g., ProtoOANewOrderRes = ProtoOAExecutionEvent).
  • The client internally assigns each request a unique ID and tracks pending requests, allowing multiple concurrent requests with the same account ID to be properly correlated.
  • When a ProtoOAExecutionEvent arrives from the server, the client matches it against pending requests to determine which request it corresponds to, then returns the event as the synchronized response.
  • If an error occurs, the server may respond with ProtoOAErrorRes instead, which the client properly handles before attempting to match execution events.

Why map asynchronous events to synchronous requests: The cTrader OpenAPI does not provide dedicated response types for order management operations, instead returning generic ProtoOAErrorRes on errors or ProtoOAExecutionEvent on success. This inconsistency (error uses one type, success uses another) makes error handling and response correlation ambiguous. By internally managing this mapping and exposing a synchronous interface, callers benefit from intuitive error handling and clear request/response pairing without needing to subscribe to execution events or manually match incoming events to outgoing requests.

  • APIClient — main interface. Important methods:

    Connection management:

    • Connect() error / Disconnect() — establish or close the connection

    Account authentication:

    • AuthenticateAccount(CtraderAccountId, AccessToken) (*types.ProtoOAAccountAuthRes, error) — authenticate with a specific cTrader account using an access token. Must be called before making account-specific requests or subscribing to account events.
    • LogoutAccount(CtraderAccountId, bool) (*types.ProtoOAAccountLogoutRes, error) — logout from a cTrader account. The boolean parameter controls whether to wait for the server's ProtoOAAccountDisconnectEvent confirmation before returning.
    • RefreshAccessToken(AccessToken, RefreshToken) (*types.ProtoOARefreshTokenRes, error) — refresh an expired access token using a refresh token, returns a new access token.

    Request/Response:

    • SendRequest(RequestData) error — sends a protobuf-typed request and unmarshals the response into the provided response object.

    Event subscriptions:

    • SubscribeAPIEvent(APIEventSubData) / UnsubscribeAPIEvent(...) — subscribe/unsubscribe for server-side subscription-based events.
    • SubscribeClientEvent(SubscribableClientEventData) / UnsubscribeClientEvent(...) — subscribe/unsubscribe for client-side events.

    Event listening:

    • ListenToAPIEvent(ctx, APIEventListenData) — register a long-running listener channel for push events. APIEventListenData includes optional EventKeyData for fine-grained filtering (e.g., by account ID and symbol ID).
    • ListenToClientEvent(ctx, ClientEventListenData) — listen for client-side events (connection loss, reconnect events, fatal errors).

    Client event types: Fatal client errors, connection loss, reconnect success, and reconnect fail.

    Error handling: Fatal (non-recoverable) client errors are emitted as FatalErrorEvent. If a listener channel is registered, the error is sent to the channel and the client recovers by reconnecting. Without a listener, a fatal error raises a panic.

    Reconnection: The API Client automatically handles connection losses. Register listeners for ConnectionLossEvent, ReconnectSuccessEvent, and ReconnectFailEvent using ListenToClientEvent. Previously subscribed API Events are automatically resubscribed before ReconnectSuccessEvent is emitted.

    Runtime configuration:

    • WithQueueBufferSize(int) updates the number of queued requests that may be buffered by the internal request queue before backpressure applies.
    • WithTCPMessageBufferSize(int) updates the size of the channel used to receive inbound TCP messages from the network reader.
    • WithRequestContextManagerIterationTimeout(time.Duration) updates interval used by the request context manager to periodically check for expired request contexts.
    • WithRequestTimeout(time.Duration) updates the duration until a request roundtrip is aborted no matter if already sent or not.
    • DisableConcurrentEventEmits() disables concurrent event emit; events are passed sequentially to event channels instead of being spawned in separate goroutines. This reduces overhead but may block the client if an event channel buffer is full.
    • DisableDefaultRateLimiter() to disable the client-side rate limiter.

    Rate limiting: The client enforces rate limits to prevent server-side throttling:

    • 50 live requests per second (ProtoOALiveView subscriptions)
    • 5 historical requests per second (ProtoOAHistoricalData requests)

    If the server-side rate limit is still exceeded due to network divergence, the request is automatically re-enqueued, so callers do not need to handle rate limit errors.

  • ApplicationCredentials{ ClientId, ClientSecret } — credentials used by the application to authenticate with the OpenAPI. Validate with CheckError().

  • CtraderAccountId — thin typed alias over int64 for explicit account ID references.

  • AccessToken — thin typed alias over string for access tokens obtained after authenticating an account.

  • RefreshToken — thin typed alias over string for refresh tokens used to obtain new access tokens.

Error types

Several error types provide fine-grained control over error handling:

  • ResponseError — wraps server-side errors returned in ProtoOAErrorRes. Contains ErrorCode, Description, and optional MaintenanceEndTimestamp (if the server is undergoing maintenance).

  • RequestContextManagerNodeNotIncludedError — internal error indicating a request context was not found. Typically not used by callers.

  • UnexpectedMessageTypeError — raised when the server sends a message with an unexpected payload type. Includes the numeric message type for debugging.

  • ProtoUnmarshalError — wraps errors during protobuf unmarshalling, including the context (e.g., "proto OA execution event") where the error occurred.

  • Event helpers and adapters:

    • APIEvent and ClientEvent — marker interfaces for event types.
    • CastToAPIEventType[T] and CastToClientEventType[T] — helpers to cast generic event types to concrete event types.
    • ProtoOAExecutionEvent — accessible to listen to for specific ExecutionType values: DEPOSIT_WITHDRAW, BONUS_DEPOSIT_WITHDRAW, or SWAP. Other execution types are handled internally as responses to order management requests and are not emitted as standalone API events.
    • SpawnAPIEventHandler and SpawnClientEventHandler — start small goroutines that forward typed events to your handler, eliminating the need for manual type assertions.
  • Fine-grained event filtering:

    • APIEventListenData and ClientEventListenData — data structures for configuring event listeners.
    • EventKeyData — optional parameter in APIEventListenData for filtering events by subscription-specific criteria (e.g., account ID and symbol ID for spot events). When nil, all events of the specified type are delivered.
    • KeyDataSpotEvent, KeyDataDepthEvent, KeyDataTrailingSLChangedEvent, etc. — concrete key data types for filtering specific event subtypes.

Examples

  1. Basic connect and simple request
package main

import (
	"context"
	"fmt"
	"github.com/linuskuehnle/ctraderopenapi"
	"github.com/linuskuehnle/ctraderopenapi/types"
)

func main() {
	cred := ctraderopenapi.ApplicationCredentials{ClientId: "id", ClientSecret: "secret"}
	client, err := ctraderopenapi.NewAPIClient(cred, ctraderopenapi.Environment_Demo)
	if err != nil {
		panic(err)
	}

	if err := client.Connect(); err != nil {
		panic(err)
	}
	defer client.Disconnect()

	req := types.ProtoOAVersionReq{}
	var res types.ProtoOAVersionRes
	reqData := ctraderopenapi.RequestData{
		Ctx:     context.Background(),
		Req:     &req,
		Res:     &res,
	}
	if err := client.SendRequest(reqData); err != nil {
		fmt.Println("request failed:", err)
		return
	}

	fmt.Println("version:", res.GetVersion())
}
  1. Sending an order with custom response type (no explicit response)
package main

import (
	"context"
	"fmt"
	"github.com/linuskuehnle/ctraderopenapi"
	"github.com/linuskuehnle/ctraderopenapi/types"
)

func main() {
	cred := ctraderopenapi.ApplicationCredentials{ClientId: "id", ClientSecret: "secret"}
	client, err := ctraderopenapi.NewAPIClient(cred, ctraderopenapi.Environment_Demo)
	if err != nil {
		panic(err)
	}

	if err := client.Connect(); err != nil {
		panic(err)
	}
	defer client.Disconnect()

	// Authenticate with an account first
	accountId := ctraderopenapi.CtraderAccountId(123456)
	accessToken := ctraderopenapi.AccessToken("your-access-token")
	
	if _, err := client.AuthenticateAccount(accountId, accessToken); err != nil {
		panic(err)
	}

	// Send a new order - response is an execution event internally mapped to the request
	orderReq := types.ProtoOANewOrderReq{
		// ... configure order details
	}
	var orderRes types.ProtoOANewOrderRes
	reqData := ctraderopenapi.RequestData{
		Ctx: context.Background(),
		Req: &orderReq,
		Res: &orderRes, // This is actually a ProtoOAExecutionEvent (custom response type)
	}
	
	if err := client.SendRequest(reqData); err != nil {
		fmt.Println("order request failed:", err)
		return
	}

	fmt.Println("order execution event:", orderRes.GetExecutionType())
}
  1. Account authentication and logout
package main

import (
	"fmt"
	"github.com/linuskuehnle/ctraderopenapi"
)

func main() {
	cred := ctraderopenapi.ApplicationCredentials{ClientId: "id", ClientSecret: "secret"}
	client, err := ctraderopenapi.NewAPIClient(cred, ctraderopenapi.Environment_Demo)
	if err != nil {
		panic(err)
	}

	if err := client.Connect(); err != nil {
		panic(err)
	}
	defer client.Disconnect()

	// Authenticate with a cTrader account
	accountId := ctraderopenapi.CtraderAccountId(123456)
	accessToken := ctraderopenapi.AccessToken("your-access-token")
	
	authRes, err := client.AuthenticateAccount(accountId, accessToken)
	if err != nil {
		fmt.Println("authentication failed:", err)
		return
	}

	fmt.Println("authenticated successfully:", authRes)

	// Use the authenticated account to make requests or subscribe to events...

	// Logout from the account (waitForConfirm=true waits for server confirmation)
	if _, err := client.LogoutAccount(accountId, true); err != nil {
		fmt.Println("logout failed:", err)
		return
	}

	fmt.Println("logged out successfully")
}
  1. Token refresh
package main

import (
	"fmt"
	"github.com/linuskuehnle/ctraderopenapi"
	"github.com/linuskuehnle/ctraderopenapi/types"
)

func main() {
	cred := ctraderopenapi.ApplicationCredentials{ClientId: "id", ClientSecret: "secret"}
	client, err := ctraderopenapi.NewAPIClient(cred, ctraderopenapi.Environment_Demo)
	if err != nil {
		panic(err)
	}

	if err := client.Connect(); err != nil {
		panic(err)
	}
	defer client.Disconnect()

	// Refresh an expired access token
	expiredToken := ctraderopenapi.AccessToken("expired-token")
	refreshToken := ctraderopenapi.RefreshToken("refresh-token")
	
	refreshRes, err := client.RefreshAccessToken(expiredToken, refreshToken)
	if err != nil {
		fmt.Println("token refresh failed:", err)
		return
	}

	// Use the new access token for subsequent requests
	newAccessToken := ctraderopenapi.AccessToken(refreshRes.GetAccessToken())
	fmt.Println("new access token:", newAccessToken)
}
  1. Subscribe to spot events and handle them with the typed adapter
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

onEventCh := make(chan ctraderopenapi.APIEvent)
listenData := ctraderopenapi.APIEventListenData{
	EventType:    ctraderopenapi.APIEventType_Spot,
	EventCh:      onEventCh,
	EventKeyData: &ctraderopenapi.KeyDataSpotEvent{
		Ctid:     ctraderopenapi.CtraderAccountId(123456),
		SymbolId: 1,
		Period:   types.ProtoOATrendbarPeriod_M1,
	},
}
if err := client.ListenToAPIEvent(ctx, listenData); err != nil {
	panic(err)
}

_ = ctraderopenapi.SpawnAPIEventHandler(ctx, onEventCh, func(e *types.ProtoOASpotEvent) {
	fmt.Println("spot event:", e)
})

sub := ctraderopenapi.APIEventSubData{
	EventType: ctraderopenapi.APIEventType_Spot,
	SubcriptionData: &ctraderopenapi.SpotEventData{
		CtraderAccountId: ctraderopenapi.CtraderAccountId(123456),
		SymbolIds:        []int64{1, 2, 3},
	},
}
if err := client.SubscribeAPIEvent(sub); err != nil {
	panic(err)
}
  1. Listen for client events; e.g. ReconnectSuccessEvent:

clientCh := make(chan ctraderopenapi.ClientEvent)
listenData := ctraderopenapi.ClientEventListenData{
	EventType: ctraderopenapi.ClientEventType_ReconnectSuccessEvent,
	EventCh:   clientCh,
}
if err := client.ListenToClientEvent(context.Background(), listenData); err != nil {
	panic(err)
}
ctraderopenapi.SpawnClientEventHandler(context.Background(), clientCh, func(e *types.ReconnectSuccessEvent) {
	fmt.Println("reconnected")
})

I suggest registering all event listener channels before calling apiClient.Connect(). apiClient.Disconnect() unregisters all event listener channels; if you want to reconnect and use the same listeners, explicitly register them again before the next Connect() call.

Authentication workflow:

  1. Create and connect the API client with application credentials
  2. Authenticate with a specific account using AuthenticateAccount(accountId, accessToken)
  3. Make account-specific requests or subscribe to events
  4. Optionally refresh access tokens with RefreshAccessToken() if tokens expire (see APIEvent ProtoOAAccountsTokenInvalidatedEvent)
  5. Logout with LogoutAccount() when finished with the account

Running tests

Some tests exercise live interactions and expect credentials via environment variables or a .env file (see stubs_test.go). To run unit/integration tests locally:

go test ./...

To run a focused test and vet the code:

go vet ./...
go test ./... -run TestClientConnectDisconnect

License

This project is licensed under the Apache License 2.0 — see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	ConfigDefault_RequestTimeout                        = time.Second * 1
	ConfigDefault_QueueBufferSize                       = 10
	ConfigDefault_TCPMessageBufferSize                  = 10
	ConfigDefault_RequestContextManagerIterationTimeout = datatypes.DefaultRequestContextManagerIterationTimeout
	ConfigDefault_ConcurrentEventEmits                  = true

	MinRequestTimeout                        = time.Millisecond * 50
	MinQueueBufferSize                       = 1
	MinTCPMessageBufferSize                  = 1
	MinRequestContextManagerIterationTimeout = datatypes.MinRequestContextManagerIterationTimeout
)
View Source
const (

	// Demo environment endpoint address
	EndpointAddress_Demo endpointAddress = "demo.ctraderapi.com:5035"
	// Live environment endpoint address
	EndpointAddress_Live endpointAddress = "live.ctraderapi.com:5035"
)
View Source
const (
	// Subscribable events
	APIEventType_Spot         apiEventType = datatypes.PROTO_OA_SPOT_EVENT
	APIEventType_LiveTrendbar              = 1
	APIEventType_DepthQuote                = datatypes.PROTO_OA_DEPTH_EVENT

	// Listenable events
	APIEventType_TrailingSLChanged        = datatypes.PROTO_OA_TRAILING_SL_CHANGED_EVENT
	APIEventType_SymbolChanged            = datatypes.PROTO_OA_SYMBOL_CHANGED_EVENT
	APIEventType_TraderUpdated            = datatypes.PROTO_OA_TRADER_UPDATE_EVENT
	APIEventType_Execution                = datatypes.PROTO_OA_EXECUTION_EVENT
	APIEventType_MarginChanged            = datatypes.PROTO_OA_MARGIN_CHANGED_EVENT
	APIEventType_AccountsTokenInvalidated = datatypes.PROTO_OA_ACCOUNTS_TOKEN_INVALIDATED_EVENT
	APIEventType_ClientDisconnect         = datatypes.PROTO_OA_CLIENT_DISCONNECT_EVENT
	APIEventType_AccountDisconnect        = datatypes.PROTO_OA_ACCOUNT_DISCONNECT_EVENT
	APIEventType_MarginCallUpdate         = datatypes.PROTO_OA_MARGIN_CALL_UPDATE_EVENT
	APIEventType_MarginCallTrigger        = datatypes.PROTO_OA_MARGIN_CALL_TRIGGER_EVENT
)
View Source
const (
	// API Client events
	ClientEventType_FatalErrorEvent clientEventType = iota + 1 + 100
	ClientEventType_ConnectionLossEvent
	ClientEventType_ReconnectSuccessEvent
	ClientEventType_ReconnectFailEvent
)
View Source
const (
	// Heartbeat_Interval_Seconds is the interval at which heartbeat messages are sent to the server.
	Heartbeat_Timeout_Seconds = 9
)

Variables

View Source
var (
	DefaultReconnectBackoffLadder   = []time.Duration{1 * time.Second, 2 * time.Second, 5 * time.Second, 10 * time.Second}
	DefaultReconnectBackoffStepDown = 30 * time.Second
)

Functions

func CastToAPIEventType added in v0.3.1

func CastToAPIEventType[T APIEvent](event APIEvent) (T, bool)

CastToAPIEventType attempts to cast a generic `APIEvent` to the concrete typed event `T`. It returns the typed value and `true` if the assertion succeeded; otherwise it returns the zero value and `false`.

This helper is commonly used by small adapter goroutines that accept a generic `APIEvent` channel but want to call a typed handler (for example converting `APIEvent` to `*ProtoOASpotEvent`).

func CastToClientEventType added in v0.1.1

func CastToClientEventType[T ClientEvent](event ClientEvent) (T, bool)

CastToClientEventType attempts to cast a generic `ClientEvent` to the concrete typed event `T`. It returns the typed value and `true` if the assertion succeeded; otherwise it returns the zero value and `false`.

This helper is commonly used by small adapter goroutines that accept a generic `ClientEvent` channel but want to call a typed handler (for example converting `ClientEvent` to `*ReconnectSuccessEvent`).

func SpawnAPIEventHandler added in v0.2.0

func SpawnAPIEventHandler[T APIEvent](ctx context.Context, onEventCh chan APIEvent, onEvent func(T)) error

SpawnAPIEventHandler starts a simple goroutine that reads `APIEvent` values from `onEventCh`, attempts to cast each value to the concrete type `T` and invokes `onEvent` for matching values.

This helper is useful when callers want a lightweight adapter: it performs the type assertion and drops events that don't match `T`.

Important notes:

  • `ctx` controls the lifetime of the handler. When `ctx` is canceled the goroutine exits. `onEventCh` must be closed by the sender to terminate the loop if `ctx` remains active.
  • `onEventCh` will be read-only for the goroutine; callers must not close it while other readers expect it to remain open.
  • The helper does not recover from panics in `onEvent`; if the typed handler may panic wrap it appropriately.

func SpawnClientEventHandler added in v0.1.1

func SpawnClientEventHandler[T ClientEvent](ctx context.Context, onEventCh chan ClientEvent, onEvent func(T)) error

SpawnClientEventHandler starts a simple goroutine that reads `ClientEvent` values from `onEventCh`, attempts to cast each value to the concrete type `T` and invokes `onEvent` for matching values.

This helper is useful when callers want a lightweight adapter: it performs the type assertion and drops events that don't match `T`.

Important notes:

  • `ctx` controls the lifetime of the handler. When `ctx` is canceled the goroutine exits. `onEventCh` must be closed by the sender to terminate the loop if `ctx` remains active.
  • `onEventCh` will be read-only for the goroutine; callers must not close it while other readers expect it to remain open.
  • The helper does not recover from panics in `onEvent`; if the typed handler may panic wrap it appropriately.

Types

type APIClient added in v0.1.1

type APIClient interface {
	// WithRequestTimeout updates the duration until a request roundtrip is aborted no
	// matter if already sent or not.
	//
	// It must be called while the client is not connected (before `Connect`) and returns
	// the same client to allow fluent construction.
	WithRequestTimeout(time.Duration) APIClient

	// WithQueueBufferSize updates the number of queued requests that may be buffered
	// by the internal request queue before backpressure applies.
	//
	// It must be called while the client is not connected (before `Connect`) and returns
	// the same client to allow fluent construction.
	WithQueueBufferSize(int) APIClient

	// TCPMessageBufferSize updates the size of the channel used to receive inbound
	// TCP messages from the network reader.
	//
	// It must be called while the client is not connected (before `Connect`) and returns
	// the same client to allow fluent construction.
	WithTCPMessageBufferSize(int) APIClient

	// WithRequestContextManagerIterationTimeout updates interval used by the request
	// context manager to periodically check for expired request contexts. Timeout must
	// be greater than MinRequestContextManagerIterationTimeout.
	//
	// It must be called while the client is not connected (before `Connect`) and returns
	// the same client to allow fluent construction.
	WithRequestContextManagerIterationTimeout(time.Duration) APIClient

	// DisableConcurrentEventEmits disables the concurrent event emit which means that event
	// messages will be passed sequentially to the event channels registered with
	// ListenToAPIEvent or ListenToClientEvent. This is a performance feature with the
	// drawback that the API client blocks once an event channel buffer is full.
	//
	// By default each event is emitted inside an explicitly spawned goroutine to prevent the
	// API client from blocking, hence it is less performant.
	DisableConcurrentEventEmits() APIClient

	// DisableDefaultRateLimiter disables the internal request rate limiter. Only do this
	// when you either use your own rate limiter or if you do not expect to ever reach the
	// request rate limit.
	//
	// It must be called while the client is not connected (before `Connect`) and returns
	// the same client to allow fluent construction.
	DisableDefaultRateLimiter() APIClient

	// Connect connects to the cTrader OpenAPI server, authenticates the application and
	// starts the keepalive routine.
	Connect() error
	// Disconnect stops the keepalive routine and closes the connection.
	// Disconnect is a cleanup function. Event listeners are removed and any resources
	// held by the client are released. After calling Disconnect, the client
	// must not be used again unless Connect is called again. All event subscriptions and
	// listeners are removed.
	// Ongoing request roundtrips (via SendRequest, SubscribeAPIEvent, UnsubscribeAPIEvent,
	// or explicit request functions like AuthenticateAccount, LogoutAccount, RefreshAccessToken)
	// will be terminated and the functions will return RequestContextManagerClearedError.
	Disconnect()

	// AuthenticateAccount authenticates the client with the specified cTrader account
	// using the provided credentials. This must be called before making account-specific
	// requests or subscribing to account events.
	AuthenticateAccount(ctid CtraderAccountId, accessToken AccessToken) (*types.ProtoOAAccountAuthRes, error)

	// LogoutAccount logs out from the specified cTrader account.
	// After a successful logout, the account will no longer receive events
	// and any further requests for the account will fail until it is.
	// waitForConfirm controls whether this function waits for the server event
	// `ProtoOAAccountDisconnectEvent` confirming the logout before returning.
	//
	// Note: The confirmation of a successful logout is not this function returning,
	// but when the server sends the corresponding ProtoOAAccountDisconnectEvent message.
	LogoutAccount(ctid CtraderAccountId, waitForConfirm bool) (*types.ProtoOAAccountLogoutRes, error)

	// RefreshAccessToken refreshes an expired access token using the provided
	// refresh token. Returns a new access token that can be used for subsequent
	// authentication requests.
	RefreshAccessToken(expiredToken AccessToken, refreshToken RefreshToken) (*types.ProtoOARefreshTokenRes, error)

	// SendRequest sends a request to the server and waits for the response.
	// The response is written to the Res field of the provided RequestData struct.
	SendRequest(RequestData) error

	// SubscribeAPIEvent subscribes the currently authenticated client for
	// the provided subscription-based event. The `eventData` argument
	// chooses the event type and provides the subscription parameters
	// (for example, account id and symbol ids for spot quotes).
	//
	// The call will send the corresponding subscribe request to the
	// server and return any transport or validation error. When the
	// server starts sending matching events, they will be dispatched to
	// the library's internal event clients and any registered listeners.
	SubscribeAPIEvent(eventData APIEventSubData) error

	// UnsubscribeAPIEvent removes a previously created subscription. The
	// `eventData` must match the original subscription parameters used
	// to subscribe. This call sends the corresponding unsubscribe
	// request to the server and returns any transport or validation error.
	UnsubscribeAPIEvent(eventData APIEventSubData) error

	// ListenToAPIEvent registers a long-running listener for listenable
	// events (server-initiated push events).
	//
	// Arguments:
	//   - Context to control the lifetime of the listener. When ctx is canceled,
	//     the listener is removed and its event channel is closed.
	//   - APIEventListenData struct containing the event type and channel to receive events.
	//
	// Note: callbacks that need typed event values can use `CastToAPIEventType`
	// or the `SpawnAPIEventHandler` helper to adapt typed functions.
	//
	// To register a typed callback without writing a manual wrapper, use
	// `SpawnAPIEventHandler` which starts a small goroutine that adapts the
	// generic `APIEvent` channel to a typed client. Example:
	//
	//   onSpot := func(e *ProtoOASpotEvent) { fmt.Println(e) }
	//   onEventCh := make(chan APIEvent)
	//   if err := client.ListenToAPIEvent(ctx, APIEventType_Spot, onEventCh); err != nil { /* ... */ }
	//   if err := SpawnAPIEventHandler(ctx, onEventCh, onSpot); err != nil { /* ... */ }
	ListenToAPIEvent(context.Context, APIEventListenData) error

	// ListenToClientEvent registers a long-running listener for listenable
	// api client events (connection loss / reconnect success / reconnect fail).
	//
	// Arguments:
	//   - Context to control the lifetime of the listener. When ctx is canceled,
	//     the listener is removed and its event channel is closed.
	//   - ClientEventListenData struct containing the event type and channel to receive events.
	//
	// Note: callbacks that need typed event values can use `CastToClientEventType`
	// or the `SpawnClientEventHandler` helper to adapt typed functions.
	//
	// To register a typed callback without writing a manual wrapper, use
	// `SpawnClientEventHandler` which starts a small goroutine that adapts the
	// generic `ListenToClientEvent` channel to a typed client. Example:
	//
	//   onConnLoss := func(e *ConnectionLossEvent) { fmt.Println(e) }
	//   onEventCh := make(chan ClientEvent)
	//   if err := client.ListenToClientEvent(ctx, ClientEventType_ConnectionLossEvent, onEventCh); err != nil { /* ... */ }
	//   if err := SpawnClientEventHandler(ctx, onEventCh, onConnLoss); err != nil { /* ... */ }
	ListenToClientEvent(context.Context, ClientEventListenData) error
}

APIClient is the main entry point for interacting with the cTrader OpenAPI. It exposes methods to connect/disconnect, send RPC-like requests, and subscribe to or listen for server-side events.

Concurrency / lifecycle notes:

  • Implementations are safe for concurrent use by multiple goroutines.
  • The client maintains an internal lifecycle (started via Connect, stopped via Disconnect). Certain operations assume a running lifecycle (for example, sending requests or listening to events).

Error handling:

  • Fatal server-side or protocol errors are delivered via the FatalErrorEvent client event; when such an error is emitted the client will be disconnected and cleaned up. the channel stays open until a fatal error occurs no matter connect/disconnect state.

Usage summary:

  • Create the client with NewApiClient, call Connect, then use SendRequest, SubscribeAPIEvent/UnsubscribeAPIEvent, or ListenToAPIEvent as required. Call Disconnect when finished.

func NewAPIClient added in v0.1.1

func NewAPIClient(cred ApplicationCredentials, env Environment) (APIClient, error)

NewAPIClient creates a new API client interface instance. The returned client is not connected automatically.

type APIClientNotConnectedError added in v0.1.1

type APIClientNotConnectedError struct {
	CallContext string
}

APIClientNotConnectedError is returned when an operation that requires an active connection is attempted while the API client is not connected. The CallContext field contains a short description of the call that produced the error (for example "SendRequest").

func (*APIClientNotConnectedError) Error added in v0.1.1

type APIEvent added in v0.2.3

type APIEvent = datatypes.APIEvent

APIEvent marks protobuf API event message types that can be listened to (push-style events).

These event types are delivered by the server independently from any single client's request; users can register listener channels of type `APIEvent` using `ListenToAPIEvent`.

type APIEventListenData added in v0.3.1

type APIEventListenData struct {
	EventType    apiEventType
	EventCh      chan APIEvent
	EventKeyData apiEventKeyData
}

APIEventListenData describes the parameters for listening to API events.

  • `EventType` selects which event to listen for.
  • `EventCh` receives an `APIEvent` that will be delivered for each matching event.
  • `EventKeyData` provides subscription-specific data for filtering (used by event listener).

Mapping of `EventType` → concrete callback argument type:

  • APIEventType_Spot -> ProtoOASpotEvent
  • APIEventType_DepthQuote -> ProtoOADepthEvent
  • APIEventType_TrailingSLChanged -> ProtoOATrailingSLChangedEvent
  • APIEventType_SymbolChanged -> ProtoOASymbolChangedEvent
  • APIEventType_TraderUpdated -> ProtoOATraderUpdatedEvent
  • APIEventType_Execution -> ProtoOAExecutionEvent
  • APIEventType_MarginChanged -> ProtoOAMarginChangedEvent
  • APIEventType_AccountsTokenInvalidated -> ProtoOAAccountsTokenInvalidatedEvent
  • APIEventType_ClientDisconnect -> ProtoOAClientDisconnectEvent
  • APIEventType_AccountDisconnect -> ProtoOAAccountDisconnectEvent
  • APIEventType_MarginCallUpdate -> ProtoOAMarginCallUpdateEvent
  • APIEventType_MarginCallTrigger -> ProtoOAMarginCallTriggerEvent

EventCh behaviour:

  • The provided channel is used by the library to deliver events of the requested `EventType`. The library will close the channel when the listener's context (`ctx`) is canceled or when the client is disconnected. Callers should treat channel close as end-of-stream and not attempt to write to the channel.

EventKeyData usage:

  • When nil, all events of the specified `EventType` are delivered to `EventCh`.
  • When set to a concrete KeyData* type (e.g., KeyDataSpotEvent), only events matching the key data's criteria are delivered. The event handler uses BuildKey() to generate a key from the KeyData fields and routes only matching events to this listener.
  • Example: setting EventKeyData to KeyDataSpotEvent{Ctid: 12345, SymbolId: 1} will deliver only spot events for that specific account and symbol.
  • This enables fine-grained event filtering without the need for listener-side filtering.

func (*APIEventListenData) CheckError added in v0.3.1

func (d *APIEventListenData) CheckError() error

Checks if APIEventListenData is correctly configured.

If ok, returns nil.

type APIEventSubData added in v0.3.1

type APIEventSubData struct {
	EventType        apiEventType
	SubscriptionData SubscriptionData
}

APIEventSubData groups the event type and subscription-specific data for `SubscribeAPIEvent` and `UnsubscribeAPIEvent` calls.

  • EventType selects which server-side event to subscribe/unsubscribe.
  • SubcriptionData is a concrete struct implementing `SubscriptionData` that provides the required parameters for that event (for example, account id and symbol ids for Spot events).

func (*APIEventSubData) CheckError added in v0.4.0

func (d *APIEventSubData) CheckError() error

type AccessToken added in v0.2.0

type AccessToken = datatypes.AccessToken

AccessToken is the token that is being used to access a set of account ids. It is a thin typed alias over string to make call sites explicit.

type AccessTokenAlreadyExistsError added in v0.2.3

type AccessTokenAlreadyExistsError = datatypes.AccessTokenAlreadyExistsError
/datatypes/account_manager.go

AccessTokenAlreadyExistsError is an alias for `datatypes.AccessTokenAlreadyExistsError`. It is returned by the account manager when attempting to add an access token that is already registered.

type AccessTokenDoesNotExistError added in v0.2.3

type AccessTokenDoesNotExistError = datatypes.AccessTokenDoesNotExistError

AccessTokenDoesNotExistError is an alias for `datatypes.AccessTokenDoesNotExistError`. It is returned by the account manager when an operation references an access token that is not registered with the manager.

type AccountIdAlreadyExistsError added in v0.2.3

type AccountIdAlreadyExistsError = datatypes.AccountIdAlreadyExistsError

AccountIdAlreadyExistsError is an alias for `datatypes.AccountIdAlreadyExistsError`. It is returned by the account manager when attempting to add an account ID that is already registered under the given access token.

type AccountIdDoesNotExistError added in v0.2.3

type AccountIdDoesNotExistError = datatypes.AccountIdDoesNotExistError

AccountIdDoesNotExistError is an alias for `datatypes.AccountIdDoesNotExistError`. It is returned by the account manager when an operation references an account ID that is not registered with the manager.

type AccountIdDoesNotExistOnTokenError added in v0.2.3

type AccountIdDoesNotExistOnTokenError = datatypes.AccountIdDoesNotExistOnTokenError

AccountIdDoesNotExistOnTokenError is an alias for `datatypes.AccountIdDoesNotExistOnTokenError`. It is returned by the account manager when an operation references an account ID that is not associated with the given access token.

type ApplicationCredentials

type ApplicationCredentials struct {
	ClientId     string
	ClientSecret string
}

ApplicationCredentials holds the client credentials required to authenticate the application with the cTrader OpenAPI proxy. Both fields are required.

func (ApplicationCredentials) CheckError

func (c ApplicationCredentials) CheckError() error

CheckError validates the ApplicationCredentials, returning a descriptive error when either the client id or client secret are missing.

type BaseEvent added in v0.3.1

type BaseEvent = datatypes.BaseEvent

BaseEvent is the interface that all events must implement.

type ClientEvent added in v0.2.3

type ClientEvent = datatypes.ClientEvent

ClientEvent marks events emitted by the API client itself (for example connection loss, reconnect success, etc).

These event types are emitted internally by the client based on the client behaviour and its connection status; users can register listener channels of type `ClientEvent` using `ListenToClientEvent`.

type ClientEventListenData added in v0.3.1

type ClientEventListenData struct {
	EventType clientEventType
	EventCh   chan ClientEvent
}

ClientEventListenData describes the parameters for listening to client events.

  • `EventType` selects which event to listen for.
  • `EventCh` receives a `ClientEvent` that will be delivered for each matching event.

Mapping of `EventType` → concrete callback argument type:

  • ClientEventType_FatalErrorEvent -> FatalErrorEvent
  • ClientEventType_ConnectionLossEvent -> ConnectionLossEvent
  • ClientEventType_ReconnectSuccessEvent -> ReconnectSuccessEvent
  • ClientEventType_ReconnectFailEvent -> ReconnectFailEvent

EventCh behaviuor:

  • The provided channel is used by the library to deliver events of the requested `eventType`. The library will close the channel when the listener's context (`ctx`) is canceled or when the client is disconnected. Callers should treat channel close as end-of-stream and not attempt to write to the channel.

func (*ClientEventListenData) CheckError added in v0.3.1

func (d *ClientEventListenData) CheckError() error

Checks if ClientEventListenData is correctly configured.

If ok, returns nil.

type CloseConnectionError

type CloseConnectionError = tcp.CloseConnectionError

CloseConnectionError is an alias for `tcp.CloseConnectionError` and is returned when closing the underlying connection fails.

type ConnectionLossEvent added in v0.1.1

type ConnectionLossEvent struct{}

ConnectionLossEvent is emitted when the TCP connection to the cTrader OpenAPI server is unexpectedly lost. Listeners may use this to trigger local reconnection logic or cleanup.

func (*ConnectionLossEvent) IsListenableClientEvent added in v0.1.1

func (e *ConnectionLossEvent) IsListenableClientEvent()

func (*ConnectionLossEvent) ToDistributableEvent added in v0.3.1

func (*ConnectionLossEvent) ToDistributableEvent() DistributableEvent

type CtraderAccountId

type CtraderAccountId = datatypes.CtraderAccountId

CtraderAccountId represents a cTrader account identifier. It is a thin typed alias over int64 to make call sites explicit.

type DepthQuoteEventData added in v0.2.3

type DepthQuoteEventData struct {
	CtraderAccountId CtraderAccountId
	SymbolIds        []int64
}

Subscription data for the Depth Quote Event (ProtoOADepthEvent).

func (*DepthQuoteEventData) CheckError added in v0.2.3

func (d *DepthQuoteEventData) CheckError() error

CheckError checks if the provided subscription data is valid. Returns an error if it is invalid.

type DistributableEvent added in v0.3.1

type DistributableEvent = datatypes.DistributableEvent

DistributableEvent marks protobuf API event message types that can be listened to (push-style events) AND can be used in an EventListener instance.

Distributable means you can add a specific event listener channel via ListenToAPIEvent and provide key data. That way each event is matched to the key data, and if it matches the event will only be sent to the specifically provided event listener channel for that key data.

type EnqueueOnClosedConnError

type EnqueueOnClosedConnError struct {
}

EnqueueOnClosedConnError is returned when an attempt is made to enqueue a request on a closed connection.

func (*EnqueueOnClosedConnError) Error

func (e *EnqueueOnClosedConnError) Error() string

type Environment

type Environment int

Environment represents the cTrader OpenAPI environment to connect to.

const (
	// Demo environment is used for cTrader Demo accounts.
	Environment_Demo Environment = iota
	// Live environment is used for cTrader Live accounts.
	Environment_Live Environment = iota
)

func (Environment) GetAddress

func (env Environment) GetAddress() endpointAddress

GetAddress returns the endpoint address for the referenced environment.

type EventKeyAlreadyIncludedError added in v0.3.1

type EventKeyAlreadyIncludedError struct {
	EventKey apiEventKey
}

EventKeyAlreadyIncludedError is returned when the provided event key is included in the referenced EventListener instance during an operation that aims to add that event key to the EventListener.

func (*EventKeyAlreadyIncludedError) Error added in v0.3.1

type EventKeyNotIncludedError added in v0.3.1

type EventKeyNotIncludedError struct {
	EventKey apiEventKey
}

EventKeyNotIncludedError is returned when the provided event key is not included in the referenced EventListener instance during an operation that aims to remove that event key from the EventListener.

func (*EventKeyNotIncludedError) Error added in v0.3.1

func (e *EventKeyNotIncludedError) Error() string

type EventSubscriptionAlreadyExistsError added in v0.2.3

type EventSubscriptionAlreadyExistsError[EventT comparable] = datatypes.EventSubscriptionAlreadyExistsError[EventT]

EventSubscriptionAlreadyExistsError is an alias for `datatypes.EventSubscriptionAlreadyExistsError`. It is returned by the account manager when attempting to add an event subscription that already exists for the given account and event type.

type EventSubscriptionDoesNotExistError added in v0.2.3

type EventSubscriptionDoesNotExistError[EventT comparable] = datatypes.EventSubscriptionDoesNotExistError[EventT]

EventSubscriptionDoesNotExistError is an alias for `datatypes.EventSubscriptionDoesNotExistError`. It is returned by the account manager when attempting to remove an event subscription that does not exist for the given account and event type.

type FatalErrorEvent added in v0.1.5

type FatalErrorEvent struct {
	Err error
}

FatalErrorEvent is emitted when a fatal error occurs in the API client. The `Err` field contains the underlying error.

Listeners may use this event to trigger application-level shutdown or cleanup logic.

func (*FatalErrorEvent) IsListenableClientEvent added in v0.1.5

func (e *FatalErrorEvent) IsListenableClientEvent()

func (*FatalErrorEvent) ToDistributableEvent added in v0.3.1

func (*FatalErrorEvent) ToDistributableEvent() DistributableEvent

type FunctionInvalidArgError

type FunctionInvalidArgError = datatypes.FunctionInvalidArgError

FunctionInvalidArgError is an alias for `datatypes.FunctionInvalidArgError`. It is returned by library functions when a caller provides an argument that fails validation (for example a nil pointer where a struct is expected, or an argument with invalid contents). The embedded `FunctionName` and `Err` fields provide the callee context and the underlying validation error.

type GenericResponseError

type GenericResponseError struct {
	ErrorCode               string
	Description             string
	MaintenanceEndTimestamp uint64
}

GenericResponseError is used when the server returns an error that cannot be mapped to a more specific client-side error type. It carries an ErrorCode and optional Description and MaintenanceEndTimestamp to help callers decide how to react (retry, wait, surface to user).

func (*GenericResponseError) Error

func (e *GenericResponseError) Error() string

func (*GenericResponseError) IsOngoingMaintenance added in v0.1.4

func (e *GenericResponseError) IsOngoingMaintenance() bool

type InvalidAddressError

type InvalidAddressError = tcp.InvalidAddressError
/tcp/helpers.go

InvalidAddressError is an alias for `tcp.InvalidAddressError` and is returned when the configured TCP address is invalid or cannot be parsed.

type KeyDataAccountDisconnectEvent added in v0.3.1

type KeyDataAccountDisconnectEvent struct {
	Ctid CtraderAccountId
}

KeyDataAccountDisconnectEvent is the type for ProtoOAAccountDisconnectEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataAccountDisconnectEvent) BuildKey added in v0.3.1

func (k *KeyDataAccountDisconnectEvent) BuildKey() apiEventKey

type KeyDataDepthEvent added in v0.3.1

type KeyDataDepthEvent struct {
	Ctid     CtraderAccountId
	SymbolId int64
}

KeyDataDepthEvent is the type for ProtoOADepthEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataDepthEvent) BuildKey added in v0.3.1

func (k *KeyDataDepthEvent) BuildKey() apiEventKey

type KeyDataExecutionEvent added in v0.3.1

type KeyDataExecutionEvent struct {
	Ctid          CtraderAccountId
	ExecutionType types.ProtoOAExecutionType
	PositionId    int64
	OrderId       int64
	DealId        int64
}

KeyDataExecutionEvent is the type for ProtoOAExecutionEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataExecutionEvent) BuildKey added in v0.3.1

func (k *KeyDataExecutionEvent) BuildKey() apiEventKey

type KeyDataMarginCallTriggerEvent added in v0.3.1

type KeyDataMarginCallTriggerEvent struct {
	Ctid CtraderAccountId
}

KeyDataMarginCallTriggerEvent is the type for ProtoOAMarginCallTriggerEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataMarginCallTriggerEvent) BuildKey added in v0.3.1

func (k *KeyDataMarginCallTriggerEvent) BuildKey() apiEventKey

type KeyDataMarginCallUpdateEvent added in v0.3.1

type KeyDataMarginCallUpdateEvent struct {
	Ctid CtraderAccountId
}

KeyDataMarginCallUpdateEvent is the type for ProtoOAMarginCallUpdateEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataMarginCallUpdateEvent) BuildKey added in v0.3.1

func (k *KeyDataMarginCallUpdateEvent) BuildKey() apiEventKey

type KeyDataMarginChangedEvent added in v0.3.1

type KeyDataMarginChangedEvent struct {
	Ctid       CtraderAccountId
	PositionId int64
}

KeyDataMarginChangedEvent is the type for ProtoOAMarginChangedEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataMarginChangedEvent) BuildKey added in v0.3.1

func (k *KeyDataMarginChangedEvent) BuildKey() apiEventKey

type KeyDataSpotEvent added in v0.3.1

type KeyDataSpotEvent struct {
	Ctid     CtraderAccountId
	SymbolId int64
	Period   types.ProtoOATrendbarPeriod
}

KeyDataSpotEvent is the type for ProtoOASpotEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataSpotEvent) BuildKey added in v0.3.1

func (k *KeyDataSpotEvent) BuildKey() apiEventKey

type KeyDataSymbolChangedEvent added in v0.3.1

type KeyDataSymbolChangedEvent struct {
	Ctid CtraderAccountId
}

KeyDataSymbolChangedEvent is the type for ProtoOASymbolChangedEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataSymbolChangedEvent) BuildKey added in v0.3.1

func (k *KeyDataSymbolChangedEvent) BuildKey() apiEventKey

type KeyDataTraderUpdatedEvent added in v0.3.1

type KeyDataTraderUpdatedEvent struct {
	Ctid CtraderAccountId
}

KeyDataTraderUpdatedEvent is the type for ProtoOATraderUpdatedEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataTraderUpdatedEvent) BuildKey added in v0.3.1

func (k *KeyDataTraderUpdatedEvent) BuildKey() apiEventKey

type KeyDataTrailingSLChangedEvent added in v0.3.1

type KeyDataTrailingSLChangedEvent struct {
	Ctid       CtraderAccountId
	PositionId int64
	OrderId    int64
}

KeyDataTrailingSLChangedEvent is the type for ProtoOATrailingSLChangedEvent key generation. Used in ListenToAPIEvent.

func (*KeyDataTrailingSLChangedEvent) BuildKey added in v0.3.1

func (k *KeyDataTrailingSLChangedEvent) BuildKey() apiEventKey

type LifeCycleAlreadyRunningError

type LifeCycleAlreadyRunningError = datatypes.LifeCycleAlreadyRunningError
/datatypes/lifecycle.go

LifeCycleAlreadyRunningError indicates an attempt to start the internal lifecycle (heartbeat, channel handlers) while it is already running.

type LifeCycleNotRunningError

type LifeCycleNotRunningError = datatypes.LifeCycleNotRunningError

LifeCycleNotRunningError indicates an operation that requires the lifecycle to be running was called while it was stopped.

type LiveTrendbarEventData added in v0.2.3

type LiveTrendbarEventData struct {
	CtraderAccountId CtraderAccountId
	SymbolId         int64
	Period           types.ProtoOATrendbarPeriod
}

Subscription data for the Live Trendbar Event.

func (*LiveTrendbarEventData) CheckError added in v0.2.3

func (d *LiveTrendbarEventData) CheckError() error

CheckError checks if the provided subscription data is valid. Returns an error if it is invalid.

type MaxReconnectAttemptsReachedError added in v0.1.1

type MaxReconnectAttemptsReachedError = tcp.MaxReconnectAttemptsReachedError

MaxReconnectAttemptsReachedError is an alias for `tcp.MaxReconnectAttemptsReachedError`. It is returned when the TCP client has reached the maximum number of configured reconnect attempts without successfully reconnecting.

type NoConnectionError

type NoConnectionError = tcp.NoConnectionError

NoConnectionError is an alias for `tcp.NoConnectionError` and is used to indicate that an operation that requires an open connection was attempted when no connection is available (for example `Send` or `Read` when the client is disconnected).

type OpenConnectionError

type OpenConnectionError = tcp.OpenConnectionError
/tcp/client.go

OpenConnectionError is an alias for `tcp.OpenConnectionError` and is returned when the underlying TCP client fails to open a connection (for example due to network errors or a refused connection).

type OperationBlockedError

type OperationBlockedError = tcp.OperationBlockedError

OperationBlockedError is an alias for `tcp.OperationBlockedError`. It signals that an operation cannot be performed because another mutually-exclusive mode is active (for example calling `Read` when a message handler is set on the TCP client).

type ProtoMarshalError

type ProtoMarshalError struct {
	CallContext string
	Err         error
}

ProtoMarshalError wraps errors produced while marshalling a protobuf payload. CallContext describes the logical context (for example "request bytes") to aid debugging and logging.

func (*ProtoMarshalError) Error

func (e *ProtoMarshalError) Error() string

type ProtoUnmarshalError

type ProtoUnmarshalError struct {
	CallContext string
	Err         error
}

ProtoUnmarshalError wraps errors produced while unmarshalling a protobuf payload. CallContext describes the logical context (for example "proto OA spot event") to aid debugging and logging.

func (*ProtoUnmarshalError) Error

func (e *ProtoUnmarshalError) Error() string

type ReconnectFailEvent added in v0.1.1

type ReconnectFailEvent struct {
	Err error
}

ReconnectFailEvent is emitted when the client's reconnect loop fails repeatedly and gives up (or when an error occurs during reconnect). The `Err` field contains the underlying error.

func (*ReconnectFailEvent) IsListenableClientEvent added in v0.1.1

func (e *ReconnectFailEvent) IsListenableClientEvent()

func (*ReconnectFailEvent) ToDistributableEvent added in v0.3.1

func (*ReconnectFailEvent) ToDistributableEvent() DistributableEvent

type ReconnectSuccessEvent added in v0.1.1

type ReconnectSuccessEvent struct{}

ReconnectSuccessEvent is emitted after a successful reconnect and re-authentication cycle. It indicates the client is operational again.

func (*ReconnectSuccessEvent) IsListenableClientEvent added in v0.1.1

func (e *ReconnectSuccessEvent) IsListenableClientEvent()

func (*ReconnectSuccessEvent) ToDistributableEvent added in v0.3.1

func (*ReconnectSuccessEvent) ToDistributableEvent() DistributableEvent

type RefreshToken added in v0.2.0

type RefreshToken = datatypes.RefreshToken

RefreshToken is the token that is being used to update the AccessToken when it expires. It is a thin typed alias over string to make call sites explicit.

type RequestContextExpiredError

type RequestContextExpiredError = datatypes.RequestContextExpiredError
/datatypes/request_ctx_manager.go

RequestContextExpiredError is an alias for `datatypes.RequestContextExpiredError`. It is used by the request queue/mapper to indicate that a request's provided `context.Context` has been cancelled or has timed out before the request could be sent or responded to. The wrapped `Err` field contains the original context error (for example `context.Canceled`).

type RequestContextManagerAlreadyRunningError added in v0.4.0

type RequestContextManagerAlreadyRunningError = datatypes.RequestContextManagerAlreadyRunningError

RequestContextManagerAlreadyRunningError indicates an attempt to start the request context manager goroutine when it is already active.

type RequestContextManagerClearedError added in v0.4.0

type RequestContextManagerClearedError = datatypes.RequestContextManagerClearedError

RequestContextManagerClearedError is returned to each SendRequest and Subscribe/Unsubscribe call when the API client is being disconnected while there are still unfinished request roundtrips.

type RequestContextManagerNodeAlreadyIncludedError added in v0.4.0

type RequestContextManagerNodeAlreadyIncludedError = datatypes.RequestContextManagerNodeAlreadyIncludedError

RequestContextManagerNodeNotIncludedError is returned when attempting to add a request node that is already managed by the context manager.

type RequestContextManagerNodeNotIncludedError added in v0.4.0

type RequestContextManagerNodeNotIncludedError = datatypes.RequestContextManagerNodeNotIncludedError

RequestContextManagerNodeNotIncludedError is returned when attempting to remove a request node that is not managed by the context manager.

type RequestContextManagerNotRunningError added in v0.4.0

type RequestContextManagerNotRunningError = datatypes.RequestContextManagerNotRunningError

RequestContextManagerNotRunningError indicates operations on the request context manager were attempted while the context manager worker was not running.

type RequestData

type RequestData = datatypes.RequestData

RequestData is the argument struct for SendRequest.

  • Ctx: Request context. If context.Err() is not nil, the request response will not be awaited or if the request is still in queue it will be removed from queue. Either way SendRequest will abort and return context.Err(). Do not apply a context timeout to this context, since then the timeout will not take into account time spent in the package internal request rate limiter and request queue. If you want to set a custom timeout, use field `Timeout`.
  • Timeout: Request network timeout. Overrides default timeout set with `WithRequestTimeout`. Applied right after elect (hence after passing internal rate limiter and request queue) and right before emit, so it only takes into account network roundtrip time.
  • Req: Request message. Must be a pointer to a protobuf message struct.
  • Res: Pointer to an empty protobuf message struct where the response will be unmarshalled into. When no response is expected, leave this field empty.

The request cancels on either of the two conditions:

  • Ctx is cancelled.
  • Timeout is reached.

type ResponseError

type ResponseError struct {
	ErrorCode               string
	Description             string
	MaintenanceEndTimestamp int64
	RetryAfter              uint64
}

ResponseError represents a structured error returned by the server in response to a request. It includes an ErrorCode, optional human-readable Description, a maintenance end timestamp (if the server indicates a planned maintenance window) and an optional RetryAfter value indicating how many seconds the client should wait before retrying.

func (*ResponseError) Error

func (e *ResponseError) Error() string

func (*ResponseError) IsOngoingMaintenance added in v0.1.4

func (e *ResponseError) IsOngoingMaintenance() bool

type SpotEventData added in v0.2.3

type SpotEventData struct {
	CtraderAccountId CtraderAccountId
	SymbolIds        []int64
}

Subscription data for the Spot Event (ProtoOASpotEvent).

func (*SpotEventData) CheckError added in v0.2.3

func (d *SpotEventData) CheckError() error

CheckError checks if the provided subscription data is valid. Returns an error if it is invalid.

type SubscriptionData

type SubscriptionData interface {

	// CheckError validates the subscription payload and returns a
	// non-nil error when the payload is invalid.
	CheckError() error
	// contains filtered or unexported methods
}

SubscriptionData describes data required to subscribe or unsubscribe to a subscription-based event (for example, account id and symbol ids for the Spot event). Implementations validate their fields via `CheckError` and are passed to `SubscribeAPIEvent` / `UnsubscribeAPIEvent`.

type UnexpectedMessageTypeError

type UnexpectedMessageTypeError struct {
	MsgType datatypes.ProtoOAPayloadType
}

UnexpectedMessageTypeError is returned when an incoming message from the server has a payload type that the client code does not expect or cannot handle. It includes the numeric message type for debugging/logging.

func (*UnexpectedMessageTypeError) Error

Directories

Path Synopsis
internal
tcp

Jump to

Keyboard shortcuts

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