Strategies

Core.SymbolMethod

Symbol representation of the strategy (name of the module).

Strategies.StrategyType

The strategy is the core type of the framework.

  • self: The strategy module

  • config: The Config the strategy was instantiated with

  • timeframe: The smallest timeframe the strategy uses

  • cash: The quote currency used for trades

  • cash_committed: Cash kept busy by pending orders

  • buyorders: Active buy orders

  • sellorders: Active sell orders

  • holdings: Assets with non zero balance

  • universe: All the assets that the strategy knows about

  • lock: A lock for thread safety

The strategy type is concrete according to:

  • Name (Symbol)
  • Exchange (ExchangeID), read from config
  • Quote cash (Symbol), read from config
  • Margin mode (MarginMode), read from config
  • Execution mode (ExecMode), read from config

Conventions for strategy defined attributes:

  • S: the strategy type.
  • SC: the strategy type (exchange generic).
  • TF: the smallest timeframe that the strategy uses
  • DESCRIPTION: Name or short description for the strategy could be different from module name
Strategies.StrategyMethod

Initializes a new Strategy object

Strategy(
    self::Module,
    mode::Misc.ExecMode,
    margin::Misc.MarginMode,
    timeframe::TimeFrames.TimeFrame,
    exc::Exchange,
    uni::Collections.AssetCollection;
    config
)

This function takes a module, execution mode, margin mode, timeframe, exchange, and asset collection to create a new Strategy object. It also accepts a config object to set specific parameters. The function validates the universe of assets and the strategy's cash, sets the exchange, and initializes orders and holdings.

Base.countMethod

Counts the number of orders for a given order side in a strategy.

count(
    s::Strategies.Strategy,
    side::Type{<:OrderTypes.OrderSide}
) -> Int64

This function iterates over the orders of a given side (Buy or Sell) in a strategy. It increments a counter by the length of the orders. The function returns the total count of orders.

Base.fill!Method

Fills the strategy with the specified timeframes.

fill!(s::Strategies.Strategy; kwargs...)

This function fills the strategy with the specified timeframes. It first creates a set of timeframes and adds the strategy's timeframe, the timeframes from the strategy's configuration, and the timeframe attribute of the strategy. It then fills the universe of the strategy with these timeframes.

Base.getpropertyMethod

Retrieves a property of a strategy using a string key.

getproperty(s::Strategies.Strategy, sym::String) -> Any

This function first gets the universe of the strategy and then retrieves the property using the string key.

Base.getpropertyMethod

Retrieves a property of a strategy.

getproperty(s::Strategies.Strategy, sym::Symbol) -> Any

This function checks if the property is directly on the strategy or the strategy's configuration. If the property is not found, it checks the configuration's attributes.

Base.similarMethod

Creates a similar strategy with optional changes.

similar(
    s::Strategies.Strategy;
    mode,
    timeframe,
    exc
) -> Union{Strategies.Strategy{var"#s182", _A, _B, <:Misc.MarginMode{H}} where H<:Misc.HedgedMode, Strategies.Strategy{var"#s182", _A, _B, M} where {H<:Misc.HedgedMode, M<:Misc.MarginMode{H}}} where {var"#s182"<:Misc.ExecMode, _A, _B<:ExchangeID}

The similar function creates a new strategy that is similar to the given one. It allows for optional changes to the mode, timeframe, and exchange. The new strategy is created with the same self, margin mode, and universe as the original, but with a copy of the original's configuration.

Collections.iscashableMethod

Checks if the strategy's cash matches its universe.

iscashable(s::Strategies.Strategy) -> Bool

The iscashable function checks if the cash of the strategy is cashable within the universe of the strategy. It returns true if the cash is cashable, and false otherwise.

Data.candleatMethod

Get the candle for the asset at date with timeframe tf.

Exchanges.marketsidMethod

Retrieves the market identifiers for a given strategy type.

marketsid(s::Type{<:S<:Strategies.Strategy}) -> Any

The marketsid function invokes the call! function with the strategy type and StrategyMarkets() as arguments. This function is used to fetch the market identifiers associated with a specific strategy type.

