User avatar
Matthew
Site Admin
Site Admin
Posts: 92
Joined: July 1st, 2020
Location: Australia
Contact: Website Facebook Twitter TradingView Profile

Forex Position Size Calculator

Hey scripters!

As some of you may know, I recently began playing around with AutoView which is a Chrome extension that allows you to automate your trade execution using TradingView alerts.

I know there are better alternatives out there for crypto traders such as 3commas, but for forex traders like myself there's really no tools or services out there that come close to making automated trading the forex markets easy without using complex programming languages and APIs which I haven't got the time to get into at the moment.

So I've been trying really hard to wrap my head around AutoView to see if I can automate some of my simpler strategies to free up more time to work on other things such as helping students and clients with their own scripts.

So far I've got AutoView working about 90% of the way to how I want it to, but the biggest technical issue I've encountered is that the extension doesn't allow you to automatically adjust your position size on each trade based on your account balance.

I like to risk 1% per trade on any strategies that have an average win rate below 60%, and so this posed a problem with automating my pullback indicator script. At first I began autotrading it with a fixed position size but I quickly figured out that wasn't going to work. Trading a fixed position size using an ATR stop is dangerous because some trades can have a large stop loss due to market volatility which causes inconsistency in my risk management, and the bot took a trade today that risked 6% of my account.

Luckily the trade won lol, but that is way beyond what I'm comfortable risking on an automated system with a low win rate. So I set out to come up with a solution.

The best solution I found was to simulate my account balance in the script and automatically calculate my position size based on that. And so this code below will do just that :cool:

It even takes into consideration the exchange rate between your account balance currency vs. the base currency or quote currency etc. - so as far as I can tell, it's 100% accurate no matter what forex pair you're trading or what currency your account is denominated in. Obviously the script cannot tell what my real account balance is, but theoretically, if I update my account balance in my alerts each week, this shouldn't be a big deal.

Now that I can take my account balance into consideration the script should remain fairly consistent in terms of risking roughly 1% per trade. By using a high R:R profile of 1.4+ I only need to win 40% of my trades minimum to turn a profit, so I'm optimistic that I can get the script to perform profitably with this new risk management functionality. I'm going to leave the script running on a $1000 account for the next few weeks to see what happens.

I'll be recording a lesson on how I use this code in my automated scripts at some point soon, so when I release the Mentorship Program keep an eye out for that.

Here's the script (note that it will only work for FOREX markets):

Code: Select all

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading
// www.zenandtheartoftrading.com
// @version=4
study("PSMP - Position Size Calculator", overlay=false)

// Get user input
accountBalance  = input(title="Account Balance", type=input.float, defval=1000.0)
accountCurrency = input(title="Account Currency", type=input.string, defval="USD", options=["AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NZD", "USD"])
riskPerTrade    = input(title="Risk Per Trade %", type=input.float, defval=1.0)
stopSize        = input(title="Stop Loss Size (Pips)", type=input.float, defval=10.0)

// Check if our account currency is the same as the base or quote currency (for risk $ conversion purposes)
accountSameAsCounterCurrency = accountCurrency == syminfo.currency
accountSameAsBaseCurrency = accountCurrency == syminfo.basecurrency
// Check if our account currency is neither the base or quote currency (for risk $ conversion purposes)
accountNeitherCurrency = not accountSameAsCounterCurrency and not accountSameAsBaseCurrency

// Get currency conversion rates if applicable
conversionCurrencyPair = accountSameAsCounterCurrency ? syminfo.tickerid : accountCurrency + syminfo.currency
conversionCurrencyRate = security(symbol=conversionCurrencyPair, resolution="D", expression=close)

// Calculate position size
getPositionSize(stopLossSizePoints) =>
    riskAmount = (accountBalance * (riskPerTrade / 100)) * (accountSameAsBaseCurrency or accountNeitherCurrency ? conversionCurrencyRate : 1.0)
    riskPerPoint = (stopLossSizePoints * syminfo.pointvalue)
    positionSize = (riskAmount / riskPerPoint) / syminfo.mintick
    round(positionSize)

// Draw data
stopLossSizeFromPipsToPoints = stopSize * 10
plot(getPositionSize(stopLossSizeFromPipsToPoints), color=color.red, transp=100, title="Position Size")
plot(conversionCurrencyRate, color=color.orange, transp=100, title="Conversion Currency Rate")

Deep-Wave
Pine Script Master
Pine Script Master
Posts: 44
Joined: September 4th, 2020
Contact: TradingView Profile

Re: Forex Position Size Calculator

Hi Matt,
that is freaking awesome, i love that it even takes the exchange rates into consideration, thank you so much for sharing!
I will definitely try this out once i have a strategy i feel comfortable with. :happy1:

Ricardo
Pine Script Rookie
Pine Script Rookie
Posts: 1
Joined: December 13th, 2020

Re: Forex Position Size Calculator

Hello Matthew

This piece of code has done nothing but wonders to my trading algorithm. Thank you very much

dusktrader
Pine Script Scholar
Pine Script Scholar
Posts: 32
Joined: February 24th, 2021
Contact: TradingView Profile

Re: Forex Position Size Calculator

I am very interested in this script. I saw your video on it and it is something that I'm looking for as well. Not yet for auto-trading, but for the same reason... I trade the pairs that I've proven are most valuable and trend-worthy in my testing (currently manual). But to effectively trade cross-pairs (or any pair) you need to quickly determine your lot size and calculate stoploss. So for that I'm excited to dive-in and use your tool.

Can you please share what the technical limits are regarding AutoView? I think I heard in your video - or read somewhere - that AutoView cannot communicate back to TradingView, it can only respond to triggers (is that accurate)? If true, is the reason for this due to a Chrome limitation, or is it that the AutoView extension (which is closed-source) just cannot do it? If the latter, just curious if you have brought this up with the developer yet as a suggestion?

Btw I just emailed the author (the support people?) and they responded very quickly. I asked if they had plans to include forex.com as an integrated broker, and they said it was one of the most requested -- meaning yes, it's coming! For now I will play around with Oanda, but looking forward to forex.com support.

Just thinking out loud here... but if the above is true (no feedback AutoView-> TradingView) then I think the way I would try to solve that problem is to put the burden on the TradingView side. For example, the script or indicator that is triggering AutoView needs to also calculate and communicate the stop it wants. Is this technically possible?

Thank you for sharing your script btw!

Return to “Share Your Scripts”