PTS Logo

Beginners guide to Easy Language code with simple examples

How to make indicators, signals and strategies in Tradestation and MultiCharts

Programming in EasyLanguage: This tutorial guide gives easy examples of Tradestation code that you can be easily understood. Creating indicators and code signals made easy.

How to code simple strategies and indicators coded in Easy Language that can be used in Tradestation or MultiCharts to improve your code knowledge. There is an easy chess puzzle too.

If the code is too complicated for you then you can book a private consultation to get me to make your own custom strategy-indicator. Please email me your query first.

 

Easy language page joke

 

 The fix for division by zero errors are shown lower down this page. Taking regular brain breaks when coding can easily help performance

 



Beginners example No.1 ( Price up and down counter demonstration only)

Inputs:length(20);

vars: move(0),summove(0);

If close > close [1] then move = 1;

if close < close [1] then move=-1;

if close = close [1] then move=0;

summove= summation(move,length);


plot1(summove,"up-downcount");



Copy and paste the code above into your development environment in Tradestation or MultiCharts as Indicator. Then click on compile, or verify.

This code detects if the closing price today is greater than or less that the closing price of yesterday. ( This can be put on daily charts or minute charts and the close[1] refers to the previous bar or previous day)

If you typed close[2] it would refer to the close 2 days or bars ago instead.

Then we have the summation of the last ( length 20 ) bars.

To see how it works, you can change this line of code plot1(summove,"up-downcount"); to this plot1(move,"up-downcount"); Then click compile.

You can then see your indicator plots a line which is either 1, -1 or 0

The inputs written at the top represent values that can be changed by the user when plotting the indicator on the chart. Once you plot the indicator in its original form you can change the length to 50 or 20 or 100 to see how it affects the plot.

Variables are shown here as "vars" and these are values I created to store the values outputted by the 3 lines of code starting if close ...and the summove variable.

Summove= summation( move,length); This means the variable summove is created from adding up the sum of the last 20 bars ( or length period ) bars with all the 1 and -1 and 0 values.

You can experiment by trying it different values.
 


Beginners example No.2 (Adjustable weighting percent blended moving average) 


Inputs:length1(50),length2(20),factor(0.5);

variables: slow(0),fast(0),blended(0);

slow= average(close,length1);
fast= average(close,length2);

value1=factor;

if value1<0 then value1=0;
if value1>1 then value1=1;

value2= 1-factor;

blended= (slow*value1)+(fast*value2);

plot1(blended,"blended");


You can read the above code first before creating this indicator and see if you can understand what it is doing.

There are two moving averages used with slow length of 50 and a fast length of 20, the input called factor is adjustable to assign a weighting to each one.

If factor is set to 0.5 it will add 50% of the slow average to 50% of the fast average and create a blended average of the two periods.

To see maximum values of the slow average set factor to 1, to see the plot constructed entirely of the faster average you can set factor to 0.

You can experiment with values like 0.1 and 0.9 to see the affects of adjustments to the weighting.

Code tips

If you use the name value1 or value2 or value 99 as variables, then you do not need to declare the names of these at the top part.

Value2= 1-factor is a very neat way to get 2 variables to automatically assign 1% of one part and 99% of the other part so when added they will always =100%

Limit the user error by restricting inputs by making the variables read them. ( The code for value1 does this after reading the factor input )

Code tricks to try

If you look at the slow and fast variables you will see they both use averages (average is this code means simple average).

You can try making the slow one into a weighted average or an exponential average and mixing these up to make your own blended average combination.

 

Beginners example No.3 Simple binary trend indicator


{This example is for making a plot that goes into sub graph 2 and does not overlay over the price as the 2 above examples do.}

inputs: slow_length(80),fast_length(12);

variables: binary_trend(0);

if average(close,fast_length) > average(close,slow_length) then begin binary_trend=1;

end else binary_trend =-1;


{commenting code is done by using these squiggly brackets around text}

//In easylanguage code you can also comment code with two slashes at the far left of the text so this line of text is not read by the program

plot1(binary_trend,"Bin_Trend");




This indictor decides the "binary trend" which means it converts it to a number. Thus uptrend =1 downtrend =-1 and the initial value is assigned as 0.

Code tips

