Exchanges API

The Exchanges module provides unified interfaces for connecting to cryptocurrency exchanges through the CCXT library. It handles exchange connectivity, market data access, and order management across multiple exchanges.

Overview

The Exchanges module includes:

  • Exchange connection and authentication management
  • Unified market data interfaces
  • Order placement and management
  • Account and balance information
  • Market information and trading rules
  • Sandbox and live trading modes

Core Exchange Types

Exchange Identification

Exchange Connection

Market Data Access

Market Information

Fee Information

Market Data Retrieval

Account Management

Account Information

Balance Information

Order Management

Order Placement

Order Monitoring

Exchange Configuration

Exchange Parameters

Market Symbol Mapping

Error Handling and Resilience

Connection Management

Market Data Validation

Multi-Exchange Support

Exchange Comparison

Complete API Reference

Exchanges.LEVERAGED_PAIR_OPTIONSConstant

A leveraged pair is a pair like BTC3L/USD.

  • :yes : Leveraged pairs will not be filtered.
  • :only : ONLY leveraged will be kept.
  • :from : Selects non leveraged pairs, that also have at least one leveraged sibling.
source
Exchanges.CcxtTradeType

A named tuple representing a trade in the CCXT (CryptoCurrency eXchange Trading) library.

  • timestamp

  • symbol

  • order

  • type

  • side

  • takerOrMaker

  • price

  • amount

  • cost

  • fee

  • fees

source
Exchanges.CurrencyCashType

A CurrencyCash contextualizes a Cash instance w.r.t. an exchange. Operations are rounded to the currency precision.

  • cash

  • limits

  • precision

  • fees

  • sandbox

source
Exchanges.CurrencyCashMethod

Create a CurrencyCash object.

CurrencyCash(
    id::Type{<:ExchangeID},
    cash_type::Type{<:Cash},
    v;
    sandbox,
    account
) -> Exchanges.CurrencyCash
source
Exchanges.LeverageTierType

A type representing a tier of leverage.

  • min_notional

  • max_notional

  • max_leverage

  • tier

  • mmr

  • bc

This type is used to store and manage information about a specific leverage tier. Each tier is defined by its minimum and maximum notional values, maximum leverage, tier number, and maintenance margin requirement.

source
Ccxt.issupportedMethod

Check if a timeframe is supported by an exchange.

issupported(tf::TimeFrames.TimeFrame, exc) -> Any
source
Data.load_ohlcvMethod

Loads all pairs for a given timeframe, matching the global exc (Exchange object) and config.

load_ohlcv(timeframe::AbstractString; kwargs...) -> Any
source
Data.load_ohlcvMethod

Loads all pairs for a given exchange and timeframe, matching the global config and zi (Zarr Instance).

load_ohlcv(
    exc::Exchange,
    timeframe::AbstractString;
    kwargs...
)
source
Data.load_ohlcvMethod

Load given pairs from the global exc (Exchange object) and zi (Zarr Instance).

load_ohlcv(
    pairs::Union{AbstractDict, AbstractArray},
    timeframe::AbstractString;
    kwargs...
) -> Union{Dict{String, Zarr.ZArray}, Dict{String, Data.PairData}}
source
Data.load_ohlcvMethod

Load all pairs from the exchange according to the configured quote currency and timeframe.

load_ohlcv(

) -> Union{Dict{String, Zarr.ZArray}, Dict{String, Data.PairData}}
source
Data.save_ohlcvMethod

Updates pair data of the globally set Exchange instance.

save_ohlcv(pair, timeframe, data; kwargs...)
source
Exchanges._lpfMethod

Returns the limits, precision, and fees for a currency as a named tuple.

_lpf(
    exc,
    cur
) -> NamedTuple{(:limits, :precision, :fees), <:Tuple{@NamedTuple{min::Float64, max::Float64}, Union{Float64, Int64}, Number}}

The tuple fields can be nothing if the currency property is not provided.

source
Exchanges.checkMethod

Checks if the python exchange instance supports all the calls required by Planar.

check(exc::Exchange; type)
  • exc: an Exchange object to perform the check on.
  • type (optional, default is :basic): a symbol representing the type of check to perform.
source
Exchanges.default_leverage_tierMethod

