# EDUCATIONAL TESTER EXAMPLE — one symbol, initially flat; not for live trading.
# First bullish candle: attempt a 0.01 market buy. First later bearish candle:
# attempt to close the whole position. At most one entry and one exit request.
# Acceptance is not a fill; errors stop the example. No retries, restart recovery,
# position reconciliation or risk controls. Choose valid size/funds in Studio.
# GETTING STARTED
# 1. Open Data and download candles for an exchange, market, and symbol.
# 2. Press F5 inside a project: the XTester engine runs this file with Rscript over the
#    project's candles, executing orders, fees and balances itself; this file only decides.
#    R must be installed (https://cloud.r-project.org); the R pack adds jsonlite and the language server.
# 3. Add your decisions in on_bar. context$api places orders (buy, sell, place_order,
#    close_position); context$indicators reads the engine's indicators (rsi, sma, ema,
#    call("ADX", list(period = 14))); context$logger writes to the strategy log.
# Ask the AI assistant to explain this file.
create_strategy <- function() {
  state <- new.env()
  state$phase <- 0L
  list(
    on_init = function(context) {
      context$logger$info(paste("UserStrategy initialized:", xtester_symbol_text(context$parameters$symbol_key)))
    },
    on_tick = function(context, price) {
    },
    on_bar = function(context, symbol_key, bar) {
      if (state$phase == 0L && bar$close > bar$open) {
        result <- context$api$buy("0.01")
        state$phase <- if (result$success) 1L else 2L
        if (!result$success) context$logger$info(result$error_message)
      } else if (state$phase == 1L && bar$close < bar$open) {
        result <- context$api$close_position()
        state$phase <- 2L
        if (!result$success) context$logger$info(result$error_message)
      }
    },
    on_finish = function(context) {
    }
  )
}
