Documentation
¶
Index ¶
- Constants
- Variables
- func CastToAPIEventType[T APIEvent](event APIEvent) (T, bool)
- func CastToClientEventType[T ClientEvent](event ClientEvent) (T, bool)
- func SpawnAPIEventHandler[T APIEvent](ctx context.Context, onEventCh chan APIEvent, onEvent func(T)) error
- func SpawnClientEventHandler[T ClientEvent](ctx context.Context, onEventCh chan ClientEvent, onEvent func(T)) error
- type APIClient
- type APIClientNotConnectedError
- type APIEvent
- type APIEventListenData
- type APIEventSubData
- type AccessToken
- type AccessTokenAlreadyExistsError
- type AccessTokenDoesNotExistError
- type AccountIdAlreadyExistsError
- type AccountIdDoesNotExistError
- type AccountIdDoesNotExistOnTokenError
- type ApplicationCredentials
- type BaseEvent
- type ClientEvent
- type ClientEventListenData
- type CloseConnectionError
- type ConnectionLossEvent
- type CtraderAccountId
- type DepthQuoteEventData
- type DistributableEvent
- type EnqueueOnClosedConnError
- type Environment
- type EventKeyAlreadyIncludedError
- type EventKeyNotIncludedError
- type EventSubscriptionAlreadyExistsError
- type EventSubscriptionDoesNotExistError
- type FatalErrorEvent
- type FunctionInvalidArgError
- type GenericResponseError
- type InvalidAddressError
- type KeyDataAccountDisconnectEvent
- type KeyDataDepthEvent
- type KeyDataExecutionEvent
- type KeyDataMarginCallTriggerEvent
- type KeyDataMarginCallUpdateEvent
- type KeyDataMarginChangedEvent
- type KeyDataSpotEvent
- type KeyDataSymbolChangedEvent
- type KeyDataTraderUpdatedEvent
- type KeyDataTrailingSLChangedEvent
- type LifeCycleAlreadyRunningError
- type LifeCycleNotRunningError
- type LiveTrendbarEventData
- type MaxReconnectAttemptsReachedError
- type NoConnectionError
- type OpenConnectionError
- type OperationBlockedError
- type ProtoMarshalError
- type ProtoUnmarshalError
- type ReconnectFailEvent
- type ReconnectSuccessEvent
- type RefreshToken
- type RequestContextExpiredError
- type RequestContextManagerAlreadyRunningError
- type RequestContextManagerClearedError
- type RequestContextManagerNodeAlreadyIncludedError
- type RequestContextManagerNodeNotIncludedError
- type RequestContextManagerNotRunningError
- type RequestData
- type ResponseError
- type SpotEventData
- type SubscriptionData
- type UnexpectedMessageTypeError
Constants ¶
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 )
const ( // Demo environment endpoint address EndpointAddress_Demo endpointAddress = "demo.ctraderapi.com:5035" // Live environment endpoint address EndpointAddress_Live endpointAddress = "live.ctraderapi.com:5035" )
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 )
const ( // API Client events ClientEventType_FatalErrorEvent clientEventType = iota + 1 + 100 ClientEventType_ConnectionLossEvent ClientEventType_ReconnectSuccessEvent ClientEventType_ReconnectFailEvent )
const (
// Heartbeat_Interval_Seconds is the interval at which heartbeat messages are sent to the server.
Heartbeat_Timeout_Seconds = 9
)
Variables ¶
Functions ¶
func CastToAPIEventType ¶ added in v0.3.1
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
func (e *APIClientNotConnectedError) Error() string
type APIEvent ¶ added in v0.2.3
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 ¶
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 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
func (e *EventKeyAlreadyIncludedError) Error() string
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 ¶
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 ¶
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 ¶
func (e *UnexpectedMessageTypeError) Error() string