Examples
Adding more examples periodically
Below is a simple MACD Crossover strategy script:
Purpose: This section is specifically designed for users to define and customize their trading strategy. It is separated from the critical initialization and result-handling sections to allow for easy modification of the strategy logic without affecting the overall structure.
Purpose: This line starts a
try
block, which is used to catch and handle exceptions that may occur during the execution of the strategy. If an error occurs, it will be caught by the correspondingexcept
block, allowing for graceful error handling and logging.
Purpose: The
interval
variable defines the time frame for the data that will be used in the strategy. In this case, it is set to "1h", meaning the strategy will use hourly data. This can be adjusted to other intervals like "1m" (minute), "1d" (daily), etc., depending on the user's needs.
Purpose: This block executes the MACD command to calculate the MACD, signal, and histogram values over the specified date range:
macd_command
Initialization: AMACDCommand
object is created using the start and end dates retrieved from thecontext
.execute()
Method: Theexecute
method of theMACDCommand
is called, which calculates and returns the MACD data (a DataFrame containing the MACD line, signal line, and histogram).macd_data
: The resulting MACD data is stored inmacd_data
, which will be used later to determine trading signals.
Purpose: This block retrieves the OHLC (Open, High, Low, Close) data for the specified time interval and date range:
ohlc_data
Retrieval: Theget_data
method of thedata_provider
is called, retrieving OHLC data for the given date range and interval.Data Validation: A check is performed to ensure that
ohlc_data
is notNone
and that the 'Close' column exists. If the data is missing or incomplete, an error is logged, and aValueError
is raised to halt the strategy execution.
Purpose: This block initializes the
TradeSimulation
class and sets a flag to track open positions:simulation
Initialization: ATradeSimulation
object is created, which will be used to simulate buying and selling actions within the strategy.position_open
Flag: This boolean flag is set toFalse
, indicating that no position is currently open at the start of the strategy execution.
Purpose: This block iterates over the MACD data to simulate trades based on the MACD crossover strategy:
Looping Over MACD Data: The loop starts from index 1 and iterates through the MACD data.
Extracting Values: For each iteration:
macd_value
andsignal_value
are the current MACD and signal line values.previous_macd_value
andprevious_signal_value
are the MACD and signal line values from the previous period.close_price
is the closing price from the OHLC data at the current period.trade_date
is the corresponding date for the current period.
Purpose: This block checks for a buy signal based on the MACD crossover:
Buy Condition: The strategy looks for the MACD line to cross above the signal line (i.e.,
macd_value > signal_value
andprevious_macd_value <= previous_signal_value
) and ensures no position is currently open (not position_open
).Executing Buy Order: If the condition is met, a
buy
order is placed using theTradeSimulation
object, buying 10 units of the ticker at the current closing price and date.Update Position Flag: The
position_open
flag is set toTrue
, indicating that a position has been opened.
Purpose: This block checks for a sell signal based on the MACD crossover:
Sell Condition: The strategy looks for the MACD line to cross below the signal line (i.e.,
macd_value < signal_value
andprevious_macd_value >= previous_signal_value
) and ensures a position is currently open (position_open
).Executing Sell Order: If the condition is met, a
sell
order is placed using theTradeSimulation
object, selling 10 units of the ticker at the current closing price and date.Update Position Flag: The
position_open
flag is set toFalse
, indicating that the position has been closed.
Purpose: This block calculates the final profit/loss (P/L) for the strategy:
Retrieve Current Price: The current price of the ticker is fetched using the
get_current_price
method of thedata_provider
.Price Validation: A check ensures that the current price is not
None
. If it is, an error is logged, and aValueError
is raised to halt the strategy.Calculate P/L: The
calculate_pl
method of theTradeSimulation
object is called to calculate the final P/L based on the current prices.Log P/L: The final P/L is logged for the user’s reference.
Purpose: This block handles any exceptions that occur during the strategy execution:
Error Logging: If an exception is raised within the
try
block, it is caught here, and the error message is logged, specifying the error that occurred.
Purpose: Marks the end of the user-defined section, indicating that all strategy-specific code should be placed between the start and end markers of this section.
Last updated