How to count how many times "AddOrder" is executed?

MrJefe

New member
Im writing a backtesting "Strategy" for ThinkorSwim. Is there any way to tell the script to count every time it executes the "AddOrder" commands? Lets say my script uses the order definitions below. I'd like the script to count how many times "longWin" and "longLoss" were executed and display on-screen the strategy's win rate. Right now Im just manually counting the wins and losses in the "Show Report" but that's massively time consuming. Anyone tried this?



def longEntry = <insert entry conditions here>;
def longWin = <insert winning trade conditions, usually a Profit Target>;
def longLoss = <insert losing trade conditions, usually a Stop Loss>;

AddOrder(OrderType.BUY_TO_OPEN, longEntry, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Long", price = close);

AddOrder(OrderType.SELL_TO_CLOSE, longWin, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Long Win", price = close);

AddOrder(OrderType.SELL_TO_CLOSE, longLoss, tickcolor = Color.RED, arrowcolor = Color.RED, name = "Long Loss", price = close);
 
Solution
Hi guys, i found this conversation very interesting. Do you know how to limit addorder to only once per trading session? I would love to use it for backtesting and make sure my strategy is executed only once per day. thanks in advance hal_once

study the formulas in this lower study.
this looks for trigger signal(s) changing from 0 to 1.
you can pick how many triggers to process per day. default is one.


Ruby:
# do_once_03
# halcyonguy
# 2020-07

# make an output var that changes only x times a day, with multiple input triggers

declare lower;

input maxtrades = 1;

def lastbar = !isnan(close) && isnan(close[-1]);
#def istoday = if GetLastDay() == GetDay() then 1 else 0;
def dow2 = GetDayofWeek(GetYYYYMMDD());

input...
addorder is triggered by a condition. you can count how many times that conditiin is true.
Code:
def longwincount = totalsum(longwin);

https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/TotalSum


or you can increment a counter when a variable changes value, like when longwin is true.
Code:
def longwincount2 = if barnumber() == 1 then 0 else if longwin then longwincount2[1] + 1 else longwincount2[1];

https://usethinkscript.com/threads/...-bars-on-entire-chart-or-specified-time.5496/
 
addorder is triggered by a condition. you can count how many times that conditiin is true.
Code:
def longwincount = totalsum(longwin);

https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/TotalSum


or you can increment a counter when a variable changes value, like when longwin is true.
Code:
def longwincount2 = if barnumber() == 1 then 0 else if longwin then longwincount2[1] + 1 else longwincount2[1];

https://usethinkscript.com/threads/...-bars-on-entire-chart-or-specified-time.5496/
Bless your thinkscript knowledge
 
Hi, I'd like to add a condition in the code of my strategy that limits the number of trades the strategy can enter per day based on a user's desired input. I already have a piece of code that limits the time window when a trade can be taken each day, but this seems to be a bit beyond my limited coding skills. Any help is appreciated!
 
if addorder is triggered and then the condition becomes true again while the strategy is still in an open position (in which case a new addorder is NOT triggered), does the counter still keep adding on to the count?
 
Hi, I'd like to add a condition in the code of my strategy that limits the number of trades the strategy can enter per day based on a user's desired input. I already have a piece of code that limits the time window when a trade can be taken each day, but this seems to be a bit beyond my limited coding skills. Any help is appreciated!

you could have an input for a max count, then check if the trigger counter is less than the max number. this would be a 2nd formula, like an enable , to pass on to the addorder.

Code:
input max_buys = 4;
def longwincount = totalsum(longwin);
def buy = if longwincount <= max_buys then 1 else 0;
then use buy , as the trigger for addorder.
 
if addorder is triggered and then the condition becomes true again while the strategy is still in an open position (in which case a new addorder is NOT triggered), does the counter still keep adding on to the count?
yes, i think the counter will count every occurance of longwin.
would have to add other conditions to check , to the counter formula, to alter when its value is changed.
 
Hi guys, i found this conversation very interesting. Do you know how to limit addorder to only once per trading session? I would love to use it for backtesting and make sure my strategy is executed only once per day. thanks in advance
 
Hi guys, i found this conversation very interesting. Do you know how to limit addorder to only once per trading session? I would love to use it for backtesting and make sure my strategy is executed only once per day. thanks in advance hal_once

study the formulas in this lower study.
this looks for trigger signal(s) changing from 0 to 1.
you can pick how many triggers to process per day. default is one.


Ruby:
# do_once_03
# halcyonguy
# 2020-07

# make an output var that changes only x times a day, with multiple input triggers

declare lower;

input maxtrades = 1;

def lastbar = !isnan(close) && isnan(close[-1]);
#def istoday = if GetLastDay() == GetDay() then 1 else 0;
def dow2 = GetDayofWeek(GetYYYYMMDD());

input reset_each_day = yes;
def dow = if reset_each_day then dow2 else 0;

# ==================================================================
# replace this section with your trigger formula(s)
# replace the trigger2 =  formula with your master trigger formula

# test formulas , 2 averages
def cls = close;
input length1 = 7;
input length2 = 11;
def AvgExp1 = ExpAverage(cls, length1);
def AvgExp2 = ExpAverage(cls, length2);
# trigger signal
def trigger2 = if avgexp1 > AvgExp2 then 1 else 0;
# =================================================================

# set it true when the trigger2 signal changes from a low to a high
def trigger = (trigger2[1] == 0 and trigger2[0] == 1);

def cnt = if barnumber() == 1 then 0
 else if ((dow <> dow[1]) and trigger) then 1
 else if (dow <> dow[1]) then 0
 else if trigger then (cnt[1] + 1)
 else cnt[1];

def buy = ( trigger and cnt <= maxtrades);

plot trig2 = if trigger2 then 2 else 1;
plot once2 = if buy then 4 else 3;
plot buy2 = if buy then 6 else 5;

# top and bottom lines, to make it easier to see signal lines
plot a = 0;
plot b = 7;

# desc bubbles location
input bubble_offset = 2;
input show_bubbles = yes;
def x = show_bubbles and lastbar[bubble_offset];

addchartbubble(x , 0.5 , "trigger" , Color.YELLOW , yes);
addchartbubble(x , 2.5 , maxtrades + "/" + (if reset_each_day then "day" else "chart"), Color.YELLOW , yes);
addchartbubble(x , 4.5 , "buy" , Color.YELLOW , yes);

# day separator lines
addverticalline((dow <> dow[1]), "day", color.cyan);

#addchartbubble(1, 9, dow + "\n" + dow[1] , color.cyan, no);
#addchartbubble(1, 9, trigger + "\n" + cnt , color.cyan, no);
#plot t = 9.5;
#


in this example , the code is set to 1 output pulse per day.
this shows a pulsing trigger signal. on the first 0 to 1 move, not a sustained 1 from yesterday, an output pulse is created.
22-01-29 AIG 3min
3Un7usO.jpg
 
Last edited:
Solution
I've been struggling with something similar. attempting to count not only the long entries, but the stop outs and take profits as well. The problem is finding a way to create an "orderON" variable that switches to 1 on the order entry and to 0 on the exit. Since the "variables" for Thinkscript all seem to be data dependent, constants that may only be defined once, I haven't been able to figure out how to proceed. If anyone has any ideas they would be greatly welcome. Thanks in advance.
 
I've been struggling with something similar. attempting to count not only the long entries, but the stop outs and take profits as well. The problem is finding a way to create an "orderON" variable that switches to 1 on the order entry and to 0 on the exit. Since the "variables" for Thinkscript all seem to be data dependent, constants that may only be defined once, I haven't been able to figure out how to proceed. If anyone has any ideas they would be greatly welcome. Thanks in advance.

this is a template.
remove the test data code, between the ////////// , and replace with your desired code for generating buy signals.

-----------------

this uses several if-then blocks and several variables, to count buys and sells.
this is for long trades only.

you didn't provide any rules or code, so i had to create this from scratch.
i used 2 averages crossing, to generate a buy signal.

when a buy happens , it saves the close as the buy price.
from that buy price , 2 numbers are added the buy price, to come up with a stop gain price and a stop loss price.
when close goes beyond one of the stop prices, the trade ends.
during a trade, trade = 1

horizontal lines are drawn during a trade,
...green = stop gain
...white = buy price
...red = stop loss

i picked 2 numbers at random for the default stops,
...gain $ = 0.50
...loss $ = -0.20

3 labels show the counts for, buys, sells-gain, sell-loss


Code:
# template_buysell2_long_avgs_x_trade

# buy signals based on averages crossing
# sell signals based on gain and loss target levels

def na = Double.NaN;
def bn = BarNumber();

# /////////////////////////////
# test data
# for buying , short avg crossing above long avg

def price = close;

input ma1_len = 9;
input ma1_type =  AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);

input ma2_len = 33;
input ma2_type =  AverageType.EXPONENTIAL;
def ma2 = MovingAverage(ma2_type, price, ma2_len);


input show_lines = yes;
plot z1 = if show_lines then ma1 else na;
 z1.SetDefaultColor(GetColor(1));
 #z1.setlineweight(1);
 z1.HideBubble();
plot z2 = if show_lines then ma2 else na;
 z2.SetDefaultColor(GetColor(2));
 #z2.setlineweight(1);
 z2.HideBubble();

def ma1xup = (ma1 crosses above ma2);
def ma1xdwn = (ma1 crosses below ma2);

# /////////////////////////////
# configure buy , sell vars

def buy = ma1xup;
def sell = ma1xdwn;

#-----------------------------

# numbers added to the buy price to determine sell levels
input stop_gain = 0.5;
input stop_loss = -0.2;

# when a buy happens, record the close. use that close as a ref for the stops +- $x
# just for long trades
def buy_pr;
def sell_gain_pr;
def sell_loss_pr;
def trade;
def gain;
def buy_cnt;
def sell_gain_cnt;
def sell_loss_cnt;
if bn == 1 then {
 buy_pr = 0;
 sell_gain_pr = 0;
 sell_loss_pr = 0;
 trade = 0;
 gain = 0;
 buy_cnt = 0;
 sell_gain_cnt = 0;
 sell_loss_cnt = 0;

} else if buy and !trade[1] then {
# not in a trade, process a buy. record the close as the buy price
 buy_pr = close;
 sell_gain_pr = buy_pr + stop_gain;
 sell_loss_pr = buy_pr + stop_loss;
 trade = 1;
 gain = 0;
 buy_cnt = buy_cnt[1] + 1;
 sell_gain_cnt = sell_gain_cnt[1];
 sell_loss_cnt = sell_loss_cnt[1];

} else if trade[1] and close > sell_gain_pr[1] then {
# price reached target, sell for gain
 buy_pr = 0;
 sell_gain_pr = 0;
 sell_loss_pr = 0;
 trade = 0;
 gain = close - buy_pr[1];
 buy_cnt = buy_cnt[1];
 sell_gain_cnt = sell_gain_cnt[1]+1;
 sell_loss_cnt = sell_loss_cnt[1];

} else if trade[1] and close < sell_loss_pr[1] then {
# price fell below stop, sell for loss
 buy_pr = 0;
 sell_gain_pr = 0;
 sell_loss_pr = 0;
 trade = 0;
 gain = close - buy_pr[1];
 buy_cnt = buy_cnt[1];
 sell_gain_cnt = sell_gain_cnt[1];
 sell_loss_cnt = sell_loss_cnt[1]+1;

} else if !isnan(close) then {
 buy_pr = buy_pr[1];
 sell_gain_pr = sell_gain_pr[1];
 sell_loss_pr = sell_loss_pr[1];
 trade = trade[1];
 gain = close - buy_pr[1];
 buy_cnt = buy_cnt[1];
 sell_gain_cnt = sell_gain_cnt[1];
 sell_loss_cnt = sell_loss_cnt[1];

} else {
 buy_pr = 0;
 sell_gain_pr = 0;
 sell_loss_pr = 0;
 trade = 0;
 gain = 0;
 buy_cnt = 0;
 sell_gain_cnt = 0;
 sell_loss_cnt = 0;
}


# --------------------
addlabel(1, "Buys " + buy_cnt, color.white);
addlabel(1, "Sells , gain " + sell_gain_cnt , color.green);
addlabel(1, "Sells , loss " + sell_loss_cnt , color.red);


#---------------------
# lines

plot zb = if buy_pr > 0 then buy_pr else if buy_pr[1] > 0 then buy_pr[1] else na;
zb.SetDefaultColor(Color.white);
zb.setlineweight(2);
zb.hidebubble();

plot zstopg = if buy_pr > 0 then sell_gain_pr else if buy_pr[1] > 0 then sell_gain_pr[1] else na;
zstopg.SetDefaultColor(Color.green);
zstopg.setlineweight(1);
zstopg.hidebubble();

plot zstopl = if buy_pr > 0 then sell_loss_pr else if buy_pr[1] > 0 then sell_loss_pr[1] else na;
zstopl.SetDefaultColor(Color.red);
zstopl.setlineweight(1);
zstopl.hidebubble();

# ---------------------

input show_buy_arrows = yes;
def arroff = 11;
def y = arroff * ticksize();

plot zbuy = if show_buy_arrows and buy then low-y else na;
zbuy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
zbuy.SetDefaultColor(Color.green);
zbuy.setlineweight(3);
zbuy.hidebubble();


#x.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
#x.SetDefaultColor(Color.red);
#x.setlineweight(1);
#x.hidebubble();


#----------------------
# sell shapes

# sell gain - triangle
def sellgain = if trade[1] and close > sell_gain_pr[1] then 1 else 0;
plot zsg = if sellgain then high + y else na;
zsg.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
zsg.SetDefaultColor(Color.green);
zsg.setlineweight(4);
zsg.hidebubble();

# sell loss - square
def sellloss = if trade[1] and close < sell_loss_pr[1] then 1 else 0;
plot zsl = if sellloss then low - y else na;
zsl.SetPaintingStrategy(PaintingStrategy.SQUARES);
zsl.SetDefaultColor(Color.red);
zsl.setlineweight(4);
zsl.hidebubble();

#

PYPL 20D hour
show 5 buys , 2 sells at gain , 2 sells at loss, 1 active trade
stops calculated from buy price
gain $ = 0.50
loss $ = -0.20
green triangle above last bar on a trade with a gain
red square below last bar on a trade with a loss
kUXcddw.jpg
 
Last edited:
this is a template.
remove the test data code, between the ////////// , and replace with your desired code for generating buy signals.

-----------------

this uses several if-then blocks and several variables, to count buys and sells.
this is for long trades only.

you didn't provide any rules or code, so i had to create this from scratch.
i used 2 averages crossing, to generate a buy signal.

when a buy happens , it saves the close as the buy price.
from that buy price , 2 numbers are added the buy price, to come up with a stop gain price and a stop loss price.
when close goes beyond one of the stop prices, the trade ends.
during a trade, trade = 1

horizontal lines are drawn during a trade,
...green = stop gain
...white = buy price
...red = stop loss

i picked 2 numbers at random for the default stops,
...gain $ = 0.50
...loss $ = -0.20

3 labels show the counts for, buys, sells-gain, sell-loss


Code:
# template_buysell2_avgs_x_trade

# buy signals based on averages crossing
# sell signals based on gain and loss target levels

def na = Double.NaN;
def bn = BarNumber();

# /////////////////////////////
# test data
# for buying , short avg crossing above long avg

def price = close;

input ma1_len = 9;
input ma1_type =  AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);

