# Debugger

The strategy debugger helps you understand exactly what your strategy is doing at every step. Instead of guessing why your strategy makes certain trading decisions, you can **pause execution**, **inspect variables**, and **step through your code line by line** to see exactly how your strategy logic works.

<figure><img src="https://3175477167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYCh2t4HDhRRiAIqY93vK%2Fuploads%2F3O5bCsHq0C3n4o91OPbp%2Fimage.png?alt=media&#x26;token=435a3d80-d41d-40c6-9eda-d9c1f289760b" alt="" width="563"><figcaption><p>Debug session where execution has stopped at line 35.</p></figcaption></figure>

**Why use the debugger?**

* **Understand your strategy** - See exactly what's happening at each step
* **Find bugs** - Discover why your strategy isn't working as expected
* **Verify logic** - Confirm your buy/sell conditions trigger correctly
* **Learn from behavior** - Watch how your strategy reacts to different price movements
* **Optimize decisions** - Identify where your strategy could be improved

### What is the Debugger?

The debugger is like putting your strategy in "slow motion." You can:

1. **Set breakpoints** - Mark lines where execution should pause
2. **Run your strategy** - Execute against real historical signals
3. **Inspect variables** - See current prices, wallet balance, and your custom variables
4. **Step through code** - Execute one line at a time to understand the flow
5. **Continue execution** - Resume normal speed after inspecting

Think of it like watching a replay of a game with the ability to pause, rewind, and see all player stats at any moment.

### When to Use the Debugger

#### Perfect for:

* **First-time testing** - Before running any backtest, step through one signal to verify logic
* **Unexpected behavior** - Your backtest shows strange results you can't explain
* **Failed conditions** - You expected a buy/sell but nothing happened
* **Complex strategies** - Multiple steps and conditions that are hard to track mentally
* **Learning** - Understanding how JavaScript code translates to trading decisions

#### Not needed for:

* **Working strategies** - If your strategy performs as expected, regular backtesting is faster
* **Simple strategies** - Basic buy at 2x, sell at 5x logic is easy to understand without debugging
* **Final validation** - After debugging, use regular backtesting for full historical testing

### How to Use the Debugger

#### Step 1: Open Debug Mode

In your strategy's **Development** tab:

1. Click on the Debug to initiate a new session
2. The debug controls will appear: **Stop**, **Step Over**, **Step Into,** and **Continue**

<figure><img src="https://3175477167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYCh2t4HDhRRiAIqY93vK%2Fuploads%2FJ00iCe7lhFj302RcXdIy%2Fimage.png?alt=media&#x26;token=dd99f252-4c86-478c-8c78-3161d1671503" alt="" width="440"><figcaption><p>The debug buttons becomes active after having started a session.</p></figcaption></figure>

#### Step 2: Set Breakpoints

**What are breakpoints?** Lines in your code where execution will pause, allowing you to inspect what's happening.

<figure><img src="https://3175477167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYCh2t4HDhRRiAIqY93vK%2Fuploads%2FmQiedUeNf7w6YUvNrLgU%2Fimage.png?alt=media&#x26;token=435132ea-c4b1-463e-a415-044165e476da" alt="" width="563"><figcaption><p>Strategy with four breakpoints.</p></figcaption></figure>

**How to set breakpoints:**

1. **Click the left margin** (gutter area) next to any line number in your code editor
2. A **red dot** appears indicating a breakpoint is set
3. Click the red dot again to remove the breakpoint
4. You can set multiple breakpoints throughout your strategy

**Pro tip:** Set breakpoints at key decision points:

* Start of buy logic: `checkBuy(entry, current) {`
* Start of sell logic: `checkSell(entry, current) {`
* Before important calculations or comparisons
* Inside if/else branches to see which path executes

#### Step 3: Run the simulation

1. Click **"Run Simulation"** with your breakpoints set
2. The debugger will start executing your strategy
3. Execution will **automatically pause** when it hits your first breakpoint
4. The editor will **highlight the current line** in yellow/gold
5. A **yellow arrow** appears in the gutter showing execution position

<figure><img src="https://3175477167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYCh2t4HDhRRiAIqY93vK%2Fuploads%2FHsgTsJg0CpN1nlir2HYi%2Fimage.png?alt=media&#x26;token=b42d8225-5518-4d56-9459-4797b6a35a29" alt="" width="482"><figcaption><p>Execution has stopped at line 47. With the debug controls </p></figcaption></figure>

#### Step 4: Inspect Variables

When paused at a breakpoint, you can see variable values:

**Hover over variables:**

* Move your mouse over any variable name in the code
* A tooltip shows the current value
* Example: Hover over `currentPrice` to see the actual token price at that moment

<figure><img src="https://3175477167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYCh2t4HDhRRiAIqY93vK%2Fuploads%2FMIpX5xbKMlO8bR93uT2S%2Fimage.png?alt=media&#x26;token=6acc4675-6c68-4c3e-8188-7a1bd50d4c37" alt="" width="563"><figcaption><p>Hovering over a variable shows its value. In this case we see the value of the entryPrice variable.</p></figcaption></figure>

#### Step 5: Control Execution

Once paused, use the debug controls to navigate:

**Step Over** (▶ arrow button):

* Execute the **current line** and move to the next line
* Stays at the current level (doesn't dive into function calls)
* Use this most often to walk through your code line by line

**Step Into** (↘ arrow button):

* If the current line calls a function, **jump inside** that function
* Useful for debugging helper functions or nested logic
* Press repeatedly to go deeper into function calls

**Continue** (▶ play button):

* **Resume normal execution** until the next breakpoint
* Use this to skip through sections you know are working
* Execution will pause again at your next breakpoint (or complete if no more breakpoints)

**Stop** (■ square button):

* **End the debug session** completely
* Returns to normal editor mode
* Use this when you're done debugging or want to start over

### Common Debugging Scenarios

#### Scenario 1: "My Strategy Never Buys"

**Problem:** Backtest shows 0 trades, but you expected buys to happen.

**Debug approach:**

1. Set a breakpoint at the **start of your buy function** (`checkBuy`)
2. Run the debugger
3. When paused, inspect the condition: `if (currentPrice <= entryPrice * 0.9)`
4. Hover over `currentPrice` and `entryPrice` to see actual values
5. Calculate manually: Is the condition true or false?
6. If false, adjust your threshold (maybe 0.95 instead of 0.9)

**Common causes:**

* Your buy condition is too strict (waiting for 20% dip that never happens)
* You're comparing the wrong variables
* Logic error: using `>` when you meant `<`

#### Scenario 2: "My Strategy Buys at the Wrong Time"

**Problem:** Backtest shows buys, but they happen too early or too late.

**Debug approach:**

1. Set breakpoints at the **start and inside your buy logic**
2. Step through several price ticks
3. Watch when the buy condition becomes true
4. Check: Is `currentPrice` what you expected?
5. Are you using the right comparison? (`entryPrice * 2` for 2x, not `entryPrice + 2`)

**Common issues:**

* Buying on first price tick instead of waiting for dip
* Not accounting for price already being above entry (missed signal)
* Incorrect multiplication/division in price calculations

#### Scenario 3: "My Strategy Sells Too Early"

**Problem:** Backtest shows exits at 2x when you wanted 5x.

**Debug approach:**

1. Set a breakpoint in your **sell function** (`checkSell`)
2. Step through execution after a buy happened
3. Inspect your sell condition: `if (currentPrice >= entryPrice * 5)`
4. Verify the multiple calculation is correct
5. Check if you have multiple exit conditions that trigger earlier than expected

**Common mistakes:**

* Multiple return statements, with an early exit triggering first
* Using strategy context incorrectly (checking wrong variable)
* Logic error in step ordering (selling before checking max profit)

#### Scenario 4: "My Variables Aren't Updating"

**Problem:** You're storing data in context but it's always undefined.

**Debug approach:**

1. Set breakpoint where you **write to context**: `this.strategy.context.hasBought = true`
2. Step over that line
3. Hover over `this.strategy.context.hasBought` - is it now `true`?
4. Set another breakpoint where you **read from context**
5. Verify the value is still there

**Common issues:**

* Typo in variable name (wrote `hasBought` but reading `hasBought_`)
* Accessing nested object that doesn't exist (`context.trades.count` when `context.trades` is undefined)
* Overwriting entire context object instead of specific property

#### Scenario 5: "Complex Logic Doesn't Make Sense"

**Problem:** Strategy has multiple conditions and you don't know which path it takes.

**Debug approach:**

1. Set breakpoints at **every if/else branch**
2. Step through slowly
3. Observe which breakpoints get hit
4. When execution pauses, you know that branch executed
5. Inspect variables to understand why

**Example:**

```javascript
checkSell(entry, current) {
  // Breakpoint 1: Always hits
  if (current > entry * 10) {
    // Breakpoint 2: Only hits if 10x reached
    return { sell: true, partToSellInPercentage: 100 };
  }

  // Breakpoint 3: Hits if didn't sell above
  if (current < entry * 0.5) {
    // Breakpoint 4: Only hits if lost 50%
    return { sell: true, partToSellInPercentage: 100 };
  }

  // Breakpoint 5: Hits if neither condition met
  return { sell: false, partToSellInPercentage: 0 };
}
```

By seeing which breakpoints activate, you understand the decision path.

### Tips for Effective Debugging

#### Start Simple

* Debug **one signal at a time** (1-2 day date range)
* Remove all breakpoints except 1-2 key lines
* Once comfortable, add more breakpoints and longer ranges

#### Use Breakpoints Strategically

**Good breakpoint locations:**

* First line of each step function
* Before and after important calculations
* Inside conditional branches (if/else)
* Where you modify strategy context

**Avoid too many breakpoints:**

* Don't set breakpoints on every single line
* Skip variable declarations and simple assignments
* Focus on decision points and calculations

#### Watch the Whole Flow

Don't just debug one function - step through an entire signal:

1. Watch signal arrive (entry price set)
2. Step through multiple price ticks
3. See buy condition eventually trigger
4. Continue stepping through price changes
5. Watch sell condition finally trigger
6. Verify final profit/loss

This gives you complete understanding of your strategy's lifecycle.

#### Use Continue Wisely

If you know early price ticks aren't interesting:

1. Set a breakpoint where you expect action (e.g., when profit reaches 2x)
2. Click **Continue** to fast-forward to that point
3. Execution automatically pauses at your breakpoint
4. Saves time vs. stepping through every single line

#### Compare Expected vs. Actual

Before stepping through, **predict what should happen**:

* "Price dropped 10%, so buy condition should be true"
* "We're at 3x profit, so this should trigger sell"

Then step through and see if reality matches expectations. Mismatches reveal bugs.

#### Take Notes

When you discover issues:

* Note which line has the bug
* Write down the actual vs. expected values
* Document the fix you need to make

This helps when debugging multiple issues or returning to debugging later.

### Debug Mode Limitations

**Debugging is slower than backtesting:**

* Manual stepping takes time
* Use regular backtesting for full historical validation
* Debug only when you need to understand specific behavior

**Debugging shows one signal at a time:**

* You step through one token's price history
* Can't see how strategy performs across hundreds of signals
* Use regular backtesting to see overall performance

**Debug session can timeout:**

* If you pause too long (5+ minutes), session may disconnect
* You'll need to restart and re-set breakpoints
* Keep debug sessions focused and active
