2026/04/20

1-1. NK-Fixed SMA

This is an SMA equipped with a feature that allows you to adjust when to start real-time drawing, anywhere from 0 seconds to 5 minutes before the candle closes. It also includes other useful features.

[SMA]

The SMA (Simple Moving Average) is a pure average value calculated by taking the sum of prices (usually the closing price of the candlestick) over a specified period and dividing it by that period. It is the most historic indicator in technical analysis and serves as the "foundation of everything," integrated into trading systems worldwide.


Example of SMA displayed on TradingView
Source: TradingView

[NOTICE & LICENSE]
・For educational and informational purposes only; does not constitute investment advice. We assume no liability for any economic loss arising from the use of this tool.
・Tested on Pine Script v6. Provided "As-Is" with no guarantee of updates in response to future TradingView specification changes. We do not provide individual installation support or accept modification requests.
・Governed by the MIT License.
// SPDX-FileCopyrightText: 2026 NK-report https://www.nk-report.com/
// SPDX-License-Identifier: MIT
//
// Disclaimer: This script is for educational purposes only and does not constitute investment advice.

//@version=6
indicator("NK-Fixed SMA", shorttitle="NK-Fixed SMA", overlay=true)

// ==============================================================================
// 【01】 免責・ライセンス
// ==============================================================================
//
// Indicator is published for free: https://www.nk-report.com/p/tradingview-code.html
//
// Disclaimer: This script is for educational and informational purposes only and does not constitute investment advice.
//
// 1. This code has been tested with Pine Script v6 as of 2026.
//    We do not provide individual support or modifications for any issues caused by future specification changes.
// 2. This script was independently created using an LLM, based on general calculation logic.
//    It is distributed under the MIT License.
// ------------------------------------------------------------------------------
// MIT License 
//
// Copyright 2026 NK-report https://www.nk-report.com/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

// ==============================================================================
// 【02】 UI設定と言語
// ==============================================================================
// 1. 言語辞書の定義(テキストの定数化)

const string GRP_FIXED   = "Fixed Settings"
const string LBL_SEC     = "Real-time Draw Start (X seconds before bar closes)"
const string TT_SEC      = "Adjust between 0 and 300 seconds (5 mins). Hides drawings on the current bar until the specified time (e.g., 10 secs before close) is reached.\nEntering 0 disables this feature and draws in real-time constantly."

const string GRP_SMA     = "SMA Settings"
const string LBL_LEN     = "Length"
const string LBL_SRC     = "Source"
const string LBL_COLOR   = "Color"
const string LBL_WIDTH   = "Width"

// 2. UI(ユーザー入力画面)の構築 & 3. トップダウン処理への適合
// ※Pine Script v6のコンパイルエラーを防ぐため、入力値の型(string/int等)は記述せず自動推論させます

i_sec    = input.int(0, title=LBL_SEC, minval=0, maxval=300, group=GRP_FIXED, tooltip=TT_SEC)

i_len    = input.int(20, title=LBL_LEN, minval=1, group=GRP_SMA,  inline="SMA1")
i_src    = input.source(close, title=LBL_SRC, group=GRP_SMA, inline="SMA1")

i_color  = input.color(color.blue, title=LBL_COLOR, group=GRP_SMA, inline="SMA2")
i_width  = input.int(2, title=LBL_WIDTH, minval=1, maxval=5, group=GRP_SMA, inline="SMA2")


// ==============================================================================
// 【03】 全コード共通仕様(タイムゾーン・時間インフラ処理)
// ==============================================================================
// 1. 基本時間単位のシステム定義(定数化)
const int MS_PER_SEC  = 1000

// ==============================================================================
// 【04】 各カテゴリ共通仕様 (NK-Fixed Core Logic)
// ==============================================================================
// 1. カテゴリ固有のインフラ構築(コア機能の定義)
// 「足が閉じる指定秒数前になるまでリアルタイム描画を非表示にする」というFixed固有の判定ロジック

bool is_draw_ready = true

// リアルタイム足であり、かつユーザーが0秒より大きい数値を設定している場合のみ処理
if barstate.isrealtime and i_sec > 0
    // 特殊チャート(練行足など)で time_close が na になる場合のエラークラッシュを回避
    if not na(time_close)
        // チャートの足が閉じる予定時刻から現在時刻を引いて残り時間(ミリ秒)を算出
        int time_left_ms = time_close - timenow
        int threshold_ms = i_sec * MS_PER_SEC
        
        // 残り時間がユーザーの指定秒数を上回っている間は描画フラグを折る(非表示)
        if time_left_ms > threshold_ms
            is_draw_ready := false


// ==============================================================================
// 【05】 このコード固有の計算仕様 (Specific Indicator Logic)
// ==============================================================================
// 1. インジケーター固有の純粋な数学的処理
// 現在のチャート(純正データ)のみを使用し、リペイント(架空の数値)を完全に排除した純粋な計算
float calc_val = ta.sma(i_src, i_len)

// 2. ロジックの完全な隔離と差し替えの容易性

// 3. 視覚的装飾の排除とデータの引き渡し
// 描画フラグ(is_draw_ready)に基づき、表示させないタイミングでは純粋なデータに「na(欠損値)」を代入して引き渡す
float final_val = is_draw_ready ? calc_val : na


// ==============================================================================
// 【06】 描画と出力 (Rendering & Outputs)
// ==============================================================================
// 1. チャートへの視覚的出力(プロットと装飾)
plot(final_val, title="NK-Fixed SMA", color=i_color, linewidth=i_width, style=plot.style_line)

// 2. ロジックとデザインの完全分離

// 3. アラート(通知)条件の統合
// ※投資助言を回避するため、方向性を指示する言葉(Buy/Sell等)は使わず、純粋な事実・状態のみを通知します
bool cross_over  = ta.crossover(close, calc_val) and is_draw_ready
bool cross_under = ta.crossunder(close, calc_val) and is_draw_ready

alertcondition(cross_over,  title="SMA Cross Over",  message="Price crossed over NK-Fixed SMA")
alertcondition(cross_under, title="SMA Cross Under", message="Price crossed under NK-Fixed SMA")

* After setting your preferred colors, please click "Save as default" in the settings tab.
* The indicator may not display correctly unless you follow the steps: Create New -> Indicator -> Paste.