input ma2_len = 33;
input ma2_type =  AverageType.EXPONENTIAL;
def ma2 = MovingAverage(ma2_type, price, ma2_len);


input show_lines = yes;
plot z1 = if show_lines then ma1 else na;
 z1.SetDefaultColor(GetColor(1));
 #z1.setlineweight(1);
 z1.HideBubble();
plot z2 = if show_lines then ma2 else na;
 z2.SetDefaultColor(GetColor(2));
 #z2.setlineweight(1);
 z2.HideBubble();

def ma1xup = (ma1 crosses above ma2);
def ma1xdwn = (ma1 crosses below ma2);

# /////////////////////////////
# configure buy , sell vars

def buy = ma1xup;
def sell = ma1xdwn;

#-----------------------------

# numbers added to the buy price to determine sell levels
input stop_gain = 0.5;
input stop_loss = -0.2;

# when a buy happens, record the close. use that close as a ref for the stops +- $x
# just for long trades
def buy_pr;
def sell_gain_pr;
def sell_loss_pr;
def trade;
def gain;
def buy_cnt;
def sell_gain_cnt;
def sell_loss_cnt;
if bn == 1 then {
 buy_pr = 0;
 sell_gain_pr = 0;
 sell_loss_pr = 0;
 trade = 0;
 gain = 0;
 buy_cnt = 0;
 sell_gain_cnt = 0;
 sell_loss_cnt = 0;

} else if buy and !trade[1] then {
# not in a trade, process a buy. record the close as the buy price
 buy_pr = close;
 sell_gain_pr = buy_pr + stop_gain;
 sell_loss_pr = buy_pr + stop_loss;
 trade = 1;
 gain = 0;
 buy_cnt = buy_cnt[1] + 1;
 sell_gain_cnt = sell_gain_cnt[1];
 sell_loss_cnt = sell_loss_cnt[1];

} else if trade[1] and close > sell_gain_pr[1] then {
# price reached target, sell for gain
 buy_pr = 0;
 sell_gain_pr = 0;
 sell_loss_pr = 0;
 trade = 0;
 gain = close - buy_pr[1];
 buy_cnt = buy_cnt[1];
 sell_gain_cnt = sell_gain_cnt[1]+1;
 sell_loss_cnt = sell_loss_cnt[1];

} else if trade[1] and close < sell_loss_pr[1] then {
# price fell below stop, sell for loss
 buy_pr = 0;
 sell_gain_pr = 0;
 sell_loss_pr = 0;
 trade = 0;
 gain = close - buy_pr[1];
 buy_cnt = buy_cnt[1];
 sell_gain_cnt = sell_gain_cnt[1];
 sell_loss_cnt = sell_loss_cnt[1]+1;

} else if !isnan(close) then {
 buy_pr = buy_pr[1];
 sell_gain_pr = sell_gain_pr[1];
 sell_loss_pr = sell_loss_pr[1];
 trade = trade[1];
 gain = close - buy_pr[1];
 buy_cnt = buy_cnt[1];
 sell_gain_cnt = sell_gain_cnt[1];
 sell_loss_cnt = sell_loss_cnt[1];

} else {
 buy_pr = 0;
 sell_gain_pr = 0;
 sell_loss_pr = 0;
 trade = 0;
 gain = 0;
 buy_cnt = 0;
 sell_gain_cnt = 0;
 sell_loss_cnt = 0;
}


