PlanarStrategyTools
This module implements routines common to many strategies.
PlanarStrategyTools.MovingExtrema — Type
MovingExtrema2: keep track of minimum and maximum values within a moving window.
PlanarStrategyTools.MovingExtrema — Method
MovingExtrema2: Keep track of minima and maxima within a moving window.
MovingExtrema(
window::Int64
) -> PlanarStrategyTools.MovingExtrema
Base.extrema — Method
Get the minimum and maximum values in the MovingExtrema2 buffer.
extrema(
q::PlanarStrategyTools.MovingExtrema
) -> Tuple{Union{Missing, Float64}, Union{Missing, Float64}}
Base.push! — Method
Pushes a new value to the MovingExtrema2 buffer.
push!(
q::PlanarStrategyTools.MovingExtrema,
value::Float64
) -> Deque{Float64}
PlanarCore.Misc.call! — Method
Initiates the warmup process for all assets in the universe for a real-time strategy.
call!(
cb::Function,
s::PlanarCore.Strategies.RTStrategy,
ats::Dates.DateTime,
::PlanarStrategyTools.SimWarmup;
n_candles
)
Runs warmup simulation on all assets in the strategy's universe simultaneously.
PlanarCore.Misc.call! — Method
Initiates the warmup process for a real-time strategy instance.
call!(
cb::Function,
s::PlanarCore.Strategies.RTStrategy,
ii::PlanarCore.Instances.InstrumentInstance,
ats::Dates.DateTime,
::PlanarStrategyTools.SimWarmup;
n_candles
)
If warmup has not been previously completed for the given asset instance, it performs the necessary preparations.
PlanarCore.Misc.call! — Method
Initiates the warmup process for all assets in the universe for a simulation strategy.
call!(
cb::Function,
s::PlanarCore.Strategies.SimStrategy,
::PlanarStrategyTools.SimWarmup;
n_candles
)
Runs warmup simulation on all assets in the strategy's universe simultaneously.
PlanarCore.Misc.call! — Method
Initializes warmup attributes for a strategy.
call!(
s::PlanarCore.Strategies.Strategy,
::PlanarStrategyTools.InitSimWarmup;
timeout,
warmup_period
) -> Any
PlanarStrategyTools._warmup! — Method
Executes the warmup routine for all assets in a simulation strategy.
_warmup!(
callback::Function,
s::PlanarCore.Strategies.SimStrategy;
n_candles
)
Simplified version for simulation strategies that don't need timestamp parameter.
PlanarStrategyTools._warmup! — Method
Executes the warmup routine for all assets in the universe with a custom callback.
_warmup!(
callback::Function,
s::PlanarCore.Strategies.Strategy,
ats::Dates.DateTime;
n_candles
)
The function prepares the trading strategy by simulating past data for all assets in the universe before live execution starts.
PlanarStrategyTools._warmup! — Method
Executes the warmup routine with a custom callback for a strategy.
_warmup!(
callback::Function,
s::PlanarCore.Strategies.Strategy,
ii::PlanarCore.Instances.InstrumentInstance,
ats::Dates.DateTime;
n_candles
)
The function prepares the trading strategy by simulating past data before live execution starts.
PlanarStrategyTools.belowtotal — Method
Check if collateral is below a calculated threshold
belowtotal(s, ii, 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].
PlanarStrategyTools.calculate_slope — Method
Calculate the slope of a signal based on its trace buffer.
calculate_slope(sig) -> Any
Calculates the slope using simple rate of change between first and last valid values.
PlanarStrategyTools.cdfrompnl — Method
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.
PlanarStrategyTools.cmpab — Method
Compares two properties of a signal state.
cmpab(sig, a, b) -> Bool
PlanarStrategyTools.copyohlcv! — Method
Updates the OHLCV data for a destination asset instance from a source.
copyohlcv!(
ai_dst,
ai_src::PlanarCore.Instances.InstrumentInstance
)
Existing OHLCV data for the destination is cleared before copying to ensure accurate and up-to-date information.
PlanarStrategyTools.copyohlcv! — Method
Copies OHLCV data from one strategy instance to another.
copyohlcv!(
s_dst::PlanarCore.Strategies.Strategy,
s_src::PlanarCore.Strategies.Strategy
)
Ensures that the destination strategy's asset instances are updated with the source's OHLCV data for matching market symbols.
PlanarStrategyTools.copypnl! — Method
Copies simulated PnL data to the main strategy instance.
copypnl!(s, ii, 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.
PlanarStrategyTools.degrees — Method
Calculate angle of a slope.
degrees(slp) -> Any
Calculates the angle in degrees of the slope slp.
PlanarStrategyTools.get_signal_value — Method
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.
PlanarStrategyTools.hasentrycash — Method
Verify if free cash is above the entry cost minimum
hasentrycash(s, ii) -> Any
PlanarStrategyTools.hasexitcash — Method
Assess if amount exceeds the minimum exit amount
hasexitcash(amt, ii) -> Any
PlanarStrategyTools.indicator_range — Method
Return the inputs for the fit! function of the signal.
PlanarStrategyTools.indicator_range — Method
Return the inputs for the fit! function of the signal.
PlanarStrategyTools.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.
PlanarStrategyTools.iscrossed — Method
Check if a signal crossover condition is met at a given time.
iscrossed(s, ii, 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.
PlanarStrategyTools.iscrossed — Method
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).
PlanarStrategyTools.islastts — Method
Check if last timestamp is within time frame for a simulation strategy.
islastts(
_::PlanarCore.Strategies.SimStrategy,
_,
ats,
tf
) -> Tuple{Bool, Any}
Checks if the last timestamp ts is within the time frame tf for the simulation strategy s.
PlanarStrategyTools.isrecenttrade — Method
Checks if a trade was made recently
isrecenttrade(
ii::PlanarCore.Instances.InstrumentInstance,
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.
PlanarStrategyTools.isstaleohlcv — Method
Determines if the OHLCV data is stale for specified conditions.
isstaleohlcv(
s::PlanarCore.Strategies.RTStrategy,
ii;
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.
PlanarStrategyTools.isstaleohlcv — Method
Determines if the OHLCV data is stale for a simulation strategy.
isstaleohlcv(
s::PlanarCore.Strategies.SimStrategy,
args...;
kwargs...
) -> Bool
For a simulation strategy it is always up-to-date, so always returns false.
PlanarStrategyTools.istrending! — Method
Check if an asset is trending for a given signal
istrending!(
s::PlanarCore.Strategies.Strategy,
ii::PlanarCore.Instances.InstrumentInstance,
ats::Dates.DateTime,
sig_name;
func
) -> Bool
Checks if the asset ii 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)::BoolPlanarStrategyTools.liveloop — Method
Map function asynchronously for a real-time strategy.
liveloop(f, s::PlanarCore.Strategies.RTStrategy, iter)
Asynchronously maps the function f over the iterable iter for the real-time strategy s.
PlanarStrategyTools.liveloop — Method
Apply function to iterable for a simulation strategy.
liveloop(
f,
s::PlanarCore.Strategies.SimStrategy,
iter
) -> Any
Applies the function f to each element of the iterable iter for the simulation strategy s.
PlanarStrategyTools.liveloop — Method
Apply function to iterable for a strategy.
liveloop(f, s::PlanarCore.Strategies.Strategy)
Applies the function f to each element of the iterable iter for the strategy s.
PlanarStrategyTools.livesleep — Method
Sleep function for a real-time strategy.
livesleep(s::PlanarCore.Strategies.RTStrategy, n) -> Any
Makes the real-time strategy s sleep for n seconds.
PlanarStrategyTools.livesleep — Method
Sleep function for a simulation strategy.
livesleep(s::PlanarCore.Strategies.SimStrategy, _)
Does nothing for the simulation strategy s.
PlanarStrategyTools.log — Method
Log function for a strategy.
log(s::PlanarCore.Strategies.RTStrategy, f, args...)
Logs the function f with its arguments args for the strategy s.
PlanarStrategyTools.log — Method
Log function for a simulation strategy.
log(s::PlanarCore.Strategies.SimStrategy, f, args...)
Logs the function f with its arguments args for the simulation strategy s.
PlanarStrategyTools.rateab — Method
Calculates the rate of change of a property of a signal state.
rateab(sig, a, b) -> Tuple{Any, Any}
PlanarStrategyTools.select_orderkwargs — Method
Select additional keyword arguments for Buy orders based on order type
select_orderkwargs(
otsym::Symbol,
::Type{PlanarCore.OrderTypes.Buy},
ii,
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.
PlanarStrategyTools.select_orderkwargs — Method
Selects an order type based on the strategy, order side, and position side
select_orderkwargs(
otsym::Symbol,
::Type{PlanarCore.OrderTypes.Sell},
ii,
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.
PlanarStrategyTools.select_ordertype — Function
Selects an order type based on the strategy, order side, and position side
select_ordertype(
s::PlanarCore.Strategies.Strategy,
os::Type{<:PlanarCore.OrderTypes.OrderSide};
...
) -> Tuple{Type, Any}
select_ordertype(
s::PlanarCore.Strategies.Strategy,
os::Type{<:PlanarCore.OrderTypes.OrderSide},
p::PlanarCore.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.
PlanarStrategyTools.signal_value — Method
Dispatch on typeof(sig.state)
PlanarStrategyTools.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.
PlanarStrategyTools.signals! — Method
Update signals for a strategy.
signals!(
s::PlanarCore.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.
PlanarStrategyTools.signals! — Method
Update signals for a strategy.
signals!(
s::PlanarCore.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.
PlanarStrategyTools.signals — Method
Create multiple signal definitions and instantiate a new Signals17 object.
signals(
signals,
timeframes,
count,
params
) -> PlanarStrategyTools.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.
PlanarStrategyTools.track_expectancy! — Method
Calculates the win rate and profit/loss thresholds for a trading strategy.
track_expectancy!(s, ii) -> Any
Updates s[:profit_thresh] and s[:loss_thresh] based on the trading results.
PlanarStrategyTools.trackcd! — Method
Updates the cooldown period for an asset instance in the strategy.
trackcd!(s, ii, ats, ts) -> Any
The function calculates the cooldown period for the asset instance ii in the strategy s at the current timestamp ts.
PlanarStrategyTools.tracklev! — Method
Adjusts the leverage for an asset based on the Kelly criterion.
tracklev!(
s,
ii,
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.
PlanarStrategyTools.trackpnl! — Method
Records the profit and loss (PnL) for a given asset instance at a specific timestamp.
trackpnl!(s, ii, ats, ts; interval, pnl_func) -> Any
The PnL is calculated based on the position side and the closing price at the given timestamp.
PlanarStrategyTools.trackqt! — Method
Tracks the target quantity of an asset over time for trading strategy s.
trackqt!(s, ii, ats; f) -> Any
The quantity is determined by the function f and is adjusted based on the asset ii and timestamp ats.
PlanarStrategyTools.update_data! — Method
Update or initialize mutable data related to asset information.
update_data!(ii, tf) -> DataFrames.DataFrame
This function acquires or creates a data frame for the ii 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.
PlanarStrategyTools.update_signal! — Method
Update signal
update_signal!(ii, ats, ai_signals, sig_name; tf, count)
Updates the signal sig_name for asset ii based on new data up to timestamp ats. Uses a lookback window of count timeframes tf.
PlanarStrategyTools.waitohlcv — Method
Waits for OHLCV data to update up to a specified time.
waitohlcv(s, since; interval, timeout)
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.
See Also
- Strategy Development - Guide: Strategy development and implementation
- Optimization - Strategy development and implementation