Returns a default leverage tier for a specific symbol.

default_leverage_tier(
    sym
) -> SortedDict{Int64, Exchanges.LeverageTier{Float64}, Base.Order.ForwardOrdering}

The default leverage tier has generous limits.

source
Exchanges.filter_marketsMethod

Get the markets of the ccxt instance, according to min_volume and quote currency.

filter_markets(
    exc;
    min_volume,
    quot,
    sep,
    type
) -> Dict{Any, Any}

The filter_markets function takes the following parameters:

  • exc: an Exchange object to get the markets from.
  • min_volume (optional, default is 10e4): the minimum volume that a market should have.
  • quot (optional, default is "USDT"): the quote currency to filter the markets by.
  • sep (optional, default is '/'): the separator used in market strings.
source
Exchanges.futuresMethod

Returns the matching futures exchange instance, if it exists, or the input exchange otherwise.

source
Exchanges.getexchange!Function

getexchage!: ccxt exchange by symbol either from cache or anew.

getexchange!(x::Symbol; ...) -> Exchange
getexchange!(
    x::Symbol,
    params;
    account,
    sandbox,
    markets,
    kwargs...
) -> Exchange

It uses a WS instance if available, otherwise an async instance.

source
Exchanges.is_pair_activeMethod

Check if a currency pair is active on an exchange.

is_pair_active(pair::AbstractString, exc::Exchange) -> Any
source
Exchanges.isfileyoungerMethod

Checks if a file is younger than a specified period.

isfileyounger(f::AbstractString, p::Dates.Period) -> Any
  • f: a string that represents the path to the file.
  • p: a Period object that represents the time period.
source
Exchanges.lastpriceMethod

Fetch the latest price for a specific pair from an exchange.

lastprice(
    pair::AbstractString,
    exc::Exchange;
    kwargs...
) -> Any
  • pair: a string representing the currency pair to fetch the latest price for.
  • exc: an Exchange object to fetch the latest price from.
  • kwargs (optional): any additional keyword arguments are passed on to the underlying fetch operation.
source
Exchanges.leverage!Method

Update the leverage for a specific symbol.

leverage!(exc::Exchange, v, sym; side, timeout) -> Any
  • exc: an Exchange object to update the leverage on.
  • v: a Real number representing the new leverage value.
  • sym: a string representing the symbol to update the leverage for.
source
Exchanges.leverage_tiersMethod

Fetch the leverage tiers for a specific symbol from an exchange.

leverage_tiers(exc::Exchange, sym::AbstractString) -> Any
  • exc: an Exchange object to fetch the leverage tiers from.
  • sym: a string representing the symbol to fetch the leverage tiers for.
source
Exchanges.loadmarkets!Method

Load exchange markets.

loadmarkets!(exc; cache, agemax)
  • exc: an Exchange object that represents the exchange to load markets from.
  • cache (optional, default is true): a boolean that indicates whether to rely on storage cache.
  • agemax (optional, default is Day(1)): a Period object that represents the maximum cache valid period.
source
Exchanges.marginmode!Method

Update margin mode for a specific symbol on the exchange.

Also sets if the position is hedged or one sided. For customizations, dispatch to dosetmargin.

marginmode!(
    exc::Exchange,
    mode,
    symbol;
    hedged,
    kwargs...
) -> Any
source
Exchanges.market!Method

Retrieves a cached market (1minute) or fetches it from exchange.

market!(pair, exc::Exchange) -> Any
source
Exchanges.market_feesMethod

Fetch the market fees for a specific pair from an exchange.

market_fees(
    pair::AbstractString,
    exc::Exchange;
    only_taker
) -> NamedTuple{(:taker, :maker, :min, :max), <:NTuple{4, Any}}
  • pair: a string representing the currency pair to fetch the market fees for.
  • exc (optional, default is the current exchange): an Exchange object to fetch the market fees from.
  • only_taker (optional, default is nothing): a boolean indicating whether to fetch only the taker fee. If nothing, both maker and taker fees are fetched.
source
Exchanges.market_limitsMethod

Fetch the market limits for a specific pair from an exchange.

