StrategyTools
This module implements routines common to many strategies.
StrategyTools.MovingExtrema
— TypeMovingExtrema2: keep track of minimum and maximum values within a moving window.
StrategyTools.MovingExtrema
— MethodMovingExtrema2: Keep track of minima and maxima within a moving window.
MovingExtrema(window::Int64) -> StrategyTools.MovingExtrema
Base.:/
— MethodTimeFrame division
/(tf::TimeFrames.TimeFrame, d; type) -> Any
Base.extrema
— MethodGet the minimum and maximum values in the MovingExtrema2 buffer.
extrema(
q::StrategyTools.MovingExtrema
) -> Tuple{Union{Missing, Float64}, Union{Missing, Float64}}
Base.push!
— MethodPushes a new value to the MovingExtrema2 buffer.
push!(
q::StrategyTools.MovingExtrema,
value::Float64
) -> Deque{Float64}
Misc.call!
— MethodInitiates 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!
— MethodInitializes warmup attributes for a strategy.
call!(
s::Strategies.Strategy,
::InitSimWarmup;
timeout,
n_candles
) -> Bool
StrategyTools._warmup!
— MethodExecutes 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.belowtotal
— MethodCheck 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.cdfrompnl
— MethodCalculates 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.cmpab
— MethodCompares two properties of a signal state.
cmpab(sig, a, b) -> Bool
StrategyTools.copyohlcv!
— MethodUpdates 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!
— MethodCopies 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!
— MethodCopies 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.degrees
— MethodCalculate angle of a slope.
degrees(slp) -> Any
Calculates the angle in degrees of the slope slp
.
StrategyTools.get_signal_value
— MethodRetrieve 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.hasentrycash
— MethodVerify if free cash is above the entry cost minimum
hasentrycash(s, ai) -> Any
StrategyTools.hasexitcash
— MethodAssess if amount exceeds the minimum exit amount
hasexitcash(amt, ai) -> Any
StrategyTools.initpnl!
— FunctionInitializes 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.iscrossed
— MethodCheck 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.iscrossed
— MethodDetermine 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.islastts
— MethodCheck 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.isrecenttrade
— MethodChecks 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.isstaleohlcv
— MethodDetermines 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.isstaleohlcv
— MethodDetermines 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!
— MethodCheck 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.liveloop
— MethodMap 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.liveloop
— MethodApply 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.liveloop
— MethodApply 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.livesleep
— MethodSleep function for a real-time strategy.
livesleep(s::Strategies.RTStrategy, n) -> Any
Makes the real-time strategy s
sleep for n
seconds.
StrategyTools.livesleep
— MethodSleep function for a simulation strategy.
livesleep(s::Strategies.SimStrategy, _)
Does nothing for the simulation strategy s
.
StrategyTools.log
— MethodLog function for a strategy.
log(s::Strategies.RTStrategy, f, args...)
Logs the function f
with its arguments args
for the strategy s
.
StrategyTools.log
— MethodLog 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.rateab
— MethodCalculates the rate of change of a property of a signal state.
rateab(sig, a, b) -> Tuple{Any, Any}
StrategyTools.select_orderkwargs
— MethodSelect 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_orderkwargs
— MethodSelects 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_ordertype
— FunctionSelects 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.signal_range
— MethodReturn the inputs for the fit!
function of the signal.
StrategyTools.signal_value
— MethodDispatch on typeof(sig.state)
StrategyTools.signals!
— MethodUpdate 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!
— MethodUpdate 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!
— MethodUpdate 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.signals
— MethodCreate 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!
— MethodCalculates 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!
— MethodUpdates 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!
— MethodAdjusts 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!
— MethodRecords 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!
— MethodTracks 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!
— MethodUpdate 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!
— MethodUpdate 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.waitohlcv
— MethodWaits 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.