If you plot the 80 period moving average and the 12 period moving average on the chart you can check the trend indicator is working.

Using end else statements to reduce code length. EG above assumes that if the trend is not 1 then it must be -1.

Code tricks to try

If you try using another method to assign the trend is up or down and replace the code with your idea.

EG. You use the stochastic oscillator with above 50 being uptrend and below 50 being down trend.

The equal to 50 can be caught by saying this. If stochastic is >=50 then count as uptrend ( psuedo code)
 


Just added this new page with some open code on using the Qstick Indicator with two different lengths.

Surprisingly good for a trading strategy

Both versions of Quick stick have to be above zero to go long in this code example.
Opens up a new tab so you dont lose your place in the page

Qstick trading system

The simple qstick trading system 

Beginners example No.4 ( Simple length adjusting algorithm ) 


Inputs:basic_length(20),max_length(50),min_length(10);

variables: used_length(0),monitor(0);

if close = highest(close,basic_length) or close = lowest(close,basic_length)



then begin monitor= monitor[1]-1; end else monitor=monitor[1]+0.5;


if monitor < min_length then monitor = min_length;
if monitor > max_length then monitor = max_length;


plot1(monitor,"monitor");

This is the first stage of making an algorithm to control length applied to an indicator.

You can see that if you plot this indicator in subgraph 2 it ranges between 50 and 10 which are the max and min lengths allowed. ( But these are adjustable inputs )

If the price is making a new high or low for the basic length period it will slow down by 1 length increment for each bar that the condition is true.

If the price not making a new high or low for the same period it will reduce length by 0.5 length increment for each bar the condition is true.

Code tricks to try

If you try changing the values of the -1 and the 0.5 to larger or smaller amounts you can tune it to suit your requirements.

Below I will show you how to build this code into a length changing indicator.



 
Tip

To be a better programmer: Eat oily fish or take omega 3 capsules. It does not make you smarter but seems to enable better organisation, concentration and focus.

Notice how easy on your eyes this colour scheme is, try adjusting your schema to suit your preferences so you can work easier.

Grey-Green tones are good.

Some say that listening to gentle and low volume classical music boosts exam results in students.

Some others say that green is good because it is the only colour your eyes do not need to adjust to view it. Maybe this is why forests are relaxing?

Tip

To be a worse programmer: Listen to loud rap or rock n roll music while coding: Seems to cause a massive decrease in performance. 

Stay up until 3am to complete the project. The work you do between 2-3 will totally mess up what you did before 1am or 2am.

Enthusiam to complete a task is great but is counteracted by the dumbing down of brain functions caused by the tiredness

Notice the pink background is not as easy on the eyes as the green or grey? Choose a relaxing eye colour for your coding environment.


Beginners example No.5 ( Simple length adjusting weighted moving average ) 




Inputs:basic_length(20),max_length(30),min_length(10);

variables: used_length(0),monitor(0),l_changer(0);



if close = highest(close,basic_length) or close = lowest(close,basic_length)

then begin monitor= monitor[1]-1; end else monitor=monitor[1]+0.5;




if monitor < min_length then monitor = min_length;
if monitor > max_length then monitor = max_length;

l_changer=waverage(close,monitor);

plot1(l_changer,"l_changer");





You can see that another variable has been added which is a weighted moving average and the trick here is to replace the usual field of length with the algorithm monitor

 which is adjusting the length applied.

Code tricks to try

If you plot a 20 period weighted average next to it on the subgraph one. You can see how the code above length changing average is slower at some period and faster in

 other periods.

The above indicator is place in subgraph no1 overlayed with the price. Example code no4 is placed in sub 2.

You can observe the length changing algorithm in action and see how it affects the speed of the weighted average.
 

This page contains the formula for a regular weighted moving average together with diagrams and table showing it.

 Beginners example No.6 ( How to prevent division by zero errors )


This example shows how to correct division by zero errors in Tradestation Easy Language or MultiCharts

The image below is a good likeness for a division by zero event.

Computers act like the functioning of the road in the picture. They can't deal with it in a manly fashion and just crash and report fatal error warning messages.
Division by zero causes problemsDivide by zero and the World ends


Division by zero is a frequent problem experienced in programming. The answer is always infinity, so we have to prevent anything getting divided by zero in the first place.

