Strategy · Pine Script v4 · Own pane

Moon Phase

by koradiyakaushal

This strategy estimates the Moon's age from the chart date and marks full-moon and new-moon transitions with circles on the price chart.

View on GitHub

GitHub stars12on the repository
Pine versionv4older, still runs
Lines of code143
Settings5inputs
LicenceMIT
Last update5 years ago30 Jul 2021

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

143 lines of Pine Script v4 from [STRAT]moon_cycle.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

[STRAT]moon_cycle.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=4

SystemName = "Moon Phase"
InitCapital = 1000
InitPosition = 100
InitCommission = 0
CalcOnorderFills = false
is_overlay = true

strategy(title=SystemName, shorttitle=SystemName, 
 initial_capital=InitCapital, default_qty_type=strategy.percent_of_equity, 
 default_qty_value=InitPosition,commission_type=strategy.commission.percent, commission_value=InitCommission, calc_on_order_fills=CalcOnorderFills, 
 precision=6, max_lines_count=500, max_labels_count=500, overlay=is_overlay, max_bars_back=20)

DateFilter      = input(true, "═════════════ Backtest Date Range Filtering", group="Date")

i_startTime = input(defval = timestamp("01 Jan 2021 00:00 +0000"), title = "Start Time", type = input.time, group="Date")
i_endTime = input(defval = timestamp("30 Dec 2021 23:30 +0000"), title = "End Time", type = input.time, group="Date")

TradeDateIsAllowed() => DateFilter ? time >= i_startTime and time <= i_endTime : true

// INPUT    --- {

fillBackground = input(true, "Fill Background?")

//} --- INPUT

_STOPLOSS = input(5, type=input.float, title="stop loss(%)")

// FUNCTION --- {

normalize(_v) =>
    x = _v
    x := x - floor(x)
    if x < 0
        x := x + 1
    x

calcPhase(_year, _month, _day) =>

    int y = na
    int m = na
    float k1 = na 
    float k2 = na 
    float k3 = na
    float jd = na
    float ip = na

    y := _year - floor((12 - _month) / 10)       
    m := _month + 9
    if m >= 12 
        m := m - 12
    
    k1 := floor(365.25 * (y + 4712))
    k2 := floor(30.6 * m + 0.5)
    k3 := floor(floor((y / 100) + 49) * 0.75) - 38
    
    jd := k1 + k2 + _day + 59
    if jd > 2299160
        jd := jd - k3
    
    ip := normalize((jd - 2451550.1) / 29.530588853)
    age = ip * 29.53

//} --- FUNCTION

// INIT     --- {

age = calcPhase(year, month, dayofmonth)
moon = 
     floor(age)[1] > floor(age) ? 1 : 
     floor(age)[1] < 15 and floor(age) >= 15 ? -1 : na

//} --- INIT

// PLOT     --- {

plotshape(
     moon==1, 
     "Full Moon", 
     shape.circle, 
     location.top, 
     color.new(color.white, 20), 
     size=size.normal
     )   

plotshape(
     moon==-1, 
     "New Moon", 
     shape.circle, 
     location.bottom, 
     color.new(color.gray, 20), 
     size=size.normal
     )   

var color col = na
if moon == 1 and fillBackground
    col := color.navy
if moon == -1 and fillBackground
    col := color.gray

bgcolor(col, title="Moon Phase")

//} --- PLOT
Entry_Type = "Both"
stop_loss = 5

long_entry  = (strategy.position_size == 0 and Entry_Type != "Sell" and TradeDateIsAllowed() and (moon[1]==-1))
short_entry = (strategy.position_size == 0 and Entry_Type != "Buy" and TradeDateIsAllowed() and (moon[1]==1))

long_exit = (strategy.position_size != 0 and moon==1)
short_exit = (strategy.position_size != 0 and moon==-1)

float _SL = na
float _EP = na

_EP         := (strategy.position_size != 0) ? _EP[1] : na
_SL         := (strategy.position_size != 0) ? _SL[1] : na

