Strategies
Strategies.STRATEGY_LOAD_CALLBACKS
— ConstantFunctions that are called (with the strategy as argument) right after strategy construction.
Core.Symbol
— MethodSymbol
representation of the strategy (name of the module).
Strategies.AbstractStrategy
— TypeThe base type for all strategies.
Strategies.BuyOrdersDict
— TypeSortedDict
of holding buy orders
Strategies.BuyPriceTimeOrdering
— TypeOrdering for buy orders (highest price first)
Strategies.CrossStrategy
— TypeCross margin strategy.
Strategies.ExchangeAsset
— TypeAssetInstance
by ExchangeID
Strategies.ExchangeBuyOrder
— TypeBuyOrder
by ExchangeID
Strategies.ExchangeOrder
— TypeOrder
by ExchangeID
Strategies.ExchangeSellOrder
— TypeSellOrder
by ExchangeID
Strategies.IsolatedStrategy
— TypeIsolated margin strategy.
Strategies.LiveStrategy
— TypeLive trading strategy.
Strategies.LoadStrategy
— TypeStrategies.MarginStrategy
— TypeStrategy with isolated or cross margin.
Strategies.NoMarginStrategy
— TypeStrategy with no margin at all.
Strategies.PaperStrategy
— TypePaper trading strategy.
Strategies.PriceTime
— TypePriceTime
named tuple
Strategies.RTStrategy
— TypeReal time strategy (Paper
, Live
).
Strategies.ResetStrategy
— TypeStrategies.SellOrdersDict
— TypeSortedDict
of holding sell orders
Strategies.SellPriceTimeOrdering
— TypeOrdering for sell orders (lowest price first)
Strategies.SimStrategy
— TypeSimulation strategy.
Strategies.StartStrategy
— TypeStrategies.StopStrategy
— TypeStrategies.Strategy
— TypeThe strategy is the core type of the framework.
self
: The strategy moduleconfig
: TheConfig
the strategy was instantiated withtimeframe
: The smallest timeframe the strategy usescash
: The quote currency used for tradescash_committed
: Cash kept busy by pending ordersbuyorders
: Active buy orderssellorders
: Active sell ordersholdings
: Assets with non zero balanceuniverse
: All the assets that the strategy knows aboutlock
: 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 smallesttimeframe
that the strategy usesDESCRIPTION
: Name or short description for the strategy could be different from module name
Strategies.Strategy
— MethodInitializes 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.
Strategies.StrategyMarkets
— TypeStrategies.WarmupPeriod
— TypeBase.count
— MethodCounts 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!
— MethodFills 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.getproperty
— MethodRetrieves 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.getproperty
— MethodRetrieves 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.nameof
— MethodThe name of the strategy module.
Base.nameof
— MethodThe name of the strategy module.
Base.similar
— MethodCreates 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.iscashable
— MethodChecks 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.candleat
— MethodGet the candle for the asset at date
with timeframe tf
.
ExchangeTypes.exchange
— MethodStrategy exchange.
Exchanges.marketsid
— MethodRetrieves 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.freecash
— MethodCash that is not committed, and therefore free to use for new orders.
Misc.attrs
— MethodThe strategy Config
attributes.
Misc.call!
— MethodCalled on each timestep iteration, possible multiple times. Receives:
current_time
: the current timestamp to evaluate (the current candle would becurrent_time - timeframe
).ctx
: The context of the executor.
call!(
_::Strategies.Strategy,
current_time::Dates.DateTime,
ctx
)
Misc.call!
— MethodWhen 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!
— MethodCalled at the end of the reset!
function applied to a strategy.
call!(_::Strategies.Strategy, _::Strategies.ResetStrategy)
Misc.call!
— MethodCalled before the strategy is started.
call!(_::Strategies.Strategy, _::Strategies.StartStrategy)
Misc.call!
— MethodCalled after the strategy is stopped.
call!(_::Strategies.Strategy, _::Strategies.StopStrategy)
Misc.call!
— MethodHow much lookback data the strategy needs.
call!(
s::Strategies.Strategy,
_::Strategies.WarmupPeriod
) -> Any
Misc.call!
— MethodCalled to construct the strategy, should return the strategy instance.
call!(
_::Type{<:Strategies.Strategy},
cfg,
_::Strategies.LoadStrategy
)
Misc.call!
— MethodMarket symbols that populate the strategy universe
Misc.execmode
— MethodReturns the strategy execution mode.
Misc.marginmode
— MethodGet the strategy margin mode.
Misc.reset!
— FunctionResets 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._assetval
— MethodCalculates 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._assetval
— MethodCalculates 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_marginmode
— MethodDetermines 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._file
— MethodDetermines 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_projectless
— MethodRetrieves 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._mmh
— MethodUpdates 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_contracts
— MethodChecks 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_checks
— MethodPerforms 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_config
— MethodDetermines 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_type
— MethodDetermines 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_bysym
— FunctionRetrieves 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.assets
— MethodAssets loaded by the strategy.
Strategies.bare_load
— MethodLoads 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_total
— FunctionCalculates 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_total
— MethodCalculates 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_total
— MethodCalculates 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_total
— MethodCalculates 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!
— MethodSet strategy defaults.
Strategies.default_load
— MethodLoads 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_path
— MethodFinds 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.instances
— MethodStrategy assets instance.
Strategies.lasttrade_date
— FunctionReturns 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_func
— MethodReturns 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.lasttrade_price_func
— MethodThe asset close price of the candle where the last trade was performed.
Strategies.logpath
— MethodGenerates 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.logs
— MethodRetrieves 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_holdings
— MethodCalculates 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!
— MethodReloads 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_strategy
— MethodSaves 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!
— MethodKeeps 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.strategy
— FunctionLoads 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!
— MethodLoads 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!
— MethodLoads 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
— MethodReturns the default strategy (BareStrat
).
Strategies.strategy_cache_path
— MethodReturns 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.throttle
— MethodThe throttle
attribute determines the strategy polling interval.
Strategies.trades_count
— MethodCounts 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_count
— MethodCounts 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.trades_count
— MethodAll trades recorded in the strategy universe (includes liquidations).
Strategies.tradesedge
— MethodReturns 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.tradesedge
— MethodReturns 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.tradesperiod
— MethodReturns 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.tradesrange
— FunctionReturns 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.universe
— MethodThe strategy AssetCollection
.
Strategies.@define_candle_func
— MacroDefines 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.@interface
— MacroProvides 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.
Strategies.@notfound
— MacroRaises an error when a strategy is not found at a given path.