There are two methods of doing this.

Method 1

If value1 = 0 then value1=value1+0.000000001;

So we simply add a tiny number to it, which is so tiny it will not make too much difference to the outputs.

This is not ideal and a more precise and programmatically correct method is show in method 2 below.

Method 2

If value1 <> 0 then value2 = value3 / value1

This forces the computer to ask if the value1 is 0 or not before doing its calculations.

If it is 0 it will return the default value that was assigned to value1 in the variables when you created it.

Voila
 





If you like what you see, feel free to SIGN UP to ideas new product and zero spam less than 12 emails per year.


Tip

Further notes on division.

Using division in programming is the slowest of all the basic maths functions and it uses up more resources faster than multiplication.

If you can use multiplication instead then use it and your code will easily run faster

EG.

Bad method     XYZ = (Low + High) /2;

Better method XYZ = (Low + High) * 0.5;


Making this change to your code can be the difference between missing or getting filled in a fast market.

One day this could mean a load of money is saved and even if it doesnt it will reduce your energy bill by a penny or two over fifty years, or a dollar / pound / euro in five

minutes when the inevitable hyper inflation kicks in.
 Floating point overflow.


A Mnemonics expert advised taking regular 5-10 minute breaks each hour to rest your programming brain while keeping it active by doing some other brain actions


CHESS PUZZLE

You can figure this one out with a bit of time

White to move

Mate in two moves.

Solution lower down the page and some more relaxing trading related items that you can use during brain rest breaks.

 
Chess puzzle No.1 






Tip

To solve this puzzle the theme is that a player cannot miss a move, the rules state that each player has to move when it is their turn, even if the only move is certain death.

It may look impossible at first glance, but it isnt.

The clue is there just think it through.

After whites move then black is in "Zugzwang" which is a German term meaning there is no move to do that doesn't make the position worse.

If you solved it, there is another chess puzzle on this page It is a very hard one with not much chance of solving it unless you are a grandmaster.

Code Tip

How to comment out code in Easy Language to stop it being used.

There are two ways to comment code to stop it being read by the programme

//Two slashes at the start of the text means everything to the right of the slashes is invisible to the programme.

To comment out a small snippet of code you can use the curly brackets to obfuscate certain parts of code {this little bit of text is invisible to the programme}

The brackets have to be curly like this {hidden words} if you using other brackets it does not hide the text.



Hidden text appears in green font so you can see it is commented out and is there just for your notation to understand that part of code.


Videos of trading systems in action

Solving the problem of not having the last entry price function in Tradestation 


A useful function for Tradestation programmers.

User of Tradestation's programming environment may have experienced difficulties with multiple entry price models as the built in function ENTRYPRICE(NUMBER) only refers

to the entry price of a new "overall position" rather than an entry of sequence of trades which go to make up an overall position.

The software does not have a function to call the 2nd or 3rd or greater entry prices in a position where several trades are placed.

While developing a Martingale model I ended up creating a special function to do just that so it was easier to call from.

i have developed a function is called "LastEntryPrice" and will always call the most recent entryprice regardless of how many entries are employed.

So if you need a triple entry model to work you can use the regular "ENTRYPRICE" function to call the first trade and then the LASTENTRYPRICE function to call the next ones.

Sample code below

//First exit

IF currentcontracts= first_size and marketposition=-1

and ENTRYPRICE-CLOSE > 12.50

THEN BUYTOCOVER ("1st exit short") next bar on highest(high,5) stop;

//Second exit

IF currentcontracts= first_size+Second_Size

and marketposition=-1 and LASTENTRYPRICE-CLOSE > 25

THEN BUYTOCOVER ("2nd exit short") NEXT BAR AT MARKET;


This function will be available upon request if anyone asks me for it.
 Email me for details.



Beginners example No.7 Just how good things can be when you get it right and create a something special 


Over the last thirty five years I have studied many aspects of technical analysis and automatic trading systems, bespoke indicators drawing tools etc.

It does not happen by luck, mostly it is a few hundred ideas that are not as good as hoped but one or two work well.

Perseverence is vital, it takes time to be able to design cycle finding code like John Ehlers, also takes time to be that good at maths.