if long_entry
    _EP := close
    _SL := ((1-(_STOPLOSS/100))*close)

if short_entry
    _EP := close
    _SL := ((1+(_STOPLOSS/100))*close)

strategy.entry("Long", strategy.long, when=long_entry)
strategy.close(id="Long", comment="tp", when=long_exit)

strategy.entry("Short", strategy.short, when=short_entry)
strategy.close(id="Short", comment="tp", when=short_exit)

if (strategy.position_size > 0 and close < _SL)
    strategy.close(id="Long", comment="sl", when=close)
if (strategy.position_size < 0 and close > _SL)
    strategy.close(id="Short", comment="sl", when=close)

plot_EP = plot(_EP, title="Entry Level", color=color.blue,  linewidth=1, style=plot.style_linebr)
plot_SL = plot(_SL, title="Stop Loss",   color=color.red,   linewidth=2, style=plot.style_linebr)

fill(plot_SL, plot_EP, title="SL Background", color=color.red,   transp = 75)

Overview

Moon Phase optionally fills the background navy or gray on those bars. It opens a long after a new-moon signal and a short after a full-moon signal, only while flat and inside an optional date window, using percent-of-equity sizing by default. It closes the long on the next full-moon signal and the short on the next new-moon signal. A percentage stop is calculated from the entry price, but the visible code does not place that stop order.

Details

Published by

koradiyakaushal on GitHub

Type

Strategy, Pine Script v4

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
═════════════ Backtest Date Range FilteringbooltrueDateFilter
Start Timetimetimestamp("01 Jan 2021 00:00 +0000")i_startTime
End Timetimetimestamp("30 Dec 2021 23:30 +0000")i_endTime
Fill Background?booltruefillBackground
stop loss(%)float5_STOPLOSS
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

HA UnivLong&Short Futures calculates Heikin Ashi candles and builds a channel using simple moving averages of Heikin Ashi highs and lows. It enters long positions when the upper channel line crosses above the lower channel line and opens short positions on the

Strategy v5 TrendMoving averages
Updated 2 months ago · None stated GitHub repository of HA UnivLong&Short Futures

Q-Trend + KVO Strategy

by TradersPost
218 stars

This strategy combines the ATR-banded Q-Trend indicator with the Klinger Volume Oscillator (KVO) to execute confluence trades. It enters long when a Q-Trend buy trigger aligns with a positive KVO value and a bullish candle confirmation, taking short trades und

Strategy v6 TrendVolume
Updated 3 months ago · None stated GitHub repository of Q-Trend + KVO Strategy

MACD Crossover (tutorial)

by pineforge-4pass
193 stars

This strategy calculates the Moving Average Convergence Divergence indicator and plots the MACD line, signal line, and histogram in a separate pane. It enters long positions when the MACD line crosses above the signal line and enters short positions when it cr

Strategy v6 Oscillators & momentumMoving averages
Updated today · Apache-2.0 GitHub repository of MACD Crossover (tutorial)
114 stars

This strategy estimates price behavior using ordinary least squares regression between higher-timeframe data and a generated dataset, smoothed by a Karobein oscillator. It enters long positions when the oscillator turns upward and short positions when it turns

Strategy v4 Oscillators & momentumAI / machine learning Repaints

10PreBuyer

by hasnocool
106 stars

10PreBuyer is a dip-buying strategy that submits limit orders below recent price action using a discounted Hull Moving Average (HMA). It calculates the highest HMA value of high prices over a selected period, multiplied by a percentage discount factor, and pla

Strategy v4 Moving averagesMean reversion
Updated 2 years ago · GPL-3.0 GitHub repository of 10PreBuyer

Bar States Example S

by be-thomas
65 stars

This Pine Script strategy demonstrates the usage of bar state variables by highlighting the chart background color. It evaluates whether the current candle is the final bar on the chart using the barstate.islast condition and applies a silver background color

Strategy v5
Updated 4 days ago · GPL-3.0 GitHub repository of Bar States Example S

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers