> For the complete documentation index, see [llms.txt](https://market-quant.gitbook.io/home/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://market-quant.gitbook.io/home/api-reference/trade-simulation/trade-simulation-example.md).

# Trade Simulation Example

Below you will find how to set up a strategy using an example foun in the demo\_examples folder.

### Strategy Setup w/ Example Strategy

Once the `TradingEngine` is initialized, you can apply a trading strategy to it. In this example, we use a `MACDStrategy` to simulate trades based on the Moving Average Convergence Divergence (MACD) indicator.

Code for the MACDstrategy, located in `demo_examples/strategies` :

```python
class MACDStrategy:
    def __init__(self, trading_engine, macd_params=None):
        self.trading_engine = trading_engine
        self.macd_params = macd_params if macd_params else {}
        self.macd_indicator = MACDIndicator(**self.macd_params)

    def apply_strategy(self):
        # Fetches data from the engine
        data = self.trading_engine.data_engine.fetch_data()

        # Calculates the MACD and signal using the indicator class
        data = self.macd_indicator.calculate(data)

        for i in range(1, len(data)):
            date = data['Date'][i]
            macd = data['MACD'][i]
            signal = data['Signal'][i]
            previous_macd = data['MACD'][i - 1]
            previous_signal = data['Signal'][i - 1]

            # Checks for cover signal (MACD crosses above signal line) to close the short
            if previous_macd <= previous_signal and macd > signal:
                price = data['Close'][i]
                # If in a short position, cover it
                if self.trading_engine.simulator.account_manager.positions.get('long', {}).get('quantity', 0) > 0:
                    self.trading_engine.simulator.sell(date, price, self.trading_engine.shares)

            # Checks for short signal (MACD crosses below signal line)
            elif previous_macd >= previous_signal and macd < signal:
                price = data['Close'][i]
                # Short the stock
                self.trading_engine.simulator.buy(date, price, self.trading_engine.shares)
```

**MACD Strategy Constructor Arguments:**

| **Argument**      | **Type**        | **Description**                               |
| ----------------- | --------------- | --------------------------------------------- |
| `engine`          | `TradingEngine` | The initialized trading engine instance.      |
| `macd_params`     | `dict`          | Dictionary containing the MACD parameters:    |
| - `short_period`  | `int`           | The short-period EMA (typically 12 periods).  |
| - `long_period`   | `int`           | The long-period EMA (typically 26 periods).   |
| - `signal_period` | `int`           | The signal line period (typically 9 periods). |

**Example Usage**:

```python
from strategies.macd_strategy import MACDStrategy

macd_strategy = MACDStrategy(
    engine=engine,
    macd_params={
        "short_period": 12,
        "long_period": 26,
        "signal_period": 9
    }
)
```

This sets up the MACD strategy using the specified MACD parameters and links it to the previously initialized `TradingEngine`.

#### Applying the Strategy:

*To apply the strategy, you need to add the following command to your script:*

```
macd_strategy.apply_strategy()
```

\
*Full implementation example:*

<pre class="language-python"><code class="lang-python">from marketquant.strategy_simulator import TradingEngine
from strategies.macd_strategy import MACDStrategy

def main():

    # User Note: Initialize the trading core with your params for data_provider, ticker, start_date, end_date,
    # candle_aggregation, starting_balance, and shares below.
    engine = TradingEngine(
        <a data-footnote-ref href="#user-content-fn-1">data_provider</a>="yahoo",
        <a data-footnote-ref href="#user-content-fn-2">ticker</a>="SPY",
        <a data-footnote-ref href="#user-content-fn-3">start_date</a>="2023-01-01",
<strong>        <a data-footnote-ref href="#user-content-fn-4">end_date</a>="2024-08-01",
</strong>        <a data-footnote-ref href="#user-content-fn-5">candle_aggregation</a>="1d",
<strong>        <a data-footnote-ref href="#user-content-fn-6">starting_balance</a>=100000,
</strong>        <a data-footnote-ref href="#user-content-fn-7">shares</a>=100,
        <a data-footnote-ref href="#user-content-fn-8">print_tradehistory</a>=False,
        <a data-footnote-ref href="#user-content-fn-9">print_pnl</a>=True,
        <a data-footnote-ref href="#user-content-fn-10">print_balance</a>=True,
        <a data-footnote-ref href="#user-content-fn-11">print_buypower</a>=True,
        <a data-footnote-ref href="#user-content-fn-12">print_unrealizedpnl</a>=True,
        <a data-footnote-ref href="#user-content-fn-13">print_timecomplexity</a>=True,
        <a data-footnote-ref href="#user-content-fn-14">chart</a>=True
    )

    # User Note: Initializes the MACD strategy with the trading engine and MACD parameters
    macd_strategy = MACDStrategy(engine, macd_params={
        "short_period": 12,
        "long_period": 26,
        "signal_period": 9
    })

    macd_strategy.apply_strategy()

    # Example: This prints the results of the enabled outputs
    engine.print_results()

if __name__ == "__main__":
    main()
</code></pre>

[^1]: The data provider to be used for fetching historical stock data (e.g., `yahoo`, `schwab`).

[^2]: The stock ticker to simulate trades on (e.g., `AAPL`, `SPY`).

[^3]: The starting date of the trade simulation in `YYYY-MM-DD` format.

[^4]: The end date of the simulation in `YYYY-MM-DD` format.

[^5]: The time interval for stock candles (`1d`, `1h`, etc.).

[^6]: The initial capital (cash balance) available for the trading simulation.

[^7]: The number of shares to be traded per buy/sell order.

[^8]: Whether to print the trade history at the end of the simulation.

[^9]: Whether to print the profit and loss (P\&L) summary at the end.

[^10]: Whether to print the account balance (buy, sell, short, cover).

[^11]: Whether to print the remaining buying power (cash available). This is useful to see your buying power at the end if you are still in a trade with an unrealized return.

[^12]: Whether to print unrealized profit and loss during open positions after strategy has been ran.

[^13]: Whether to print the time complexity of the input data during execution.

[^14]: Whether to display a chart of stock prices and the trading strategy execution (e.g., buy/sell markers, profit/loss chart).
