Golden Triangle Strategy
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee

//@version=4

//Golden Triangle strategy setup is a variation of the buy-the-dip strategy, by Charlotte Hudgin.
//You can find the detailed explanataion here  by Thomas N. Bulkowski   http://thepatternsite.com/GoldenTriangle.html

strategy(title="Golden Triangle Strategy", overlay=true,pyramiding=2, default_qty_type=strategy.percent_of_equity,  default_qty_value=10,    initial_capital=10000, currency=currency.USD, max_bars_back=200)
// variables  BEGIN

var triangleFound=false
var windupPrice=0.00

var stopLossVal=0.00

//find the index of highest high  of n periods 
findIndexForWhiteSpace(smaLength1, lookbackPds1) =>
    prev_index=0
    smaVal1=sma(close, smaLength1)
    for i=1 to lookbackPds1
        if low[i]<smaVal1[i] and close[i]>smaVal1[i]
            prev_index:=i
            break
        if open[i] < smaVal1[1] and high[i]<smaVal1[i]
            prev_index:=0
            break
    prev_index

//find the index of highest high  of n periods 
index_HH(pds) =>
    tHH =0.00
    HH_index=1
    for i=1 to pds
        if high[i]>tHH
            tHH:=high[i]
            HH_index:=i
          
    HH_index
    
//find the index of lowest low  of n periods 
index_LL(pds) =>
    tLL = low[0]
    LL_index=1
    for i=1 to pds
        if low[i]<tLL
            tLL:=low[i]
            LL_index:=i
          
    LL_index

    

smaLength=input(50,title="SMA Length")
lookBackPds=input(200,title="Look Back periods")

riskCapital = input(title="Risk % of capital", defval=10, minval=1)
stopLoss = input(title="Stop Loss%", defval=6, minval=1)
changeBarColor = input(true, title="chage bar color")
showAllTriangles = input(false, title="show Triangles even after Long position is taken")

//pivot points 
pivotPeriod = input(defval = 5, title="Pivot Point Period", minval = 1, maxval = 50)
atrFactor=input(defval = 3, title = "ATR Factor", minval = 1, step = 0.1)
atrPeriod=input(defval = 50, title = "ATR Period", minval=1)


smaVal = sma(close, smaLength)

//plot sma
plot(smaVal, color = color.green, linewidth = 1, transp=0)


isPriceAbove50=true
for i=1 to 10
    if not(high[i]>smaVal and low[i]>smaVal)
        isPriceAbove50:=false
        break
   
    
    
longCondition= isPriceAbove50   and high>smaVal and low<smaVal //check for current candle        


lastIndex=findIndexForWhiteSpace(smaLength, lookBackPds)


// On the last price bar, make a new trend line
HH_index=index_HH(lastIndex)
//LL_index=index_LL(numPeriods)


drawCondition=showAllTriangles==true ? longCondition and lastIndex>1  : longCondition and lastIndex>1 and strategy.position_size<1

if (drawCondition  ) //longCondition and lastIndex>1 )  //and strategy.position_size<1
    //draw line from last touch point to pivot (Gighest High)
    line.new(x1=bar_index[lastIndex], y1=low[lastIndex],
         x2=bar_index[HH_index], y2=high[HH_index], color=color.red, width=2)
    //draw line from Highest to current price touch point
    line.new(x1=bar_index[HH_index], y1=high[HH_index],
         x2=bar_index, y2=close, color=color.green, width=2) 
    //draw line from previous touch to current touch -- This is trianle base
    line.new(x1=bar_index[lastIndex], y1=low[lastIndex],
         x2=bar_index, y2=close, color=color.blue, width=2)           
    triangleFound:=true
    windupPrice:=low[lastIndex]    //+ ( abs(high[HH_index]-low[lastIndex])*0.61)
    //mycomment:="High="+tostring(HH_index,"######")
    
//voulmeConfirmed= triangleFound and volume[0]>volume[1] and volume[0]>volume[2] and volume[0]>volume[3] and volume[0]>volume[4]
vwapVal=vwap

//pivot points calculation BEGIN
float pvtHigh = na
float pvtLow = na
pvtHigh := pivothigh(pivotPeriod, pivotPeriod)
pvtLow := pivotlow(pivotPeriod, pivotPeriod)

float center = na
center := center[1]
float lastpp = pvtHigh ? pvtHigh : pvtLow ? pvtLow : na

if lastpp
    if na(center)
        center := lastpp
    else
        center := (center * 2 + lastpp) / 3

Up = center - (atrFactor * atr(atrPeriod))
Dn = center + (atrFactor * atr(atrPeriod))

float TUp = na
float TDown = na
Trend = 0
TUp := close[1] > TUp[1] ? max(Up, TUp[1]) : Up
TDown := close[1] < TDown[1] ? min(Dn, TDown[1]) : Dn
Trend := close > TDown[1] ? 1: close < TUp[1]? -1: nz(Trend[1], 1)
//Trailingsl = Trend ==s 1 ? TUp : TDown

//draw pivot points
Trailingstop = Trend == 1 ? TUp : TDown
tslColor = Trend == 1 and nz(Trend[1]) == 1 ? color.lime : Trend == -1 and nz(Trend[1]) == -1 ? color.red : na
plot(Trend==1 ? TUp:na, color = tslColor ,  linewidth = 2, title = "Pivot Trailing Stop")


//pivot points calculation END

//Entry--
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity  * riskCapital / 100 ) /  (close*stopLoss/100)  

//check if cash is sufficient  to buy qty1  , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1

//Entry
//strategy.entry(id="GT LE", comment="GT LE SL="+tostring(close*(1-(stopLoss*0.01)), "####.##"),  long=true,  qty=qty1 , when= triangleFound and crossover(close,vwapVal) )    //and strategy.position_size<1

strategy.entry(id="GT LE", comment="GT LE SL="+tostring(close*(1-(stopLoss*0.01)), "####.##"),  long=true,  qty=qty1 , when= triangleFound and Trend == 1    and crossover(close,vwapVal) )    //and strategy.position_size<1 



triangleFound:= strategy.position_size>=1 ? false :triangleFound

//stoploss
stopLossVal:=  strategy.position_size>=1 ?  (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00


//Add
//if (strategy.position_size>=1 and  close>stopLossVal  and close<TUp )  //longCondition   and crossover(close, vwapVal)
  //  strategy.entry(id="GT LE", comment="Add", long=true, when= strategy.position_size>=1 and longCondition and close>vwapVal)  //close<strategy.position_avg_price and crossover(close,smaVal))   
  //  strategy.entry(id="GT LE", comment="Add  new SL="+tostring(close*(1-(stopLoss*0.01)), "####.##"), long=true) 
    //stoploss

//stopLossVal:=  strategy.position_size>=1 ?  (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00


//barcolor(strategy.position_size>=1 ? color.blue : na)

//Take profit
takeProfitVal=   strategy.position_size>=1 ?  (strategy.position_avg_price * (1+(2*0.01) )) : 0.00
//takeProfitVal=   strategy.position_size>=1 ?  windupPrice : 0.00

//barcolor(strategy.position_size>=1  and changeBarColor==true ? (close>takeProfitVal? color.purple : color.blue): na)

//draw initil stop loss
plot(strategy.position_size>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr,  linewidth = 2, title = "stop loss")


bgcolor(strategy.position_size>=1?color.blue:na, transp=80)

//plot(close>strategy.position_avg_price ? TUp: stopLossVal>0 ? stopLossVal : na, color = color.green ,  linewidth = 2, title = "Pivot Trailing Stop")

//Exit
//strategy.close(id="GT LE", comment="GT Exit",   when=close>=takeProfitVal)
//strategy.close(id="GT LE", comment="GT Exit",   when=close>takeProfitVal and crossunder(close,smaVal))   --- original
//strategy.close(id="GT LE", comment="GTVW Exit  points="+tostring(close-strategy.position_avg_price,"###.##"),   when=close>strategy.position_avg_price and crossunder(vwapVal,smaVal) )  //close<vwapVal and close<smaVal)
strategy.close(id="GT LE", comment="GTVW Exit  points="+tostring(close-strategy.position_avg_price,"###.##"),   when=close>strategy.position_avg_price and crossunder(vwapVal,smaVal))    // and crossunder(vwapVal,smaVal)
//strategy.close(id="GT LE", comment="GTVW Exit  points="+tostring(close-strategy.position_avg_price,"###.##"),   when= vwapVal < TUp )    // and crossunder(vwapVal,smaVal)

//strategy.close(id="GT LE", comment="GTVW Exit  points="+tostring(close-strategy.position_avg_price,"###.##"),   when=close>strategy.position_avg_price and crossunder(vwapVal,smaVal))


//strategy.close(id="GT LE", comment="SL Exit points="+tostring(close-strategy.position_avg_price,"###.##") ,  when= close< stopLossVal )   //windupPrice

strategy.close(id="GT LE", comment="SL Exit points="+tostring(close-strategy.position_avg_price,"###.##") ,  when=crossunder(close,stopLossVal) )   //windupPrice     (strategy.position_avg_price - close ) > 10
    