# --------------------
addlabel(1, "Buys " + buy_cnt, color.white);
addlabel(1, "Sells , gain " + sell_gain_cnt , color.green);
addlabel(1, "Sells , loss " + sell_loss_cnt , color.red);


#---------------------
# lines

plot zb = if buy_pr > 0 then buy_pr else if buy_pr[1] > 0 then buy_pr[1] else na;
zb.SetDefaultColor(Color.white);
zb.setlineweight(2);
zb.hidebubble();

plot zstopg = if buy_pr > 0 then sell_gain_pr else if buy_pr[1] > 0 then sell_gain_pr[1] else na;
zstopg.SetDefaultColor(Color.green);
zstopg.setlineweight(1);
zstopg.hidebubble();

plot zstopl = if buy_pr > 0 then sell_loss_pr else if buy_pr[1] > 0 then sell_loss_pr[1] else na;
zstopl.SetDefaultColor(Color.red);
zstopl.setlineweight(1);
zstopl.hidebubble();

# ---------------------

input show_buy_arrows = yes;
def arroff = 11;
def y = arroff * ticksize();

plot zbuy = if show_buy_arrows and buy then low-y else na;
zbuy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
zbuy.SetDefaultColor(Color.green);
zbuy.setlineweight(3);
zbuy.hidebubble();


#x.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
#x.SetDefaultColor(Color.red);
#x.setlineweight(1);
#x.hidebubble();


#----------------------
# sell shapes

# sell gain - triangle
def sellgain = if trade[1] and close > sell_gain_pr[1] then 1 else 0;
plot zsg = if sellgain then high + y else na;
zsg.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
zsg.SetDefaultColor(Color.green);
zsg.setlineweight(4);
zsg.hidebubble();

# sell loss - square
def sellloss = if trade[1] and close < sell_loss_pr[1] then 1 else 0;
plot zsl = if sellloss then low - y else na;
zsl.SetPaintingStrategy(PaintingStrategy.SQUARES);
zsl.SetDefaultColor(Color.red);
zsl.setlineweight(4);
zsl.hidebubble();

#

PYPL 20D hour
show 5 buys , 2 sells at gain , 2 sells at loss, 1 active trade
stops calculated from buy price
gain $ = 0.50
loss $ = -0.20
green triangle above last bar on a trade with a gain
red square below last bar on a trade with a loss
dx19upt.png


Thanks a bunch, this is so very helpful!
 
I've been struggling with something similar. attempting to count not only the long entries, but the stop outs and take profits as well. The problem is finding a way to create an "orderON" variable that switches to 1 on the order entry and to 0 on the exit. Since the "variables" for Thinkscript all seem to be data dependent, constants that may only be defined once, I haven't been able to figure out how to proceed. If anyone has any ideas they would be greatly welcome. Thanks in advance.

