# trail_stop_offset_inc_00c
#https://usethinkscript.com/threads/trailing-stop-loss-help-needed.16492/
#Trailing Stop Loss - Help needed
#Once the price is $2 above entry price, activate the trailing stop loss, and from therein it will increment by .01 as #price increases accordingly.
#------------------------------
# test data
# ma_cross
def na = double.nan;
def bn = barnumber();
def price = close;
input ma1_len = 21;
input ma1_type = AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);
input ma2_len = 55;
input ma2_type = AverageType.EXPONENTIAL;
def ma2 = Movingaverage(ma2_type, price, ma2_len);
input show_test_data_lines = yes;
plot z1 = if show_test_data_lines then ma1 else na;
#z1.setdefaultcolor(color.light_gray);
z1.setdefaultcolor(color.yellow);
#z1.setlineweight(1);
z1.hidebubble();
plot z2 = if show_test_data_lines then ma2 else na;
z2.setdefaultcolor(color.light_gray);
#z2.setlineweight(1);
z2.hidebubble();
#------------------------------
# test signals
def buy1 = ma1 crosses above ma2;
def sell1 = ma1 crosses below ma2;
#------------------------------
input stop_price_offset = -2.00;
#input cross_stop_amt = 0.3;
def big = 99999;
# horz buy level
def buy_pr = if bn == 1 or sell1 then big
else if buy1 then close
else buy_pr[1];
def y = (buy_pr + stop_price_offset);
def cls_diff1 = close - close[1];
def cls_diff2 = close - buy_pr;
def stop_lvl = if bn == 1 then 0
else if sell1 then 0
else if close < stop_lvl[1] then 0
else if buy1 then y
else if (stop_lvl[1] > 0 and cls_diff1 > 0) then max(stop_lvl[1], close + stop_price_offset)
else stop_lvl[1];
# horz buy level
plot z3 = if buy_pr < big then buy_pr else na;
z3.setdefaultcolor(color.green);
z3.setlineweight(1);
#z3.hidebubble();
plot z4 = if stop_lvl > 0 and stop_lvl < big then stop_lvl else na;
z4.setdefaultcolor(color.cyan);
z4.setlineweight(2);
#z4.hidebubble();
def sell2 = if sell1 or (stop_lvl[1] > 0 and stop_lvl == 0) then 1 else 0;
def buy2 = if stop_lvl[1] == 0 then buy1 else 0;
input trade_size = 1;
AddOrder(OrderType.BUY_TO_OPEN, buy2, open[-1], tradeSize = trade_size, tickColor = Color.green, arrowColor = Color.green, name = "buy");
AddOrder(OrderType.SELL_TO_CLOSE, sell2, open[-1] , tradeSize = trade_size, tickcolor = Color.red, arrowcolor = Color.red, name = "sell");
#-----------------------------
input test1_bubble = no;
addchartbubble(test1_bubble, low*0.98,
buy1 + "\n" +
stop_lvl
, color.yellow, no);
#