market_limits(
    pair::AbstractString,
    exc::Exchange;
    precision,
    default_leverage,
    default_amount,
    default_price,
    default_cost
) -> NamedTuple
  • pair: a string representing the currency pair to fetch the market limits for.
  • exc: an Exchange object to fetch the market limits from.
  • precision (optional, default is price=nothing, amount=nothing): a named tuple specifying the precision for price and amount.
  • default_leverage (optional, default is DEFAULT_LEVERAGE): the default leverage to use if not specified in the market data.
  • default_amount (optional, default is DEFAULT_AMOUNT): the default amount to use if not specified in the market data.
  • default_price (optional, default is DEFAULT_PRICE): the default price to use if not specified in the market data.
  • default_cost (optional, default is DEFAULT_COST for non-fiat quote pairs and DEFAULT_FIAT_COST for fiat quote pairs): the default cost to use if not specified in the market data.
source
Exchanges.market_precisionMethod

Precision of the (base, quote) currencies of the market.

market_precision(
    pair::AbstractString,
    exc::Exchange
) -> NamedTuple{(:amount, :price), <:Tuple{Any, Any}}
source
Exchanges.maxleverageMethod

Get the maximum leverage for a specific size and symbol from an exchange.

maxleverage(
    exc::Exchange,
    sym::AbstractString,
    size::Real
) -> Real
  • exc: an Exchange object to fetch the maximum leverage from.
  • sym: a string representing the symbol to fetch the maximum leverage for.
  • size: a Real number representing the size to fetch the maximum leverage for.
source
Exchanges.price_rangesMethod

Get price ranges using tickers data from exchange.

price_ranges(pair::AbstractString, args...; exc, kwargs...)

The price_ranges function takes the following parameters:

  • pair: a string representing the currency pair.
  • args...: a variable number of arguments to pass to the price ranges calculation.
  • exc (optional, default is global exc): an Exchange object to get the tickers data from.
  • kwargs...: a variable number of keyword arguments to pass to the price ranges calculation.
source
Exchanges.ratelimit!Function

Enable or disable rate limit.

ratelimit!(exc::Exchange) -> Bool
ratelimit!(exc::Exchange, flag) -> Any
source
Exchanges.sandbox!Method

Enable sandbox mode for exchange. Should only be called on exchange construction.

sandbox!(
    exc::Exchange;
    flag,
    remove_keys
) -> Union{Nothing, Bool}
  • exc (optional, default is global exc): an Exchange object to set the sandbox mode for.
  • flag (optional, default is the inverse of the current sandbox mode status): a boolean indicating whether to enable or disable sandbox mode.
  • remove_keys (optional, default is true): a boolean indicating whether to remove the API keys while enabling sandbox mode.
source
Exchanges.setexchange!Method

Initializes an exchange struct.

setexchange!(
    exc::Exchange,
    args...;
    markets,
    kwargs...
) -> ExchangeTypes.CcxtExchange
  • exc: an Exchange object to be set.
  • args...: a variable number of arguments to pass to the exchange setup.
  • markets (optional, default is :yes): a symbol that indicates whether to load markets during setup.
  • kwargs...: a variable number of keyword arguments to pass to the exchange setup.

Configures the matching ccxt class, optionally loads the markets, sets the exchange timeframes, and sets the exchange API keys.

source
Exchanges.spotsymbolMethod

Trims the settlement currency in futures. (mkt is a ccxt market.)

spotsymbol(sym, mkt) -> Any
source
Exchanges.ticker!Method

Fetch the ticker for a specific pair from an exchange.

ticker!(pair, exc::Exchange; timeout, func, delay) -> Any

The ticker! function takes the following parameters:

  • pair: a string representing the currency pair to fetch the ticker for.
  • exc: an Exchange object to fetch the ticker from.
  • timeout (optional, default is 3 seconds): the maximum time to wait for the ticker fetch operation.
  • func (optional, default is the result of _tickerfunc(exc)): the function to use to fetch the ticker.
source
Exchanges.tickerpriceMethod

Get price from ticker.

tickerprice(tkr) -> Any

The tickerprice function takes the following parameters:

  • tkr: a Ticker object.
source
Exchanges.tickersMethod

Get the exchange tickers.