figured someone would ask for shorts to be added... to post11 study
this version does longs and shorts

--------------------------
this is just a template.
this is meant for someone to replace the buy code with their code , not to use as is.
the test code for buy signals is just the crossing of 2 averages

-------------------------

another version of the template , in post#11

show long trades and short trades
counts the trades
shows profits , per trade and total


Code:
# template_buysell3_long_short

# add short trades


# buy signals based on averages crossing
# sell signals based on gain and loss target levels

def na = Double.NaN;
def bn = BarNumber();

# /////////////////////////////
# test data
# for buying , short avg crossing above long avg

def price = close;

input ma1_len = 9;
input ma1_type =  AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);

input ma2_len = 33;
input ma2_type =  AverageType.EXPONENTIAL;
def ma2 = MovingAverage(ma2_type, price, ma2_len);


input show_lines = yes;
plot z1 = if show_lines then ma1 else na;
 z1.SetDefaultColor(GetColor(1));
 #z1.setlineweight(1);
 z1.HideBubble();
plot z2 = if show_lines then ma2 else na;
 z2.SetDefaultColor(GetColor(2));
 #z2.setlineweight(1);
 z2.HideBubble();

def ma1xup = (ma1 crosses above ma2);
def ma1xdwn = (ma1 crosses below ma2);

# /////////////////////////////

# configure buy , sell vars

def long_buy = ma1xup;

def short_buy = ma1xdwn;



#-----------------------------

# numbers added to the buy price to determine sell levels
input stop_gain = 0.5;
input stop_loss = -0.2;


#-----------------------------------
# long trades
# when a long buy happens, record the close. use that close as a ref for the stops +- $x
# just for long trades
def long_buy_pr;
def long_sell_gain_pr;
def long_sell_loss_pr;
def long_trade;
def long_gain;
def long_gain_total;
def long_buy_cnt;
def long_sell_gain_cnt;
def long_sell_loss_cnt;
if bn == 1 then {
 long_buy_pr = 0;
 long_sell_gain_pr = 0;
 long_sell_loss_pr = 0;
 long_trade = 0;
 long_gain = 0;
 long_gain_total = 0;
 long_buy_cnt = 0;
 long_sell_gain_cnt = 0;
 long_sell_loss_cnt = 0;

} else if long_buy and !long_trade[1] then {
# not in a trade, process a buy. record the close as the buy price
 long_buy_pr = close;
 long_sell_gain_pr = long_buy_pr + stop_gain;
 long_sell_loss_pr = long_buy_pr + stop_loss;
 long_trade = 1;
 long_gain = 0;
 long_gain_total = long_gain_total[1];
 long_buy_cnt = long_buy_cnt[1] + 1;
 long_sell_gain_cnt = long_sell_gain_cnt[1];
 long_sell_loss_cnt = long_sell_loss_cnt[1];

} else if long_trade[1] and close > long_sell_gain_pr[1] then {
# price reached target, sell for gain
 long_buy_pr = 0;
 long_sell_gain_pr = 0;
 long_sell_loss_pr = 0;
 long_trade = 0;
 long_gain = close - long_buy_pr[1];
 long_gain_total = long_gain_total[1] + long_gain;
 long_buy_cnt = long_buy_cnt[1];
 long_sell_gain_cnt = long_sell_gain_cnt[1]+1;
 long_sell_loss_cnt = long_sell_loss_cnt[1];

} else if long_trade[1] and close < long_sell_loss_pr[1] then {
# price fell below stop, sell for loss
 long_buy_pr = 0;
 long_sell_gain_pr = 0;
 long_sell_loss_pr = 0;
 long_trade = 0;
 long_gain = close - long_buy_pr[1];
 long_gain_total = long_gain_total[1] + long_gain;
 long_buy_cnt = long_buy_cnt[1];
 long_sell_gain_cnt = long_sell_gain_cnt[1];
 long_sell_loss_cnt = long_sell_loss_cnt[1]+1;

} else if !isnan(close) then {
 long_buy_pr = long_buy_pr[1];
 long_sell_gain_pr = long_sell_gain_pr[1];
 long_sell_loss_pr = long_sell_loss_pr[1];
 long_trade = long_trade[1];
 long_gain = close - long_buy_pr[1];
 long_gain_total = long_gain_total[1];
 long_buy_cnt = long_buy_cnt[1];
 long_sell_gain_cnt = long_sell_gain_cnt[1];
 long_sell_loss_cnt = long_sell_loss_cnt[1];

} else {
 long_buy_pr = 0;
 long_sell_gain_pr = 0;
 long_sell_loss_pr = 0;
 long_trade = 0;
 long_gain = 0;
 long_gain_total = 0;
 long_buy_cnt = 0;
 long_sell_gain_cnt = 0;
 long_sell_loss_cnt = 0;
}

#----------------------------


