Write a custom indicator
When the 67 built-in indicators are not enough, write your own.
Every new account has an example, Simple Moving Average (key SMA_Example), in the Indicators list. Open it to see a complete one.
1. Create it
Section titled “1. Create it”Do this: In the Indicators list, type a name, select New, and give it a short key such as myMomentum. You will call the indicator by this key.
2. Write the three functions
Section titled “2. Write the three functions”function validate(periods) { if (typeof periods !== "number" || periods < 1 || periods > 100) { error("periods must be between 1 and 100"); }}
function getBufferSize(periods) { return periods + 1;}
function onIntervalClose(periods) { const closes = prices(periods + 1); return closes[0] - closes[periods];}validatechecks the arguments and stops with a message if they are wrong.getBufferSizesays how many bars of history the indicator needs.onIntervalClosereturns the indicator’s value for the bar that just closed.prices()lists the newest close first, so this is the change overperiodsbars.
3. Test it
Section titled “3. Test it”Do this: Save, then select New Test. Pick an instrument, interval and date range, and enter 10 for periods.
You should see: The indicator’s output on a chart, with its log. A test that runs for more than 30 seconds is stopped. Saved indicators also appear under Custom in a chart’s Indicators panel.
4. Use it in an algorithm
Section titled “4. Use it in an algorithm”function onIntervalClose() { if (myMomentum(10) > 0 && OPEN_POSITIONS_COUNT === 0) { openPosition("BUY", { riskPercentage: 1, stopLossPips: 20 }); }}The algorithm gets the number your onIntervalClose returned. Each custom indicator call counts toward the limit of 10 indicator settings per algorithm.
Read next
Section titled “Read next”- Writing your own indicators: lines, ranges, panels and several lines at once.
- Indicators
- Indicators explained