StrategyTools

This module implements routines common to many strategies.

StrategyTools.MovingExtremaMethod

MovingExtrema2: Keep track of minima and maxima within a moving window.

MovingExtrema(window::Int64) -> StrategyTools.MovingExtrema
Base.:/Method

TimeFrame division

/(tf::TimeFrames.TimeFrame, d; type) -> Any
Base.extremaMethod

Get the minimum and maximum values in the MovingExtrema2 buffer.

extrema(
    q::StrategyTools.MovingExtrema
) -> Tuple{Union{Missing, Float64}, Union{Missing, Float64}}
Base.push!Method

Pushes a new value to the MovingExtrema2 buffer.

push!(
    q::StrategyTools.MovingExtrema,
    value::Float64
) -> Deque{Float64}
Misc.call!Method

Initiates the warmup process for a real-time strategy instance.

call!(
    cb::Function,
    s::Strategies.RTStrategy,
    ai::Instances.AssetInstance,
    ats::Dates.DateTime,
    ::SimWarmup;
    n_candles
)

If warmup has not been previously completed for the given asset instance, it performs the necessary preparations.

Misc.call!Method

Initializes warmup attributes for a strategy.

call!(
    s::Strategies.Strategy,
    ::InitSimWarmup;
    timeout,
    n_candles
) -> Bool
StrategyTools._warmup!Method

Executes the warmup routine with a custom callback for a strategy.

_warmup!(
    callback::Function,
    s::Strategies.Strategy,
    ai::Instances.AssetInstance,
    ats::Dates.DateTime;
    n_candles
)

The function prepares the trading strategy by simulating past data before live execution starts.

StrategyTools.belowtotalMethod

Check if collateral is below a calculated threshold

belowtotal(s, ai, p; qt) -> Any

Determines if the collateral of a position p is less than the minimum required amount or a dynamic threshold based on s[:qt_base].

StrategyTools.cdfrompnlMethod

Calculates the cooldown period based on the profit and loss values.

cdfrompnl(s, pnl) -> Any
cdfrompnl(s, pnl, cdu) -> Any

This function calculates the cooldown period (cd) using the profit and loss (pnl) values, the cooldown unit (cdu), and the strategy's cooldown_base.

StrategyTools.cmpabMethod

Compares two properties of a signal state.

cmpab(sig, a, b) -> Bool
StrategyTools.copyohlcv!Method

Updates the OHLCV data for a destination asset instance from a source.

copyohlcv!(ai_dst, ai_src::Instances.AssetInstance)

Existing OHLCV data for the destination is cleared before copying to ensure accurate and up-to-date information.

StrategyTools.copyohlcv!Method

Copies OHLCV data from one strategy instance to another.

copyohlcv!(
    s_dst::Strategies.Strategy,
    s_src::Strategies.Strategy
)

Ensures that the destination strategy's asset instances are updated with the source's OHLCV data for matching market symbols.

StrategyTools.copypnl!Method

Copies simulated PnL data to the main strategy instance.

copypnl!(s, ai, s_sim, ai_sim) -> Union{Nothing, Bool}

Transfers PnL data from a simulation instance to the corresponding asset in the main strategy and marks the asset as warmed up.

StrategyTools.degreesMethod

Calculate angle of a slope.

degrees(slp) -> Any

Calculates the angle in degrees of the slope slp.

StrategyTools.get_signal_valueMethod

Retrieve a signal value from a dictionary for a given key.

get_signal_value(ct, k) -> Any

Extracts the sig.value from the property of the dictionary item identified by k.

StrategyTools.initpnl!Function

Initializes the PnL tracking structure for each asset in the universe.

initpnl!(
    s;
    ...
) -> LittleDict{Any, Any, Vector{Any}, Vector{Any}}
initpnl!(
    s,
    uni;
    n,
    ma
) -> LittleDict{Any, Any, Vector{Any}, Vector{Any}}

Sets up a LittleDict with a circular buffer to store PnL data, defaulting to 100 entries.

StrategyTools.iscrossedMethod

Check if a signal crossover condition is met at a given time.

iscrossed(s, ai, ats, sig_b, drc::Val) -> Any

Evaluates if the closing prices at specified times cross a threshold in the direction drc. Uses timeframes and signals to determine the crossover.