#----------------------------
# short trades
# when a short buy happens, record the close. use that close as a ref for the stops +- $x
# just for short trades
def short_buy_pr;
def short_sell_gain_pr;
def short_sell_loss_pr;
def short_trade;
def short_gain;
def short_gain_total;
def short_buy_cnt;
def short_sell_gain_cnt;
def short_sell_loss_cnt;
if bn == 1 then {
 short_buy_pr = 0;
 short_sell_gain_pr = 0;
 short_sell_loss_pr = 0;
 short_trade = 0;
 short_gain = 0;
 short_gain_total = 0;
 short_buy_cnt = 0;
 short_sell_gain_cnt = 0;
 short_sell_loss_cnt = 0;

} else if short_buy and !short_trade[1] then {
# not in a trade, process a buy. record the close as the buy price
 short_buy_pr = close;
 short_sell_gain_pr = short_buy_pr - stop_gain;
 short_sell_loss_pr = short_buy_pr - stop_loss;
 short_trade = 1;
 short_gain = 0;
 short_gain_total = short_gain_total[1];
 short_buy_cnt = short_buy_cnt[1] + 1;
 short_sell_gain_cnt = short_sell_gain_cnt[1];
 short_sell_loss_cnt = short_sell_loss_cnt[1];

} else if short_trade[1] and close < short_sell_gain_pr[1] then {
# price reached target, sell for gain
 short_buy_pr = 0;
 short_sell_gain_pr = 0;
 short_sell_loss_pr = 0;
 short_trade = 0;
 short_gain = short_buy_pr[1] - close;
 short_gain_total = short_gain_total[1] + short_gain;
 short_buy_cnt = short_buy_cnt[1];
 short_sell_gain_cnt = short_sell_gain_cnt[1]+1;
 short_sell_loss_cnt = short_sell_loss_cnt[1];

} else if short_trade[1] and close > short_sell_loss_pr[1] then {
# price fell below stop, sell for loss
 short_buy_pr = 0;
 short_sell_gain_pr = 0;
 short_sell_loss_pr = 0;
 short_trade = 0;
 short_gain = short_buy_pr[1] - close;
 short_gain_total = short_gain_total[1] + short_gain;
 short_buy_cnt = short_buy_cnt[1];
 short_sell_gain_cnt = short_sell_gain_cnt[1];
 short_sell_loss_cnt = short_sell_loss_cnt[1]+1;

} else if !isnan(close) then {
 short_buy_pr = short_buy_pr[1];
 short_sell_gain_pr = short_sell_gain_pr[1];
 short_sell_loss_pr = short_sell_loss_pr[1];
 short_trade = short_trade[1];
 short_gain = short_buy_pr[1] - close;
 short_gain_total = short_gain_total[1];
 short_buy_cnt = short_buy_cnt[1];
 short_sell_gain_cnt = short_sell_gain_cnt[1];
 short_sell_loss_cnt = short_sell_loss_cnt[1];

} else {
 short_buy_pr = 0;
 short_sell_gain_pr = 0;
 short_sell_loss_pr = 0;
 short_trade = 0;
 short_gain = 0;
 short_gain_total = short_gain_total[1];
 short_buy_cnt = 0;
 short_sell_gain_cnt = 0;
 short_sell_loss_cnt = 0;
}


#---------------------------

def lgain = round(long_gain,2);
def sgain = round(short_gain,2);
def lgainttl = round(long_gain_total,2);
def sgainttl = round(short_gain_total,2);

# --------------------

addlabel(1, "   ", color.black);
addlabel(1, "LONG trades", color.green);
addlabel(1, "Buys " + long_buy_cnt, color.white);
addlabel(1, "Sells , gain " + long_sell_gain_cnt , color.green);
addlabel(1, "Sells , loss " + long_sell_loss_cnt , color.red);
addlabel(1, "profit " +  lgainttl, color.yellow);


addlabel(1, "   ", color.black);
addlabel(1, "SHORT trades", color.red);
addlabel(1, "Buys " + short_buy_cnt, color.white);
addlabel(1, "Sells , gain " + short_sell_gain_cnt , color.green);
addlabel(1, "Sells , loss " + short_sell_loss_cnt , color.red);
addlabel(1, "profit " +  sgainttl, color.yellow);
addlabel(1, "   ", color.black);



#---------------------
# lines

plot zlb = if long_buy_pr > 0 then long_buy_pr else if long_buy_pr[1] > 0 then long_buy_pr[1] else na;
zlb.SetDefaultColor(Color.white);
zlb.setlineweight(2);
zlb.hidebubble();

