Strategy example

Moving Average Cross

Readonly source from tests/EasyLanguage/dorian-draper-learning, generated Pine Script v6, and an expiry-free example EX5.

Original EasyLanguage

  1. {-------------------------------------------------------------------
  2. Mov Avg Cross v1
  3. Description:
  4. - Moving Average Crossover strategy using simple moving averages
  5. - Enters long when the fast MA crosses above the slow MA, and short when it crosses below
  6. - Exits positions if they have been held for a minimum time and haven't reached a minimum profit
  7. -------------------------------------------------------------------}
  8. Input:
  9. ShortPrice(Close),
  10. LongPrice(Close),
  11. ShortLen(9),
  12. LongLen(18),
  13. MinHold(8),
  14. MinProfit(100);
  15. Vars:
  16. ShortMA(0),
  17. LongMA(0);
  18. ShortMA = Average(ShortPrice, ShortLen);
  19. LongMA = Average(LongPrice, LongLen);
  20. {Setup entrada}
  21. If ShortMA Crosses Over LongMA Then
  22. Buy Next Bar at Market;
  23. If ShortMA Crosses Under LongMA Then
  24. SellShort Next Bar at Market;
  25. {Setup salida}
  26. If BarsSinceEntry > MinHold and OpenPositionProfit < MinProfit Then
  27. Begin
  28. Sell Next Bar at Market;
  29. BuyToCover Next Bar at Market;
  30. End;

Generated Pine Script v6

  1. //@version=6
  2. strategy("MovingAverageCross_v1", overlay=true)
  3. shortprice = input.source(close, "shortprice")
  4. longprice = input.source(close, "longprice")
  5. shortlen = input.float(9.0, "shortlen")
  6. longlen = input.float(18.0, "longlen")
  7. minhold = input.float(8.0, "minhold")
  8. minprofit = input.float(100.0, "minprofit")
  9. var float shortma = 0
  10. var float longma = 0
  11. __el_call1 = ta.sma(shortprice, int(shortlen))
  12. __el_call2 = ta.sma(longprice, int(longlen))
  13. if bar_index >= 17
  14. shortma := __el_call1
  15. longma := __el_call2
  16. if ta.crossover(shortma, longma)
  17. strategy.entry("Buy", strategy.long)
  18. if ta.crossunder(shortma, longma)
  19. strategy.entry("SellShort", strategy.short)
  20. if (strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : 0) > minhold and strategy.openprofit < minprofit
  21. strategy.close_all(comment="Sell")
  22. strategy.close_all(comment="BuyToCover")

Compiled MetaTrader 5 example

The EX5 uses the original script filename stem and has no PineAnywhere expiration guard.

Download MovingAverageCross_v1.ex5
An unexpected error occurred. Reload×

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please retry or reload the page.