Strategy · Pine Script v6 · On the chart

USDTHB TFEX Strategy

by lumduan

A pivot based strategy intended for the USDTHB futures on a 30-minute chart.

View on GitHub

Repaints

GitHub stars1on the repository
Pine versionv6current
Lines of code197
Settings3inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago29 Apr 2025

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

197 lines of Pine Script v6 from usd_thb_tfex_strategy.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

usd_thb_tfex_strategy.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © lumduan
//@version=6

// For USDTHB TFEX Strategy Timeframe 30 minutes


// ————— Constants
float RISK_FREE_RATE = 2.2 // Risk-free rate for calculating Sharpe ratio
HIGH_PRICE_BAR_COLOR = color.green
LOW_PRICE_BAR_COLOR = color.red
int HIGH_PRICE_BAR_WIDTH = 1
int LOW_PRICE_BAR_WIDTH = 1
int prec      = 2 // Precision of return percentages

TABLE_HEADER_COLOR = color.new(color.black, 0)
TABLE_INDEX_COLOR = color.new(color.gray, 0)
TABLE_CELL_COLOR = color.new(color.black, 0)
TABLE_YEAR_CELL_POSITIVE_COLOR = color.new(color.green, 0)
TABLE_YEAR_CELL_NEGATIVE_COLOR = color.new(color.red, 0)



int CONTACT_PER_ORDER = 20 
float COMMISSION_PRICE = 10.1 //THB

// Inputs for configuring the pivot point calculation
int leftBars  = input(82) // Number of bars to the left for pivot calculation
int rightBars = input(1) // Number of bars to the right for pivot calculation

bool show_table = input.bool(defval = true, title = "Show Return Rate Table On/Off") // Show or hide the table


strategy(title = "USDTHB TFEX Strategy",overlay = true, calc_on_every_tick = true, default_qty_type = strategy.fixed, default_qty_value = CONTACT_PER_ORDER, commission_type = strategy.commission.cash_per_contract, commission_value = COMMISSION_PRICE , risk_free_rate = RISK_FREE_RATE)



swingHigh = ta.pivothigh(leftBars,rightBars)
swingLow = ta.pivotlow(leftBars,rightBars)

// Initialize high and low price variables
float highPrice = 0.0
highPrice := not na(swingHigh) ? swingHigh : highPrice[1] // Update high price if a new swing high is detected, else carry forward previous value

float lowPrice = 0.0
lowPrice := not na(swingLow) ? swingLow : lowPrice[1] // Update low price if a new swing low is detected, else carry forward previous value

// Long Entry Logic
bool longEntry = false
longEntry := not na(swingHigh) ? true : (longEntry[1] and high > highPrice ? false : longEntry[1]) // Entry on swing high or invalidate if price exceeds current high

// Short Entry Logic
bool shortEntry = false
shortEntry := not na(swingLow) ? true : (shortEntry[1] and low < lowPrice ? false : shortEntry[1]) // Entry on swing low or invalidate if price drops below current low

// Place Long Entry Order
if (longEntry)
    strategy.entry(id="Long", direction=strategy.long, comment="Long", stop=highPrice + syminfo.mintick)
// Place Short Entry Order
if (shortEntry)
    strategy.entry("Short", strategy.short, comment="Short", stop=lowPrice - syminfo.mintick)

// Plot high and low prices on the chart
plot(highPrice, color = HIGH_PRICE_BAR_COLOR, linewidth = HIGH_PRICE_BAR_WIDTH)
plot(lowPrice, color = LOW_PRICE_BAR_COLOR,   linewidth = LOW_PRICE_BAR_WIDTH)


// ======= TABLE ====================================================================================================

// Detect new month and new year
bool newMonth = month(time) != month(time[1]) // True if the current bar is in a new month
bool newYear  = year(time)  != year(time[1])  // True if the current bar is in a new year

// Retrieve current equity and calculate bar profit/loss %
float equity = strategy.equity

// Calculate the profit or loss for the current bar as a percentage change from the previous bar's equity
float profitLossPercent = equity / equity[1] - 1 
float ProfitLoss = equity - equity[1]

// Initialize variables for current month and year P&L %
float currentMonthProfit = 0.0
float currentYearProfit  = 0.0

// Initialize variables for current month and year P&L %
float currentMonthPnL = 0.0
float currentYearPnL  = 0.0