tickers(
    exc::Exchange,
    quot;
    min_vol,
    skip_fiat,
    with_margin,
    with_leverage,
    as_vec,
    verbose,
    type,
    cross_match
)
  • exc: an Exchange object to fetch the tickers from.
  • quot: only choose pairs where the quote currency equals quot.
  • min_vol: the minimum volume of each pair.
  • skip_fiat (optional, default is true): ignore fiat/fiat pairs.
  • with_margin (optional, default is the result of config.margin != NoMargin()): only choose pairs enabled for margin trading.
  • with_leverage (optional, default is :no): if :no, skip all pairs where the base currency matches the leverage_pair_rgx regex.
  • as_vec (optional, default is false): return the pair list as a Vector instead of as a Dict.
  • verbose (optional, default is true): print detailed output about the operation.
  • type (optional, default is the result of markettype(exc)): the type of markets to fetch tickers for.
  • cross_match list of other exchanges where the filter pairs must also be present in
source
Exchanges.tierMethod

Get the leverage tier for a specific size from a sorted dictionary of tiers.

tier(
    tiers::SortedDict{Int64, Exchanges.LeverageTier},
    size::Real
) -> Tuple{Union{Nothing, Int64}, Exchanges.LeverageTier}
  • tiers: a SortedDict where the keys are integers representing the size thresholds and the values are LeverageTier objects.
  • size: a Real number representing the size to fetch the tier for.
source
Exchanges.timeout!Function

Set exchange timeout. (milliseconds)

timeout!(exc::Exchange) -> Int64
timeout!(exc::Exchange, v) -> Any
source
Exchanges.@tickers!Macro

Fetch and cache tickers data.

The @tickers! macro takes the following parameters:

  • type (optional, default is nothing): the type of tickers to fetch and cache.
  • force (optional, default is false): a boolean that indicates whether to force the data fetch, even if the data is already present.
source
ExchangeTypes.CcxtExchangeType

The CcxtExchange type wraps a ccxt exchange instance. Some attributes frequently accessed are copied over to avoid round tripping python. More attributes might be added in the future. To instantiate an exchange call getexchange! or setexchange!.

source
ExchangeTypes.ExchangeType

Abstract exchange type.

Defines the interface for interacting with crypto exchanges. Implemented for CCXT in CcxtExchange.

source
ExchangeTypes.ExchangeType

Instantiates a new Exchange wrapper for the provided x Python object.

This constructs a CcxtExchange struct with the provided Python object. It extracts the exchange ID, name, and other metadata. It runs any registered hook functions for that exchange. It sets a finalizer to close the exchange when garbage collected.

Returns the new Exchange instance, or an empty one if x is None.

source
ExchangeTypes.ExchangeIDType

A structure for handling Exchange IDs in CCXT.

This structure is used to manage Exchange IDs in the CCXT library. It contains methods for creating an Exchange ID from a symbol, a Python object, or directly from a symbol type. It ensures that the symbol is in the list of valid exchange IDs.

source
Base.firstMethod

Return the first available property from a variable number of Symbol arguments in the given Exchange.

first(exc::Exchange, args::Symbol...) -> Any

This function iterates through the provided Symbols and returns the value of the first property that exists in the Exchange object.

source
Base.getpropertyMethod

Attributes not matching the Exchange struct fields are forwarded to the wrapped ccxt class instance.

source
Base.hashMethod

The hash of an exchange object is reduced to its symbol (the function used to instantiate the object from ccxt).

source
ExchangeTypes._hasMethod

Checks if the specified feature feat is supported by any of the exchanges available through the ccxt library.

Arguments

  • s::Symbol: The feature to check for support across exchanges.
  • full::Bool=true: If true, checks both static and instantiated properties of the exchange for support.

Returns

  • Vector{String}: A list of exchange names that support the specified feature.
source
ExchangeTypes.close_excMethod

Closes the given exchange.

close_exc(
    exc::ExchangeTypes.CcxtExchange
) -> Union{Nothing, Task}

This function attempts to close the given exchange if it exists. It checks if the exchange has a 'close' attribute and if so, it schedules the 'close' coroutine for execution.

source
ExchangeTypes.decimal_to_sizeMethod

Converts value v to integer size with precision p.

decimal_to_size(v, p::ExcPrecisionMode; exc) -> Any

Used when converting exchange API responses to integer sizes for orders.

source

See Also