StrategyTools.iscrossedMethod

Determine if a crossover occurred in a specified direction.

iscrossed(::Val{:above}; a, b, prev_a, prev_b)

Checks if values a, b, and c satisfy the conditions for a crossover in the specified direction (:above or :below).

StrategyTools.islasttsMethod

Check if last timestamp is within time frame for a simulation strategy.

islastts(
    _::Strategies.SimStrategy,
    _,
    ats,
    tf
) -> Tuple{Bool, Any}

Checks if the last timestamp ts is within the time frame tf for the simulation strategy s.

StrategyTools.isrecenttradeMethod

Checks if a trade was made recently

isrecenttrade(
    ai::Instances.AssetInstance,
    ats::Dates.DateTime,
    tf::TimeFrames.TimeFrame;
    cd
) -> Bool

Checks if a trade was made recently by checking if the last trade time for the given asset instance is more recent than the current time frame. If no trades were made, it returns true.

StrategyTools.isstaleohlcvMethod

Determines if the OHLCV data is stale for specified conditions.

isstaleohlcv(s::Strategies.RTStrategy, ai; ats, tf, backoff)

The function checks whether the latest time stamp of OHLCV data is not older than the backoff period. If older, it returns true, indicating the data is stale. Used to avoid reprocessing the same ohlcv candle.

StrategyTools.isstaleohlcvMethod

Determines if the OHLCV data is stale for a simulation strategy.

isstaleohlcv(
    s::Strategies.SimStrategy,
    args...;
    kwargs...
) -> Bool

For a simulation strategy it is always up-to-date, so always returns false.

StrategyTools.istrending!Method

Check if an asset is trending for a given signal

istrending!(
    s::Strategies.Strategy,
    ai::Instances.AssetInstance,
    ats::Dates.DateTime,
    sig_name;
    func
) -> Bool

Checks if the asset ai is trending at time ats for the signal sig_name in the strategy s. The trending condition is determined by the provided func::Function which has the signature:

func(::SignalState, ::Int, ::DataFrame)::Bool
StrategyTools.liveloopMethod

Map function asynchronously for a real-time strategy.

liveloop(f, s::Strategies.RTStrategy, iter)

Asynchronously maps the function f over the iterable iter for the real-time strategy s.

StrategyTools.liveloopMethod

Apply function to iterable for a simulation strategy.

liveloop(f, s::Strategies.SimStrategy, iter) -> Any

Applies the function f to each element of the iterable iter for the simulation strategy s.

StrategyTools.liveloopMethod

Apply function to iterable for a strategy.

liveloop(f, s::Strategies.Strategy)

Applies the function f to each element of the iterable iter for the strategy s.

StrategyTools.livesleepMethod

Sleep function for a real-time strategy.

livesleep(s::Strategies.RTStrategy, n) -> Any

Makes the real-time strategy s sleep for n seconds.

StrategyTools.livesleepMethod

Sleep function for a simulation strategy.

livesleep(s::Strategies.SimStrategy, _)

Does nothing for the simulation strategy s.

StrategyTools.logMethod

Log function for a strategy.

log(s::Strategies.RTStrategy, f, args...)

Logs the function f with its arguments args for the strategy s.

StrategyTools.logMethod

Log function for a simulation strategy.

log(s::Strategies.SimStrategy, f, args...)

Logs the function f with its arguments args for the simulation strategy s.

StrategyTools.rateabMethod

Calculates the rate of change of a property of a signal state.

rateab(sig, a, b) -> Tuple{Any, Any}
StrategyTools.select_orderkwargsMethod

Select additional keyword arguments for Buy orders based on order type

select_orderkwargs(
    otsym::Symbol,
    ::Type{OrderTypes.Buy},
    ai,
    ats;
    incr
) -> Union{@NamedTuple{}, NamedTuple{(:price,), <:Tuple{Any}}}

Depending on the order type symbol, additional keyword arguments are selected to define order parameters like price. This method specifically handles the Buy side logic by adjusting price based on closing value.

StrategyTools.select_orderkwargsMethod

Selects an order type based on the strategy, order side, and position side

