A Backtest as an indicator

A Backtest as an indicator

I created an indicator to allow me to simulate a backtest and display the results straigth on the graph.

Works with any strategy using only MKT orders.

Feel free to try out.

1) What this “homemade backtest” does

This indicator turns any signal you write into a lightweight, visual backtest that runs directly on your chart. You provide orders via the variable TradingSignal (positive to buy, negative to sell), and the engine handles entries, scaling, unit price, realized/unrealized P&L, fixed/trailed stops, and profit targets. It lets you iterate quickly on ideas without converting everything into a full system.


2) How the engine works (in plain English)

  • You send market orders through TradingSignal. The order is executed at the opening price of the next bar, adjusted by Spread in ticks.

  • Positions accumulate: the engine sums all signals into Position. It supports scale-in/scale-out (e.g., +2 then −1).

  • Cost basis tracking: UnitPrice is updated whenever size changes; realized P&L (PL) is computed on reductions/reversals.

  • Exit levels:

    • TargetLevel = unit price ± TargetPct

    • StopLevel = unit price ∓ StopPct

    • StopTrailing follows price using StopTrailingPct and resets on unit-price change.

  • Visualization: colored segments/text show unit price, local P&L at each trade, and active stop/target lines.

  • Unrealized P&L updates on every bar from UnitPrice to the current closing price (spread-aware).


3) Parameters you can tune

Declared once at the top (they appear in the indicator’s settings):

  • Spread (ticks): Simulates execution friction. Use the instrument’s typical spread in ticks. Set to 0 to ignore.

  • TargetPct (%): Take-profit distance from UnitPrice. Set to 0 to hide/disable targets.

  • StopPct (%): Fixed stop distance from UnitPrice. Set to 0 to hide/disable fixed stops.

  • StopTrailingPct (%): Trailing stop distance from the trailing reference. Set to 0 to hide/disable trailing stops.

You can change these interactively to see how your strategy behaves with different trade management settings.


4) How to set it up in ProRealTime (step-by-step)

  1. Create a new indicator in ProBuilder and paste the full code you were given.

  2. Leave everything above the “write your code below” banner untouched. That block is the engine.

  3. In the lower block, either keep the sample MA crossover or replace it with your own logic (see next section).

  4. If you don’t have a custom price series, define CustomClose = Close before your averages, or replace CustomClose with Close.

  5. Apply the indicator to your chart. You’ll see unit price lines, stop/target levels, and trade P&L callouts appear when signals occur.

  6. Tune Spread, TargetPct, StopPct, and StopTrailingPct from the indicator’s parameters to stress-test your idea.


5) Writing your own TradingSignal (the only line you should change)

  • You must output the order quantity you want on that bar:

    • Positive value = buy (e.g., +1, +2),

    • Negative value = sell/short (e.g., -1, -3).

  • Orders are market and are executed on the next bar’s open (with spread applied and sign-aware).

  • You can scale in/out by sending additional positive/negative quantities on later bars.

  • Do not overwrite engine variables declared above (e.g., don’t write UnitPrice = ...). The only variable you’re allowed to drive is TradingSignal. Reading them is fine (e.g., use PL, Position, UnitPrice in conditions).

Example (provided in the code):

  • P1 = 20, P2 = 50, AvType = 0 (simple average).

  • Av1 = Average[P1,AvType](CustomClose) and Av2 = Average[P2,AvType](CustomClose).

  • TradingSignal = (Av1 CROSSES OVER Av2) * 2 - (Av1 CROSSES UNDER Av2) * 1

    • Buys 2 when fast crosses above slow, sells 1 when it crosses below (scale-out).


6) Reading the on-chart visuals

  • Unit price (blue): horizontal line segments marking your current cost basis. A vertical blue “jump” appears when size changes.

  • Target (green): your take-profit line from UnitPrice.

  • Fixed stop (magenta-red dotted): your hard stop from UnitPrice.

  • Trailing stop (purple-pink dotted): follows highs in long trades (or lows in shorts) and resets when UnitPrice changes.

  • Trade callouts: when an order fires, you’ll see PrevPos -> Position and a dotted line to the fill level.

    • Green callout = realized profit on that transaction, red = realized loss.

  • Unrealized P&L: tracked internally as UnrealizedPL for the open position.


7) Optional outputs with RETURN

By default the script returns nothing to keep charts clean. You can enable the optional RETURN block at the end to display:

  • TradingSignal (histogram): see when/where orders are sent.

  • Position (histogram): visualize net exposure and scaling.

  • UnrealizedPL: running P&L of the open trade.

To enable it, comment out RETURN and uncomment the provided RETURN lines.


8) Tips, limitations & troubleshooting

  • Execution model: orders are next-bar-open; there’s no intra-bar fill logic. Large gaps may jump straight to target/stop without intermediate prints.

  • Spread only: slippage isn’t modeled beyond Spread. If you need extra friction, increase Spread.

  • Disable lines: set any of TargetPct, StopPct, or StopTrailingPct to 0.

  • CustomClose not defined? Add CustomClose = Close in your “write code below” section before using it in calculations.

  • Position sizing: use integers in TradingSignal to control scale-in/out. The engine tracks average price correctly for partial exits.

  • Don’t touch engine variables: changing UnitPrice, PL, Position, etc., will break accounting. Only write to TradingSignal.

  • Color meanings:

    • Green segments/text = profitable transaction.

    • Red segments/text = losing transaction.

    • Blue = unit price.

    • Dotted lines = stops/trailing and trade link.


9) Code placement reminder

Only add or modify logic below the banner:

// -------------------------------------------------write your code below-----------------------------------------------------------------------------

There you can:

  • Declare your own settings (e.g., periods, thresholds).

  • Compute indicators on Close or your own CustomClose.

  • Output only TradingSignal.

Share this

Risk disclosure:

No information on this site is investment advice or a solicitation to buy or sell any financial instrument. Past performance is not indicative of future results. Trading may expose you to risk of loss greater than your deposits and is only suitable for experienced investors who have sufficient financial means to bear such risk.

ProRealTime ITF files and other attachments : How to import ITF files into ProRealTime platform?

PRC is also on YouTube, subscribe to our channel for exclusive content and tutorials

avatar
Register or
Related users ' posts
Ciccarelli Franco Scusa e cosa devo cambiare? Grazie
Sofitech Bonjour Ivan, comment pourrais tu modifier ce code pour qu'un histogramme indiquant la créat...
geroniman Merci Ivan, cet indicateur est excellent. Comme les cours s'arretent souvent sur les 50% d'u...
YvesRobert Hello davidelaferla, how do you put a stop loss and where exactly ? the moment you enter on ...
Hypersimo Buongiorno Davide a quale distanza inserire stop loss e tp nella strategia? grazie
beanpole Thank you for sharing the code. I applied it to the "CAC40 Index" on Euronext market on a da...
Marius Zammit Still learning and very new to all this. Can this indicator be turned into an automated trad...
Nicolas Yes sure, please create a dedicated post in the automated trading forum.
leederbyshire Hi is it possible to replace the dots with red/green vertical lines? Thank you.
Kris75 Hi, This is great !! anyone ever developped a strategy about it ???
swapping hello Kris75, not that I know but it is possible to make a scenario ;)
digitation Hi swapping, Thanks for sharing this useful tool. I was wondering how difficult it would be...

Top