R/doc_Processor.R

# Copyright (C) 2016-2018 Stanislav Kovalevsky
#
# This file is part of QuantTools.
#
# QuantTools is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# QuantTools is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with QuantTools. If not, see <http://www.gnu.org/licenses/>.

#' @title C++ Processor class
#' @description C++ class documentation
#' @section Usage: \code{Processor( int timeFrame, double latencySend, double latencyReceive )}
#' @param timeFrame candle timeframe in seconds
#' @param latencySend,latencyReceive latency in seconds
#' @family backtesting classes
#' @family C++ classes
#'
#' @section Public Members and Methods:
#' \tabular{lll}{
#'  \strong{Name}                           \tab \strong{Return Type}       \tab \strong{Description}               \cr
#'  \code{onCandle( \link{Candle} candle )} \tab \code{std::function}       \tab called on new candle event         \cr
#'  \code{onTick( \link{Tick} tick )}       \tab \code{std::function}       \tab called on new tick event           \cr
#'  \code{onMarketOpen()}                   \tab \code{std::function}       \tab called on trading hours start      \cr
#'  \code{onMarketClose()}                  \tab \code{std::function}       \tab called on trading hours end        \cr
#'  \code{onIntervalOpen()}                 \tab \code{std::function}       \tab called on intervals start          \cr
#'  \code{onIntervalClose()}                \tab \code{std::function}       \tab called on intervals end            \cr
#'  \code{Feed( \link{Tick} tick )}         \tab \code{void}                \tab process by individual tick         \cr
#'  \code{Feed( Rcpp::DataFrame ticks )}    \tab \code{void}                \tab batch process, see 'Ticks' section \cr
#'  \code{SendOrder( \link{Order}* order )} \tab \code{void}                \tab send order to exchange             \cr
#'
#'  \code{SetCost( \link{Cost} cost )}      \tab \code{void}                \tab set trading costs                  \cr
#'  \code{SetCost( Rcpp::List cost )}       \tab \code{void}                \tab see 'cost' in 'Options' section    \cr
#'  \code{SetStop( Rcpp::List stop )}       \tab \code{void}                \tab see 'stop' in 'Options' section    \cr
#'  \code{SetStartTradingTime( double t )}  \tab \code{void}                \tab see 'trade_start' in 'Options' section     \cr
#'  \code{SetLatencyReceive( double x )}    \tab \code{void}                \tab see 'latency_receive' in 'Options' section \cr
#'  \code{SetLatencySend( double x )}       \tab \code{void}                \tab see 'latency_send' in 'Options' section    \cr
#'  \code{SetLatency( double x )}           \tab \code{void}                \tab see 'latency' in 'Options' section \cr
#'  \code{SetTradingHours( double start, double end )}
#'                                          \tab \code{void}                \tab see 'trading_hours' in 'Options' section  \cr
#'  \code{SetPriceStep( double priceStep )} \tab \code{void}                \tab see 'price_step' in 'Options' section     \cr
#'  \code{SetExecutionType( ExecutionType executionType )}
#'                                          \tab \code{void}                \tab see 'execution_type' in 'Options' section \cr
#'  \code{SetExecutionType( std::string executionType )}
#'                                          \tab \code{void}                \tab see 'execution_type' in 'Options' section \cr
#'  \code{SetIntervals( std::vector<double> starts, std::vector<double> ends )}
#'                                          \tab \code{void}                \tab see 'intervals' in 'Options' section                                \cr
#'  \code{AllowLimitToHitMarket()}          \tab \code{void}                \tab see 'allow_limit_to_hit_market' in 'Options' section                \cr
#'  \code{AllowExactStop()}                 \tab \code{void}                \tab see 'allow_exact_stop' in 'Options' section                         \cr
#'  \code{SetOptions( Rcpp::List options )} \tab \code{void}                \tab see 'Options' section                                               \cr
#'  \code{StopTrading()}                    \tab \code{void}                \tab if called trading stop triggered. See 'stop' in 'Options' section   \cr
#'  \code{CanTrade()}                       \tab \code{bool}                \tab check if trading not stopped                                        \cr
#'  \code{IsTradingHoursSet()}              \tab \code{bool}                \tab check if trading hours set                                          \cr
#'  \code{CancelOrders()}                   \tab \code{void}                \tab cancel active orders                                                \cr
#'  \code{GetCandle()}                      \tab \code{Candle}              \tab get current candle                                                  \cr
#'  \code{GetPosition()}                    \tab \code{int}                 \tab total executed position, positive means long, negative means short  \cr
#'  \code{GetPositionPlanned()}             \tab \code{int}                 \tab total number of orders processing ( not executed or cancelled yet ) \cr
#'  \code{GetMarketValue()}                 \tab \code{double}              \tab total portfolio percent value ( initial value is 0 )                \cr
#'  \code{GetCandles()}                     \tab \code{Rcpp::List}          \tab candles history, see 'Candles' section                              \cr
#'  \code{GetOrders()}                      \tab \code{Rcpp::List}          \tab orders history, see 'Orders' section                                \cr
#'  \code{GetTrades()}                      \tab \code{Rcpp::List}          \tab trades history, see 'Trades' section                                \cr
#'  \code{GetSummary()}                     \tab \code{Rcpp::List}          \tab trades summary, see 'Summary' section                               \cr
#'  \code{GetOnCandleMarketValueHistory()}  \tab \code{std::vector<double>} \tab vector of portfolio value history recalculated on candle complete   \cr
#'  \code{GetOnCandleDrawDownHistory()}     \tab \code{std::vector<double>} \tab vector of portfolio drawdown history recalculated on candle complete\cr
#'  \code{GetOnDayClosePerformanceHistory()}\tab \code{Rcpp::List}          \tab daily performance history, see 'Daily Performance' section          \cr
#'  \code{Reset()}                          \tab \code{void}                \tab resets to initial state
#' }
#' @example /inst/examples/sma_crossover.R
#' @example /inst/examples/bbands.R
#' @example /inst/examples/bbands_market_maker.R
#' @section Execution Model:
#' System sends new order and after \code{latencySend} seconds it reaches exchange.
#' System receives confirmation of order placement \code{latencyReceive} seconds later.
#' When execution conditions met on exchange - order is executed and system receives
#' execution confirmation \code{latencyReceive} seconds later.\cr
#' When system sends cancel request to exchange and after \code{latencySend} seconds
#' when exchange receives cancel request if order is not executed yet it is cancelled and
#' cancellation confirmation is received by system after \code{latencyReceive} seconds.\cr
#' Two execution types supported \code{trade}(default) and \code{bbo}.
#' \code{trade} type processes orders using tick \code{price}s and \code{bbo} processes orders using preceding tick \code{bid} and \code{ask} values.
#' Market orders in \code{bbo} mode executed at worst price: at \code{bid} for sells and at \code{ask} for buys, in \code{trade} mode at current tick \code{price}.
#' Buy limit orders executed when \code{ask} goes under order price and sell orders executed when \code{bid} goes above order price.
#' In case limit order is placed in the market it is executed as market order if \code{allow_limit_to_hit_market} set to \code{TRUE} (default is \code{FALSE}).\cr
#'
#' @section Ticks:
#' Ticks must be a data.frame/data.table with at least the following columns:
#' \tabular{ll}{
#'  \strong{Name} \tab \strong{Description} \cr
#'  time          \tab time                 \cr
#'  price         \tab price                \cr
#'  volume        \tab volume
#' }
#' tick id is ticks row number.
#' @section Candles:
#' Candles returned as data.table with the following columns:
#' \tabular{ll}{
#'  \strong{Name} \tab \strong{Description} \cr
#'  time          \tab time when formed     \cr
#'  open          \tab first tick price     \cr
#'  high          \tab maximum tick price   \cr
#'  low           \tab minimum tick price   \cr
#'  close         \tab last tick price      \cr
#'  volume        \tab total volume traded  \cr
#'  id            \tab tick id when formed ( first tick after time formed )
#' }
#' @section Orders:
#' Orders returned as data.table with the following columns:
#' \tabular{ll}{
#'  \strong{Name}  \tab \strong{Description}                                                            \cr
#'  id_trade       \tab trade id                                                                        \cr
#'  id_sent        \tab tick id when order was sent to exchange                                         \cr
#'  id_processed   \tab tick id when enter order execution or cancelled confirmation was received ( first tick after \code{time_processed} ) \cr
#'  time_sent      \tab time when order was sent to exchange                                            \cr
#'  time_processed \tab time when order execution or cancelled confirmation was received                \cr
#'  price_init     \tab initial price                                                                   \cr
#'  price_exec     \tab execution price                                                                 \cr
#'  side           \tab \code{buy}/\code{sell}                                                          \cr
#'  type           \tab \code{limit}/\code{market}/\code{stop}/\code{trail}                             \cr
#'  state          \tab \code{new}/\code{registered}/\code{executed}/\code{cancelling}/\code{cancelled} \cr
#'  comment        \tab comment
#' }
#' @section Trades:
#' Two orders are combined into trade by trade id. The first and the second orders are called enter and exit respectively. \cr
#' Trade side is long if enter order is buy and short if enter order is sell. \cr
#' Orders must be buy and sell only. Two buys or two sells not allowed. Trade can be \cr
#' \itemize{
#'   \item \code{new} when order to open trade is just placed
#'   \item \code{opened} when trade is not closed yet
#'   \item \code{closed} when trade is flat. \cr
#' }
#' Trades returned as data.table with the following columns:
#' \tabular{ll}{
#'  \strong{Name} \tab \strong{Description}                                      \cr
#'  id_trade      \tab trade id                                                  \cr
#'  id_sent       \tab tick id when enter order was sent to exchange             \cr
#'  id_enter      \tab tick id when enter order execution confirmation was received ( first tick after enter \code{time_executed} ) \cr
#'  id_exit       \tab tick id when exit order execution confirmation was received ( first tick after exit \code{time_executed} )   \cr
#'  time_sent     \tab time when enter order sent to exchange                    \cr
#'  time_enter    \tab time when enter order execution confirmation was received \cr
#'  time_exit     \tab time when exit order execution confirmation was received  \cr
#'  side          \tab side \code{long}/\code{short}                             \cr
#'  price_enter   \tab enter order execution price                               \cr
#'  price_exit    \tab exit order execution price                                \cr
#'  pnl           \tab trade pnl net                                             \cr
#'  mtm           \tab mark-to-market                                            \cr
#'  mtm_min       \tab min mark-to-market                                        \cr
#'  mtm_max       \tab max mark-to-market                                        \cr
#'  cost          \tab absolute trading cost                                     \cr
#'  pnl_rel       \tab trade pnl net in basis points                             \cr
#'  mtm_rel       \tab mark-to-market in basis points                            \cr
#'  mtm_min_rel   \tab min mark-to-market in basis points                        \cr
#'  mtm_max_rel   \tab max mark-to-market in basis points                        \cr
#'  cost_rel      \tab relative trading cost in basis points                     \cr
#'  state         \tab \code{new}/\code{opened}/\code{closed}
#' }
#' @section Summary:
#' Back test summary statistics:
#' \tabular{ll}{
#'  \strong{Name} \tab \strong{Description}                                              \cr
#'  from          \tab first tick time                                                   \cr
#'  to            \tab last tick time                                                    \cr
#'  days_tested   \tab number of trading days tested                                     \cr
#'  days_traded   \tab number of trading days traded ( at least one order was executed ) \cr
#'  n_per_day     \tab number of trades per day                                          \cr
#'  n             \tab number of trades                                                  \cr
#'  n_long        \tab number of long trades                                             \cr
#'  n_short       \tab number of short trades                                            \cr
#'  n_win         \tab number of winning trades                                          \cr
#'  n_loss        \tab number of loosing trades                                          \cr
#'  pct_win       \tab percent of winning trades                                         \cr
#'  pct_loss      \tab percent of loosing trades                                         \cr
#'  avg_win       \tab average winning trade in basis points                             \cr
#'  avg_loss      \tab average loosing trade in basis points                             \cr
#'  avg_pnl       \tab average trade pnl in basis points                                 \cr
#'  win           \tab total won in percent                                              \cr
#'  loss          \tab total lost in percent                                             \cr
#'  pnl           \tab total pnl in percent                                              \cr
#'  max_dd        \tab maximum drawdown in percent                                       \cr
#'  max_dd_start  \tab time the maximum drawdown started                                 \cr
#'  max_dd_end    \tab time the maximum drawdown recovered                               \cr
#'  max_dd_length \tab number of calendar days in the maximum drawdown period            \cr
#'  sharpe        \tab annualized Sharpe ratio calulated on daily returns                \cr
#'  sortino       \tab annualized Sortino ratio calulated on daily returns               \cr
#'  r_squared     \tab R Squared calulated on daily PnL values                           \cr
#'  avg_dd        \tab average drawdown calulated on daily drawdown history
#' }
#'
#' @section Daily Performance:
#' Back test daily performance history:
#' \tabular{ll}{
#'  \strong{Name} \tab \strong{Description}    \cr
#'  date          \tab date                    \cr
#'  return        \tab return                  \cr
#'  pnl           \tab cumulative pnl          \cr
#'  drawdown      \tab drawdown                \cr
#'  n_per_day     \tab number of closed trades \cr
#'  avg_pnl       \tab average trade pnl
#' }
#'
#' @section Options:
#' List of following elements. All options are optional.
#' \describe{
#'  \item{\strong{cost}}{
#'    list or data.table with items identical to \link{Cost} C++ class.
#'    \cr E.g. if set to \code{ data.table( tradeAbs = -0.01, shortRel = -0.05 / 360 ) } means you pay -$0.01 per executed
#'    order and -5\% p.a. overnight short.
#'  }
#'  \item{\strong{stop}}{
#'    list or data.table with at least one item:
#'    \describe{
#'      \item{drawdown}{
#'        Trading stops when drawdown exceeds set value. E.g. if set to -0.02 then when drawdown exceeds 2\% trading stops.
#'      }
#'      \item{loss}{
#'        Trading stops when market value (P&L) is lower set value. E.g. if set to -0.05 then when market value (P&L) is lower than -5\% trading stops.
#'      }
#'      If stop rule triggered no orders sent to exchange and opened trades closed by market orders.
#'    }
#'  }
#'  \item{\strong{trade_start}}{
#'    POSIXct timestamp. All orders ignored until specified time. Useful to 'warm-up' strategy.
#'  }
#'  \item{\strong{latency_send, latency_receive, latency}}{
#'    numeric value. Latency can be set by send/receive or overall. 'latency' sets send and receive latency as \code{x / 2}. See 'Execution Model' section.
#'  }
#'  \item{\strong{trading_hours}}{
#'    numeric vector of length two. Sets trading hours start and end according to formula:\cr \code{hours + minutes / 60 + seconds / 3600}. \cr If set \code{onMarketOpen}, \code{onMarketClose} events are executed at corresponding times.
#'    \cr E.g. if set to \code{c( 10.25, 17.5 )} means \code{onMarketOpen} event called every day at '10:15' and \code{onMarketClose} event called every day at '17:30'.
#'    \cr For convenience \code{IsTradingHoursSet()} method can be used to check wether trading hours are set.
#'
#'  }
#'  \item{\strong{allow_limit_to_hit_market}}{
#'    if TRUE, limit order execution price set to market price if executed on same tick as registered.
#'  }
#'  \item{\strong{allow_exact_stop}}{
#'    if TRUE, stop order executed at set price.
#'  }
#'  \item{\strong{price_step}}{
#'    if positive, limit order init price rounded to \code{price_step} down for buy orders and up for sell orders before placement.
#'    if negative, limit order init price rounded to \code{price_step} up for buy orders and down for sell orders before placement.
#'  }
#'  \item{\strong{execution_type}}{
#'    \code{trade} or \code{bbo}.
#'  }
#'  \item{\strong{intervals}}{
#'    sorted multi row data.table with POSIXct timestamps columns \code{start, end}. Represents time intervals. At time start \code{onIntervalOpen} called and at time end \code{onIntervalClose} called.
#'  }
#'
#' }
#' @name Processor
#' @rdname cpp_Processor
NULL

Try the QuantTools package in your browser

Any scripts or data that you put into this service are public.

QuantTools documentation built on Oct. 23, 2020, 7:54 p.m.