// Calculate current month Profit/Loss
currentMonthProfit := newMonth ? 0.0 : currentMonthProfit[1] + ProfitLoss
// Calculate current year Profit/Loss
currentYearProfit := newYear ? 0.0 : currentYearProfit[1] + ProfitLoss


// Calculate current monthly P&L %
currentMonthPnL := newMonth ? 0.0 : (1 + currentMonthPnL[1]) * (1 + profitLossPercent) - 1
// Calculate current yearly P&L %
currentYearPnL := newYear ? 0.0 : (1 + currentYearPnL[1]) * (1 + profitLossPercent) - 1

// Arrays to store Monthly and Yearly P&Ls
var float[] monthlyProfit = array.new_float(0) // Array to store monthly P&L values
var int[] monthlyProfitCount = array.new_int(0) // Array to store timestamps for monthly P&L

var float[] yearlyProfit = array.new_float(0) // Array to store yearly P&L values
var int[] yearlyProfitCount = array.new_int(0) // Array to store timestamps for yearly P&L

// Arrays to store Monthly and Yearly P&Ls %
var float[] monthlyPnLs = array.new_float(0) // Array to store monthly P&L% values
var int[] monthlyPnLsCount = array.new_int(0) // Array to store timestamps for monthly P&L%

var float[] yearlyPnLs = array.new_float(0) // Array to store yearly P&L% values
var int[] yearlyPnLsCount = array.new_int(0) // Array to store timestamps for yearly P&L%

// Track whether P&L computation was performed
bool pnlComputed = false

// Store monthly P&L when a new month starts or on the last bar
if (not na(currentMonthProfit[1]) and (newMonth or barstate.islast))
    if (pnlComputed[1])
        array.pop(monthlyProfit) // Remove last value if already computed
        array.pop(monthlyProfitCount)
    
    array.push(monthlyProfit, currentMonthProfit[1]) // Add current month P&L
    array.push(monthlyProfitCount, time[1]) // Add corresponding timestamp

// Store monthly P&L% when a new month starts or on the last bar
if (not na(currentMonthPnL[1]) and (newMonth or barstate.islast))
    if (pnlComputed[1])
        array.pop(monthlyPnLs) // Remove last value if already computed
        array.pop(monthlyPnLsCount)
    
    array.push(monthlyPnLs, currentMonthPnL[1]) // Add current month P&L
    array.push(monthlyPnLsCount, time[1]) // Add corresponding timestamp

// Store yearly P&L when a new year starts or on the last bar
if (not na(currentYearProfit[1]) and (newYear or barstate.islast))
    if (pnlComputed[1])
        array.pop(yearlyProfit) // Remove last value if already computed
        array.pop(yearlyProfitCount)
    
    array.push(yearlyProfit, currentYearProfit[1]) // Add current year P&L
    array.push(yearlyProfitCount, time[1]) // Add corresponding timestamp

// Store yearly P&L when a new year starts or on the last bar
if (not na(currentYearPnL[1]) and (newYear or barstate.islast))
    if (pnlComputed[1])
        array.pop(yearlyPnLs) // Remove last value if already computed
        array.pop(yearlyPnLsCount)
    
    array.push(yearlyPnLs, currentYearPnL[1]) // Add current year P&L
    array.push(yearlyPnLsCount, time[1]) // Add corresponding timestamp


// Set to true on the last bar to indicate that P&L% computation has been performed
pnlComputed := barstate.islast ? true : (pnlComputed[1] ? pnlComputed[1] : false)

// Profit/Loss table
var table monthlyProfitTable = table(na)