Instruments.freecashMethod

Cash that is not committed, and therefore free to use for new orders.

Misc.attrsMethod

The strategy Config attributes.

Misc.call!Method

Called on each timestep iteration, possible multiple times. Receives:

  • current_time: the current timestamp to evaluate (the current candle would be current_time - timeframe).
  • ctx: The context of the executor.
call!(
    _::Strategies.Strategy,
    current_time::Dates.DateTime,
    ctx
)
Misc.call!Method

When an order is canceled the strategy is pinged with an order error.

call!(
    s::Strategies.Strategy,
    ::OrderTypes.Order,
    err::OrderTypes.OrderError,
    ::Instances.AssetInstance;
    kwargs...
) -> Any
Misc.call!Method

Called at the end of the reset! function applied to a strategy.

call!(_::Strategies.Strategy, _::Strategies.ResetStrategy)
Misc.call!Method

Called before the strategy is started.

call!(_::Strategies.Strategy, _::Strategies.StartStrategy)
Misc.call!Method

Called after the strategy is stopped.

call!(_::Strategies.Strategy, _::Strategies.StopStrategy)
Misc.call!Method

How much lookback data the strategy needs.

call!(
    s::Strategies.Strategy,
    _::Strategies.WarmupPeriod
) -> Any
Misc.call!Method

Called to construct the strategy, should return the strategy instance.

call!(
    _::Type{<:Strategies.Strategy},
    cfg,
    _::Strategies.LoadStrategy
)
Misc.call!Method

Market symbols that populate the strategy universe

Misc.reset!Function

Resets the state of a strategy.

reset!(s::Strategies.Strategy)
reset!(s::Strategies.Strategy, config)

The reset! function is used to reset the state of a given strategy. It empties the buy and sell orders, resets the holdings and assets, and optionally re-applies the strategy configuration defaults. If the strategy is currently running, the reset operation is aborted with a warning.

Strategies._assetvalMethod

Calculates the asset value for both long and short positions.

_assetval(
    ai::Instances.AssetInstance{<:AbstractAsset, <:ExchangeID, M} where M<:Misc.WithMargin,
    n_holdings,
    min_hold,
    max_hold;
    price
)

This function iterates over both long and short positions. If the asset instance for a position is not zero, it increments the number of holdings and calculates the value of the asset for the position at the current price. It then updates the minimum and maximum holdings using the _mmh function. The function returns the updated number of holdings, minimum holdings, and maximum holdings.

Strategies._assetvalMethod

Calculates the asset value for a NoMarginInstance.

_assetval(
    ai::Instances.AssetInstance{<:AbstractAsset, <:ExchangeID, NoMargin},
    n_holdings,
    min_hold,
    max_hold;
    price
)

This function checks if the cash of the NoMarginInstance is not zero. If it's not, it increments the number of holdings and calculates the value of the asset at the current price. It then updates the minimum and maximum holdings using the _mmh function. The function returns the updated number of holdings, minimum holdings, and maximum holdings.

Strategies._defined_marginmodeMethod

Determines the margin mode of a module.

_defined_marginmode(mod) -> Any

This function attempts to determine the margin mode of a given module. It first tries to access the S property of the module to get the margin mode. If this fails, it then tries to access the SC property of the module.

Strategies._fileMethod

Determines the file path for a strategy source.

_file(src, cfg, is_project) -> Any

This function determines the file path for a strategy source based on whether it is a project or not. If it is a project, it constructs the file path relative to the configuration path. If it is not a project, it retrieves the source file from the strategy's configuration or defaults to a predefined path. In case the file path is not found, it throws an ArgumentError with a detailed message.

Strategies._include_projectlessMethod

Retrieves the source file for a strategy without a project.

The _include_projectless function retrieves the source file for a strategy that does not have a project. It checks the sources attribute of the strategy's configuration.

Strategies._mmhMethod

Updates the minimum and maximum holdings based on the provided value.

_mmh(ai, val, min_hold, max_hold) -> Tuple{Any, Any}

Given an asset instance, a value, and the current minimum and maximum holdings, this function updates the minimum and maximum holdings if the provided value is less than the current minimum or greater than the current maximum. It returns the updated minimum and maximum holdings.

Strategies._no_inv_contractsMethod

Checks for inverse contracts in an exchange.

_no_inv_contracts(exc::Exchange, uni)

This function checks for the presence of inverse contracts in a given exchange. If any inverse contracts are found, it asserts an error.

Strategies._strat_load_checksMethod

Performs checks on a loaded strategy.

_strat_load_checks(
    s::Strategies.Strategy,
    config::Misc.Config
) -> Strategies.Strategy

This function performs checks on a loaded strategy. It asserts that the margin mode and execution mode of the strategy match the configuration. It also sets the verbose property of the strategy to false.

Strategies._strategy_configMethod

Determines the configuration for a strategy.

_strategy_config(src, path; load, config_args...)

This function determines the configuration for a strategy based on the source and path. If the strategy is to be loaded, it attempts to load the strategy cache. If the cache does not exist or is not a valid configuration, it creates a new configuration.

Strategies._strategy_typeMethod

Determines the strategy type of a module.

_strategy_type(mod, cfg) -> Any

This function determines the strategy type of a given module. It first tries to access the S property of the module to get the strategy type. If this fails, it then tries to access the SC property of the module. The function also checks if the exchange is specified in the strategy or in the configuration.

Strategies.asset_bysymFunction

Retrieves an asset instance by symbol.

asset_bysym(s::Strategies.Strategy, sym) -> Any
asset_bysym(s::Strategies.Strategy, sym, dict_bysim) -> Any

This function retrieves an asset instance by symbol sym from a strategy s. It first checks if the asset instance is already cached in the strategy's attributes. If not, it retrieves the asset instance from the strategy's universe. If the asset instance is not found, it returns nothing.

Strategies.bare_loadMethod

Loads a strategy without default settings.

bare_load(
    mod::Module,
    t::Type,
    config::Misc.Config
) -> Union{Strategies.Strategy{var"#s182", _A, _B, <:Misc.MarginMode{H}} where H<:Misc.HedgedMode, Strategies.Strategy{var"#s182", _A, _B, M} where {H<:Misc.HedgedMode, M<:Misc.MarginMode{H}}} where {var"#s182"<:Misc.ExecMode, _A, _B<:ExchangeID}

This function loads a strategy without default settings. It invokes the call! function of the module with the strategy type and StrategyMarkets(). It then creates a new Strategy instance with the module, assets, and configuration. The sandbox property is set based on the mode of the configuration. Finally, it performs checks on the loaded strategy.

Strategies.current_totalFunction

Calculates the total value of a MarginStrategy with Paper.

current_total(
    s::Strategies.Strategy{Misc.Paper, N, <:ExchangeID, <:Misc.WithMargin, C} where {N, C};
    ...
) -> Any
current_total(
    s::Strategies.Strategy{Misc.Paper, N, <:ExchangeID, <:Misc.WithMargin, C} where {N, C},
    price_func;
    kwargs...
) -> Any

This function calculates the total value of a MarginStrategy{Paper} by summing up the value of all holdings and cash. The value of each holding is calculated using a provided price function. The default price function used is lasttrade_price_func, which returns the closing price of the last trade.

Strategies.current_totalMethod

Calculates the total value of a MarginStrategy.

current_total(
    s::Strategies.SimStrategy{N, <:ExchangeID, <:Misc.WithMargin, C} where {N, C};
    price_func,
    kwargs...
) -> Any

This function calculates the total value of a MarginStrategy by summing up the value of all holdings and cash. The value of each holding is calculated using a provided price function. The default price function used is lasttrade_price_func, which returns the closing price of the last trade.

Strategies.current_totalMethod

Calculates the total value of a NoMarginStrategy.

current_total(
    s::Strategies.SimStrategy{N, <:ExchangeID, NoMargin, C} where {N, C};
    price_func,
    kwargs...
) -> Any

This function calculates the total value of a NoMarginStrategy by summing up the value of all holdings and cash. The value of each holding is calculated using a provided price function. The default price function used is lasttrade_price_func, which returns the closing price of the last trade.

Strategies.current_totalMethod

Calculates the total value of a NoMarginStrategy with Paper.

current_total(
    s::Strategies.Strategy{Misc.Paper, N, <:ExchangeID, NoMargin, C} where {N, C};
    price_func,
    kwargs...
) -> Any

This function calculates the total value of a NoMarginStrategy{Paper} by summing up the value of all holdings and cash. The value of each holding is calculated using a provided price function. The default price function used is lasttrade_price_func, which returns the closing price of the last trade.

Strategies.default_loadMethod

Loads a strategy with default settings.

default_load(
    mod::Module,
    t::Type,
    config::Misc.Config
) -> Union{Strategies.Strategy{var"#s182", _A, _B, <:Misc.MarginMode{H}} where H<:Misc.HedgedMode, Strategies.Strategy{var"#s182", _A, _B, M} where {H<:Misc.HedgedMode, M<:Misc.MarginMode{H}}} where {var"#s182"<:Misc.ExecMode, _A, _B<:ExchangeID}

This function loads a strategy with default settings. It invokes the call! function of the module with the strategy type and StrategyMarkets(). It then creates a new Strategy instance with the module, assets, and configuration. The sandbox property is set based on the mode of the configuration. Finally, it performs checks on the loaded strategy.

Strategies.find_pathMethod

Finds the path of a given file.

find_path(file, cfg) -> Any

The find_path function checks various locations to find the path of a given file. It checks the current working directory, user directory, configuration directory, and project directory. If the file is not found, it raises an error.

Strategies.lasttrade_dateFunction

Returns the date of the last trade for an asset instance.

lasttrade_date(ai) -> Any
lasttrade_date(ai, def) -> Any

This function returns the date of the last trade for an AssetInstance. If the history of the asset instance is empty, it returns the timestamp of the last candle.

Strategies.lasttrade_funcMethod

Returns a function for the last trade date of a strategy.

lasttrade_func(s) -> Union{typeof(last), Returns}

This function returns a function that, when called, gives the date of the last trade for a Strategy. If there is no last trade, it returns the last function.

Strategies.logpathMethod

Generates the path for strategy logs.

logpath(
    s::Strategies.Strategy;
    name,
    path_nodes...
) -> String

The logpath function generates a path for storing strategy logs. It takes the strategy and optional parameters for the name of the log file and additional path nodes. The function checks if the directory for the logs exists and creates it if necessary. It then returns the full path to the log file.

Strategies.logsMethod

Retrieves the logs for a strategy.

logs(s::Strategies.Strategy) -> Vector{Any}

The logs function collects and returns all the logs associated with a given strategy. It fetches the logs from the directory specified in the strategy's path.

Strategies.minmax_holdingsMethod

Calculates the minimum and maximum holdings for a strategy.

minmax_holdings(
    s::Strategies.Strategy
) -> NamedTuple{(:min, :max, :count), <:Tuple{Tuple{Any, Any}, Tuple{Any, Any}, Int64}}

This function iterates over the holdings of a strategy. For each holding, it calculates the current price and updates the number of holdings, minimum holdings, and maximum holdings using the _assetval function. The function returns the minimum holdings, maximum holdings, and the count of holdings.

Strategies.reload!Method

Reloads OHLCV data for assets in the strategy universe.

reload!(s::Strategies.Strategy)

The reload! function empties the data for each asset instance in the strategy's universe and then loads new data. This is useful for refreshing the strategy's knowledge of the market state.

Strategies.save_strategyMethod

Saves the state of a strategy.

save_strategy(s)

This function saves the state of a given strategy. It determines the cache path and saves the strategy state to this path.

Strategies.sizehint!Method

Keeps track of max allocated containers size for strategy and asset instances in the universe.

sizehint!(s::Strategies.Strategy)

This function keeps track of the maximum allocated containers size for strategy and asset instances in the universe. It updates the sizes of various containers based on the current state of the strategy.

Strategies.strategyFunction

Loads a strategy from a source, module, or string.