select_orderkwargs(
    otsym::Symbol,
    ::Type{OrderTypes.Sell},
    ai,
    ats;
    incr
) -> Union{@NamedTuple{}, NamedTuple{(:price,), <:Tuple{Any}}}

Selects an order type os based on the strategy s and the position side p. The order type is determined by the ordertype attribute of the strategy.

StrategyTools.select_ordertypeFunction

Selects an order type based on the strategy, order side, and position side

select_ordertype(
    s::Strategies.Strategy,
    os::Type{<:OrderTypes.OrderSide};
    ...
) -> Tuple{Type, Any}
select_ordertype(
    s::Strategies.Strategy,
    os::Type{<:OrderTypes.OrderSide},
    p::Misc.PositionSide;
    t
) -> Tuple{Type, Any}

Selects an order type os based on the strategy s and the position side p. The order type is determined by the ordertype attribute of the strategy.

StrategyTools.signals!Method

Update or initialize strategy signals.

signals!(s, args...; kwargs...)

Handles dynamic indicator updates based on strategy configurations. Redirects to signals! with appropriate value tagging and error management.

StrategyTools.signals!Method

Update signals for a strategy.

signals!(s::Strategies.Strategy, ats, _::Val{:update})

Iterates over the universe of assets and for each asset iterates over the configured signals. Calls update_signal! to update each indicator with the current asset time series and configuration.

StrategyTools.signals!Method

Update signals for a strategy.

signals!(
    s::Strategies.Strategy,
    ::Val{:warmup};
    force,
    history
) -> Union{Nothing, Bool}

Iterates over the universe of assets and for each asset iterates over the configured signals. Calls update_signal! to update each indicator with the current asset time series and configuration.

StrategyTools.signalsMethod

Create multiple signal definitions and instantiate a new Signals17 object.

signals(
    signals,
    timeframes,
    count,
    params
) -> StrategyTools.Signals17

Constructs a dictionary of signals from input tuples and then creates a Signals17 instance using these definitions. Each signal configuration is converted into a typed tuple preserving the structure required by Signals17.

StrategyTools.track_expectancy!Method

Calculates the win rate and profit/loss thresholds for a trading strategy.

track_expectancy!(s, ai) -> Any

Updates s[:profit_thresh] and s[:loss_thresh] based on the trading results.

StrategyTools.trackcd!Method

Updates the cooldown period for an asset instance in the strategy.

trackcd!(s, ai, ats, ts) -> Any

The function calculates the cooldown period for the asset instance ai in the strategy s at the current timestamp ts.

StrategyTools.tracklev!Method

Adjusts the leverage for an asset based on the Kelly criterion.

tracklev!(
    s,
    ai,
    ats;
    dampener
) -> Union{Nothing, NamedTuple{(:time, :raw_val, :value), <:Tuple{Any, Any, Any}}}

Applies a damping function to the raw Kelly leverage to ensure it remains within practical limits.

StrategyTools.trackpnl!Method

Records the profit and loss (PnL) for a given asset instance at a specific timestamp.

trackpnl!(s, ai, ats, ts; interval, pnl_func) -> Any

The PnL is calculated based on the position side and the closing price at the given timestamp.

StrategyTools.trackqt!Method

Tracks the target quantity of an asset over time for trading strategy s.

trackqt!(s, ai, ats; f) -> Any

The quantity is determined by the function f and is adjusted based on the asset ai and timestamp ats.

StrategyTools.update_data!Method

Update or initialize mutable data related to asset information.

update_data!(ai, tf) -> DataFrames.DataFrame

This function acquires or creates a data frame for the ai asset using the timeframe tf, then refreshes its OHLCV data by fetching new entries from the specified time onwards, based on the asset's symbol and exchange details. The update process may involve checking the existing data timestamps to avoid unnecessary data retrieval.

StrategyTools.update_signal!Method

Update signal

update_signal!(ai, ats, ai_signals, sig_name; tf, count)

Updates the signal sig_name for asset ai based on new data up to timestamp ats. Uses a lookback window of count timeframes tf.

StrategyTools.waitohlcvMethod

Waits for OHLCV data to update up to a specified time.

waitohlcv(s, since; interval)

The function continuously checks if the latest data in each asset's time frame is up-to-date with the since parameter. It pauses execution using sleep for the given interval until the condition is met.