if show_table

    // Create a table for profit/loss
    if (barstate.islast)
        monthlyProfitTable := table.new(position = position.top_right, columns = 14, rows = array.size(yearlyProfit) +1, border_width = 1)
        table.cell(monthlyProfitTable, 0,  0, "Y|M",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 1,  0, "Jan",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 2,  0, "Feb",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 3,  0, "Mar",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 4,  0, "Apr",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 5,  0, "May",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 6,  0, "Jun",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 7,  0, "Jul",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 8,  0, "Aug",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 9,  0, "Sep",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 10, 0, "Oct",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 11, 0, "Nov",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 12, 0, "Dec",  text_color = color.white, bgcolor = TABLE_HEADER_COLOR)
        table.cell(monthlyProfitTable, 13, 0, "Year", text_color = color.white, bgcolor = TABLE_HEADER_COLOR)

        // Create a row for each year
        for yearIndex = 0 to array.size(yearlyProfit) - 1
            // Create year index cell
            table.cell(monthlyProfitTable, 0, yearIndex + 1, str.tostring(year(array.get(yearlyProfitCount, yearIndex))), text_color = color.white, bgcolor = TABLE_CELL_COLOR)

            // Create Year  P&L cells
            string yearlyReturnValue = str.format("{0,number,integer}", math.round(number = array.get(yearlyProfit, yearIndex), precision = prec))
            string yearlyReturnPercent = str.tostring(math.round(number = array.get(yearlyPnLs,yearIndex)*100, precision = prec)) + " %"
            yearColor = array.get(yearlyProfit, yearIndex) > 0 ? TABLE_YEAR_CELL_POSITIVE_COLOR : TABLE_YEAR_CELL_NEGATIVE_COLOR
            table.cell(monthlyProfitTable, 13, yearIndex + 1, yearlyReturnValue + " \n" + yearlyReturnPercent, text_color = color.white, bgcolor = yearColor)
        
        for monthIndex = 0 to array.size(monthlyProfit) - 1
            string monthlyReturnValue = str.format("{0,number,integer}", math.round(number = array.get(monthlyProfit, monthIndex), precision = prec))
            string monthlyReturnPercent = str.tostring(math.round(number = array.get(monthlyPnLs, monthIndex)*100, precision = prec)) + "%"
            monthRow = year(array.get(monthlyProfitCount, monthIndex)) - year(array.get(yearlyProfitCount, 0)) + 1
            monthColumn = month(array.get(monthlyProfitCount, monthIndex))
            monthColor = array.get(monthlyProfit, monthIndex) > 0 ? TABLE_YEAR_CELL_POSITIVE_COLOR : TABLE_YEAR_CELL_NEGATIVE_COLOR
            table.cell(monthlyProfitTable, monthColumn, monthRow, monthlyReturnValue + "\n" + monthlyReturnPercent, text_color = color.white, bgcolor = monthColor)

Overview

USDTHB TFEX Strategy detects swing highs and swing lows using a long left bar count and a one bar right count, tracks the latest levels, and trades breakouts of them with a fixed contract count and a per-contract commission. A monthly and yearly return table is optional. Pivots confirm late and orders run on every tick, and there is no stop loss. It draws on the price chart.

Details

Published by

lumduan on GitHub

Draws

On the price chart

Markets

Forex

Timeframes

M15-H1

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)
  • 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
leftBarsint82leftBars
rightBarsint1rightBars
Show Return Rate Table On/Offbooltrueshow_table
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

This trend-following strategy executes a classic Donchian channel breakout system designed to cross-validate backtest results against external framework benchmarks. It triggers a long entry when the closing price breaks above the highest high of the prior entr

Strategy v6 BreakoutTrend
Updated yesterday · AGPL-3.0 GitHub repository of Forven S01509 - Simple Donchian 20/10 Breakout
257 stars

This strategy plots running pivot highs as red R circles and pivot lows as blue S circles directly on the price chart. It computes an EMA 3 and a Cto trend line from close prices, then generates long signals on upward EMA-Cto crossovers combined with price pos

Strategy v6 TrendMoving averages Repaints
Updated 6 weeks ago · None stated GitHub repository of Best Chart 1m Strategy Candle Bar

STRG-HOLP

by harryguiacorn
220 stars

STRG-HOLP is a trading strategy that identifies High of Low Period (HOLP) and Low of High Period (LOHP) breakout setups. It tracks the lowest low or highest high over a user-defined lookback window. A long trade opens when the close breaks above the high of th

Strategy v5 BreakoutSupport & resistance
Updated 1 year ago · None stated GitHub repository of STRG-HOLP
106 stars

This script monitors opening gap conditions and breakout behavior relative to the first candle's range across up to twenty configurable stock tickers. It detects whether following bars remain inside the opening range before breaking out, displaying the status

Strategy v4 Screeners & dashboardsBreakout Repaints
Updated 2 years ago · GPL-3.0 GitHub repository of 1St Bar GAP+BkOut Screener v2 by RM

This trend breakout strategy plots Donchian Channels consisting of upper, lower, and middle bands directly on the main price chart. Long positions enter when price touches the upper channel and pulls back to or below the middle band, placing a stop loss at the

Strategy v6 TrendBreakout
Updated 2 months ago · MPL-2.0 GitHub repository of Donchian Strategy - Dynamic TP, Fixed SL, 1% Risk, Daily Target

More Breakout scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers