# Plot an average price line, plus optional profit or loss bubble.
#hint: (As of 5/15/24 Works for day trading!\n - maybe does not account for long term splits! )\n\nPlot the average position price line and\n show the price in a bubble at the end.\n For multiple entry prices the average line\nadjusts for each new position on a chart with daily aggregation.\n A green line for long and light red for short positions.\n\n Optionally add a profit and loss bubble.
input show_price_line = yes;
input show_profit_or_loss = yes;
# GetQuantity appears to fail randomly as the following reference suggets
# https://usethinkscript.com/threads/getquantity-stuck.12758/
def quantity = GetQuantity();
def bubble_above = yes;
def bubble_below = no;
def long_position = quantity > 0;
def short_position = quantity < 0;
# Reference:
# https://www.reddit.com/r/thinkorswim/comments/t3nwja/automatically_draw_a_line_on_the_chart_when_each/
# https://www.reddit.com/user/Mobius_ts/
# March 17, 2021
def avgPrice = GetAveragePrice();
plot Entry = if (long_position) and show_price_line then
avgPrice
else if short_position and show_price_line then
avgPrice
else
Double.NaN;
Entry.DefineColor("long", Color.LIME);
Entry.DefineColor("short", Color.LIGHT_RED);
Entry.DefineColor("out", Color.GRAY);
Entry.AssignValueColor(if long_position then
Entry.Color("long")
else if short_position then
Entry.Color("short")
else
Entry.Color("out"));
Entry.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
Entry.SetLineWeight(3);
# # #
# show average price in a bubble at the end of the Entry price horizontal line
# just one bubble at the last bar # Reference:
# https://usethinkscript.com/resources/
# thinkscript-addchartbubble-add-and-customize-chart-bubbles.13/
def placeInTime = !IsNaN(close) and IsNaN(close[-1]) && HighestAll(BarNumber());
AddChartBubble( long_position and placeInTime, Entry,
"long $" + Entry ,
Color.GREEN,
bubble_below);
AddChartBubble(short_position and placeInTime , Entry,
"short $" + Entry ,
Color.RED,
bubble_above);
# # #
# Calculate position profit or loss
def profit_or_loss = quantity * (close - Entry);
AddChartBubble(placeInTime and show_profit_or_loss == yes , Entry,
"pnl $" + profit_or_loss,
if profit_or_loss > 0 then
Color.LIGHT_GREEN
else if profit_or_loss < 0 then
Color.LIGHT_RED
else
Color.GRAY,
bubble_below);
#
# # #
# FWIW. There is some additional discussion about EntryPrice()
# https://usethinkscript.com/threads/thinkscript-get-entryprice-function.1610/