Here are some of my best formulas all completely solid in their execution they are all done in EasyLanguage code.


Or if you use EasyLanguage for MultiCharts you can see the same products here


Practice makes perfect and persistence is vital. You can make anything you want if you keep at it.

Most of the things I make get abandoned it is the continual trying and testing that leads to a good concept making it to the finishing line.



Some of the excellent qualities of Demand Index went into the creation of the Precision Index Oscillator shown below, a highly complex consensus indicator that provides

pinpoint top and bottom identification in the form of highlights when plus or minus 3.141 is reached ( hence the name Pi-Osc ) the results speak for themselves.
 

The Pi-Osc 


The image below is part two of the code for the Day-Trading-Permissions-Filter 


There are screenshots to show you how it works on the link below.

If you found the second part of this code on this page you can find the start of it here.

To create the paint bar study- Simply copy and paste the code you typed for the indicator and remove the two plots and replace with paint bar code.

First go to file - new - indicator then add PB to the end of the old name so its appears above the other in the list.

Remove-

PLOT1(ADDER,"Day-Trading-Permission");

PLOT2(LEVEL,"Level of Threshold");

Then add this-

IF ADDER > LEVEL THEN PLOTPAINTBAR(HIGH,LOW);

To create the trading system -Remove the plot or paint bar code and add your entry and exit code as normal but this time use the extra code for the day trading permission filter.

First go to file new - signal then copy the code without the plot or paint bar code

Then add this-

If adder > level and "your long entry code" then buy next bar at market;

If adder > level and "your short entry code" then sellshort next bar at market;

Exit stops can and MUST be used in the normal way without using the day trading permission filter. EG.

If marketposition=1 then sell next bar at lowest(close,50) stop; // long exit

If marketposition=-1 and then buytocover next bar at highest(close,35) stop; // short exit

Adjust to suit your needs.

Please note this is EasyLanguage code and is very similar to the TV so if you want to create you own trading system for TradingView converting it over is relatively simple.

Happy coding.

 
The day trading permissions filter 

Code above is the 2nd part of day trading permission code



The first part of this code is found here at the bottom of the day trading page

 


More examples of clever things you can do with EasyLanguage code.

The code in the red panel on the link below creates a very dependable double trend strategy with PLA Dynamical GOLD the fastest moving average on the planet.

This page shows how to call PLA Dynamical GOLD and use the function to make other interesting strategies indicators etc from it.


Beginners example No.8  CurrentContracts code logic not operating correctly and also explains how to code partial exits in easy language code.

In the currentcontracts code in easy language, this is not always executing as one expects.

These code examples show how to reduce drawdowns usually found in trend following systems by gently scaling out of positions. This is an easy to follow extract.

Some examples of it working correctly.

If marketposition=1 and currentcontracts = 100 and close=lowest(close,20) then sell 50 contracts total next bar at market; // This works and the word "total" instructs it to
 just sell 50 of the open 100 long contracts or shares.

You can expand on this use with this code below

If marketposition=1 and currentcontracts = 100 and close=lowest(close,20) then sell (currentcontracts * 0.25) contracts total next bar at market; // This works and the

word "total" instructs it to just sell 25% of the open 100 long contracts or shares.

Please note this code does not round perfectly if asking to sell a quarter of 10, it will usually sell 3 if asked for an amount the does not round to a whole number.

The accuracy improves if holding a large block of shares or contracts like 10,000 and then the error of rounding is reduced.

So if you know in advance the exact value, then there is no need to use the ( currentcontracts * 0.25) type of code as you can just type in the exact amount.

The code (currentcontracts * 0.25) can be changed to engineer multiple exits for different reasons such as being overbought or many up bars in a row etc, to scale out and

take some profits when a trade is going well. This helps smooth out the equity curve by selling when the sun is shining and reduces drawdown depths.

Incorrect code example that appears it would work but does not work.

If currentcontracts <> currentcontracts[1] then {do something}


How to correct it is simple but it is not obvious why it needs to be done at all. The solution is to make a variable and put it at the top of page with the others thus

Inputs: Length(20), otherinputs(2);

Variables: CC(0); // It could be called anything but cc is a short name which works for me, but you can name the variable to anything you wish.

