Amibroker: How to Use the If, Then Else Function (IIF)


Beginners Course  |  Intermediate Course  |  Amibroker Course

Sometimes in Amibroker we want to be able to do something, but only if a certain condition is met.  For example we might want to have a faster exit to our stock if we’ve been in it too long, or maybe change our entry criteria if an Index is moving up.  To do this, we can use the IIF (If, Then, Else) function in Amibroker.

In this video we are going to use our IIF (If, Then Else) to change the colour of a Moving Average.  So in other words:

  • If:          If our moving average is pointing up
  • Then:   Then return the colour green
  • Else:     (If it is pointing down) return the colour red

Pretty simple eh?  And Amibroker makes it even simpler by the use of this code.

Check out the video below!

You can also check out the video on Plotting your trading system, as we use that function to plot our colour-changing moving average.

The code for IIF is:

  • IIF( ARRAY or condition, Value if True, Value if False);

For example in our colour changing Moving Average, we used:

  • IIF(MovingAv > MovingAvPrev, ColorGreen, ColorRed);

So it returns the colour green if our condition is met, but the colour red if it is not met.

Try It Out For Yourself

So now you have the basics of If Then Else.  Try it out with different conditions and different results!  I hope it helps you on your trading system journey.

Happy trending,

– Dave McLachlan

Beginners Course  |  Intermediate Course  |  Amibroker Course Home

Videos in the FREE Amibroker Course:

  1. Amibroker: How To Import A Watchlist With A CSV File
  2. Amibroker: How To Backtest A Single Stock Or Index
  3. Amibroker: How To Backtest a Portfolio or Group of Stocks
  4. Amibroker: How To Optimize A Trading System
  5. Amibroker: How To Scan The Market For Buy And Sell Signals
  6. Amibroker: How To Use Explore To Find And Filter Stocks
  7. Amibroker: How To Add Position Sizing Using AFL
  8. Amibroker: How to Add An Index Filter To Your Trading System Using AFL
  9. Amibroker: How To Plot Your Trading System On A Chart (incl. Buy/Sell Arrows)
  10. Amibroker: How to Use the If, Then Else Function (IIF)
  11. Amibroker: How to Code the ATR Trailing Stop (Chandelier) using ApplyStop
  12. Amibroker: How to Plot ApplyStop on a Chart
  13. Amibroker: How to Code Van Tharp Position Sizing (Fixed Fractional)
  14. Amibroker: How to “Scale In” to Positions (1) – Buying Once a Month
  15. Amibroker: How to “Scale In” to Positions (2) – Pyramiding Three Times
  16. Amibroker: How to Use “Cross”, When One Thing Crosses Another
  17. Amibroker Advanced: How to Compare Equity Curves

FREE Trading System Video Lessons:

  1. 7 Free Trading Systems and Their Returns From The Last 13 Years
  2. Seven Full Trading Systems Revisited, With Completely New Data
  3. Trading System: How to Create A Buy and Hold Trading System
  4. Trading System: How to Code “Sell In May And Go Away”
  5. Trading System: How to Code a Moving Average Channel That Made 23% p.a
  6. Trading System: How to Code Highest Highs As Used In 52 Week Highs Or Turtle Trading System
  7. Trading System: How to Code a Bollinger Band Breakout Trading System
  8. Trading System: How to Code a Moving Average Crossover That Returned 28% per annum
  9. Trading System: How to Refer to Previous Signals For MAup Trading System
  10. Trading System: How to Code the Leap Of Faith (Gaps) Trading System That Returned 24% p.a.
  11. Trading System: How to Code a Short Selling System (Plus Results)
  12. Trading System: Meb Faber Trading System Using Different Timeframes
  13. Trading System: How to Code the Three Billion Dollar Trading System

FREE Amibroker Q & A Videos:

  1. Amibroker Q & A: How To Do A Monte Carlo Test? (on ALL versions)
  2. Amibroker Q & A: Visualising Monte Carlo Data with Histograms and Scatter Plots
  3. Amibroker Q & A: How to Create the 52 Week High/Low Index with AddToComposite
  4. Amibroker Q & A: How to Code Trend Pilot: Five Consecutive Days Above or Below a Moving Average
  5. Amibroker Q & A: Three “Hacks” To Improve Your Coding Skills
  6. Amibroker Q & A: How to Remove Excess Signals

August 11, 2013  Tags: , , ,   Posted in: Amibroker, Amibroker Course