strategy(src::Union{Module, String, Symbol}; ...) -> Any
strategy(
    src::Union{Module, String, Symbol},
    path::String;
    load,
    config_args...
) -> Any

This function loads a strategy from a given source, module, or string. It first determines the configuration for the strategy based on the source and path. If the strategy is to be loaded, it attempts to load the strategy cache. Finally, it returns the loaded strategy.

Strategies.strategy!Method

Loads a strategy from a module.

strategy!(mod::Module, cfg::Misc.Config) -> Any

This function loads a strategy from a given module. It first checks and sets the mode and margin of the configuration if they are not set. It then determines the strategy type of the module and checks if the exchange is specified in the strategy or in the configuration. Finally, it tries to load the strategy with default settings, if it fails, it loads the strategy without default settings.

Strategies.strategy!Method

Loads a strategy from a symbol source.

strategy!(src::Symbol, cfg::Misc.Config) -> Any

This function loads a strategy from a given symbol source. It first determines the file path for the strategy source and checks if it is a project. If it is a project, it activates and instantiates the project. The function then includes the source file and uses it. If the source file is not defined in the parent module, it is evaluated and tracked for changes. Finally, the function returns the loaded strategy.

Strategies.strategy_cache_pathMethod

Returns the path to the strategy cache.

strategy_cache_path() -> String

This function returns the path to the strategy cache. It checks if the path exists and creates it if it doesn't.

Strategies.trades_countMethod

Counts all trades recorded in the strategy universe.

trades_count(
    s::Strategies.Strategy,
    _::Val{:liquidations}
) -> NamedTuple{(:trades, :liquidations), <:Tuple{Any, Any}}

This function iterates over the universe of a strategy. For each asset instance in the universe, it increments a counter by the length of the asset instance's history. The function returns the total count of trades.

Strategies.trades_countMethod

Counts the number of long, short, and liquidation trades in the strategy universe.

trades_count(
    s::Strategies.Strategy,
    _::Val{:positions}
) -> NamedTuple{(:long, :short, :liquidations), <:Tuple{Any, Any, Any}}

This function iterates over the universe of a strategy. For each asset instance in the universe, it counts the number of long trades, short trades, and liquidation trades. The function returns the total count of long trades, short trades, and liquidation trades.

Strategies.tradesedgeMethod

Returns the first and last trade of any asset in the strategy universe.

tradesedge(s::Strategies.Strategy) -> Tuple{Any, Any}

This function returns the first and last trade of any asset in the strategy universe for a given Strategy. If there are no trades, it returns nothing.

Strategies.tradesedgeMethod

Returns the dates of the first and last trade present in the strategy.

tradesedge(
    _::Type{Dates.DateTime},
    s::Strategies.Strategy
) -> Tuple{Any, Any}

This function returns the dates of the first and last trade of any asset in the strategy universe for a given Strategy.

Strategies.tradesperiodMethod

Returns the recorded trading period from the trades history present in the strategy.

tradesperiod(s::Strategies.Strategy) -> Any

This function returns the recorded trading period from the trades history present in the strategy. It calculates the period by subtracting the start date from the stop date.

Strategies.tradesrangeFunction

Returns a DateRange spanning the historical time period of the trades recorded by the strategy.

tradesrange(
    s::Strategies.Strategy;
    ...
) -> TimeTicks.DateRange
tradesrange(
    s::Strategies.Strategy,
    tf;
    start_pad,
    stop_pad
) -> TimeTicks.DateRange

This function returns a DateRange that spans the historical time period of the trades recorded by the strategy. It calculates the range by adding the start and stop pads to the edges of the trades.

Strategies.@define_candle_funcMacro

Defines a set of functions for a given candle function.

This macro generates two functions for each candle function passed to it. The first function is for getting the candle data from an AssetInstance at a specific date. The second function is for getting the candle data from a Strategy at a specific date with a specified timeframe. The timeframe defaults to the strategy's timeframe if not provided.

Strategies.@interfaceMacro

Provides a common interface for strategy execution.

The interface macro imports the call! function from the Strategies module, the assets and exchange functions, and the call! function from the Executors module. This macro is used to provide a common interface for strategy execution.