Position Size Calculator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cjcjesse

//@version=4
study("Position Size Calculator","Calc", true)
accbalance = input(5000.00, title="Account Balance")
riskper = input(0.01, title="Risk Percentage")
bufferfrac = input(5.0, title="Wiggle Room")
prevhigh = high[1] + ((high[1] - low[1]) / bufferfrac)
prevlow = low[1] - ((high[1] - low[1]) / bufferfrac)

riskdiff = prevhigh - prevlow
size = floor((accbalance * riskper) / riskdiff)
cost = close * size

var tbl = table.new(position.top_right, 4, 2)

if (barstate.islast)
    table.cell(tbl, 0, 0, "Long",  bgcolor = #aaaaaa, width = 7, height = 4)
    table.cell(tbl, 1, 0, "Short", bgcolor = #aaaaaa, width = 7, height = 4)
    table.cell(tbl, 2, 0, "Size",  bgcolor = #aaaaaa, width = 7, height = 4)
    table.cell(tbl, 3, 0, "Cost", bgcolor = #aaaaaa, width = 7, height = 4)
     
    table.cell(tbl, 0, 1, tostring(prevhigh),  bgcolor = color.green, width = 7, height = 4)
    table.cell(tbl, 1, 1, tostring(prevlow), bgcolor = color.red, width = 7, height = 4)  
    table.cell(tbl, 2, 1, tostring(size),  bgcolor = color.blue, width = 7, height = 4)
    table.cell(tbl, 3, 1, tostring(cost), bgcolor = color.yellow, width = 7, height = 4)