8 Responses

  1. Martin Siegert - December 3, 2013

    Thanks for your videos.

    I want to make a Exploration for Buy and Hold Performance for all Stocks in Index like Dow Jones Industrial from 01012013 till Year end. How can I do that. If I use your Buy&Hold-System I only get the result of the first stock.
    Thanks for help in advance !


  2. Dave McLachlan - December 3, 2013

    Hey Martin,

    No idea off the top of my head. But it shouldn’t be too hard to figure out. Do you want to buy each stock evenly? If you have them in a watchlist, and set your position sizing to 30 positions and 3.33% in each (or however many stocks are listed in your index divided into 100), it should work out.

    There is a tutorial on Position Sizing on my site.

    Cheers – Dave

  3. micky - January 24, 2014

    Hi Dave,

    I want to first say thanks for your tutorials; they have been absolutely fantastic and a great help. You really have a knack for teaching!

    The one thing I would love to learn is how to test two systems (which have different risk size and stops) within one portfolio back this possible? E.G.

    System 1 =

    Index = Foreign (“SPY”,”C”,True);
    Indexfastma = MA (Index, 40);
    Indexslowma = MA (Index, 120);

    Buy = Close > 5
    AND Volume > 1.5 * MA( Volume , 20 )
    AND Volume > 200000
    AND Indexfastma > Indexslowma

    AND MA( Close , 40 ) > MA( Close , 120 )
    AND C>Ref(HHV(H,40),-1);
    Sell = 0; // selling only by stop

    TrailStopAmount = 5 * ATR( 20 );
    Capital = 10000; /* IMPORTANT: Set it also in the Settings: Initial Equity */

    Risk = 200;
    PositionSize = (Risk/TrailStopAmount)*BuyPrice;
    ApplyStop( 2, 2, TrailStopAmount, 0 );
    PositionScore = 100 + 1.5 * MA( Volume , 20


    System 2 =

    Index = Foreign (“SPY”,”C”,True);
    Indexfastma = MA (Index, 40);
    Indexslowma = MA (Index, 120);
    Buy = MA( Close , 40 ) > MA( Close , 120 )
    AND Indexfastma > Indexslowma
    AND Close < BBandBot( Close, 40, 2 )
    AND StochD ( 20, 3, 1 ) 200000
    AND Close > 5;
    Sell = 0; // selling only by stop

    TrailStopAmountLose = 2.25 * ATR( 20 );
    TrailStopAmountWin = 4 * ATR( 20 );
    Capital = 10000; /* IMPORTANT: Set it also in the Settings: Initial Equity */

    Risk = 100;
    PositionSize = (Risk/TrailStopAmountLose)*BuyPrice;
    ApplyStop( 0, 2, TrailStopAmountLose, 1 );
    ApplyStop( 1, 2, TrailStopAmountWin, 1 );

    PositionScore = 100 + 1.5 * MA( Volume , 20 );


    How can I run both systems on a portfolio test in one go?

    If you could help me out or point me in the right direction for further learning I would be very grateful.



  4. Dave McLachlan - January 24, 2014

    Hey Micky,

    Thanks for the kind words.

    I have no answer for you specifically (and haven’t got time to figure it out)… but I can tell you something that might help. When I was looking at “Monte Carlo” testing, I saw some code that used Optimize to do 1000 random runs of the SAME portfolio.

    Surely… you could use optimize to do just two runs, one of each DIFFERENT portfolio? Then Amibroker will spit out the two results side by side, as it does when we use optimize.

    The only thing is, it might involve using “Looping” (i.e. if your loop = 0 runs, then return “System1”, then if your loop = 1 run then return “System2”).

    Who knows? There’s probably an easier way than this even 🙂 My skill is very basic. I’m quite sure it’s possible though.

    Good luck!


  5. micky - January 25, 2014

    Hi Dave,

    Many thanks for your reply. I shall look into your possible solution. If I find out how to do it any other way I’ll leave a further comment…Perhaps your other readers might also be interested.

    Thanks again, Don’t enjoy the ashes too much!


  6. David - August 14, 2014

    Hi Dave, I followed this Let’s Learn Amibroker: Using IIF (If, Then, Else)step by step. However, when plotting I got two arrows for each day i.e red top green bottom throughout the chart. Obviously I missed something, I am using Amibroker 5.2. Any ideas? Thanks

  7. Dave McLachlan - August 21, 2014

    Hey David,

    Hmmm. Do you mean you got both a buy and sell arrow for every day? Not sure off the top of my head. It’s been a while. Feel free to send me the code you’ve done by email if you like! Could always have a look and see if anything stands out.

    Cheers – Dave

  8. sandeep - May 14, 2017

    I am new learner for amibroker and found your website and videos really good.

    I need to write a small trading logic – 3-4 lines of codes However as I am new I might take 2-3 weeks to learn and write if you can help me write that piece of code it will be really helpful.

    If you are happy helping please reply with email id and i will share the trading logic with you in email

Leave a Reply