# Trade Simulation

Reference for the trade/strategy simulation tool. To import:

```python
from marketquant.strategysimulator import TradeEngine
```

***

### Trade Simulation Setup and Trade Engine Initialization

The core class of the simulation is `TradingEngine`. This is responsible for initializing the simulation parameters such as data provider, ticker symbol, date ranges, candle aggregation, balance, and shares.

**TradingEngine Constructor Arguments:**

<table data-header-hidden><thead><tr><th width="252"></th><th width="114"></th><th width="218"></th><th></th></tr></thead><tbody><tr><td><strong>Argument</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td><td><strong>Default</strong></td></tr><tr><td><code>data_provider</code></td><td><code>str</code></td><td>The data provider to be used for fetching historical stock data (e.g., <code>yahoo</code>, <code>schwab</code>).</td><td><code>yahoo</code></td></tr><tr><td><code>ticker</code></td><td><code>str</code></td><td>The stock ticker to simulate trades on (e.g., <code>AAPL</code>, <code>SPY</code>).</td><td><code>AAPL</code></td></tr><tr><td><code>start_date</code></td><td><code>str</code></td><td>The starting date of the trade simulation in <code>YYYY-MM-DD</code> format.</td><td><code>"2023-01-01"</code></td></tr><tr><td><code>end_date</code></td><td><code>str</code></td><td>The end date of the simulation in <code>YYYY-MM-DD</code> format.</td><td><code>"2024-08-01"</code></td></tr><tr><td><code>candle_aggregation</code></td><td><code>str</code></td><td>The time interval for stock candles (<code>1d</code>, <code>1h</code>, etc.).</td><td><code>"1d"</code></td></tr><tr><td><code>starting_balance</code></td><td><code>float</code></td><td>The initial capital (cash balance) available for the trading simulation.</td><td><code>100000</code></td></tr><tr><td><code>shares</code></td><td><code>int</code></td><td>The number of shares to be traded per buy/sell order.</td><td><code>10</code></td></tr><tr><td><code>print_tradehistory</code></td><td><code>bool</code></td><td>Whether to print the trade history at the end of the simulation.</td><td><code>False</code></td></tr><tr><td><code>print_pnl</code></td><td><code>bool</code></td><td>Whether to print the profit and loss (P&#x26;L) summary at the end.</td><td><code>True</code></td></tr><tr><td><code>print_balance</code></td><td><code>bool</code></td><td>Whether to print the account balance (buy, sell, short, cover).</td><td><code>True</code></td></tr><tr><td><code>print_buypower</code></td><td><code>bool</code></td><td>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.</td><td><code>True</code></td></tr><tr><td><code>print_unrealizedpnl</code></td><td><code>bool</code></td><td>Whether to print unrealized profit and loss during open positions after strategy has been ran.</td><td><code>True</code></td></tr><tr><td><code>print_timecomplexity</code></td><td><code>bool</code></td><td>Whether to print the time complexity of the input data during execution.</td><td><code>True</code></td></tr><tr><td><code>chart</code></td><td><code>bool</code></td><td>Whether to display a chart of stock prices and the trading strategy execution (e.g., buy/sell markers, profit/loss chart).</td><td><code>True</code></td></tr></tbody></table>

Example *TradeEngine* Setup:

```python
from marketquant.strategy_simulator import TradingEngine

engine = TradingEngine(
    data_provider="yahoo",
    ticker="SPY",
    start_date="2023-01-01",
    end_date="2024-08-01",
    candle_aggregation="1d",
    starting_balance=100000,
    shares=100,
    print_tradehistory=False,
    print_pnl=True,
    print_balance=True,
    print_buypower=True,
    print_unrealizedpnl=True,
    print_timecomplexity=True,
    chart=True
)
```

***

## Placing Trades and Managing Positions

In the trade simulation engine, managing positions is critical for executing your trading strategy. The `TradingEngine` uses an internal `AccountManager` to handle all trade-related actions. You can initiate or close positions by using predefined methods such as `buy()`, `sell()`, `short()`, and `cover()`. These methods allow you to manage both long and short positions dynamically during your strategy execution.

Below is a detailed guide on how to place trades and manage positions.

***

## Managing Trades

The following methods are crucial for managing positions within a strategy. Each method can be called when certain market conditions or indicators (like MACD, RSI, etc.) meet specific criteria.

**1. `buy(date, price, shares)`**

* **Action**: Initiates or adds to a **long position** by buying shares.
* **Usage**: Use this when your strategy indicates a buy signal, such as a bullish crossover of a technical indicator.
* **Parameters**:
  * `date` (str): The date of the trade.
  * `price` (float): The price at which the shares are being bought.
  * `shares` (int): The number of shares to purchase.

**Example:**

```python
pythonCopy code# Buy signal detected in strategy
if macd > signal:
    price = data['Close'][i]
    self.trading_engine.simulator.buy(date, price, self.trading_engine.shares)
```

***

**2. `sell(date, price, shares)`**

* **Action**: Closes a **long position** by selling previously purchased shares.
* **Usage**: Use this when your strategy indicates a sell signal, such as a bearish crossover.
* **Parameters**:
  * `date` (str): The date of the trade.
  * `price` (float): The price at which the shares are being sold.
  * `shares` (int): The number of shares to sell.

**Example:**

```python
# Sell signal detected in strategy
if macd < signal:
    price = data['Close'][i]
    self.trading_engine.simulator.sell(date, price, self.trading_engine.shares)
```

***

**3. `short(date, price, shares)`**

* **Action**: Initiates or adds to a **short position** by borrowing and selling shares.
* **Usage**: Use this when your strategy indicates a short signal, such as when you anticipate the stock price will drop.
* **Parameters**:
  * `date` (str): The date of the trade.
  * `price` (float): The price at which the shares are being shorted.
  * `shares` (int): The number of shares to short.

**Example:**

```python
# Short signal detected in strategy
if macd < signal:
    price = data['Close'][i]
    self.trading_engine.simulator.short(date, price, self.trading_engine.shares)
```

***

\
**4. `cover(date, price, shares)`**

* **Action**: Closes a **short position** by buying back previously shorted shares.
* **Usage**: Use this when your strategy indicates the stock price is likely to increase, and you need to close the short position to lock in profits or avoid further losses.
* **Parameters**:
  * `date` (str): The date of the trade.
  * `price` (float): The price at which the shares are being bought back to cover the short.
  * `shares` (int): The number of shares to cover.

**Example:**

```python
# Cover signal detected in strategy
if macd > signal:
    price = data['Close'][i]
    self.trading_engine.simulator.cover(date, price, self.trading_engine.shares)
```

***

#### **General Flow of a Strategy Using These Methods**

In most strategies, these trade management methods are triggered based on conditions determined by technical indicators or price action. Here's a typical flow:

1. **Indicator Calculation**: Indicators like MACD, RSI, or moving averages are calculated.
2. **Condition Evaluation**: If the indicator meets the criteria (e.g., MACD crosses above the signal), the strategy calls the relevant trade method.
3. **Executing the Trade**: Depending on the conditions, the `buy()`, `sell()`, `short()`, or `cover()` the method is executed, and the position is adjusted accordingly.
4. **Position Management**: The `AccountManager` tracks the position, P\&L, and buying power.

***

#### **Additional Notes:**

* You can call these methods multiple times to scale positions or gradually close positions.
* It's important to track the current position to avoid over-exposing your account to risk.
* **Position Tracking**: Each method updates the `positions` attribute within the `AccountManager`, allowing you to track the status of each trade and the overall portfolio.

By understanding and utilizing these trade management methods, you can effectively simulate real-world trading strategies and optimize performance.\ <br>

***

## Use Case Notes

Users are not limited to the tools within the library. You may use any strategy where you can systematically define a buy/sell or short/cover strategy. The indicators and strategies  `demo_examples` are demos and aren't meant for real use, nor should they be used in the real world. *This tool gives you the ability to simulate and backtest strategies.*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://market-quant.gitbook.io/home/api-reference/trade-simulation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