plot zlstopg = if long_buy_pr > 0 then long_sell_gain_pr else if long_buy_pr[1] > 0 then long_sell_gain_pr[1] else na;
zlstopg.SetDefaultColor(Color.green);
zlstopg.setlineweight(1);
zlstopg.hidebubble();

plot zlstopl = if long_buy_pr > 0 then long_sell_loss_pr else if long_buy_pr[1] > 0 then long_sell_loss_pr[1] else na;
zlstopl.SetDefaultColor(Color.red);
zlstopl.setlineweight(1);
zlstopl.hidebubble();

# ---------------------

plot zsb = if short_buy_pr > 0 then short_buy_pr else if short_buy_pr[1] > 0 then short_buy_pr[1] else na;
zsb.SetDefaultColor(Color.white);
zsb.setlineweight(2);
zsb.hidebubble();

plot zsstopg = if short_buy_pr > 0 then short_sell_gain_pr else if short_buy_pr[1] > 0 then short_sell_gain_pr[1] else na;
zsstopg.SetDefaultColor(Color.green);
zsstopg.setlineweight(1);
zsstopg.hidebubble();

plot zsstopl = if short_buy_pr > 0 then short_sell_loss_pr else if short_buy_pr[1] > 0 then short_sell_loss_pr[1] else na;
zsstopl.SetDefaultColor(Color.red);
zsstopl.setlineweight(1);
zsstopl.hidebubble();

# ---------------------

input show_buy_arrows = yes;
def arroff = 11;
def y = arroff * ticksize();

plot zlbuy = if show_buy_arrows and long_buy then low-y else na;
zlbuy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
zlbuy.SetDefaultColor(Color.green);
zlbuy.setlineweight(3);
zlbuy.hidebubble();

plot zsbuy = if show_buy_arrows and short_buy then high+y else na;
zsbuy.SetPaintingStrategy(PaintingStrategy.ARROW_down);
zsbuy.SetDefaultColor(Color.cyan);
zsbuy.setlineweight(3);
zsbuy.hidebubble();

#x.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
#x.SetDefaultColor(Color.red);
#x.setlineweight(1);
#x.hidebubble();


#----------------------
# sell shapes
# long
# sell gain - triangle
def lsellgain = if long_trade[1] and close > long_sell_gain_pr[1] then 1 else 0;
plot zlsg = if lsellgain then high + y else na;
zlsg.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
zlsg.SetDefaultColor(Color.green);
zlsg.setlineweight(4);
zlsg.hidebubble();

# sell loss - square
def lsellloss = if long_trade[1] and close < long_sell_loss_pr[1] then 1 else 0;
plot zlsl = if lsellloss then low - y else na;
zlsl.SetPaintingStrategy(PaintingStrategy.SQUARES);
zlsl.SetDefaultColor(Color.red);
zlsl.setlineweight(4);
zlsl.hidebubble();

#--------------------

# sell
# short
# sell gain - triangle
def ssellgain = if short_trade[1] and close < short_sell_gain_pr[1] then 1 else 0;
plot zssg = if ssellgain then low - y else na;
zssg.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
zssg.SetDefaultColor(Color.cyan);
zssg.setlineweight(4);
zssg.hidebubble();

# sell loss - square
def ssellloss = if short_trade[1] and close > short_sell_loss_pr[1] then 1 else 0;
plot zssl = if ssellloss then high + y else na;
zssl.SetPaintingStrategy(PaintingStrategy.SQUARES);
zssl.SetDefaultColor(Color.magenta);
zssl.setlineweight(4);
zssl.hidebubble();

#-------------------
# profit bubbles

input show_profit_bubbles = yes;
# longs
def longsell = if long_trade[1] and (close > long_sell_gain_pr[1] or close < long_sell_loss_pr[1]) then 1 else 0;
addchartbubble(show_profit_bubbles and longsell, low*0.99,
 "Long\n" +
 lgain + "\n" +
 lgainttl + "  TTL"
, color.cyan, no);


# shorts
def shortsell = if short_trade[1] and (close < short_sell_gain_pr[1] or close > short_sell_loss_pr[1]) then 1 else 0;
addchartbubble(show_profit_bubbles and shortsell, high*1.01,
 "Short\n" +
 sgain + "\n" +
 sgainttl + "  TTl"
, color.orange, yes);


#

long and short trades
cyan bubbles - long
orange bubbles - short
7Eb5LKn.jpg
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
557 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top