CC= CurrentContracts;

If CC <> CC[1] then
{do something} // works fine



Beginners example No.9  Adding different names  or labels to strategy signals

When multiple entry or exit signals are employed it is helpful to have them displayed on the chart so easy debugging and identification can be done.

If close > close[30] then buy ("30 bar highest close") 1 contracts next bar at market;

If close > close[50] then buy ("50 bar highest close") 2 contracts next bar at market;

The above code has a bug in it, do you see the problem?

Both conditions can be true for the 2nd signal as the 50 bar high will also be a 30 bar high at the same time, so lets fix that by preventing the 1st line triggering again.

If currentcontracts <>1 and close > close[30] then buy ("30 bar highest close") 1 contracts next bar at market; // checks that is not already long 1 contract

If currentcontracts =1  and close > close[50] then buy ("50 bar highest close") 2 contracts next bar at market;  // checks that it is already long 1 contract and will not fire if

currentcontracts are more or less than 1

As the image shows below, you can type anything inbetween the "inverted commas" to display your unique signal elements on the chart

Easy language signals can be labelled
Hyper advanced code research project not for beginners    Planets orbits strategy project ( opens in new tab )
Beginners example No.10  Goertzels algorithm
Beginners example No.11  Understanding arrays
Beginners example No.12  Understanding arrays
Beginners example No.13  Elapsure strategies using decaying algorithmic solutions
Beginners example No.14  Machine learning trading strategy

More educational geek stuff below for your amusment to help you refresh your programming mind in between coding sessions



If you use NinjaTrader there are some easy to follow NinjaScript code examples on this page



If you use ProRealTime there are some easy to follow ProRealCode code examples on this page


REAL DEAL Stock market calculators


This page explains the essential but lightly read topic of risk control which demonstrate How to compute optimal risk


You might also enjoy this 100% accurate formula which is designed to  Compute the maximum and minimum highs and lows 30 days into the future

 

Calculate how much you will lose if the next crash is the same magnitude as it was in the 1987 crash with the Magic crash calculator

 

Real World trading practice and fun time study


Generate a report that shows your trading style and lake ratio, risk reward raio, winning trade percentage, drawdowns and more all the time your brain will

keep busy but it will relax the programming part of it while you enjoy some trading practice with actual market prices in the Trading IQ Game  which is

rather difficult.

Probably you will not exceed a 1000 Trading IQ and will give up after a few sessions. Those winners with determination can get my three of my paid

products and the MultiCharts platform as prizes.

Some extracts of ProRealCode are on this page which are easily converted to EasyLanguage code.

Samples include- Drawdown system switch off, Trailing stops, position size algorithms, infinite loops and more

  The journey of a thousand miles begins with the first step     Start the Trading IQ Game   the winning comes from the doing. Yes it is free 100%


Theoretical study


More educational content the pages below are for you Trading Lessons in several parts for new traders and improvers some parts of it are more advanced.


The least visited page on PTS site is called "Correct answer"  hopefully you can find it instead of the more popular "Incorrect answer" page.


If you still have not solved the chess puzzle, consider moving the rook somewhere which looks wrong before you scroll down to the answer below.


Always remember there are three types of people in this World. Those who can add up and those who can't :)
 

 

The help and advice of customers and readers is valuable to me.

Have a suggestion?

Tell me what you need...Send it in

 

Return to the top of page (Keep within the legal speed limit)

 

 

If you like what you see, feel free to SIGN UP  to be notified of new products - articles - less than 8 emails a year and ZERO spam-

less than 12 emails a year and ZERO spam and ZERO hard selling

 

~ About ~

 

Precision Trading Systems was founded in 2006 providing high quality indicators and trading systems for a wide range of markets and levels of experience.

Supporting NinjaTrader, Tradestation. MultiCharts, TradingView, MetaTrader 4 and MetaTrader 5

 
Bio 
 

The PTS Logo

 

Admin notes: page re designed 6th August 2023 sm icons added sc and ga at base....No1 Easy Language page in Google from 848,000,000 results

Chess puzzle solution RH6! leads to Zugzwang for black as if pawn takes rook, then pawn G7 is check mate. Or if the bishop moves away then rook x H7 is mate

Next chess puzzle here